Microsoft Visual FoxPro

Welcome to Microsoft Visual FoxPro. Visual FoxPro is the object-oriented relational database management system that makes it possible for you to create database solutions for the desktop to the Web. Visual FoxPro provides powerful data handling capabilities, rapid application development tools for maximum productivity, and the flexibility needed to build all types of database solutions.

In the Visual FoxPro Documentation

What's New in Visual FoxPro 8.0
Describes the new features and enhancements included in this version of Visual FoxPro.
Getting Started with Visual FoxPro
Provides information about where to find the Readme file, installing and upgrading from previous versions, configuring Visual FoxPro, and customizing the development environment.
Using Visual FoxPro
Gives an overview of Visual FoxPro features, describes concepts and productivity tools for developing, programming, and managing high-performance database applications and components, and provides walkthroughs that help get you started. With the robust tools and data-centric object-oriented language that Visual FoxPro offers, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.
Samples and Walkthroughs
Contains Visual FoxPro code samples and step-by-step walkthroughs that you can use for experimenting with and learning Visual FoxPro features.
Reference
Includes Visual FoxPro general, programming language, user interface, and error message reference topics.
Product Support
Provides information about Microsoft technical support for Visual FoxPro.

Additional Information

Microsoft Visual FoxPro Web Site
Provides a link to the Visual FoxPro Web site for additional information and resources for Visual FoxPro.
Microsoft Visual FoxPro Training and Resources
Provides a link to the Visual FoxPro training Web site to find information about training, books, and events for Visual FoxPro.
Accessibility for People with Disabilities
Provides information about features that make Visual FoxPro more accessible for people with disabilities.

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


What's New in Visual FoxPro 8.0

Welcome to Microsoft Visual FoxPro. Visual FoxPro is the object-oriented relational database management system that you can use to create database solutions for the desktop to the Web. Visual FoxPro provides powerful data handling capabilities, rapid application development tools for maximum productivity, and the flexibility needed to build all types of database solutions.

In This Section

Submitting Feedback about Help to Microsoft
Describes how you can send feedback about the Visual FoxPro Help documentation to Microsoft.
Interactive Development Environment (IDE) Enhancements
Describes additions and improvements made to the Visual FoxPro IDE.
Language Enhancements
Describes additions and improvements to the Visual FoxPro programming language.
Data Features Enhancements
Describes additions and improvements to Visual FoxPro data features.
Miscellaneous Enhancements
Describes other improvements made in this version of Visual FoxPro.
Behavior Changes Since Visual FoxPro 7.0
Describes changes in the behavior of existing language and functionality.
Visual FoxPro 8.0 New Reserved Words
Lists new reserved words added to Visual FoxPro.

Related Sections

Getting Started with Visual FoxPro
Provides information about where to find the ReadMe file, how to install and upgrade from previous versions, configure Visual FoxPro, and customize the development environment.
Using Visual FoxPro
Provides an overview of Visual FoxPro features, describes concepts and productivity tools for developing, programming, and managing high-performance database applications and components, and provides walkthroughs that help get you started. With the robust tools and data-centric object-oriented language that Visual FoxPro offers, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.
Samples and Walkthroughs
Contains Visual FoxPro code samples and step-by-step walkthroughs that you can use for experimenting with and learning Visual FoxPro features.
Reference
Describes Visual FoxPro general, programming language, user interface, and error message reference topics.
Product Support
Provides information about Microsoft technical support for Visual FoxPro.


Submitting Feedback about Help to Microsoft

This version of the Visual FoxPro Help documentation contains many improvements and suggestions we have gathered from our customers. We value your feedback and welcome any additional suggestions about the documentation that can help make it easier to use.

Each topic in Visual FoxPro Help contains a "Send feedback on this topic to Microsoft" hyperlink on every topic page that you can use to submit your comments about the Help topic. Clicking the link opens a message template. The message template contains the necessary information about the topic so you do not have to type it in.

Note For product and technical support issues, please contact Microsoft Technical Support so they can be addressed appropriately. For more information, see Microsoft Visual FoxPro Technical Support.

To submit feedback about the documentation

  1. Locate the Help topic that you want to submit feedback for.
  2. Near the bottom of the topic, click Send feedback on this topic to Microsoft.
  3. In the Comments section of the message template, type your comments about how the topic can be improved or needs correction.
  4. When you are finished, click Send.

See Also

What's New in Visual FoxPro 8.0 | Interactive Development Environment (IDE) Enhancements | Language Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Interactive Development Environment (IDE) Enhancements

To provide a more integrated development environment for your projects and applications, Visual FoxPro contains the following improved functionality for the IDE:

  • Visual FoxPro Task Pane Manager
  • Visual FoxPro Toolbox
  • Code references search tool
  • Enhancements to Visual FoxPro designers and editors
  • Windows-style Open and Save dialog boxes
  • Keyboard shortcut changes and enhancements
  • IntelliSense for the Watch window
  • Wordwrapping for ToolTip text
  • Viewing properties in the Properties window using Zoom

Visual FoxPro Task Pane Manager

The Visual FoxPro Task Pane Manager contains individual panes, or windows, that make essential everyday tasks easy for you to accomplish. These panes improve the discoverability of new and existing features, expose wizards for simple tasks, display Help topics, register and publish XML Web services, present samples, and can deliver dynamic content to the Visual FoxPro desktop.

For more information about the Task Pane Manager and the tasks you can perform, see Task Pane Manager, Accessing XML Web Services, Distributing XML Web Services, Walkthrough: Creating XML Web Services with Visual FoxPro, and Solutions Samples.

Visual FoxPro Toolbox

The Visual FoxPro Toolbox provides an integrated and organized way to use customizable and categorized tool sets such as class libraries, builders, and text snippets; common resources such as labels, forms, images, files, and tables, or other items such as ActiveX controls, COM classes, and wizards. The Toolbox provides complete control over its configuration, replaces the Form Controls toolbar, and enhances the IDE. The Toolbox also supports third-party add-in tool sets.

Note The Form Controls toolbar no longer opens automatically when you open a new form or class.

For more information, see ToolBox, Customizing the Toolbox, and _TOOLBOX System Variable.

Code References Search Tool

You can search for and replace code references or text in the Look Up Reference dialog box provided by the Code References tool, which you can select from the Tools menu. You can specify whether to search an entire project or folder and whether to filter on certain file types such as .vcx, .scx, .prg, and so on. For more information about searching and replacing code references, see Look Up Reference Dialog Box, Code References Window, and Searching and Replacing Code References.

Enhancements to Visual FoxPro Designers and Editors

Visual FoxPro contains numerous improvements made to its designer and editing tools. For more details, see Enhancements to Visual FoxPro Designers and Enhancements to Visual FoxPro Editors.

Windows-Style Open and Save Dialog Boxes

Visual FoxPro running on Windows 2000 and Windows XP operating systems includes the following changes in the Open, Save, and Open Picture dialog boxes:

  • A Places bar so you can navigate to common locations such as the My Documents folder and Desktop
  • The following options are available by clicking the View Menu icon: Thumbnails, Tiles, Icons, Lists, and Details. You can preview images in Windows 2000 and later by clicking Thumbnails. Visual FoxPro uses the Thumbnails view as the default setting to provide mini-previews of images. Therefore, the Open Picture dialog box no longer includes a frame for displaying an image. The Preview check box appears in the Open Picture dialog box only when running Visual FoxPro on operating systems earlier than Windows 2000.
  • The capability to resize dialog boxes

You can select multiple files in the Open dialog box after clicking Add in the Project Manager window to add a file to a project.

When you call the AGETCLASS( ) function, the Files of type list in the Open dialog box includes the program (.prg) file type. AGETCLASS( ) is no longer supported in Visual FoxPro runtime libraries because routines for parsing program (.prg) files are restricted to design time only.

For more information, see Open Dialog Box, Open Picture Dialog Box, Project Manager Window, and AGETCLASS( ) Function.

Keyboard Shortcut Changes and Enhancements

Visual FoxPro includes enhancements and behavior changes for the following keyboard shortcuts.

CTRL+TAB Keyboard Shortcut

Visual FoxPro now supports context-sensitive behavior when pressing the CTRL+TAB key combination. Pressing CTRL+TAB performs the following actions:

  • Exits a grid when focus is in a Grid control because pressing the TAB key in a grid moves you between fields.
  • Exit an edit box when focus is in an EditBox control, and the EditBox AllowTabs property is True (.T.).
    Note When EditBox AllowTabs property is False (.F.), CTRL+TAB no longer exits an edit box. Instead, CTRL+TAB moves to the next available window. You can press the TAB key to exit an edit box when AllowTabs is False.
  • Moves between pages in a PageFrame control contained in a form or dialog box. However, Visual FoxPro does not support this behavior in a project nor when the PageFrame control contains an ActiveX control.
  • Move between document and designer, or multiple-document interface (MDI), windows such as the following:
    • Form Designer at design and run time, though not when in a page frame or grid
    • Menu Designer
    • Project Manager
    • Command window
    • Database Designer
    • Report and Label Designer
    • Children of MDI windows

    Current behavior when running a user form now differs from mimicking a plain tab and moving between controls on a form.

  • Move between projects, though not when the project structure is collapsed. You can also move between project tabs that you tear off.
  • You can reverse movement by pressing SHIFT+CTRL+TAB

Visual FoxPro now preserves the order of windows and brings the newest window to the foreground instead of shifting the last window to the background.

Note Pressing the TAB key instead of CTRL+TAB now automatically enters Tab mode in the Report Designer. Support for pressing CTRL+TAB to enter Tab mode in the Report Designer has been removed.

For more information, see Keyboard Shortcuts and Report Designer.

TAB Key and SHIFT+F10 Keyboard Shortcut

You can now move to the object list in the Properties window by pressing the TAB key. In the Properties window, when you click the object list or click a tab, and then press SHIFT+F10, Visual FoxPro displays the appropriate menu. When you select a property in the Properties window properties list, pressing SHIFT+F10 opens a menu for that property.

For more information, see Keyboard Shortcuts and Properties Window.

CTRL+HOME and CTRL+END Keyboard Shortcuts

Visual FoxPro provides keyboard shortcut behavior consistent with Microsoft programs such as Excel and Access when navigating in a grid and using the BROWSE command:

  • Moves to the first record of a cursor or table in a grid and when using BROWSE by pressing CTRL+HOME.
  • Moves to the last record of cursor or table in a grid and when using BROWSE by pressing CTRL+END.

For more information, see Keyboard Shortcuts.

IntelliSense for the Watch Window

You can use IntelliSense in the debugger Watch window to view valid members of Visual FoxPro objects and properties and values for commands and functions. Visual FoxPro limits IntelliSense support to the Watch window because you cannot type directly in the Locals, Call Stack, Trace, or Debug Output windows. For more information, see Watch Window, Using Intellisense in Visual FoxPro, and IntelliSense Support in Visual FoxPro.

Wordwrapping for ToolTip Text

Visual FoxPro supports wordwrapping and increases the limit from 255 to 4,095 displayable characters for ToolTip text. For more information, see ToolTipText Property.

Viewing Properties in the Properties Window Using Zoom

Previously, it was difficult to view values of read-only properties in the Properties window properties list that extended beyond the right edge of the window without widening the window. You can now see the entire value for a read-only property by right-clicking the property in the properties list and clicking Zoom. For more information, see Properties Window.

See Also

What's New in Visual FoxPro 8.0 | Language Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Enhancements to Visual FoxPro Designers

Visual FoxPro contains numerous improvements made to its designer tools.

  • Support for additional classes in the Class Designer
  • Form Designer enhancements
    • Data Environment Builder
    • XML Web Service Builder
    • Showing most recent control selected when setting tab order
    • No maximum limit for design area
    • Persisting state of Form Designer and Form Controls toolbar
  • Table Designer enhancements
    • Building expressions in Caption field
    • Using database container (DBC) captions as expressions
    • Autoincrementing field values in the Table Designer
  • Improvements for multi-table joins and the SQL SELECT command in the View and Query designers
  • Support for moving menus in the Menu Designer
  • Report design and printing enhancements

Support for Additional Classes in the Class Designer

Visual FoxPro includes enhanced class support as follows:

  • Visual FoxPro includes the DataEnvironment, Cursor, Relation, Page, Collection, CursorAdapter, XMLAdapter, XMLField, and XMLTable classes in the New Class dialog box for the Class Designer. All DataEnvironment, Cursor, Relation, Page, Collection, CursorAdapter, XMLAdapter, XMLField, and XMLTable properties, methods, and events are available as appropriate in the Properties window when the Class Designer is open.
  • Visual FoxPro adds language support to the CREATE CLASS and MODIFY CLASS commands for the DataEnvironment, Cursor, Relation, Page, Collection, CursorAdapter, XMLAdapter, XMLField, and XMLTable classes.

Form Designer Enhancements

Visual FoxPro includes the following enhancements to the Form Designer:

  • DataEnvironment Builder

    You can use the new DataEnvironment Builder to create a data environment and to use the capabilities of CursorAdapter objects. For more information, see DataEnvironment Builder.

  • XML Web Service Builder

    You can use the new XML Web Service Builder to bind an XML Web service to a control on a Visual FoxPro form or to an object, such as a cursor adapter in the form's data environment, without writing code. For more information, see XML Web Service Builder and Accessing XML Web Services.

  • Showing most recent control selected when setting tab order

    Visual FoxPro now highlights the most recent control selected when you are determining the tab order for moving between controls on a form in the Form Designer. Visual FoxPro shows the tab order of controls by labeling them with colored numbered boxes. In previous versions, after activating several new windows or applications, it was easy to lose track of the last control selected during the tab ordering process. For more information, see Setting Tab Order for Controls.

  • No maximum limit for design area

    The default setting for Maximum Design Area on the Forms tab in the Options dialog box is now None. By changing the previous 640 x 480 resolution setting for the viewing area, Visual FoxPro prevents the form from appearing cropped inside the Form Designer. For more information, see Forms Tab, Options Dialog Box and Setting the Design Area for a Form.

  • Form Controls toolbar

    The Form Controls toolbar does not automatically open if you modify a form or other container class that does not have a FoxUser.dbf record indicating that the toolbar should open.

Table Designer Enhancements

Visual FoxPro includes the following enhancements for the Table Designer:

  • Autoincrementing field values

    You can now set automatically incrementing field values for both DBC tables and free tables. To support the autoincrement feature, the Table Designer combines the free table and DBC table designers into one consistent, enhanced user interface (UI) that contains Fields, Indexes, and Table tabs. You can select the Integer (AutoInc) data type for a field and set the Step and NextValue values in the Table Designer. Depending on whether you create a DBC or free table, Visual FoxPro makes the appropriate UI elements available. For more information, see Fields Tab, Table Designer, Indexes Tab, Table Designer, and Table Tab, Table Designer.

  • Using database container (DBC) captions as expressions and building expressions in the Caption field

    Previous versions of Visual FoxPro used hardcoded captions, or labels, for DBCs and made localization difficult for users writing international applications.

    You can now build an expression in the Caption field on the Fields tab of the Table Designer or in the View Field Properties dialog box, which opens from the Query and View Designer, for tables that are part of a database container (DBC). Clicking the ellipsis (...) button opens the Expression Builder. Expressions cannot exceed 254 characters. If expressions exceed 254 characters, the caption defaults to the field name. For more information, see Fields Tab, Table Designer and View Field Properties Dialog Box.

    When you drag fields onto a form or report from one of the designers, Visual FoxPro uses the DBC caption, if one exists, and attempts to evaluate it. Visual FoxPro evaluates this expression at design time and run time. The Report Designer has also been modified to incorporate this enhancement, though it does not produce a label when a field is dragged onto the report.

    Note Support for using expressions as field captions should be used only with DBC tables in applications running on Visual FoxPro 8.0 or later. In earlier versions, the expression appears as a string literal.

Improvements for Multi-Table Joins and the SQL SELECT Command in the Query and View Designers

Visual FoxPro enhances its Query and View designers by improving how it constructs multi-table joins and handles user-defined SQL SELECT commands. The Query and View designers contains the following enhancements:

  • Fields tab

    You can select all available tables and their fields by choosing the asterisk (*), all fields in a particular table by choosing table.*, or individual fields for your query or view. Your selections appear in the SELECT statement in the SQL window when you click View SQL or choose View SQL on the Query menu.

    You can also manually specify an asterisk, table.*, or a comma-delimited list of fields for the SELECT statement in the SQL window. For example, you can specify the SQL statement as SELECT * FROM or SELECT field1, field2, ... FROM. Your preferences are preserved during loading or generation of the query or view.

    You can include the same field multiple times in the SELECT list.

    Visual FoxPro automatically copies a field name into the Expression Builder when it is selected in the Available Fields list. Therefore, you can easily use the field name to build your expression or add a field name alias by typing it after the field name in the Expression Builder.

    A sequential field number now appears with the field name in the View Field Properties dialog box, which appears when you click the Properties button on the Fields tab.

    For more information, see Fields Tab, Query and View Designers and View Field Properties Dialog Box.

  • Join tab

    The Join tab provides the new Left Table and Right Table columns. You can specify the new Cross Join type in the Join type column. A cross join matches each record in the left table with all records in the right table. Therefore, you can set a cross join only for the left table, which cannot be a Previous join. The View Designer does not add cross joins for newly added tables, so you must add the join manually if you want to specify a position for the table.

    You can specify a priority for join and logical operations using the new Priority column.

    You can now edit the expressions that appear in Field Name and Value columns on the Join tab when they appear in the Expression builder after you select <Expression> from the Field Name or Value list. The Criteria column includes the new Is True logical operation.

    For more information, see Join Tab, Query and View Designers.

  • Filter tab

    The Filter tab supports subqueries. You can load and save a query or view with a subquery in the WHERE clause. You can select the new Exists and Is True logical operations in the Criteria column. You can specify a priority for logical operations using the new Priority column.

    Visual FoxPro no longer includes the Case button. Instead, you can use the UPPER( ), LOWER( ), and PROPER( ) functions.

    For more information, see Filter Tab, Query and View Designers

  • Order By tab

    You can select fields that are not included in the SELECT list. For more information, see Order By Tab, Query and View Designers.

  • Group By tab

    You can now specify a priority for logical operations using the new Priority column in the Having dialog box. For more information, see Having Dialog Box.

  • Miscellaneous tab

    You can select Force join to add a FORCE keyword to specify that tables are joined in the order in which they appear in the FROM clause.

    Visual FoxPro replaces the Cross tabulate check box with a button and includes the Report and Label buttons. Clicking these buttons merely adds the appropriate line of code after the query's SQL statement. No reparsing of the commands occurs when the query is reloaded. You can change or add to this code.

    Note It is possible to add multiple conflicting options by clicking these buttons multiple times. The Query Designer will attempt to warn you and provide the option to remove the previous command if it is the first conflict found. You should make sure that only the desired optional code appears in the query.

    For more information, see Miscellaneous Tab, Query and View Designers.

  • The View Designer correctly loads and generates any FROM clause with or without the JOIN option, using parentheses where needed in the ON clause.
  • Visual FoxPro provides "two-way" editing support in the Query and View designers.

    You can edit the SQL SELECT statement for queries and views and view properties that are set by DBSETPROP( ) calls in the SQL window and load the changes back into designer window.

    For more information, see Customizing Queries Using SQL SELECT Statements and Customizing Views Using SQL SELECT Statements.

  • Instead of using the automatically generated alias when you add a table or view, you can specify an alias for the table or view by typing it in the Alias box that appears in the Add Table or View dialog box.
  • Removals from the Query/View Designer:
    • Filter tab and Having dialog box

      Visual FoxPro no longer includes the Case button for matching text casing of criteria in the Example field. Instead, you can use the UPPER( ), LOWER( ), or PROPER( ) functions as needed.

    • Query Destination dialog box in Query Designer

      Visual FoxPro no longer includes the Report, Graph, and Label buttons, which supported non-SQL clauses.

    • Miscellaneous tab

      Visual FoxPro no longer includes the Cross tabulate check box.

Support for Moving Menus in the Menu Designer

You can easily move existing menus, submenus, and menu bars in the Menu Designer by using the Move Item button. In previous versions of Visual FoxPro, you could not easily move items such as menu bars after you created a new menu or made changes to an existing one. For more information, see Menu and Shortcut Designers and Move Item Dialog Box.

Report Design and Printing Enhancements

Visual FoxPro includes the following report design and printing capabilities.

Enhancements to the Report Designer

  • You can now specify whether page footers and page headers stretch or shrink to accommodate their contents by leaving the Constant band height check box cleared in the Page Footer and Page Header dialog boxes. Previously, this check box could not be cleared. The height adjusts automatically when using stretchable fields.
  • You can have stretchable and floating fields in page footers and the Summary band. For more information, see Page Footer Dialog Box and Page Header Dialog Box.
  • You can choose whether to include the page header and footer when printing the report Summary band. To specify this behavior, click Title/Summary on the Report menu when the Report Designer is open and select the Page header and Page footer check boxes. For more information, see Title/Summary Dialog Box.
  • You can choose whether to save printer settings to the appropriate memo fields in the reports header record. To make this choice, select Printer Environment from the Report menu when the Report Designer is open. Your selection persists on the Reports tab in the Options dialog box, and your settings persist for each report.

Reports Tab in Options Dialog Box

On the new Reports tab in the Options dialog box, you can perform the following tasks for new reports created in the Report Designer:

  • Set global defaults such as show grid lines, snap to grid, and horizontal/vertical grid spacing.
  • Choose report options such as use private data sessions, save the printer environment, and use database container (DBC) field captions when you drop fields onto a report.
  • Show position of the grid.
  • Set initial ruler scale and default font for reports.

For more information, see Reports Tab, Options Dialog Box.

Page X of Y Numbering

You can set up Page X of Y numbering in reports using the new _PAGETOTAL system variable. For more information, see _PAGETOTAL System Variable.

Preventing Resetting of Page Numbers

You can specify that Visual FoxPro does not reset the _PAGENO and _PAGETOTAL variables by using the NORESET keyword in the REPORT command.

For more information, see REPORT Command.

Enable Duplex Printing and Chain Multiple Reports

You can specify that printing does not continue on a new sheet at the end of printing a report by using the NOPAGEEJECT keyword in the REPORT command. Therefore, you can enable duplex printing to continue on the reverse side of a previous report. You can also chain multiple reports using NOPAGEEJECT.

For more information, see REPORT Command.

Disable the Run-Time Printing Dialog Box

You can disable the run-time printing dialog box by using the NODIALOG keyword in the REPORT command. For more information, see REPORT Command.

Determine Report Preview Mode

You can determine whether a report is being printed or appears in preview mode using the new SYS(2040) - Detect Report Status function, which returns a value of 0, 1, or 2 and respectively specifies that no active report exists, the report is in preview mode, or the report is being printed.

See Also

What's New in Visual FoxPro 8.0 | Language Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Enhancements to Visual FoxPro Editors

Visual FoxPro contains improvements made to its editor tools:

  • Search for code references and view code definitions
  • View parent and inherited code
  • Beautify code blocks
  • Printing source code syntax in color

Search for Code References and View Code Definitions

You can search for and replace code references or text using the Look Up Reference dialog box. For more information, see Searching and Replacing Code References.

You can locate and view definitions of code elements in your program files. For more information about viewing code definitions, see Viewing Code Definitions and _FOXREF System Variable.

View Parent and Inherited Code

You can now view code inherited from parent classes for objects, events, and methods, making it easier to decide whether you want to use or override the inherited code. The View Parent Code button appears in the code window only when parent classes exist. Clicking the View Parent Code button displays parent classes in bold when code exists.

If inherited code exists for methods and events appearing in the properties list of the Properties window, the class names and class libraries from which methods and events inherit code appear as follows:

Inherited cClassname ClassLibrary

You can view this inherited code by right-clicking the method or event in the properties list and selecting View Inherited Code from the shortcut menu that appears.

The View Parent and View Inherited Code features support only the viewing of parent code, not editing. You need to use the Class Browser to edit parent class code if a subclass is in use.

For more information, see Manipulating Objects and Properties Window.

Beautify Code Blocks

You can now use the Beautify tool to reformat a block of code instead of only entire files and methods. You can select the Beautify tool from the Tools menu and from the shortcut menu in the editing window of a program (.prg) file. For more information, see Formatting Code in Programs.

Printing Source Code Syntax in Color

You can now print your source code files in colors that match the appearance of code syntax in the Editing window. Visual FoxPro supports color printing for source code where color syntax appears, including programs, methods, stored procedures, and memos. To print your code files in color, you must have a color printer to select the color printing options available for your printer.

For more information, see Displaying and Printing Source Code Files in Color.

See Also

What's New in Visual FoxPro 8.0 | Language Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Language Enhancements

Visual FoxPro provides more functionality in its language by adding and enhancing classes, commands, and functions.

In This Section

New Classes, Commands, and Functions
Describes new classes, commands, and other language functionality in this version of Visual FoxPro.
Enhanced Classes, Commands, and Functions
Describes enhanced classes, commands, and other language functionality in this version of Visual FoxPro.

Related Sections

What's New in Visual FoxPro 8.0
Describes new features and enhancements for this version of Visual FoxPro.
Interactive Development Environment (IDE) Enhancements
Describes additions and improvements to the Visual FoxPro IDE.
Data Features Enhancements
Describes additions and improvements to Visual FoxPro data features.
Miscellaneous Enhancements
Describes other improvements made in this version of Visual FoxPro.
Behavior Changes Since Visual FoxPro 7.0
Describes changes in the behavior of existing language and functionality.


New Classes, Commands, and Functions

Visual FoxPro provides new classes, commands, functions, and system variables with the following features:

  • Structured error handling using TRY...CATCH...FINALLY, THROW, and Exception class
  • Collection class
  • XMLAdapter, XMLTable, XMLField classes and other XML enhancements
  • Binding events from native Visual FoxPro objects
  • Defining and subclassing member classes
  • Delayed control binding on forms using BindControls property
  • Remote data connectivity using CursorAdapter class
  • Automatic sizing and locking for Grid and Browse columns
  • Highlighting for Grid rows and selected fields
  • Position pictures relative to captions
  • Controlling orientation of tabs on PageFrame controls
  • Hyperlinks support for TextBox and EditBox controls
  • Support for Windows XP Themes in all controls
  • GDI+ image support (animated .gif files, RotateFlip property)
  • Controlling font character sets on objects supporting fonts
  • Support for docking windows and toolbars
  • Centering check boxes within grid columns
  • Displaying images in the text box portion of ComboBox controls
  • Using grids as list boxes
  • Empty class
  • Firing events when moving items in a list box using the mover bar
  • Adding and removing properties and values to objects at run time
  • Searching for executable (.exe) applications along file paths
  • Removing empty values where not supported
  • Enabling accumulation of mouse wheel events in the event queue
  • Choose SQL data engine compatibility prior or according to Visual FoxPro 8.0
  • Allow default output to appear on a form
  • Specify level of table validation to perform
  • New XML Web services foundation classes

Structured Error Handling Using TRY...CATCH...FINALLY, THROW, and Exception class

You can now implement structured error and exception handling using the TRY...CATCH...FINALLY functionality, which includes the new Exception class, the THROW clause, and SYS(2410) - Error Handler function.

You can define and create a subclass of the Exception class, which is used for error and exception handling. Visual FoxPro generates exception objects automatically to store information about an error when it occurs in the TRY block of a TRY...CATCH...FINALLY error handling structure.

For more information, see Structured Error Handling, TRY...CATCH...FINALLY Command, Exception Class, and SYS(2410) - Error Handler.

Collection Class

You can use collections to create a set of related items. Collections offer a way to work with contained objects and use standard ways to access and iterate through items. For more information, see Collection Class.

XMLAdapter, XMLTable, XMLField Classes and Other XML Enhancements

Visual FoxPro adds the XMLAdapter, XMLTable, and XMLField classes to enhance its compatibility with XML DiffGram and ADO.NET DataSet formats and to support hierarchically formatted XML for the following:

  • XML files that have a schema, either inline or external, associated with them and as implemented in ADO.NET DataSets
  • Microsoft XML Data Reduced Schema (XDR) as used by Microsoft SQL-XML
  • ADO Recordset schemas that are produced when an ADO Recordset is saved as XML to a file or stream

XMLAdapter is a "two-way" class. You can import XML and its contained schema to create tables, or you can create and generate XML from tables.

Note The XMLAdapter class requires Microsoft XML Core Services (MSXML) 4.0 Service Pack 1 (SP1) or later.

Visual FoxPro updates the STRCONV( ) function to support encoding and decoding hexBinary.

For more information, see XML Functionality Using XMLAdapters, Visual FoxPro and XML Schema Data Type Mapping, XMLAdapter Class, XMLTable Class, XMLField Class and STRCONV( ) Function.

Binding Events from Native Visual FoxPro Objects

Visual FoxPro extends event handling support for native Visual FoxPro objects by providing the BINDEVENT(), UNBINDEVENTS(), RAISEEVENT(), and AEVENTS() functions. For more information, see Event Binding for Visual FoxPro Objects.

Defining and Creating Subclasses for Member Classes

You can now define and create subclasses for certain member classes. These members and their parent containers include the following:

  • Page and PageFrame
  • CommandButton and CommandGroup
  • OptionButton and OptionGroup
  • Column and Grid
  • Header and Column

Using member classes, you can define consistent behavior for all members of a specific class. For example, you can define a particular behavior in the Activate event of a Page class to be used in a specific PageFrame class or object. All member pages for that page frame inherit the same code or behavior.

The PageFrame, CommandGroup, OptionGroup, and Grid classes have two new properties, MemberClassLibrary and MemberClass, which you can use to set the default custom class for member objects. When these properties are set, new member objects inherit from the specified member class. Column objects have two new properties, HeaderClassLibrary and HeaderClass, which you can set to specify a custom Header class.

You can now edit and create a subclass of the Page class in the Class Designer. The CommandButton and OptionButton classes already exist in the Class Designer. However, the Class Designer does not include the Column and Header classes.

For more information, see Member Classes.

Delayed Control Binding on Forms Using BindControls Property

You can now specify when data binding occurs for data-bound controls by setting the BindControls property for Form objects. For more information, see BindControls Property.

Remote Data Connectivity Using CursorAdapter Class

Visual FoxPro provides improved remote data connectivity by including the new CursorAdapter class and adding the DataSource and DataSourceType properties to the DataEnvironment class. For more information about the CursorAdapter class, see Data Features Enhancements.

Automatic Sizing and Locking for Grid and Browse Columns

You can fit columns to data in grids and in Browse windows automatically by setting the AllowAutoColumnFit property and using the AutoFit method. For more information, see AllowAutoColumnFit Property, AutoFit Method, and Fitting Columns to Data Automatically.

You can lock columns using the BROWSE command with the LOCK clause or setting the Grid LockColumns and LockColumnsLeft properties. For more information, see BROWSE Command, LockColumns Property, LockColumnsLeft Property, and Locking Columns.

Highlighting for Grid Rows and Selected Fields

You can control the color display for selected rows and items in TextBox controls in a grid by setting the HighlightForeColor, HighlightBackColor, SelectedItemBackColor, SelectedItemForecolor, and HighlightStyle properties.

Position Pictures Relative to Captions

You can position pictures relative to their captions by setting the PicturePosition property for the CommandButton, OptionButton, and CheckBox controls.

For more information, see PicturePosition Property.

Controlling Orientation of Tabs on PageFrame Controls

You can control where tabs display on a PageFrame control by setting the TabOrientation property. For more information, see TabOrientation Property.

Hyperlinks Support for TextBox and EditBox Controls

You can control whether hyperlinks are displayed and enabled within TextBox and EditBox controls by setting the EnableHyperlinks property. For more information, see EnableHyperlinks Property.

Support for Windows XP Themes in All Controls

You can now incorporate support for Windows XP Themes in applications running on Windows XP operating systems. Windows XP Themes is a new technology that controls a number of visual attributes for user interface elements, including the appearance of controls, border color and style, selection, and hover effects. For more information, see Themes Property, Style Property, and SYS(2700) - Enables Windows XP Themes.

GDI+ Image Support (Animated .gif Files, RotateFlip Property)

Visual FoxPro replaces native support for rendering Graphics Interchange Format (.gif) and Joint Photographic Electronic Group (.jpeg) formats with Graphics Device Interface+ (GDI+), the next generation graphics device interface for Microsoft Windows XP and future releases of the Windows operating system.

With GDI+, you can now rotate and invert, or flip, an image by setting the RotateFlip property on the Image control.

For more information, see Graphics Support in Visual FoxPro, RotateFlip Property, Picture Property, and Open Picture Dialog Box.

Controlling Font Character Sets on Objects Supporting Fonts

You can now control font character sets on every object that supports fonts by setting the FontCharSet property. For more information, see FontCharSet Property.

Support for Docking Windows and Toolbars

You can programmatically dock IDE tool windows and toolbars using the new DOCK WINDOW command. The new ADOCKSTATE() function returns the state of docked windows and toolbars. For more information, see Docking Windows, DOCK WINDOW Command, and ADOCKSTATE( ) Function.

Centering Check Boxes Within Grid Columns

You can align check boxes with the center of grid columns by setting the new Centered property for CheckBox controls using the following syntax:

CheckBox.Centered [= lExpr]

You can set Centered to the default value of False (.F.), which specifies no center alignment, or to True (.T.), which specifies aligning the check box with the center of the control boundaries. The Centered property works with the control's Alignment property, which aligns text, to determine on which side of a check box a caption appears. For more information, see Centered Property.

Displaying Images in the Text Box Portion of ComboBox Controls

In previous versions, images that accompanied entries in the list of a ComboBox control did not appear in the text box of the control when you selected an entry. You can optionally display an image in the text box of a ComboBox control and determine how the image appears by setting the PictureSelectionDisplay property.

For more information, see PictureSelectionDisplay Property.

Using Grids as List Boxes

You can mimic a list box using a grid by specifying whether users can select individual cells or must select the entire row by setting the Grid AllowCellSelection property. Selecting individual cells or the entire row does not the change color of the selected row or cell. The KeyPress event now also applies to the Grid control.

For more information, see AllowCellSelection Property and KeyPress Event.

Empty Class

You can use the Empty class for working with business objects. An Empty object instantiates and releases quickly for optimized performance. An Empty object is typically used in the following scenarios:

  • When adding properties to or removing properties from a running instance of the class using the ADDPROPERTY( ) and REMOVEPROPERTY( ) functions.
  • When using the SCATTER...NAME command with the ADDITIVE clause to populate contents from the current record.

The Empty class contains no intrinsic properties, methods, or events. It cannot be subclassed. You can add custom properties only at run time using the ADDPROPERTY( ) function or SCATTER...NAME command with the ADDITIVE clause.

The Empty class is available only within a program (.prg) file. You cannot define an Empty class in a visual class library (.vcx) file.

For more information, see Empty Class.

Firing Events When Moving Items in a List Box Using the Mover Bar

You can specify certain behavior such as canceling the movement of an item when you move an item up or down in a ListBox control with the mover bar using the mouse, keyboard, or programmatically with the new OnMoveItem event. OnMoveItem fires after selecting and moving the item and after every subsequent move but before the list box displays the item movement. For more details, see OnMoveItem Event.

You can programmatically move items to new positions in the list box using the new MoveItem method. For more details, see MoveItem Method.

Adding and Removing Properties and Values to Objects at Run Time

At run time, you can now dynamically add and remove properties and their values from any valid Visual FoxPro object, including created from Visual FoxPro classes, COM class, or those created by the SCATTER...NAME command. For more information, see ADDPROPERTY( ) Function and REMOVEPROPERTY( ) Function.

Searching for Executable (.exe) Applications Along File Paths

Customers that run custom Visual FoxPro applications that access data and resources over networks might sometimes experience performance degradation when the application searches the network for a function, procedure, executable file, and so on, inside another application.

You can now specify that Visual FoxPro search within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. By doing so, you can improve performance for applications that run on a local or wide area network. For more information, see SYS(2450) - Application Search Path Order and DO Command.

Removing Empty Values Where Not Supported

You can return an appropriate substitute value instead of an empty value, such as False (.F.) or 0, from two expressions. You can use this functionality to remove empty values from calculations or operations where empty values are not supported or relevant. For more information, see EVL( ) Function.

Enabling Accumulation of Mouse Wheel Events in the Event Queue

Usually, to smooth mouse wheel scrolling, Visual FoxPro accumulates mouse wheel events. With faster computers, it is not as critical to accumulate mouse wheel events, which can prevent proper implementation of the System Tray (Taskbar Notification Area) Foundation Class. You can now choose to whether to enable the accumulation of mouse wheel events in the event queue using the new SYS(2060) - Mouse Wheel Events function.

Choose SQL Data Engine Compatibility Prior or According to Visual FoxPro 8.0

You can now specify that Visual FoxPro execute SQL SELECT commands as performed prior or according to Visual FoxPro 8.0. This makes it possible for you to maintain backwards compatibility for applications that use the SQL data engine prior to Visual FoxPro 8.0. For more information, see SYS(3099) - SQL Data Engine Compatibility Mode and SET ENGINEBEHAVIOR Command.

Allowing Default Output to Appear on a Form

You can set the new Form AllowOutput property to determine whether default output appears on a form. For more information, see AllowOutput Property.

Specify Level of Table Validation to Perform

You can use the SET TABLEVALIDATE command when you want a lower level of table integrity checking than the default setting. For more information, see SET TABLEVALIDATE Command.

New XML Web Services Foundation Classes

Visual FoxPro replaces the _WebServices.vcx and _WebServices.vct Foundation Class libraries with the _ws3Utils.vcx and _ws3Client.vcx Foundation Class libraries. These new class libraries use SOAP Toolkit 3.0. For more information, see XML Web Services Foundation Classes.

See Also

Language Enhancements | Interactive Development Environment (IDE) Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Enhanced Classes, Commands, and Functions

Visual FoxPro contains the following improvements to selected classes, commands, and functions:

  • Enhanced SQL Pass-Through functionality and language improvements
  • Multiple expressions of different data types in the DEBUGOUT command
  • Specifying external DataEnvironment classes for forms
  • Language support for collating sequences and autoincrementing field values
  • Support for FontCharSet property in AFONT()
  • HOME(8) returns Visual FoxPro Projects subdirectory
  • Toggle off-screen bitmaps
  • Component Object Model (COM) enhancements for improved array and type support
  • Hand pointer setting for MousePointer property
  • MaxLength property available for ComboBox controls
  • Language support for caption expressions
  • Changing the background color of the CommandButton control
  • Displaying images in a column header
  • ToolTipText and StatusBarText properties for all visual controls
  • Refresh method for Label and Shape controls
  • Providing multiple configuration files
  • Suppressing display of data-related messages in the status bar
  • SYS(2007) returning checksum values greater than 16 bits
  • Removing white space from text merges
  • Updating an existing object with values from current record using SCATTER...NAME
  • Specifying an object when inserting a new table record using SQL INSERT command
  • Hiding columns
  • CLEAR DEBUG resets Debugger windows when open and clears all breakpoints
  • Suspending program execution until a Windows event occurs
  • Checking for hidden or system files and directories
  • Retrieve container object reference in context with current code editing window
  • Specify name and location of mapping schema for XMLUPDATEGRAM( ) function

Enhanced SQL Pass-Through Functionality and Language Improvements

Visual FoxPro includes the following enhancements to SQL Pass-Through functionality and for shared connections.

Visual FoxPro now evaluates expressions that are passed as parameter values in a SQL statement to SQLEXEC( ). Previously, you were required to use a memory variable to pass any nonconstant values. You no longer need to enclose parameter expressions with parentheses. Visual FoxPro can now evaluate memory variable names, function calls, and parameter expressions. For more information, see SQLEXEC( ) Function.

Visual FoxPro allocates an Open Database Connectivity (ODBC) statement handle (HTSTMT) but uses an existing shared ODBC connection handle (HDBC) for every remote view that uses a shared connection. If the view does not use a shared connection, Visual FoxPro allocates a separate ODBC statement handle and ODBC connection handle.

Visual FoxPro uses the SQLEXTENDEDFETCH( ) function instead of the SQLFETCH( ) function for ODBC statement handles that use shared ODBC connection handles. Visual FoxPro sets statement options SQL_CURSOR_TYPE = SQL_CURSOR_STATIC and SQL_CONCURRENCY = SQL_CONCUR_READ_ONLY before SQLPrepare or SQLExecDirect for these ODBC statement handles. For more information about ODBC language, see the ODBC Programmer's Reference in the MSDN Library at http://msdn.microsoft.com/library/.

The SQLCONNECT( ) and SQLSTRINGCONNECT( ) functions return a numeric value as the statement handle rather than a connection handle, which you cannot obtain directly. You can still set and get connection properties using the SQLSETPROP( ) and SQLGETPROP( ) functions by passing the statement handle for that connection and the string, "Shared", as arguments. All other SQL functions use a statement handle instead of a connection handle. For more information, see SQLSETPROP( ) Function and SQLGETPROP( ) Function.

You can specify whether to create a shared connection using the new lShared and nStatementHandle parameters for the SQLCONNECT( ) function and the new lShared parameter for the SQLSTRINGCONNECT( ) function. You can also use SQLCONNECT( ) to obtain a new statement handle on a shared connection that was opened using SQLSTRINGCONNECT( ). In addition, you can specify optional values for the cUserID and cPassword parameters when using a named connection for cConnectionName. For more information, see SQLCONNECT( ) Function and SQLSTRINGCONNECT( ) Function.

Visual FoxPro supports overriding the default connection for a remote view and requires the new m.nStatementHandle parameter for supporting shared connections in the USE Command. For more information, see the USE Command.

When you include the SHARE keyword with the CONNECTION clause in the CREATE SQL VIEW command, Visual FoxPro uses new statement handle for the shared connection, if one is available. If a shared connection is not available, Visual FoxPro creates a shared connection when the view opens, which you might be able to share with other views. For more information, see CREATE SQL VIEW Command.

Multiple Expressions in the DEBUGOUT Command

You can evaluate multiple expressions of different data types and display their results in the Debug Output window using the DEBUGOUT command. For more information, see DEBUGOUT Command.

Specifying External DataEnvironment Classes for Forms

You can specify external DataEnvironment classes by setting the DEClass and DEClassLibrary properties for Form objects. For more information, see DataEnvironment Object, DEClass Property, and DEClassLibrary Property.

Language Support for Collating Sequences and Autoincrementing Field Values

You can now specify a collating sequence for an index tag when using the SQL CREATE TABLE, ALTER TABLE, and INDEX commands, which include the COLLATE clause.

The CREATE TABLE and ALTER TABLE commands support automatically incrementing field values by including the AUTOINC clause and specifying values for the NEXTVALUE and STEP clauses. The DISPLAY STRUCTURE command displays the Next and Step values for fields that use autoincrementing.

For more information, see CREATE TABLE - SQL Command, ALTER TABLE - SQL Command, INDEX Command, and DISPLAY STRUCTURE Command.

You can also specify whether attempts to update values in a field using autoincrementing generate an error. For more information, see SET AUTOINCERROR Command or the AutoIncError property in the CURSORSETPROP( ) Function.

Support for FontCharSet Property in AFONT()

Visual FoxPro supports the FontCharSet property in the AFONT() function by providing two parameters, nFontCharSet and nFlags. The first parameter specifies the character set in the cFontName. The second parameter specifies a value of 1 and populates ArrayName with character sets that are available for a particular font. for more information, see FontCharSet Property and AFONT( ) Function.

HOME(8) Returns Visual FoxPro Projects Subdirectory

HOME(8) returns the Visual FoxPro Projects subdirectory, which is the default directory for new projects and files created by Visual FoxPro, located in the user's My Documents directory. For more information, see HOME( ) Function.

Toggle Off-Screen Bitmaps

Visual FoxPro includes support for turning off-screen bitmaps off and on using a configuration file setting. You can now use the SYS(602) - Bitmap Configuration function and the values of 0 and 1 to disable and enable off-screen bitmaps at run time.

For more information, see SYS(602) - Bitmap Configuration.

Component Object Model (COM) Enhancements for Improved Array and Type Support

Visual FoxPro improves its support for creating COM components and interoperability with other COM components by including the following COM enhancements:

  • Define and specify data types other than Variant for arrays

    You can specify a data type other than Variant in the DIMENSION command by using the AS cType clause. However, you should still use the COMARRAY( ) function to control other settings for how arrays are passed to COM servers. For more information, see DIMENSION Command.

  • Strong typing of arrays for type libraries

    You can specify strong typing for arrays so they can be correctly written as a safe array to a type library when you use the new cArrayName[] parameter in the cArrayName[] [AS Type] [@] clause in the DEFINE CLASS command. For more information, see DEFINE CLASS Command.

  • Complex strong typing

    You can define a type based on a COM class using the cArrayName[] [AS Type] [@] ] [AS Type] clause in the DEFINE CLASS command. For more information, see DEFINE CLASS Command.

  • Specify how arrays are passed to COM objects using the COMARRAY( ) function

    You can specify that byte arrays should not be converted to strings by passing a value of 1000 to the nNewValue parameter in the COMARRAY( ) function. This enhancement improves support for how byte arrays are treated. For more information, see COMARRAY( ) Function.

  • Visual FoxPro now generates type libraries for COM Servers that mark Character types as BSTR instead of VARIANT in the Visual FoxPro COM type library. This new behavior matches that of the String type. For example, the following procedure appears in the COM type library with the return type of BSTR:
    PROCEDURE myProc( ) AS Character

Hand Pointer Setting for MousePointer Property

You can specify that the mouse pointer becomes the shape of a hand when you move the mouse over a control by setting the MousePointer property to a value of 15. For more information, see MousePointer Property. On Visual FoxPro applications running on Windows NT 4.0 operating systems, an arrow appears instead of a hand.

MaxLength Property Available for ComboBox Controls

You can now set the MaxLength property for ComboBox controls in addition to EditBox and TextBox controls. For more information, see MaxLength Property.

Language Support for Caption Expressions

The DBGETPROP( ) Caption field property for tables and views supports expressions as field captions. For more information, see the tables listing the field properties for tables and views in the DBGETPROP( ) Function.

Note Support for using expressions as field captions should be used only with DBC tables in applications running on Visual FoxPro 8.0 or later. In earlier versions, the expression appears as a string literal.

You can retrieve a field caption as stored in a database container (DBC) using the FIELD( ) function. For more information, see FIELD( ) Function.

Changing the Background Color of the CommandButton Control

You can now specify the background color of text and graphics in an available or unavailable command button by setting the BackColor and DisabledBackColor properties for the CommandButton control. These two properties exist for other Visual FoxPro controls. For more information, see BackColor, ForeColor Properties, and DisabledBackColor, DisabledForeColor Properties.

Displaying Images in a Column Header

You can now display images in a column header by setting the Picture property for a column Header object. Turning Themes on or off affects the appearance of the image. The Picture property exists for other Visual FoxPro controls.

For more information, see Picture Property and Themes Property.

ToolTipText and StatusBarText Properties for All Visual Controls

You can now set the ToolTipText and StatusBarText properties for all visual controls including the OptionGroup, CommandGroup, Line, Control, Container, PageFrame, OleBoundControl, Column, Header, Image, and Label controls.

For more information, see ToolTipText Property and StatusBarText Property.

Refresh Method for Label and Shape Controls

You can now use the Refresh method to update the values in and redraw the Label and Shape controls. When you call the Refresh method for a Label control, Visual FoxPro updates the Caption property and redraws the label. When you call Refresh for a Shape control, Visual FoxPro redraws the shape. For more information, see Refresh Method.

Providing Multiple Configuration Files

You can use an external configuration file in addition to an internal configuration file in circumstances where you need to configure settings separately. For example, setting SCREEN=OFF should be performed in an internal configuration file.

When starting Visual FoxPro, you can use the default configuration file from the following locations in order:

  • Current working directory
  • Directory where Visual FoxPro is installed
  • Directories listed in the DOS path

You can set Visual FoxPro to read an external configuration file following an internal configuration file by using the new ALLOWEXTERNAL directive in the internal configuration file. When you include the setting ALLOWEXTERNAL=ON in the internal configuration file, Visual FoxPro searches for an external configuration file, usually Config.fpw, and reads its settings. You can also specify a different configuration file using the -C command-line switch when starting Visual FoxPro.

Note For .exe and .dll file servers, Visual FoxPro supports only configuration files that are bound inside the server. Therefore, Visual FoxPro disregards the ALLOWEXTERNAL setting.

For more information about command-line switches, see Using Command-Line Options When Starting Visual FoxPro.

The settings in an external configuration file take precedence over those in the internal configuration file, if duplicate settings exist, because the external configuration file is read after the internal file. Visual FoxPro does not begin initialization until it reads both files.

If you want to specify the configuration file as read-only, place the file in your project and mark it as Included. If you want to specify that the file can be modified, place the file in your project and mark it as Excluded. You can then distribute the file separately with your application or executable file. By convention, configuration files use the .fpw extension.

For more information, see Special Terms for Configuration Files and Setting Configuration Options at Startup.

Suppressing Display of Data-Related Messages in the Status Bar

You can suppress the display of data-related messages in the Visual FoxPro status bar by using the new CURSOR keyword in the SET NOTIFY command. These messages include those relating to aliases, data sources, record pointers, record counts, exclusive status, and record locking status.

For more information, see SET NOTIFY Command.

SYS(2007) Returning Checksum Values Greater Than 16 Bits

You can now generate checksum values greater than 16 bits for large strings when using SYS(2007) - Checksum Value. Visual FoxPro includes a complementary function, SYS(2017) - Record Checksum Value, that calculates a checksum value based on the current record in the current work area. For more information, see SYS(2007) - Checksum Value and SYS(2017) - Record Checksum Value.

Removing White Space from Text Merges

You can specify how any white space appearing before each line in a text merge should be removed from the result by using the PRETEXT clause in the TEXT...ENDTEXT command. By providing the PRETEXT clause, Visual FoxPro improves its support for XML and Web services and provides better integration and manipulation of XML in Visual FoxPro code. For more information, see TEXT ... ENDTEXT Command.

Updating an Existing Object with Values from Current Record Using SCATTER...NAME

You can update the properties of an existing object specified by ObjectName with values from the current record by using the ADDITIVE keyword in the NAME clause of the SCATTER command. For more information, see SCATTER Command.

Specifying an Object when Inserting a New Table Record Using SQL INSERT Command

You can now insert a new record into a table with fields matching the properties of an object that you can specify using the new FROM NAME ObjectName clause in the SQL INSERT command. For more information, see INSERT - SQL Command.

Hiding Columns

You can hide grid columns by setting the Visible property for a column to False (.F.). For more information, see Column Object.

CLEAR DEBUG Resets Debugger Windows When Open and Clears All Breakpoints

Previously, the CLEAR DEBUG command did not clear all breakpoints in the Debugger. CLEAR DEBUG now clears all breakpoints automatically.

When the Debugger is open, Visual FoxPro clears all breakpoints and restores the Debugger windows to their default positions. When the Debugger is closed, Visual FoxPro opens the Debugger with the Debugger windows in their default positions.

For more information, see CLEAR Commands.

Suspending Program Execution Until a Windows Event Occurs

You can pause program execution until a Windows event occurs, such as moving the mouse, by using the new FORCE keyword with the DOEVENTS command. For more information, see DOEVENTS Command.

Checking for Hidden or System Files and Directories

You can check for hidden or system files and directories by using the new nFlags parameters in the FILE( ) and DIRECTORY( ) functions. You can also use the CD and CHDIR commands to switch to hidden files and directories. For more information, see FILE( ) Function, DIRECTORY( ) Function, and CD | CHDIR Command.

Retrieve Container Object Reference in Context with Current Code Editing Window

Visual FoxPro adds the value of 3 as a possible parameter for the ASELOBJ( ) function when you want to retrieve the container object reference in context with the currently active code editing window. For more information, see ASELOBJ( ) Function.

Specify Name and Location of Mapping Schema for XMLUPDATEGRAM( ) Function

Visual FoxPro includes the cSchemaLocation parameter in the XMLUPDATEGRAM( ) function so you can specify the name and location of mapping schema that you provide. For more information, see XMLUPDATEGRAM( ) Function.

See Also

Language Enhancements | Interactive Development Environment (IDE) Enhancements | Data Features Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Data Features Enhancements

Visual FoxPro contains the following additions and improvements to its data features:

  • Remote data connectivity using CursorAdapter class
  • Creating, subclassing, and specifying a DataEnvironment class
  • Automatically incrementing field values
  • Support for collating sequences
  • Implicit data conversion for SQL SELECT...UNION command
  • Inserting rows from a SQL SELECT command

Remote Data Connectivity Using CursorAdapter Class

You can work with a wider range of data sources using the new CursorAdapter class. The CursorAdapter class offers the following capabilities:

  • Support for native, Open Database Connectivity (ODBC), ActiveX Data Object (ADO), or Extensible Markup Language (XML) data source types
  • Use different data sources dynamically.
  • Use either the data source of the CursorAdapter object or the data environment.
  • Share data sources within the limits of the data source technology.
  • Use the CursorAdapter class as a standalone class without an associated data environment.
  • Optionally define the structure of a cursor associated with a CursorAdapter object.
  • Render data from the data source into a Visual FoxPro cursor automatically and properly, based on the data source type.
  • Control loading of data into the cursor associated with a CursorAdapter object.
  • Control how data is added, updated, and deleted using CursorAdapter properties and methods.
  • Add CursorAdapter objects to containers other than the data environment, such as forms, form sets, and other containers.

To support the new CursorAdapter functionality, Visual FoxPro includes the following enhancements:

  • Adds definition and subclassing capabilities by including the CursorAdapter class in the Class Designer and providing the CursorAdapter class for the cBaseClassName parameter in the CREATE CLASS and MODIFY CLASS commands.
  • Provides the new GETCURSORADAPTER( ) function for returning an object reference to a CursorAdapter object at run time.
  • Updates the TABLEUPDATE() function so that it recognizes and handles CursorAdapter objects.
  • Opens internal cursors as buffered cursors and sets the buffering default to Optimistic Row Buffering.
  • Includes the new CursorAdapter Builder.

For more information, see Data Access Management Using CursorAdapters, CursorAdapter Class, GETCURSORADAPTER( ) Function, and CursorAdapter Builder.

Creating, Subclassing, and Specifying a DataEnvironment Class

You can now define and create a subclass of the DataEnvironment class. When you use the Visual FoxPro IDE or the CREATE CLASS command to create a new class, Visual FoxPro provides the DataEnvironment class in the Based On list in the New Class dialog box. You can also specify the DataEnvironment class as a base class for the cBaseClassName parameter in the CREATE CLASS and MODIFY CLASS commands.

On a form, you can save the DataEnvironment class as a visual class library (.vcx) by selecting the form, choosing Save As Class from the File menu, and selecting DataEnvironment. All DataEnvironment properties, methods, and events are available as appropriate in the Properties window after opening the Class Designer.

You can specify and load an external DataEnvironment class in a form (.scx) at design or run time. You can set the form's DEClass and DEClassLibrary properties to specify an external DataEnvironment class and the class library that contains it so that when the form instantiates, the specified DataEnvironment class loads automatically.

For more information, see DataEnvironment Object, Form Object, DEClass Property and DEClassLibrary Property.

Automatically Incrementing Field Values

You can now increment field values automatically for both DBC tables and free tables using the new autoincrementing feature in Visual FoxPro. You can use the AUTOINC clause in the SQL CREATE TABLE and SQL ALTER TABLE commands to specify values for NEXTVALUE and STEP. You can also select the Integer (AutoInc) data type for a field and set values for the Next Value and Step fields in the Fields tab in the Table Designer. For more information, see CREATE TABLE - SQL Command, ALTER TABLE - SQL Command, Fields Tab, Table Designer, Autoincrementing Field Values in Tables, and Setting Autoincrementing Field Values.

The AFIELDS( ) function now returns 18 columns instead of 16 due to new support for autoincrementing field values. Column numbers 17 and 18 now specify the NextValue and Step fields, which contain values of Numeric (integer) type. For more information, see AFIELDS( ) Function.

The COPY STRUCTURE EXTENDED command adds the numeric FIELD_NEXT and FIELD_STEP fields to support autoincrementing. For more information, see COPY STRUCTURE EXTENDED Command.

Visual FoxPro modifies the table header when you turn on or add autoincrementing for field values. For more information, see Table File Structure.

You can also specify whether attempts to update values in a field using autoincrementing generate an error. For more information, see SET AUTOINCERROR Command or the AutoIncError property in the CURSORSETPROP( ) Function.

Support for Collating Sequences

In previous versions, you needed to use the SET COLLATE TO command to specify a collating sequence other than the default when creating an index or index tag. You can now specify a different collating sequence when you create or modify a table using the Indexes tab in the Table Designer and when you use the COLLATE clause and its parameter with the SQL CREATE TABLE, ALTER TABLE, and INDEX commands. For more information, see Indexes Tab, Table Designer, CREATE TABLE - SQL Command, ALTER TABLE - SQL Command, and INDEX Command.

Implicit Data Conversion for SQL SELECT...UNION Command

The SQL SELECT command with the UNION keyword now performs implicit data conversion for data types that support implicit conversions. For example, UNION operations with columns of different lengths or that contained different types previously failed unless you explicitly matched the column sizes using a conversion function. Suppose you have the following code:

CREATE CURSOR t1 (f1 c(10))
INSERT INTO t1 VALUES ('1111111111')
CREATE CURSOR t2 (f1 c(2))
INSERT INTO t2 VALUES ('11')
SELECT * FROM t1 INTO CURSOR t3 UNION SELECT * FROM t2 && Fails.

This code failed unless you explicitly match the column sizes as shown:

SELECT * FROM t1 INTO CURSOR t3 UNION SELECT SUBSTR(f1,1,2) FROM t2

You no longer need to specify or use explicit conversion functions for data types that support implicit data conversion. For more information about data type conversion and precedence, see Data Type Conversion and Precedence in SELECT - SQL Command.

Inserting Rows from a SQL SELECT Command

You can now insert rows from a SQL SELECT command when you use the SQL INSERT command. You can copy the contents of selected columns or all columns in a row. However, you must make sure the data you copy is compatible with the columns in the rows that you copy to. For more information, see the INSERT - SQL Command.

You can retrieve the number of records processed by the most recently executed table command using the _TALLY system variable, which is updated with the number of rows inserted. For more information, see _TALLY System Variable.

See Also

What's New in Visual FoxPro 8.0 | Interactive Development Environment (IDE) Enhancements | Language Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Miscellaneous Enhancements

Visual FoxPro contains the following miscellaneous enhancements:

  • Walkthrough topics
  • New Solution samples
  • New NorthWind sample database
  • Pool Manager Foundation Class
  • IntelliSense scripts
  • Task List
  • Object Browser
  • GenDBC.prg tool
  • SccText.prg tool
  • PivotTable Wizard, Mail Merge Wizard, and Referential Integrity Builder
  • TypeLib Foundation Class
  • Dr. Watson error reporting
  • Choosing a Visual SourceSafe database when opening projects
  • Support for Windows XP True Color icon images
  • Improved error message details

Walkthrough Topics

Visual FoxPro includes the following new walkthrough topics that guide you step-by-step through the following tasks:

Walkthrough: Creating Applications with Visual FoxPro

Walkthrough: Creating Tables with Visual FoxPro

Walkthrough: Retrieving Data from Different Data Sources

Walkthrough: Creating XML Web Services with Visual FoxPro

Walkthrough: Creating Reports with Visual FoxPro

Walkthrough: Creating a Visual FoxPro Application Setup Program Using InstallShield Express

For more information, see Walkthroughs.

New Solution Samples

Visual FoxPro includes the following new Solution samples so that you can experiment with and learn about the new features in Visual FoxPro:

  • Binding, Raising, Unbinding, and Retrieving Events Sample
  • Controlling MSN Messenger Sample
  • Creating a Cursor from an XML DataSet Sample
  • Creating Irregularly Shaped Windows Sample
  • Grid Highlighting, Column Resizing, and Header Images Sample
  • Loading and Generating XML Using XMLAdapter Class Sample
  • Managing Data Access Using CursorAdapters Sample
  • Member Classes Sample
  • Passing Strongly Typed Arrays Sample
  • SCATTER NAME...ADDITIVE Sample
  • Structured Exception Handling Sample
  • System Tray Icon Sample
  • Windows XP Themes Support Sample

For more information, see New Visual FoxPro 8.0 Solution Samples.

New NorthWind Sample Database

Visual FoxPro includes a new NorthWind.dbc sample database, which simulates the SQL Server and Access NorthWind database and supports automatic incrementing. You can find the NorthWind.dbc database in the ...\Samples\Northwind folder or by locating it in the Solution Samples Task Pane in the Task Pane Manager.

Pool Manager Foundation Class

The Pool Manager Foundation Class manages a pool, or collection, of objects from a single class. When you need to use an object repeatedly for a short time, use the Pool Manager class. Visual FoxPro also includes the Pool Manager Sample to demonstrate this new Foundation Class. For more information, see Pool Manager Foundation Class and Pool Manager Sample.

IntelliSense Scripts

Visual FoxPro includes the following enhancements to IntelliSense scripts:

  • New script for the IMPLEMENTS clause in the DEFINE CLASS command opens a COM interface picker. For more information, see DEFINE CLASS Command and "Working with Interfaces" in Using the Object Browser.
  • Typing WS in a program (.prg) file opens the Select dialog box for choosing a registered XML Web service. XML Web services are no longer added in code using a type, for example, LOCAL oWS AS myWebService.
  • Typing ZDEF in a .prg file displays a list of #DEFINE statements that exist in the file including those referenced in #INCLUDE files.
  • Typing ZLOC in a .prg file displays a list of available local memory variables and parameters.
  • New scripts that expand the following control statements:
    • DOCASE Expands the DO CASE...ENDCASE command.
    • DOWHILE Expands the DO WHILE...ENDDO command.
    • IFEND Expands the IF...ENDIF command.
    • IFELSE Expands the IF...ELSE...ENDIF command.
    • FOREACH Expands the FOR...EACH command.
    • FOREND Expands the FOR...ENDFOR command.
    • SCANEND Expands the SCAN...ENDSCAN command.
    • TEXTEND Expands the TEXT...ENDTEXT command.
    • WITHEND Expands the WITH...ENDWITH command.
    • TRYEND Expands the TRY...CATCH...FINALLY command.

To see a list of IntelliSense scripts, look in the FoxCode.dbf file. For more information about IntelliSense, see IntelliSense Overview, Customizing IntelliSense Using FoxCode, and Using Scripting in FoxCode.dbf.

Task List Manager

You can clean the Task List table and edit the structure of the user-defined columns table in the Tasklist Options dialog box. For more information, see Task List Manager Window and Using the Task List Manager.

Object Browser

When an interface is selected in the Object Browser, the description pane also displays the Interface ID number. For more information, see Object Browser Window.

GenDBC.prg Tool

The GenDBC.prg tool, which generates a program that can recreate a database, now supports autoincrementing, collating sequences, and filtered primary keys. For more information, see Gendbc.prg.

SccText.prg Tool

The SccText.prg tool, which is Visual FoxPro program that translates Visual FoxPro binary files into their text equivalent, includes a MethodsWrite function that writes methods in alphabetical order. When creating .sca or .vca text files for source control, methods are written in alphabetical order. This provides easier comparison for checking file differences. For more information, see _SCCTEXT System Variable and Checking for Differences in Forms, Reports, and Other Table Files.

PivotTable Wizard, Mail Merge Wizard, and Referential Integrity Builder

Visual FoxPro updates the PivotTable and Mail Merge wizards to use the Visual FoxPro OLE DB Provider for the latest version of Microsoft Office. For more information, see PivotTable Wizard and Mail Merge Wizard.

You no longer need to pack the database container (DBC) to run the Referential Integrity Builder.

TypeLib Foundation Class

The TypeLib Foundation Class in _Utility.vcx has been updated to use the Tlbinf32 COM component. For more information, see Type Library Foundation Class.

Dr. Watson Error Reporting

Visual FoxPro includes product error reporting previously shipped with Visual FoxPro 7.0 Service Pack 1. This feature allows Microsoft to keep better track of errors that occur with the product.

Choosing a Visual SourceSafe Database When Opening Projects

You can now select a Visual SourceSafe database when Visual FoxPro prompts you after it attempts to open a project it cannot find in the current database.

In previous versions, Visual FoxPro assumed that you used only one database and searched only in last opened database for the project. Visual FoxPro generated an error when you attempted to open a project from a Visual SourceSafe database different from the last database opened.

Support for Windows XP True Color Icon Images

The Windows XP operating system displays true color, or 16-bit and 24-bit icon images, in Windows Explorer. Visual FoxPro includes support for displaying true color icon image formats in the Project Information dialog box and for attaching them to an application's executable (.exe) file.

The Project Information dialog box displays the highest possible color format supported by the operating system, corresponding to the closest image format in the icon file. If you do not specify an icon file to attach to an .exe file, Visual FoxPro attaches the standard Visual FoxPro icon. For more information, see Project Tab, Project Information Dialog Box.

Improved Error Message Details

Visual FoxPro includes more details and help for certain error messages.

See Also

What's New in Visual FoxPro 8.0 | Interactive Development Environment (IDE) Enhancements | Data Features Enhancements | Language Enhancements | Miscellaneous Enhancements | Behavior Changes Since Visual FoxPro 7.0


Behavior Changes Since Visual FoxPro 7.0

Visual FoxPro includes behavior that differs from previous versions and might affect existing code. These behavior changes are organized according to the following categories:

  • Critical Changes Behavior changes most likely to affect existing code when running under Visual FoxPro 8.0. It is extremely important that you read this section.
  • Important Changes Behavior changes that might affect existing code when running under Visual FoxPro 8.0.
  • Miscellaneous Changes Behavior changes you should know about but are not likely to impact existing code.
  • Removed Items Features or files that previously existed in prior versions of Visual FoxPro.

Critical Changes

Critical behavior changes will most likely to affect existing code when running under Visual FoxPro 8.0. It is extremely important that you read this section.

SQL Data Engine

Visual FoxPro contains a new SET ENGINEBEHAVIOR command so that you can control SQL data engine compatibility. This impacts how SQL SELECT commands function. The current default behavior can be set to previous behavior using the SET ENGINEBEHAVIOR command and is described as follows:

  • You cannot use the DISTINCT clause with Memo or General fields in a SQL SELECT statement. Instead, wrap a Memo field expression inside a function such as PADR( ) or ALLTRIM( ).
  • The GROUP BY clause does not support Memo or General fields.

    The GROUP BY clause must list every field in the SELECT list, except for fields contained in an aggregate function, such as the COUNT( ) function. In addition, the GROUP BY clause must also list every field in a HAVING clause, except for fields contained in an aggregate function.

  • A SQL SELECT statement can contain the HAVING clause without the GROUP BY clause, as long as the SQL SELECT statement does not contain any aggregate functions.
  • SQL SELECT statements do not automatically remove trailing spaces from the values that are compared using the LIKE operation. In versions prior to Visual FoxPro 8.0, both values in the LIKE operation were trimmed from the right prior to evaluation so that the LIKE operation could not possibly report all the correct matches.

For more information, see SELECT - SQL Command and SET ENGINEBEHAVIOR Command.

Support for Automatically Incrementing Field Values

Visual FoxPro contains the new Integer (AutoInc) field type. The AFIELDS() function now returns 18 columns instead of 16 due to new support for autoincrementing field values. Column numbers 17 and 18 now specify the NextValue and Step fields, which contain values of Numeric (integer) type. For more information, see AFIELDS( ) Function.

The COPY STRUCTURE EXTENDED command adds the numeric FIELD_NEXT and FIELD_STEP fields to support autoincrementing. For more information, see COPY STRUCTURE EXTENDED Command.

Enabled Windows XP Themes Support by Default

Visual FoxPro contains and enables support for Windows XP Themes by default in your applications. The new Themes property for visual classes can affect your existing user interface when using Microsoft Windows XP. You can turn this support off by setting the Themes property at the control, form, or _SCREEN system variable level, or using the SYS(2700) - Enables Windows XP Themes function.

Though existing applications should appear fine with Themes, controls defined using @...GET or @...SAY and similar @... commands are not compatible with Windows XP Themes. Therefore, when running programs written with FoxPro 2.x on Windows XP or later, you should set the _SCREEN Themes property to False (.F.); otherwise, the controls on the forms disappear.

You also might need to make minor modifications to forms that contain PageFrame objects. The Themes property provides a gradient effect on Page objects, so a label, option button, or similar control with text does not appear correctly if the BackStyle property of the control is set to Opaque. You can remedy this situation by setting BackStyle to Transparent.

When Themes are enabled, you should avoid using the CLEAR COMMAND for forms because it might cause paint issues with themed controls, such as command buttons, that have mouse hovering effects.

For a Grid control, Themes affects the visual appearance of column headers. If themes are enabled for a grid, the BackColor and ForeColor properties of the header are disregarded because they inherit the attributes of the theme. However, the BackColor and ForeColor properties of a Column object display independently from the setting of a grid's Themes property. A subclassed grid now respects the Column and Header ForeColor and BackColor properties of its parent.

For more information, see Themes Property and SYS(2700) - Enables Windows XP Themes.

Visual FoxPro OLE DB Provider

  • Visual FoxPro OLE DB Provider implements more compatibility with .NET such as working with Command Builder.
  • The Visual FoxPro OLE DB Provider recognizes any valid Config.fpw file placed in the same directory as the Provider to increase MVCOUNT, which sets the maximum number of variables that Visual FoxPro can maintain. For more information, see Special Terms for Configuration Files.
  • When setting the connection string for the Visual FoxPro OLE DB Provider, you can specify an existing Visual FoxPro ODBC Data Source Name (DSN) instead of a data source. The provider uses the data source indicated in the DSN and expands it to an appropriate provider connection string.
  • The GETENV( ) function is no longer supported in the Visual FoxPro OLE DB Provider.
  • You cannot query the value of ANSI using the SET command. However, the SET ANSI and SET MULTILOCKS commands remain supported.

Grid Behavior

The following changes affect grids:

  • Resizing grid column headers no longer calls the Header Click event. This change affects the column separator.
  • Setting the Column Visible property to False (.F.) hides the column. In prior versions, this setting caused the column to appear empty.
  • The Grid Refresh method visually updates the grid's record indicator even if the grid does not have focus.

Active Document Support

Visual FoxPro no longer supports Active Documents. The ActiveDoc class still exists in the Visual FoxPro language and can be instantiated. However, the functionality of hosting a Visual FoxPro application inside Internet Explorer is no longer available for security reasons.

Important Changes

Important changes might affect existing code when running under Visual FoxPro 8.0.

Syntax Validation for Views

In prior versions of Visual FoxPro, you could create a new view that contained syntax errors. Visual FoxPro now validates views to ensure no syntax problems exist.

For example, suppose you included a memory variable as part of the view definition. In previous versions, the memory variable did not need to exist when the view was created because Visual FoxPro did not perform syntax checking. Now, the memory variable must exist.

Form Deactivates When Clicking Visual FoxPro Desktop

Clicking the Visual FoxPro desktop causes the form's Deactivate event to occur and deactivates an active user form. This improvement provides better integration with the new BINDEVENT( ) function for activating and deactivating forms.

XMLTOCURSOR( ) Function

Visual FoxPro 7.0 Service Pack 1 included flag 8192 for XMLTOCURSOR( ) so you can specify importing of a specified XML file into an existing table or cursor. For more information, see XMLTOCURSOR( ) Function.

XMLTOCURSOR( ) converts a Decimal data type to Numeric 20,19 (width, precision). In Visual FoxPro 7.0, this mapped to Numeric 8,0.

TABLEUPDATE( ) Function Behavior When Setting BatchUpdateCount Property to a Value Greater Than 1

Avoid setting BatchUpdateCount to a value greater than 1 when you are updating data, using Table Buffering, and updating the table or tables in the data source from multiple clients. In this scenario, TABLEUPDATE( ) always returns True (.T.).

Due to the way that Open Database Connectivity (ODBC) behaves, Visual FoxPro is unable to detect conflicts when no error is generated by the server, yet nothing is updated, for example, no row matches the WHERE clause. This can occur when you use WhereType set to DB_KEYANDUPDATABLE, DB_KEYANDMODIFIED, or DB_KEYANDTIMESTAMP, and another user has changed one of the underlying values in the WHERE clause such that the row is not found by the update statement.

You can safely set BatchUpdateCount to a value greater than 1 for INSERT, DELETE, and UPDATE operations when FORCE is True.

Opening or Closing Offline Views Within a Transaction

Due to issues related to offline views and transactions, you cannot open or close an offline view within a transaction when using USE SQLViewName in ADMIN/ONLINE mode. For more information, see the descriptions for the ADMIN and ONLINE keywords in the USE Command.

Implicit Conversion of Object References to a String

Visual FoxPro converts an object reference to the string, "(Object)", when used with the following language elements:

  • TRANSFORM( ) function
  • MESSAGEBOX( ) function
  • DEBUGOUT command
  • WAIT WINDOW command
  • ? command

This behavior applies to all native Visual FoxPro objects and COM objects. The object reference must actually exist. For more information, see TRANSFORM( ) Function, MESSAGEBOX( ) Function, DEBUGOUT Command, WAIT Command, and ? | ?? Command.

Reloading Changes in the View Designer

If the View Designer cannot reload your changes after you make changes in the View SQL window, a dialog box appears and asks the following:

"View/Query designer is unable to reload your changes. Would you like to rebuild content from the designer?"

If you select Yes, your changes are discarded in the SQL window, and Visual FoxPro returns you to the View Designer. If you select No, Visual FoxPro returns you to the SQL window.

To save a statement that cannot be parsed such as a call to a stored procedure, select No and click the Save button on the toolbar. Visual FoxPro saves the query. You can also click the Save button after entering the command in the SQL window to save the query. You do not need to click the View Designer window, which causes the View Designer to try to load and parse the query.

SET DATABASE TO Accepts an Empty String

Using the SET DATABASE command with an empty string previously generated an error that the database was not open. You can now use SET DATABASE TO "", and it behaves the same as calling SET DATABASE TO without parameters. For more information, see SET DATABASE Command.

HOME(5)

HOME(5) now returns the Visual Studio MSDN directory instead of the Visual Studio MSDN Samples directory. Visual FoxPro no longer installs its samples with MSDN. Instead, Visual FoxPro samples are now stored on the source media or CD, and you can look up their locations using the Help that is installed with Visual FoxPro. For more information, see HOME( ) Function.

Displaying Fonts in Properties Window for FontName Property

In previous versions, multiple fonts from a single family were sometimes displayed. The Properties window properties list for the FontName property and the AFONT() function now include only the actual font families. For more information, see FontName Property and AFONT( ) Function.

CTRL+HOME and CTRL+END Keyboard Shortcuts

Visual FoxPro provides keyboard shortcut behavior consistent with Microsoft programs such as Excel and Access when navigating in a grid and using the BROWSE command:

  • Moves to the first record of a cursor or table in a grid and when using BROWSE by pressing CTRL+HOME.
  • Moves to the last record of cursor or table in a grid and when using BROWSE by pressing CTRL+END.

In prior versions of Visual FoxPro, CTRL+HOME opened a memo field, similar to CTRL+PAGE UP, and CTRL+END closed the Browse window, similar to CTRL+W.

For more information, see Keyboard Shortcuts.

Keyboard Shortcut Behavior for CTRL+TAB

Visual FoxPro supports context-sensitive behavior when pressing the CTRL+TAB key combination. However, when Form AllowTabs property is False (.F.), CTRL+TAB no longer exits an edit box. Instead, CTRL+TAB moves to the next available window. You can press the TAB key to exit an edit box when AllowTabs is False.

For more information, see Interactive Development Environment (IDE) Enhancements.

DISPLAYPATH( ) Function

The DISPLAYPATH( ) function now returns title (proper) case instead of all lowercase.

Calling DODEFAULT( ) Function in Base Classes

Calling the DODEFAULT( ) function in a method that does not exist in the parent class does not produce errors. However, this behavior still produces the following results:

  • Visual FoxPro disregards any parameters that are passed because no code is executed.
  • Visual FoxPro always returns True (.T.), which is the default behavior for any procedure without an explicit RETURN statement.

This behavior affects the following scenarios:

  • Custom methods that are defined in a class
  • Native methods that are Hidden in the parent class

For more information, see DODEFAULT( ) Function.

Using DOEVENTS as a Function

You can no longer call the DOEVENTS command using parentheses, for example, DOEVENTS( ). The DOEVENTS command now supports the optional FORCE keyword. For more information, see DOEVENTS Command.

COM Server Typing for Character Types

Visual FoxPro now generates type libraries for COM Servers that mark Character types as BSTR instead of VARIANT in the Visual FoxPro COM type library. This new behavior matches that of the String type. For example, the following procedure appears in the COM type library with the return type of BSTR:

PROCEDURE myProc( ) AS Character

For more information, see DEFINE CLASS Command.

QUARTER( ) Function

The QUARTER( ) function now returns 0 if passed an empty Date or DateTime value, for example, QUARTER({//}). In prior versions of Visual FoxPro, this generated an error message.

Trapping Errors in Reports

You can now trap the following errors that were previously handled by the system error handler:

  • Errors that occur in reports
  • Errors due to tables with bad database back links

Miscellaneous Changes

The following are miscellaneous changes that you should know about but are not likely to impact existing code.

Default Instancing Setting for EXE Servers

When you create a new project containing OLEPUBLIC classes, Visual FoxPro defaults the Instancing setting in the Servers tab of the Project Information dialog box to Single Use. The Single Use setting is appropriate for building EXE servers.

When you create a Visual FoxPro dynamic-link library (.dll) COM Server, Visual FoxPro defaults the Instancing setting to Multi Use.

Visual FoxPro retains any changes made to the Instancing setting.

For more information, see Servers Tab, Project Information Dialog Box.

Number of Rows for Exporting Data Cursors

Visual FoxPro raises the maximum from 16,384 to 65,535 rows when exporting a data cursor to an Excel spreadsheet. The new limit includes one row reserved for the field header. For more information, see EXPORT Command, COPY TO Command, and The Process of Exporting Data.

Docked Windows

The state and location of docked windows, such as the Command, View, and Debug windows, persist from the last user session. You can write your own layout schemes using the new DOCK WINDOW command. Deleting or editing the FoxUser.dbf resource file, which contains your settings, restores your default window settings. For more information, see Docking Windows and DOCK WINDOW Command.

When docking a link-docked container to the Visual FoxPro desktop, a container border no longer appears. Instead, only the docked windows appear.

Value Tips for Read-Only Properties and Inherited Methods and Events

Sometimes, you might have difficulty seeing the values for read-only properties or any visual class libraries from which methods and events are inherited in the Properties window properties list. You can now view value tips for these settings by moving the mouse over the property, event, or method in the properties list. For more information, see "Viewing Properties for Objects" in Manipulating Objects.

Wordwrapping for ToolTip Text

Visual FoxPro supports wordwrapping and increases the limit from 255 to 4,095 displayable characters for ToolTip text. For more information, see ToolTipText Property.

Windows-Style Open and Save Dialog Boxes

Visual FoxPro running on Windows 2000 and Windows XP operating systems includes the following changes in the Open, Save, and Open Picture dialog boxes:

  • A Places bar so you can navigate to common locations such as the My Documents folder and Desktop
  • The following options are available by clicking the View Menu icon: Thumbnails, Tiles, Icons, Lists, and Details. You can preview images in Windows 2000 and later by clicking Thumbnails. Visual FoxPro uses the Thumbnails view as the default setting to provide mini-previews of images. Therefore, the Open Picture dialog box no longer includes a frame for displaying an image. The Preview check box appears in the Open Picture dialog box only when running Visual FoxPro on operating systems earlier than Windows 2000.
  • The capability to resize dialog boxes

You can select multiple files in the Open dialog box after clicking Add in the Project Manager window to add a file to a project.

When you call the AGETCLASS( ) function, the Files of type list in the Open dialog box includes the program (.prg) file type. AGETCLASS( ) is no longer supported in Visual FoxPro runtime libraries because routines for parsing program (.prg) files are restricted to design time only.

For more information, see Open Dialog Box, Open Picture Dialog Box, Project Manager Window, and AGETCLASS( ) Function.

Maximum Form Design Area

The maximum design area of a new form in the Form Designer is now unlimited. The default setting for Maximum Design Area on the Forms tab in the Options dialog box is now None.

AGETCLASS( ) Function Not Supported in Visual FoxPro Run Time

AGETCLASS( ) is no longer supported in Visual FoxPro runtime libraries because routines for parsing program (.prg) files are restricted to design time only.

Increase for Default MVCOUNT

The default maximum number of variables that Visual FoxPro can maintain, which you can set using MVCOUNT in a configuration file, increases from 1,024 to 16,384.

Puzzle

You can now reactivate the Visual FoxPro puzzle by typing the following in the Command window:

ACTIVATE WINDOW Puzzle

Removed Items

Visual FoxPro no longer includes the following items:

  • Samples: Client/Server, ActiveDocs Solution, Gopher Server, Pool Manager Server, and TasTrade application. The TasTrade database remains in this release of Visual FoxPro.
  • Tools: Internet Search Wizard, CliReg32.exe, and Transformer.

    The source for Converter now resides in XSource.zip.

    The functionality for CliReg32.exe has been removed and has been replaced by the Component Services Tool, which is included with Windows 2000 and XP operating systems. You can use this tool to export a COM+ Server application for installation on one or more server computers. It also contains DCOM Config support that you can use to access remote applications. To access the Component Sevices Tool, click the Windows Start menu, then Control Panel, and double-click Component Services. For more information about Component Services, see the Windows online Help for the Component Services Tool.

  • ActiveX controls: FpOLE.ocx, FpOLE.dll, and FoxTLib.ocx, which is replaced with the TLibInf32 COM component.
  • ODBC driver and redistributable merge module: VfpODBC.msm
  • Functionality: Hosting for Active Documents, though Visual FoxPro retains the Active Documents class. Visual FoxPro does not include a Vfp8run.exe file because the support file is no longer distributed with Visual FoxPro.

See Also

What's New in Visual FoxPro 8.0 | Interactive Development Environment (IDE) Enhancements | Data Features Enhancements | Language Enhancements | Miscellaneous Enhancements


Visual FoxPro 8.0 New Reserved Words

_FOXREF

_PAGETOTAL

_TASKPANE

_TOOLBOX

A

ADDTABLESCHEMA

ADOCKSTATE

AEVENTS

AFTERCURSORATTACH

AFTERCURSORCLOSE

AFTERCURSORDETACH

AFTERCURSORFILL

AFTERCURSORREFRESH

AFTERCURSORUPDATE

AFTERDELETE

AFTERINSERT

AFTERUPDATE

ALLOWAUTOCOLUMNFIT

ALLOWCELLSELECTION

ALLOWDELETE

ALLOWEXTERNAL

ALLOWINSERT

ALLOWOUTPUT

ALLOWUPDATE

APPLYDIFFGRAM

ATTACH

AUTOFIT

AUTOINC

AUTOINCERROR

AUTOOPEN

B

BEFORECURSORATTACH

BEFORECURSORCLOSE

BEFORECURSORDETACH

BEFORECURSORFILL

BEFORECURSORREFRESH

BEFORECURSORUPDATE

BEFOREDELETE

BEFOREINSERT

BEFOREUPDATE

BINDCONTROLS

BINDEVENT

C

CATCH

CENTERED

CHANGESTOCURSOR

CHILDTABLE

COLLECTION

COMPAREMEMO

CONVERSIONFUNC

CURSORADAPTER

CURSORATTACH

CURSORDETACH

CURSORFILL

CURSORREFRESH

CURSORSCHEMA

CURSORSTATUS

D

DATASOURCE

DATASOURCETYPE

DATATYPE

DECLASS

DECLASSLIBRARY

DELETECMD

DELETECMDDATASOURCE

DELETECMDDATASOURCETYPE

DETAILS

DISABLEENCODE

DOCK

DOCK WINDOW

E

ENABLEHYPERLINKS

ENDTRY

ENGINEBEHAVIOR

ERRORNO

EVL

EXCEPTION

F

FINALLY

FLAGS

FONTCHARSET

FORCECLOSETAG

FORMATTEDOUTPUT

FRACTIONDIGITS

G

GETCURSORADAPTER

GETKEY

H

HEADERCLASS

HEADERCLASSLIBRARY

HIGHLIGHTBACKCOLOR

HIGHLIGHTFORECOLOR

HIGHLIGHTSTYLE

I

INSERTCMD

INSERTCMDDATASOURCE

INSERTCMDDATASOURCETYPE

ISATTRIBUTE

ISBASE64

ISBINARY

ISDIFFGRAM

ISLOADED

ISXMLDOMELEMENT

ITEM

J

K

KEYSORT

L

LINECONTENTS

LOADXML

LOCKCOLUMNS

LOCKCOLUMNSLEFT

M

MAPN19_4TOCURRENCY

MEMBERCLASS

MEMBERCLASSLIBRARY

MOVEITEM

N

NEXTVALUE

NODIALOG

O

ONMOVEITEM

P

PARENTTABLE

PICTUREPOSITION

PICTURESELECTIONDISPLAY

PRESERVEWHITESPACE

PRETEXT

Q

R

RAISEEVENT

RELEASEXML

REMOVEPROPERTY

RESPECTCURSORCP

ROTATEFLIP

S

SELECTCMD

SOM

STACKLEVEL

T

TABLEVALIDATE

TABORIENTATION

THEMES

THROW

TOCURSOR

TOXML

TRY

U

UNBINDEVENT

UNICODE

UPDATECMD

UPDATECMDDATASOURCE

UPDATECMDDATASOURCETYPE

USEDEDATASOURCE

USERVALUE

UTF8ENCODED

V

W

WRAPCHARINCDATA

WRAPINCDATA

WRAPMEMOINCDATA

X

XMLADAPTER

XMLCONSTRAINTS

XMLFIELD

XMLNAME

XMLNAMESPACE

XMLPREFIX

XMLSCHEMELOCATION

XMLTABLE

XMLTYPE

XSDFRACTIONDIGITS

XSDMAXLENGTH

XSDTOTALDIGITS

XSDTYPE

Y

Z

See Also

What's New in Visual FoxPro | Reserved Words


Getting Started with Visual FoxPro

Microsoft Visual FoxPro is the object-oriented relational database management system that makes it possible for you to create state-of-the-art enterprise database solutions. Visual FoxPro includes professional productivity tools, documentation, and sample code for quickly building, managing, and deploying solutions.

In This Section

Locating Readme Files
Describes how to find the location of the Visual FoxPro Readme file.
Installing Visual FoxPro
Describes system requirements and how to install and add applications to Visual FoxPro.
Upgrading from Earlier Versions
Describes how Visual FoxPro protects your investment in applications built in previous versions of FoxPro.
Customizing the Visual FoxPro Environment
Explains how you can optimize your computer system, configure Visual FoxPro and development environment settings, restore your desktop, and how people with disabilities can improve accessibility to Visual FoxPro and Microsoft Windows.

Related Sections

What's New in Visual FoxPro 8.0
Describes the new features and enhancements included in this version of Visual FoxPro.
Using Visual FoxPro
Gives an overview of Visual FoxPro features, describes concepts and productivity tools for developing, programming, and managing high-performance database applications and components, and provides walkthroughs that help get you started. With the robust tools and data-centric object-oriented language that Visual FoxPro offers, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Reference
Includes Visual FoxPro general, programming language, user interface, and error message reference topics.
Samples
Contains Visual FoxPro class library, server, solutions, and foundation class code samples that you can use for experimenting with and learning Visual FoxPro features.


Locating Readme Files

The Readme.htm file is stored at the root of the Microsoft Visual FoxPro CD-ROM. Use your Internet browser to open and view the files.

To locate Readme files for additional products included in the Visual FoxPro package, see the root of each product CD-ROM.


Installing Visual FoxPro

You can install Visual FoxPro from a CD-ROM or a network to a local hard drive. You must install Visual FoxPro on a local drive, not a mapped drive.

Requirements for Installation

Visual FoxPro has the following minimum system requirements:

  • Computer: An IBM-compatible computer with a Pentium class processor
  • Peripherals: Mouse or pointing device
  • Memory: 64 MB RAM (128 MB or higher recommended)
  • Hard disk space:
    • Visual FoxPro Prerequisites: 20 MB
    • Visual FoxPro Typical Install: 165 MB
    • Visual FoxPro Maximum Install: 165 MB
  • Video: 800 x 600 resolution, 256 colors (High color 16-bit recommended)
  • Operating system: Developing applications with Visual FoxPro 8.0 is supported only on Microsoft Windows 2000 Service Pack 2 or later, and Windows XP. You can create and distribute run-time applications for Windows 98, Windows Me, Windows 2000 Service Pack 2 or later, and Windows XP.
    Note Installation on Windows NT 4.0 Terminal Server Edition is not supported.

Installing Visual FoxPro

There is no preparation required before installing Visual FoxPro. You must be an administrator on the local computer to install and use all the provided tools effectively.

You can safely install or uninstall using Visual FoxPro 8.0 Setup. If you are upgrading to Visual FoxPro 8.0, you must first uninstall Visual FoxPro 7.0. Though Visual FoxPro 8.0 and Visual FoxPro 7.0 can exist on the same computer, you cannot install Visual FoxPro 8.0 in the same directory as Visual FoxPro 7.0.

If you plan to publish XML Web services using Visual FoxPro, you might want to set up Internet Information Services (IIS) on a Windows 2000 or Windows XP computer. Refer to your operating system documentation for instructions on how to set up and configure IIS.

Note Visual FoxPro setup no longer installs any Windows operating system Service Packs or versions of Internet Explorer. It is highly recommended that you install the latest versions of these components before installing Visual FoxPro 8.0. Additionally, Visual FoxPro 8.0 is supported only on Windows 2000 Service Pack 2 or later. For details about installing the lastest Service Pack, visit the following Microsoft Web page at http://www.microsoft.com/windows2000/.

Full installation includes all Visual FoxPro program files, online help, and samples files.

To install Visual FoxPro

  1. Quit all open applications.
    Note If you use a virus protection program on your computer, override it or turn it off before running the Installation wizard. The Installation wizard might not run properly with virus protection turned on. After installation, be sure to restart your virus protection program.
  2. Insert the Visual FoxPro CD.

    The Visual FoxPro 8.0 Setup start page appears automatically.

  3. Click Install Visual FoxPro to launch Visual FoxPro Setup.
  4. To determine if you need additional components, click Prerequisites to display any necessary components.
  5. Click Install Now! to install any new components. If Visual FoxPro Prerequisites needs to only update components, click Update Now!
  6. You might need to restart your computer. When finished, click Done.

    Visual FoxPro Setup reappears.

  7. To continue installation, click Visual FoxPro.
  8. After accepting the End User License Agreement and entering the Product Key and your name, click Continue.
    Note Visual FoxPro cannot be installed on a mapped drive. You must install Visual FoxPro on a local drive. Do not attempt to use the Map Network Drive functionality in Setup.
  9. On the Options page, select the features you want to install and click Install Now! to continue.
  10. When finished, click Done to return to Visual FoxPro Setup. Click Exit to return to the Visual FoxPro 8.0 Setup start page.

If you uninstall Visual FoxPro 8.0 while Visual FoxPro 7.0 exists on your computer, certain shared registry keys used by Visual FoxPro 7.0 are removed. You must reinstall these critical shared registry keys.

If you run Visual FoxPro 7.0 from the Start menu, Visual FoxPro 7.0 Setup automatically reinstalls these keys. If you start Visual FoxPro 7.0 using other means, such as running the application executable directly, the setup program does not start automatically. You should use Add/Remove Programs in the Control Panel and the following steps to reinstall the registry keys manually:

To manually reinstall Visual FoxPro 7.0 registry keys

  1. From the Start menu, click Control Panel.
  2. Click Add/Remove Programs.
  3. Click Change/Remove for Microsoft Visual FoxPro 7.0.
  4. Click Visual FoxPro and Repair/Reinstall.

Installation Troubleshooting

You might encounter the following when installing Visual FoxPro:

  • If you cannot run Visual FoxPro and do not see error messages telling you what is wrong, the problem might be in your computer's ROM BIOS or the video driver you are using.
  • If you are using an extended keyboard, be sure it is compatible with the ROM BIOS. In addition, make sure that you are using a standard VGA or Super VGA Windows video driver.
  • If you get a "stack overflow" error message, your video driver is out of date or not designed for your video card. To correct this problem, update the video driver.
  • For additional information, see the Visual FoxPro Readme at the root of the Visual FoxPro installation CD.

Installing Additional Applications

This release includes copies of additional software that you can install and use with Visual FoxPro. These include:

  • InstallShield Express Limited Edition

    Provides the capability to package and deploy the applications that you create using Visual FoxPro. Visual FoxPro includes the updated and limited edition of InstallShield Express 3.54.

    Note The limited and full editions of InstallShield Express 3.54 are considered two versions of the same product and cannot coexist. If you install one version on a computer where another already exists, the original is uninstalled automatically. Because the limited edition contains fewer features than the full edition, you should keep the full edition on your computer.
  • Microsoft SOAP Toolkit 3.0 Samples

    Provides samples for demonstrating how to consume and publish XML Web services. Visual FoxPro Prerequisites installs the core SOAP Toolkit 3.0 components needed to access and publish XML Web services in Visual FoxPro.

  • Microsoft SQL Server 2000 Desktop Engine (MSDE)

    Provides a personal version of SQL Server.

To install InstallShield Express Limited Edition

  1. Insert the Visual FoxPro CD.

    The Visual FoxPro 8.0 Setup start page opens automatically.

  2. Click Install InstallShield Express.
  3. Follow the instructions in the InstallShield Express installation wizard.

You can also locate the Setup.exe file for InstallShield Express in the InstallShield folder on the Visual FoxPro CD.

Note Visual FoxPro 8.0 installs its redistributable merge modules in a location different from Visual FoxPro 7.0.

The following are the locations of the redistributable merge modules for Visual FoxPro 7.0 and 8.0:

Visual FoxPro 7.0: \Program Files\Common Files\Microsoft Shared\Merge Modules\

Visual FoxPro 8.0: \Program Files\Common Files\Merge Modules\

The version of InstallShield Express included with Visual FoxPro 8.0 automatically uses the new Visual FoxPro 8.0 merge module location.

Note Visual FoxPro 8.0 requires certain merge modules when creating a Visual FoxPro 8.0 redistributable custom application setup program using InstallShield Express.

You need to include the following merge modules when creating your custom setup program:

  • Microsoft Visual FoxPro 8 Runtime Libraries
  • Microsoft Visual C++ Runtime Library 7.0
  • GDI Plus Redist
  • XML 4.0

To install SOAP Toolkit 3.0 Samples

  1. Insert the Visual FoxPro CD.

    The Visual FoxPro 8.0 Setup start page opens automatically.

  2. Click Install SOAP Toolkit 3.0 Samples.
  3. Follow the instructions in the SOAP Toolkit 3.0 Samples Setup Wizard..

You can also locate the Soapsdk.msi and Soapsamp.msi files for the SOAP Toolkit in the SOAPToolkit folder on the Visual FoxPro CD.

To install MSDE

  1. Insert the Visual FoxPro CD.

    The Visual FoxPro 8.0 Setup start page opens automatically.

  2. Click Install Microsoft SQL Server Desktop Engine (MSDE) to install MSDE without an installation wizard. Click Yes to verify that you want to install MSDE.

You can also locate the Setup.exe file for MSDE in the SQLMSDE folder on the Visual FoxPro CD.

Note Visual FoxPro 8.0 includes Microsoft SQL Server 2000 Desktop Engine Service Pack 2.0. To make sure you have the most recent version and Service Pack installed, visit the Microsoft SQL Server Web page at http://www.microsoft.com/sql/default.asp. In addition, if you are distributing custom Visual FoxPro applications that require MSDE, you can obtain the redistributable merge modules from the Microsoft SQL Server Web page for use with Windows Installer-based setup programs.

Reinstalling Visual FoxPro

If you want to reinstall Visual FoxPro or install to another location, you might want to clean your user settings and other files installed by Visual FoxPro before reinstalling.

You can remove these files by deleting the contents of the ...\Application Data\Microsoft\Visual FoxPro folder inside your user settings folder. You can determine the location of the Application Data folder by typing ? HOME(7) in the Command window. These files include your FoxUser.* resource files, which contain user settings, and folders for the Toolbox and Task Pane.

However, it is possible that your resource files are in another location. You can determine their location by typing the following in the Command window:

? SYS(2005)

You should delete old Code Reference files that might be associated with projects in the project directories. These are labeled as projectname_ref.* files. You might also need to to restore the default Visual FoxPro 8.0 registry settings.

Visual FoxPro includes the VFPClean.app tool so you can make sure all core Xbase and other files are set appropriately.

To run VFPClean.app

  • Type the following line of code in the Command window:
    DO HOME()+"VFPCLEAN.APP"

See Also

Customizing the Visual FoxPro Environment | Upgrading from Earlier Versions


Upgrading from Earlier Versions

Microsoft Visual FoxPro protects your investment in applications built with previous versions of FoxPro. In Visual FoxPro, you can run many applications that were written in earlier versions with little or no conversion. You can modify and enhance applications using the Visual FoxPro language, knowing that most extensions to the language do not affect backward compatibility. In addition, you can convert FoxPro screens, projects, and reports to Visual FoxPro format.

However, it is possible that some behavior or feature changes in the current version of Visual FoxPro might affect existing Visual FoxPro source code. Therefore, you should review the new features, enhancements, and most recent behavior changes for this version. For more information, see What's New in Visual FoxPro 8.0 and Behavior Changes Since Visual FoxPro 7.0.

Conversion to Visual FoxPro Format

If you choose to convert your dBASE or FoxPro files to the Visual FoxPro format, you can take advantage of the unique features of Visual FoxPro. You can run many files from some previous versions of FoxPro directly; others require varying levels of conversion.

You can convert most projects or components created using previous versions of Visual FoxPro simply by opening or recompiling them in this version of Visual FoxPro. When you recompile components, such as forms, screens, or reports, some modifications may be necessary. You can make modifications to these components in the same way you modify the components of this version of Visual FoxPro.

You can find additional information about upgrading from previous versions of Visual FoxPro on the Microsoft Developer Network (MSDN) Web site at http://msdn.microsoft.com. You can search the MSDN Archive for documentation of previous versions of Visual FoxPro.

See Also

Getting Started with Visual FoxPro | Overview of Visual FoxPro Features | Installing Visual FoxPro | Customizing the Visual FoxPro Environment | Optimizing Your System


Customizing the Visual FoxPro Environment

After you install Visual FoxPro, you might want to customize your development environment. Environment settings include the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.

You can configure Visual FoxPro either interactively or programmatically. You can also establish configuration settings that are loaded when you start Visual FoxPro.

For information on optimizing your Visual FoxPro applications, see Optimizing Applications.

In This Section

Optimizing Your System
Explains how to get maximum performance by optimizing your operating system, Visual FoxPro, and your application.
Visual FoxPro Configuration
Explains how changing the configuration of your copy of Visual FoxPro affects the way it looks and behaves, such as establishing default locations for files used with Visual FoxPro, altering how your source code looks in an edit window, and displaying the format of dates and times.
Visual FoxPro Environment Settings
Describes different ways to change Visual FoxPro environment settings such as using the Options dialog box, setting configuration options at program startup, and using command-line options. You can configure Visual FoxPro toolbars, dock windows, set editor options, and customize the appearance of your applications without altering code.
Restoring the Visual FoxPro Interactive Environment
Describes how to close down all program operations and clear the Visual FoxPro desktop to return to its interactive state.
Accessibility for People with Disabilities
Provides information about features, products, and services that make Microsoft Visual FoxPro and the Windows operating system more accessible for people with disabilities.

Related Sections

Using Visual FoxPro
Explains how Visual FoxPro provides the tools you need to create and to manage high-performance database applications and components. With its robust tools and data-centric object-oriented language, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.
Walkthroughs
Describes how to create different types of applications and components with step-by-step guides.
Overview of Visual FoxPro Features
Describes how Visual FoxPro gives you more of everything you have come to expect in a database management system (DBMS) — speed, power, and flexibility.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Development Productivity Tools
Explains that Visual FoxPro provides developer tools for application development within the FoxPro application and the FoxPro language.


Optimizing Your System

Visual FoxPro is designed to be the fastest relational database development system. Applications you create with Visual FoxPro can have widely varying requirements and purposes. Because of this variety, you might want to optimize the operating system, Visual FoxPro, or your application for maximum performance.

In This Section

Optimizing the Operating Environment
Explains effective ways to optimize Visual FoxPro performance by getting the best use of your computer's hardware and environment.
Optimizing Visual FoxPro Startup Speed
Describes how, though Visual FoxPro is always fast, you can optimize the startup and operating speed by managing startup speed and optimizing SET commands.
Optimization of Visual FoxPro in a Multiuser Environment
Explains that when you run Visual FoxPro in a multiuser environment, you can improve performance by handling temporary files effectively and by controlling the way files are shared.

Related Sections

Getting Started with Visual FoxPro
Discusses how to get started, including information about installing, upgrading, and customizing Visual FoxPro to create state-of-the-art enterprise database solutions.
What's New in Visual FoxPro
Lists the new features and enhancements made to this version of Microsoft Visual FoxPro.
Using Visual FoxPro
Provides links to information on Visual FoxPro programming features that are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how to access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Optimizing the Operating Environment

An effective way to optimize Visual FoxPro performance is to get the best use of your computer's hardware and environment. This section addresses how to use memory effectively and how to get the best performance from your hard disk.

Using Memory and Virtual Memory Effectively

The most effective way to optimize your system for Visual FoxPro is to provide it with as much memory as possible. Visual FoxPro can take advantage of enormous amounts of computer memory. As well as providing memory, you can optimize the performance of Visual FoxPro by closing all other running applications on your computer.

To get the best use of your computer's memory while running Visual FoxPro, follow these guidelines:

  • Do not run any other Windows applications while Visual FoxPro is running.
  • Use only those memory-resident programs needed for operation.

To increase the number of applications that you can run simultaneously, Microsoft Windows supports virtual memory by swapping segments of code (code that is the least recently used) from RAM to the hard disk in the form of a paging file. As a rule, the default settings in the Windows operating system for managing virtual memory meet the requirements of most users; these settings are recommended.

Note The paging file does not improve Visual FoxPro performance and is not a substitute for more RAM.

Simplifying the Display

You can free memory for Visual FoxPro by simplifying the way windows and screen backgrounds are displayed.

  • To free memory for running applications, use a color or a pattern for the desktop background instead of wallpaper.
  • Use the lowest-resolution display that is practical for you; the higher resolution the display, the more memory your computer requires and the slower your graphics and user-interface elements appear. For VGA-compatible displays that use an extended mode driver, such as Video 7 or 8514, using the standard VGA driver ensures faster display performance (but lower resolution and less color support).

Managing Your Hard Drive

By managing your hard drive you can improve overall product speed. Follow these guidelines for getting the best performance from your hard disk:

  • Provide a generous amount of disk space.

    Disk input/output performance degrades significantly when a disk drive is nearly full. If your disk drive has little free space, you can increase Visual FoxPro performance by removing unnecessary data or by purchasing a larger capacity drive. The more free disk space available, the more likely it is that contiguous blocks of disk space are available. Visual FoxPro uses this space for changes and additions to database, table, index, memo, and temporary files. Increasing free disk space therefore improves the performance of any commands that change or add to your files. More disk space also decreases the time required to read those files in response to your queries.

Optimizing Files and Directories

The way that Windows and Visual FoxPro manage files on disk can greatly affect the performance of your application. This section explains how to:

  • Manage the number of files in a directory.
  • Manage how Visual FoxPro creates temporary files.

Managing Files in Directories

As a directory becomes increasingly congested with entries, the operating system takes longer to find files. How fast your system can search its directories is a function that is not under the control of Visual FoxPro.

To correct this situation, you must reduce the number of files in your directories. To reduce the number of files in your directories and speed up file search times, try the following:

  • Use the Project Manager to avoid creating numerous generated files. Segregate your program files into separate directories.
  • When you're ready to distribute your application, create an application or an executable file instead of numerous individually generated files.

    This procedure decreases the number of files in your application's subdirectories, thereby increasing performance.

  • If you delete a large proportion of files in one directory, copy the remaining files into a new directory or optimize the directory with a defragmenting utility program.

    Deleting files from a directory does not immediately speed directory searching. When a file is deleted, the entry remains as a "hole" in the directory and is still included in directory searches.

  • When saving files, use short file paths to increase performance. For example, "c:\Program Files\Microsoft Visual Foxpro\..." is a very long file path.

Managing Temporary Files

Visual FoxPro creates temporary files for a variety of activities. For example, Visual FoxPro creates temporary files during editing, indexing, and sorting. Text editor sessions can also create a complete temporary copy of the file being edited.

By default, Visual FoxPro creates its temporary files in the same directory that Windows stores its temporary files, unless you specifically designate an alternate location. Specify an alternate location by including one or more of the EDITWORK, SORTWORK, PROGWORK, or TMPFILES statements in the Config.fpw file.

To specify the location of temporary files

  1. From the Tools menu, choose Options and then choose the File Locations tab. Navigate down the list to Tempory Files under File Type.
  2. Enter a location for temporary files.

In most cases, you should specify one location for all Visual FoxPro temporary files. However, always make sure that the location you specify has enough space for all possible temporary files.

The directory of temporary files should contain as few files as possible. A low number of files reduces the amount of time Visual FoxPro waits for Windows to return file handles.

For more information on temporary files, see Optimizing Visual FoxPro in a Multiuser Environment.

See Also

Optimizing Your System | Optimizing Visual FoxPro Startup Speed | Managing Temporary Files | File Locations Tab, Options Dialog Box | Options Dialog Box


Optimizing Visual FoxPro Startup Speed

Though Visual FoxPro is always fast, you can optimize the startup and operating speed. This section describes enhancing Visual FoxPro performance by managing startup speed and optimizing SET commands.

Managing Startup Speed

The time required to load and start Visual FoxPro relates to the physical size of Visual FoxPro, the length of the PATH statement in effect, the number of items to be found at startup, and other factors. You can control the load size, the search path, component file locations, and the startup SET command values of Visual FoxPro.

Managing File Locations

Visual FoxPro stores the FoxUser.dbf file, which contains user settings, in the your user Application Data directory by default. You can display this location by typing HOME(7) in the Command window. Visual FoxPro seeks FoxUser.dbf and Config.fpw in the following places:

  • In the startup application or executable file, if any. For example, you might start a Visual FoxPro application by using the following command line:
    VFP8.exe MYAPP.APP

    – or –

    VFP8.exe MYAPP.EXE

    If the startup application or executable file contains a Config.fpw file, it is always used. Settings in a Config.fpw file that are bound inside an application can be overridden by specifying an external Config.fpw file, using the -C command-line switch when starting an application or Visual FoxPro.

  • In the working directory
  • Along the path established with the PATH environment variable
  • In the directory containing Visual FoxPro

Controlling File Loading

You can also speed startup by preventing Visual FoxPro from loading files you don't plan to use. If your application does not use the FoxUser or FoxHelp file, disable them in the Config.fpw file by using the following commands:

RESOURCE = OFF
HELP = OFF

Visual FoxPro seeks all other Visual FoxPro components (GENXTAB, CONVERT, and so on) only in the Visual FoxPro directory. If you place components elsewhere, you must explicitly identify the path to those components in your Config.fpw file. For example, you might specify these locations:

_TRANSPORT = c:\migrate\transport.prg
_GENXTAB = c:\crosstab\genxtab.prg
_FOXREF = c:\coderefs\foxref.app

You can use the environment variable FOXPROWCFG to explicitly specify the location of Config.fpw. For details about the FOXPROWCFG variable, see Customizing the Visual FoxPro Environment.

Optimizing the Load Size of Visual FoxPro

If you don't plan on using any of the Visual FoxPro components listed previously, set them to an empty string to speed startup.

To optimize the load size of Visual FoxPro

  • Use the following syntax:

    cFileVariable = ""

    Replace cFileVariable with _TRANSPORT, _CONVERT, or other variables as appropriate.

Optimizing Key SET Commands

You can optimize the operation of Visual FoxPro by tuning the values of certain SET commands.

The following table shows SET commands that have the greatest effect on performance, and their settings for maximum performance. You can specify SET command values by including them in the Config.fpw file, by typing them in the Command window, or by setting them in the Options dialog box.

Command Settings for Maximum Performance

SET Command | Performance Setting
SET ESCAPE Command | ON
SET OPTIMIZE Command | ON
SET REFRESH Command | 0,0
SET SYSMENU Command | DEFAULT
SET TALK Command | OFF
SET VIEW Command | OFF

See Also

Optimizing Your System | Optimization of Visual FoxPro in a Multiuser Environment | Optimizing the Operating Environment | Customizing the Visual FoxPro Environment | SET ESCAPE Command | SET REFRESH Command | SET SYSMENU Command | Command Window


Optimization of Visual FoxPro in a Multiuser Environment

When you run Visual FoxPro in a multiuser environment, you can improve performance by handling temporary files effectively and by controlling the way files are shared.

Managing Temporary Files in a Multiuser Environment

In most multiuser environments, you should place temporary files on the local drive. How you manage the files depends on the amount of disk space and RAM on the networked computers that run your application.

If networked computers have sizable hard drives with plenty of free space, you can improve performance in a multiuser environment by placing Visual FoxPro temporary work files on local drives. Redirecting a file to a local drive provides additional speed by reducing the need to access the network drive and, therefore, reducing the amount of network traffic.

On small networks, with older networked computers and slow hard drives, you might experience better performance by leaving Visual FoxPro temporary files on the file server. When in doubt, direct temporary files to the local hard drive. When working on large, heavily used networks, always redirect temporary files to the local hard drive.

For example, to redirect all temporary files to a directory called WORK on drive C:, include the following lines in your Config.fpw file:

TMPFILES=c:\work
EDITWORK=c:\work
SORTWORK=c:\work
PROGWORK=c:\work

The SORTWORK directory must be large enough to hold the temporary files that Visual FoxPro generates during sorting and indexing activities. When Visual FoxPro handles large tables, these temporary files can be very large.

By placing all your temporary files in a single directory on a local drive, you can safely erase the contents of the temporary file directory before each Visual FoxPro session. This will purge your system of any temporary files that were created but not erased by Visual FoxPro due to a system reboot or power loss.

Sharing Tables in a Multiuser Environment

If users are sharing tables on a network, the way you manage access to files through file and record locks can affect performance. You can enhance performance by using the EXCLUSIVE clause of the USE and OPEN commands.

With sharing enabled and EXCLUSIVE set to OFF, tables on a shared drive are opened for multiuser access. In this situation, the following command opens CUSTOMER.DBF in shared mode:

USE c:\customer.dbf

Visual FoxPro can buffer write operations to non-shared files, thereby increasing performance. To increase performance of APPEND, REPLACE, and DELETE commands, be sure to open local tables or databases using the EXCLUSIVE clause of the USE or OPEN commands, as in the following example:

OPEN DATABASE mycompany EXCLUSIVE
USE c:\customer.dbf EXCLUSIVE

Avoid opening and closing tables repeatedly.

For more information on accessing files in a shared environment, see Programming for Shared Access.

See Also

Optimizing Your System | Programming for Shared Access | Optimizing Applications in Multiuser Environments | USE Command | APPEND Command | REPLACE Command | DELETE Command


Visual FoxPro Configuration

The configuration of Visual FoxPro determines how your copy of Visual FoxPro looks and behaves. For example, you can establish the default locations for files used with Visual FoxPro, how your source code looks in an edit window, and the format of dates and times.

You can make changes to the Visual FoxPro configuration that exist for the current session only (temporary), or specify them as the default settings for the next time you start Visual FoxPro (permanent). If the settings are temporary, they are stored in memory and are discarded when you quit Visual FoxPro.

If you make permanent settings, they are stored in the Microsoft Windows registry or Visual FoxPro resource file. The Windows registry is a database that stores configuration information about the operating system, all Windows applications, OLE, and optional components such as ODBC. For example, the registry is where Windows stores the associations between file name extensions and applications so that when you click a file name, Windows can launch or activate the appropriate application.

For an example of how to change the registry, you can examine Registry.prg in the \Samples\Classes directory, which contains numerous methods based on Windows API calls and makes it possible for you to manipulate the Windows registry.

Similarly, Visual FoxPro stores its application-specific configuration information in the registry. When you start Visual FoxPro, the program reads the configuration information in the registry and sets the configuration according to those settings. After reading the registry, Visual FoxPro also checks for a configuration file, which is a text file in which you can store configuration settings to override the defaults stored in the registry. After Visual FoxPro has started, you can make additional configuration settings using the Options Dialog Box or SET commands. For more information, see Viewing and Changing Environment Settings.

Note The run-time version of Visual FoxPro does not read the Windows registry when starting up, as registry settings are designed primarily to configure the development environment. If you intend to distribute your Visual FoxPro applications using a run-time library, you can establish configuration settings in two ways: with a configuration file, or with a program that manipulates the Windows registry on the user's computer.

Visual FoxPro also maintains a resource file, Foxuser.dbf, that stores information about the current state of the program when you quit. For example, the resource file contains information about the location and size of the Command window, current keyboard macros, the toolbars that are displayed, and so on. The Foxuser.dbf file is an ordinary Visual FoxPro table, which you can read and change as required by your application.

Tip If the data in the Foxuser.dbf file becomes corrupted or invalid, it can cause Visual FoxPro to behave in an erratic manner. If you do not manually store anything in the table, for example keyboard macros, deleting the table might help.

See Also

Customizing the Visual FoxPro Environment | Viewing and Changing Environment Settings | Options Dialog Box | ODBC Registry Foundation Class | Command Window | Changing Configuration Settings in the Windows Registry | SET RESOURCE Command


Visual FoxPro Environment Settings

You can make changes to the Visual FoxPro environment by using the Options dialog box, editing the Windows registry, overriding default configuration settings, customizing the Project Manager, and configuring Visual FoxPro toolbars.

In This Section

Viewing and Changing Environment Settings
Describes how to view and change environment settings using the Options dialog box. You can verify environment settings by using the Options dialog box, the DISPLAY STATUS Command, or displaying the values of individual SET Commands.
Changing Configuration Settings in the Windows Registry
Describes how to set the Visual FoxPro configuration by making changes to the Windows registry, using the Registry Editor.
Setting Configuration Options at Startup
Describes how you can establish configuration settings when you first start the program, making it possible to override default settings.
Using Command-Line Options When Starting Visual FoxPro
Explains how you can specify startup options by including a command-line switch. You can use a command-line switch to ignore the default configuration file and Windows registry settings.
Customizing the Appearance of Applications
Describes how to modify the appearance of your applications without changing your application code.
Configuring Visual FoxPro Toolbars
Describes how to customize, display, and hide toolbars.
Docking Windows
Describes how you can dock dockable windows to the Visual FoxPro desktop or with each other, and you can dock windows in three different modes — normal, linked, and tabbed. You can use tabbed docking and linked docking together.
Setting Editor Options
Explains how to configure the Visual FoxPro editor to display text the way you want by setting the font and text alignment. You can also make the editor easier to use by setting your preferences for indentation, wordwrap, automatic backup copies, and other features.
Displaying and Printing Source Code Files in Color
Describes how to configure your settings so that you can display and print program files, methods, stored procedures, and memos in color.
Automating Keystroke Tasks with Macros
Describes how you can record and save keystrokes in macros by using the Macros dialog box if you find yourself using the same keystrokes repeatedly, or if you want to automate some keystroke tasks for your users.

Related Sections

Customizing the Visual FoxPro Environment
Explains that after you install Visual FoxPro, you can customize your development environment settings, including the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.
Visual FoxPro Configuration
Explains how changing the configuration of your copy of Visual FoxPro affects the way it looks and behaves, such as establishing default locations for files used with Visual FoxPro, altering how your source code looks in an edit window, and displaying the format of dates and times.
Restoring the Visual FoxPro Interactive Environment
Describes how to close down all program operations and clear the Visual FoxPro desktop to return to its interactive state.


Viewing and Changing Environment Settings

To view and change environment settings, use the Options dialog box. The Options dialog box contains a series of tabs representing different categories of environment options.

To display the Options dialog box

  • From the Tools menu, choose Options.

The Options dialog box appears and displays tabs from which you can choose desired settings. For details about options you can set using each tab, see the Options Dialog Box.

Displaying Configuration Settings

When Visual FoxPro is running, you can verify environment settings by using the Options dialog box or the DISPLAY STATUS Command, or by displaying the values of individual SET Commands.

To display multiple environment settings

  • From the Tools menu, choose Options to display the Options dialog box and view the current settings.

    – or –

  • Type DISPLAY STATUS in the Command window.

To display individual environment settings

  • Use the SET( ) Function in the Command window to display the current value of any SET commands.

For example, to view the current status of SET TALK, type:

? SET("TALK")
Note Because settings are valid only for the current data session, you must capture your settings and place them in a program or a form's Init event code for every private data session.

For more information, see SET Command Overview.

To echo Options dialog box settings to the Command window

  1. In the Options dialog box, make setting choices.
  2. Hold down the SHIFT key and choose OK.

    The settings are echoed to the Command window.

  3. Copy the setting commands from the Command window.

Saving Configuration Settings

You can save the settings you make in the Options dialog box for the current data session or as default (permanent) settings for your copy of Visual FoxPro.

To save settings for the current session only

  1. In the Options dialog box, make setting choices.
  2. Choose OK.

When you save settings for the current session only, they remain in effect until you quit Visual FoxPro (or until you change them again). To save changes permanently, save them as default settings; this stores them in the Windows registry.

To save current settings as default settings

  1. In the Options dialog box, make setting changes.
  2. Choose Set As Default.
    Note The Set as Default button is disabled until you make a change to the current settings.

You can override default settings by issuing SET commands or by specifying a configuration file when you start Visual FoxPro. For details, see Setting Configuration Options at Startup.

SET Commands and Visual FoxPro Configuration

You can programmatically modify most options displayed on the tabs in the Options dialog box using SET commands or by assigning a value to a system variable.

For example, to use a year-month-date (yy.mm.dd) format for dates, you can use the SET DATE command instead of changing the Date Format setting in the Regional tab of the Options dialog box:

SET DATE TO ANSI

If you configure the environment using SET commands, the settings take effect only for the current session of Visual FoxPro. When you quit the program, your settings are discarded, and you must reissue the SET commands. However, you can automate this process by issuing SET commands at startup or using a configuration file. For details, see Setting Configuration Options at Startup.

Tip You can also save a configuration made with SET commands by displaying the Options dialog box and saving your settings there.

See Also

Visual FoxPro Environment Settings | Setting Configuration Options at Startup | Get Application Information from the Windows Registry | Changing Configuration Settings in the Windows Registry | DISPLAY STATUS Command


Changing Configuration Settings in the Windows Registry

You can make changes directly in the Windows registry to set the Visual FoxPro configuration.

To change the Windows registry, use the Registry Editor, a utility provided with Windows.

Note Exercise caution when changing the Windows registry. Changing the wrong registry entry or making an incorrect entry for a setting can introduce an error that prevents Visual FoxPro, or even Windows itself, from starting or working properly.

To change configuration settings in the registry

  1. In Windows, start the Registry Editor.
  2. Navigate to this registry key in HKEY_CURRENT_USER:
    Software\Microsoft\VisualFoxPro\8.0\Options
  3. Double-click the name of the setting to change, and then enter a new value.
  4. Close the Registry Editor.

    Your change will be in effect the next time you start Visual FoxPro.

You can also make changes to the registry by calling Windows APIs from a Visual FoxPro program.

See Also

Visual FoxPro Environment Settings | Get Application Information from the Windows Registry | Accessing APIs | SYS(3056) - Read Registry Settings


Setting Configuration Options at Startup

You can establish configuration settings when you first start the program, which allows you to override default settings.

Using SET Commands

One way to establish configuration settings is to issue one or more SET commands when your application starts. For example, to configure your system to display a clock in the status bar when the application starts, you can issue this SET command:

SET CLOCK ON

The exact point at which you issue the SET command depends on your application. In general, you issue SET commands from your application's main program file, which is the program or form that controls access to the rest of your application. You can also issue SET commands from the Load or Init events of the form. If you are using private data sessions, it may be necessary to make these settings in the BeforeOpenTables Event of your DataEnvironment object. For details about specifying a main file for an application, see Compiling an Application .

If your application has a form set as main in the project manager, and it then launches a menu, you can add SETUP commands by entering them in the menu's Setup option. For details see Adding Setup Code to a Menu System in Designing Menus and Toolbars .

Tip An efficient way to manage SET commands for startup is to create a procedure that contains all the commands that you want to issue. You can then call the procedure from the appropriate point in your application. Keeping all the SETUP commands in a single procedure makes it easier to debug and maintain your configuration settings. You can also put the code in the class on which your application object is based, or the class on which your forms are based.

Using a Configuration File

In addition to setting the Visual FoxPro environment using the Options dialog box or SET commands, you can establish preferred settings and save them in one or more configuration files. A Visual FoxPro configuration file is a text file in which you can specify values for SET commands, set system variables, and execute commands or call functions. Visual FoxPro reads the configuration file when starting up, establishing the settings and executing the commands in the file. Settings made in the configuration file override default settings made in the Options dialog box (and stored in the Windows registry).

Using a configuration file provides several advantages. You can:

  • Override the default settings established in the Options dialog box.
  • Maintain several different configuration files, each with different settings, so that Visual FoxPro can load a configuration suitable to a particular user or project.
  • Make changes more easily than if you establish settings with the SET commands in the program initialization sequence.
  • Start a program or call a function automatically when Visual FoxPro starts.

Creating a Configuration File

To create a configuration file, use the Visual FoxPro editor, or any editor that can create text files, to create a text file in the directory where Visual FoxPro is installed. Earlier versions of Visual FoxPro created the file Config.fpw in the startup directory. Config.fpw became the default configuration file. You can create any program file and use it to establish default settings and behaviors by starting Visual FoxPro using that file either by double clicking the file or using a command line reference.

If you are creating a new configuration file, you can save it using any name you want. By convention, configuration files have the extension .fpw.

When you start Visual FoxPro, you can use a default configuration file from the following locations in order:

  • Current working directory
  • Directory where Visual FoxPro is installed
  • Directories listed in the DOS path

If Visual FoxPro does not find a configuration file in these locations, Visual FoxPro uses only the default settings established in the Options dialog box.

Note For details about specifying an alternative to the default file name or location for the configuration file, see Specifying the Configuration File to Use.

Enter configuration settings using one of these methods:

  • Make settings with the SET command.
  • Set system variables.
  • Call programs or functions.
  • Include special terms used only in configuration files.

To enter SET commands in a configuration file

  • Enter SET commands without the SET keyword and with an equal sign.

    For example, to set a default path type, use this format:

    DEFAULT = HOME()+"\VFP"

    To add a clock to the status bar, use this command:

    CLOCK = ON

To enter a setting for a system variable, use the same syntax you would use in the Command window or in a program.

To set system variables in a configuration file

  • Enter the name of the system variable, an equal sign (=), and the value to set the variable to.

    For example, the following command specifies an alternative spell-checking program:

    _SPELLCHK = "SPLLCHK.EXE"

You can also call functions or execute programs from within a configuration file by using the COMMAND command. For example, you can start an initialization program as part of the startup process.

To call functions or execute commands in a configuration file

  • Enter COMMAND, an equal sign (=), and the command to execute or function to call.

    For example, to include the Visual FoxPro version number in the caption of the main Visual FoxPro window, use this command:

    COMMAND =_SCREEN.Caption="Visual FoxPro " + VERS(4)

    The following command launches a specific application when Visual FoxPro starts:

    COMMAND = DO MYAPP.APP

You can also use special terms in a configuration file that do not correspond to SET value, system variables, or commands.

To use special terms in a configuration file

  • Enter the special term, an equal sign (=), and the setting.

    For example, to set the maximum number of variables available in Visual FoxPro, use this command:

    MVCOUNT = 2048

For a complete list of special terms for configuration files, see Special Terms for Configuration Files.

Specifying an External Configuration File

You can use an external configuration file in addition to an internal configuration file in circumstances where you need to configure settings separately. For example, setting SCREEN=OFF should be performed in an internal configuration file.

You can set Visual FoxPro to read an external configuration file following an internal configuration file by using the new ALLOWEXTERNAL directive in the internal configuration file. When you include the setting ALLOWEXTERNAL=ON in the internal configuration file, Visual FoxPro searches for an external configuration file, usually Config.fpw, and reads its settings. You can also specify a different configuration file using the -C command-line switch when starting Visual FoxPro.

Note For .exe and .dll file servers, Visual FoxPro supports only those configuration files bound inside the server. Therefore, Visual FoxPro disregards the ALLOWEXTERNAL setting.

To read an external configuration file after an internal one

  1. In the internal configuration file, set the special term ALLOWEXTERNAL to on.
    ALLOWEXTERNAL = ON
  2. When you start your program, either specify a second configuration file using the -C command-line switch or have a second configuration file in the default program path.

For more information about command-line switches, see Using Command-Line Options When Starting Visual FoxPro.

The settings in an external configuration file take precedence over those in the internal configuration file, if duplicate settings exist, because the external configuration file is read after the internal file. Visual FoxPro does not begin initialization until it reads both files.

If you want to specify the configuration file as read-only, place the file in your project and mark it as Included. If you want to specify that the file can be modified, place the file in your project and mark it as Excluded. You can then distribute the file separately with your application or executable file. By convention, configuration files use the .fpw extension.

Starting Applications or Programs Automatically

You can insert commands into a configuration file that automatically launches programs when Visual FoxPro starts. You can use these commands either to start an entire application or to start just a program, such as one that initializes system variables.

To start applications from a configuration file

  • Assign the name of your application to the _STARTUP System Variable anywhere in the configuration file:
    _STARTUP = MYAPP.APP

    -or-

  • Use the COMMAND command, which must be the last line in your configuration file:
    COMMAND = DO MYAPP.APP

Specifying the Configuration File to Use

When Visual FoxPro starts, you can specify a configuration file or bypass all configuration files, allowing Visual FoxPro to use its default settings.

When Visual FoxPro loads a configuration file, the settings in that file take precedence over corresponding default settings made in the Options dialog box.

To specify a configuration file

  • In the command line that starts Visual FoxPro, specify the -C switch and the name of the configuration file that you want to use (including a path if necessary). Do not put a space between the switch and the file name.

    -or-

  • In Windows, double-click the name of the configuration file to use. Visual FoxPro will start using the configuration file you have selected.

If you want to avoid using any configuration file, including the default file Config.fpw, you can suppress all configuration files. This causes Visual FoxPro to use only the default settings established in the Options dialog box.

To suppress a configuration file

  • In the command line that starts Visual FoxPro, add the -C switch with nothing after it.

    For example, to avoid any configuration file found in the startup directory or the system path, use this command line:

    Vfp8.exe -C

See Also

Visual FoxPro Environment Settings | Using Command-Line Options When Starting Visual FoxPro | Compiling an Application | Adding Setup Code to a Menu System | Designing Menus and Toolbars | Special Terms for Configuration Files | _STARTUP System Variable


Using Command-Line Options When Starting Visual FoxPro

In addition to using the SET command and a configuration file, you can specify startup options by including a command-line switch. For example, using command-line options, you can suppress the display of the Visual FoxPro sign-on screen or specify a non-default configuration file. The following table lists the command-line switches available in Visual FoxPro.

To use a command-line switch

  • Add the switch after Vfp8.exe or any Visual FoxPro-created .exe on the command line or in a shortcut.

    If the command-line switch includes a file name, do not put any spaces between the switch and the file name.

Command-line switches for Visual FoxPro

Switch Description
-A
 Ignores the default configuration file and Windows registry settings.
-BFileName,Duration
Displays your own bitmap (.bmp), .gif, or .jpg graphic file and specifies its duration when Visual FoxPro is started. If the bitmap you specify cannot be located, a bitmap is not displayed when Visual FoxPro is started. The -b command line switch can also be included in a Visual FoxPro shortcut.

-CFileName
 Specifies a configuration file (including path if necessary) other than the default (Config.fpw).
-DFileName
 Specifies a runtime .DLL file (including path if necessary) other than the default.
-LFileName
 Specifies a resource file (including path if necessary) other than the default, which allows you to use Visual FoxPro in a language other than the current language specified by Windows.
-R
 In earlier versions, refreshes the Windows registry with information about Visual FoxPro, such as associations for Visual FoxPro files. In later versions, use /regserver.
-T
 Suppresses the display of the Visual FoxPro sign-on screen (banner). For more information, see Preventing Display of the Sign-On Screen.
/?
List the available Command line arguments. Available in Visual FoxPro 7 and later.

/regserver
 Registers Visual FoxPro default registry keys.
REGSVR32 <server.DLL>
 Registers a .DLL component.
/unregserver
 Removes Visual FoxPro default registry keys.
/u <server.DLL>
 Removes a .dll component.

If the command switch requires arguments such as a file name, do not put a space between the switch and the argument. Separate multiple options with single spaces. For example, to specify a configuration file, use a command such as:

C:\Program Files\Microsoft Visual FoxPro 8\VFP8.EXE -CC:\MYAPP\MYAPP.FPW

Preventing Display of the Sign-On Screen

By default, when Visual FoxPro starts, it displays a sign-on screen that shows the Visual FoxPro logo, version number, and other information. If you prefer that users of your application not see this sign-on screen, you can prevent Visual FoxPro from displaying it.

To prevent the display of the sign-on screen

  • Add the -T switch to the Visual FoxPro command line as a command-line switch.
    Note For compatibility with earlier versions of Visual FoxPro, you can also set switches using the FOXPROWCFG DOS environment variable, but this method is not recommended.

For example, use a command such as:

VFP8.EXE -T

See Also

Visual FoxPro Environment Settings | Setting Configuration Options at Startup | Customizing the Visual FoxPro Environment | Configuring Visual FoxPro Toolbars


Customizing the Appearance of Applications

You can modify the appearance of your application without changing your application code by:

  • Changing the default menu system.
  • Changing the default title.
  • Changing the default application icon.

Changing the Default Visual FoxPro Menus

You can add your own menus and menu options to distributed applications by using the Menu Designer. If you don't create your own menu, the run-time environment displays a default Visual FoxPro menu.

Changing the Default Title

Your application runs in the main Visual FoxPro window. By default, the text "Microsoft Visual FoxPro" appears in the title bar.

To customize the title of the main Visual FoxPro window

  • Add the following statement to your configuration file.
    TITLE = cMyTitle

    Replace cMyTitle with the title of the main window of your application.

To include a Visual FoxPro function as part of the title, use the Caption property of the main window as in the following example.

COMMAND=_SCREEN.Caption="Visual FoxPro " + VERSION(4)

Changing the Default Application Icon

After your application is compiled, the default Visual FoxPro icon appears in the Windows Explorer or Start Menu as the application icon. You can use the generic icon that is supplied by Visual FoxPro or design your own.

If you want to display your own icon, create an icon (.ico) file with two images: one small (16-by-16) and one standard (32-by-32). Create both images as 16-color icons.

You can change the default Visual FoxPro icon in the Project Info dialog box of the Project menu.

To change the default application icon using the Project Manager

  1. In the Project Manager Window, select the main file for your project.
  2. From the Project menu, choose Project Info and then select the Project tab.
  3. Choose Attach icon.
  4. Choose Icon and then select an icon (.ico) file to assign to your project.

See Also

Designing Menus and Toolbars | Ensuring Correct Run-Time Behavior | Building Applications


Configuring Visual FoxPro Toolbars

Visual FoxPro includes the following customizable toolbars.

Tool | Associated Toolbars | Command
Database Designer | Database | CREATE DATABASE
Form Designer | Form Controls Form Designer Color Palette Layout | CREATE FORM
Print Preview | Print Preview |
Query Designer | Query Designer | CREATE QUERY
Report Designer | Report Controls Report Designer Color Palette Layout | CREATE REPORT

Activating and Deactivating Toolbars

By default, only the Standard toolbar is visible. When you use a Visual FoxPro designer tool (for example, the Form Designer), the designer displays the toolbars that you commonly need when working with that designer tool. However, you can activate a toolbar any time you require it.

To activate a toolbar

  • Run the associated tool.

    – or –

  1. From the View menu, select Toolbars.
  2. In the Toolbars dialog box, select the toolbar you want to activate.
  3. Choose OK.

To deactivate a toolbar

  • Close the associated tool.

    – or –

  1. From the View menu, select Toolbars.
  2. In the Toolbars dialog box, clear the toolbar you want to deactivate.

You can also programmatically deactivate and activate toolbars that have been previously activated by using the DEACTIVATE WINDOW or ACTIVATE WINDOW commands as in the following example.

IF WVISIBLE ("Color Palette")
DEACTIVATE WINDOW("Color Palette")
ENDIF

You can place as many toolbars on your screen as you need while working. You can dock toolbars to the top, bottom, or sides of your screen to customize your working environment. Visual FoxPro saves the positions of the toolbars so they remain where you last placed them.

To dock a toolbar

  • Drag the toolbar to the top, bottom, or side of your screen.

-or-

  • Use the DOCK WINDOW command to dock the toolbar.

Customizing Existing Toolbars

The easiest way to create custom toolbars is by modifying the toolbars already provided with Visual FoxPro. You can:

  • Modify an existing toolbar by adding or removing buttons.
  • Create a new toolbar that contains buttons from existing toolbars.

You can also define custom toolbars by creating a custom toolbar class using code. For details, see Designing Menus and Toolbars.

Modifying an Existing Visual FoxPro Toolbar

You can modify any of the toolbars provided with Visual FoxPro. For example, you might want to remove a button from an existing toolbar, or copy buttons from one toolbar to another.

To modify a Visual FoxPro toolbar

  1. From the View menu, choose Toolbars.
  2. Select the toolbar you want to customize and choose Customize.
  3. Remove buttons from the toolbar by dragging them off of the toolbar.
  4. Add buttons to the toolbar by selecting an appropriate category in the Customize Toolbar dialog box and then dragging the appropriate buttons onto the toolbar.
  5. Complete the toolbar by choosing Close in the Customize Toolbar dialog box and then closing the toolbar window.
    Tip If you change a Visual FoxPro toolbar, you can restore it to its original configuration of buttons by selecting the toolbar in the Toolbar dialog box and then choosing Reset.

Creating a New Toolbar from Existing Toolbars

You can create your own toolbars comprised of buttons from other toolbars.

To create your own toolbar

  1. From the View menu, choose Toolbars.
  2. Choose New.
  3. In the New Toolbar dialog box, name the toolbar.
  4. Add buttons to the toolbar by selecting a category in the Customize Toolbar dialog box and then dragging the appropriate buttons onto the toolbar.
  5. You can rearrange buttons on the toolbar by dragging them to the desired position.
  6. Complete the toolbar by choosing Close in the Customize Toolbar dialog box and then closing the toolbar window.
    Note You cannot reset buttons on a toolbar you create.

To delete a toolbar you created

  1. From the View menu, choose Toolbars.
  2. Select the toolbar you want to delete.
  3. Choose Delete.
  4. Choose OK to confirm the deletion.
    Note You cannot delete toolbars provided by Visual FoxPro.

See Also

Visual FoxPro Environment Settings | Using Command-Line Options When Starting Visual FoxPro | Setting Editor Options | Customizing the Visual FoxPro Environment | Designing Menus and Toolbars


Docking Windows

You can dock certain Visual FoxPro Integrated Development Environment (IDE) windows to the Visual FoxPro desktop window or with each other. The following windows are dockable:

  • Call Stack
  • Command
  • Data Session (View)
  • Debugger
  • Document View
  • Locals
  • Output
  • Properties
  • Trace
  • Watch
Note Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window.

When you drag a dockable window to a Visual FoxPro desktop window boundary, the dockable window repositions itself against the chosen boundary. The state and location of docked windows persist from the last user session.

To dock windows and toolbars programmatically and retrieve their dock states, see DOCK WINDOW Command and ADOCKSTATE( ) Function.

You can change the dockable status of a dockable window.

To enable or disable dockable status

  1. Right-click the title bar of an open and dockable window.
  2. Click Dockable to enable or disable the dockable status of the window. A check mark appears when the window is dockable.

-or-

  1. Click the desired window to make the window active.
  2. On the Window menu, click Dockable to enable or disable the dockable status of the window. A check mark appears when the window is dockable.

For more information about retrieving the dockable status for a window programmatically, see WDOCKABLE( ) Function.

Docking Modes

You can dock windows in three different modes:

  • Normal docking

    Windows dock to a boundary of the Visual FoxPro desktop window.

  • Linked docking

    Windows dock to each other and share a dockable window container.

  • Tabbed docking

    Windows dock to each other and share the full window through the use of tabs.

You can use tabbed docking and linked docking together.

To create normal docking

  1. Make sure the docking status of the window or windows is set to Dockable.
  2. Drag the window title bar to a boundary of the Visual FoxPro desktop window.

To create linked docking

  1. Make sure the docking status of the window or windows is set to Dockable.
  2. Drag the title bar of the desired window to a boundary or docking zone of the target window.

The docking zone is indicated when the window you are dragging changes shape to fit the target window. Visual FoxPro creates an additional title bar for link-docked windows.

To create tabbed docking

  1. Make sure the docking status of the window or windows is set to Dockable.
  2. Drag the title bar of the desired window to the title bar of the target window.

Visual FoxPro adds tabs to the bottom boundary of the docked windows.

To undock windows

  • To undock normal-docked windows, drag the title bar of the desired window away from the shared window boundary.

-or-

  • To undock link-docked windows, drag the title bar of the desired window away from the shared window.

-or-

  • To undock tab-docked windows, drag the tab of the desired window away from the shared window.

You can disable docking behavior by holding the CTRL key while dragging a window.

Deleting or editing the FoxUser.dbf resource file, which contains your settings, restores or changes your default window settings. For more information about altering your settings, see FoxUser Resource File Structure.

See Also

Visual FoxPro System Windows | Document View Window


Setting Editor Options

You can configure the window of the Visual FoxPro editor to display text the way you want such as setting the font, text alignment, or syntax coloring. You can also make the editor easier to use by setting preferences for indentation, wordwrap, automatic backup copies, and other features.

To configure the editing window, set your preferences in the Edit Properties dialog box that appears after you open a program or text file open and select Properties from the Edit menu. For details about settings you can configure, see Edit Properties Dialog Box.

To display the Edit Properties dialog box

  1. Open the editing window for a program, text file, or control.
  2. From the Edit menu that becomes active, select Properties.
    Tip You can display the Font dialog box directly by right-clicking the editing window and choosing Font from the shortcut menu.

For more information about opening a program or text file, see Creating Programs.

By default, the settings that you make in the Edit Properties dialog box persist for that file. For example, if you change the font, the font for all text in the current window changes. If you open another editing window, the default settings apply.

You can choose to save your settings so that they apply to all files of the same type, or not to save the new settings at all. If you apply your settings to similar file types, Visual FoxPro uses the settings you make when you edit files with the same extension, for example, all .prg files, or all method code in the Form Designer.

To avoid persisting changes to editor settings

  • In the Edit Properties window, clear the Save Preferences option and then click OK.

To apply editor options to similar files

  • In the Edit Properties dialog box, select Use These Preferences As Default and then click OK.

You can also set the color and font that the editor uses to identify keywords, comments, and other elements of programs. For details, see Editor Tab, Options Dialog Box.

See Also

Visual FoxPro Environment Settings | Editing Window | Restoring the Visual FoxPro Interactive Environment | Editor Tab, Options Dialog Box | Changing Configuration Settings in the Windows Registry | Displaying and Printing Source Code Files in Color


Displaying and Printing Source Code Files in Color

Visual FoxPro can display color syntax in the editing window for program files, methods, stored procedures, and memos. However, to display color syntax in run-time applications, Visual FoxPro must be configured to display color syntax. Additionally, run-time applications display only the default color settings because run-time applications do not check the registry for options that you change in the Options dialog box, which contains the default color settings for color syntax.

Displaying Color Syntax

To display color syntax

  1. To display the Edit Properties dialog box, follow the procedure in Setting Editor Options.
  2. In the Edit Properties dialog box, select the Syntax coloring check box.

For more information about preferences you can set for the editing window and default settings for color syntax, see Edit Properties Dialog Box and Editor Tab, Options Dialog Box.

Enabling Color Syntax Printing

You can print source code files in colors that match the appearance of code syntax in the editing window. Visual FoxPro supports color printing for source code where color syntax appears, including program files, methods, stored procedures, and memos.

To print your code files in color, you must have a color printer to select the color printing options available for your printer.

Note Background colors set in the Editor tab of the Options dialog box are not printed.

To make color printing available for source code files

  1. Open the program file or code you want to print.
  2. From the File menu, select Print.
  3. In the Print dialog box, select your color printer, and then click Properties.
  4. Select the color printing options available for your printer.

If you select color printing for source code files, hyperlinks appear underlined.

To display your file in color to the screen, use the TYPE command. To send your file to a connected color printer, use TYPE ... TO PRINTER.

See Also

Visual FoxPro Environment Settings | Editing Window | Print Dialog Box | TYPE Command


Automating Keystroke Tasks with Macros

If you find yourself repeating the same keystrokes, or if you want to automate some keystroke tasks for your users, you can record and save these keystrokes in macros by using the Macros dialog box.

Note To use macros, any keyboard you use must have function keys F1 to F9, and a CTRL key or an ALT key.

In This Section

Clearing Macro Definitions
Provides instructions on how to use the Macros dialog box to clear macro key definitions.
Creating, Saving, and Restoring Macro Sets
Describes how you can create macro sets through the Macros dialog box.
Editing Macros
Explains how the Macros dialog box makes it possible to edit existing macros.
Recording Macros
Describes the steps to record keystroke macros in Visual FoxPro.
Setting a Default Macro Set
Explains how you can create and set your own default macro set in Visual FoxPro.

Related Sections

Visual FoxPro Environment Settings
Describes different ways to change Visual FoxPro environment settings such as using the Options dialog box, setting configuration options at program startup, using command-line options. You can configure Visual FoxPro toolbars, dock windows, set editor options, and customize the appearance of your applications without altering code.
Productivity Tools
Discusses the different tools available to help make creating Visual FoxPro applications easier and faster.


Clearing Macro Definitions

You can clear macro key definitions through the Macros dialog box.

To clear a macro definition

  1. From the Macros dialog box, select a macro from the Individual Macro list.
  2. Choose Clear.

See Also

Automating Keystroke Tasks with Macros | Macros Dialog Box | Recording Macros | Editing Macros | Creating, Saving, and Restoring Macro Sets | Setting a Default Macro Set


Creating, Saving, and Restoring Macro Sets

A macro set is a defined set of keys and their associated macros stored in a file with the extension .FKY. You can create macro sets through the Macros dialog box.

To create a macro set

  1. From the Macros dialog box, create individual key macros.
  2. Choose Save.
  3. In the Save Current Macros To box, enter a name for the macro set and choose Save.

To restore a macro set

  1. From the Macros dialog box, choose Restore.
  2. Select a macro set file and then choose OK.

See Also

Automating Keystroke Tasks with Macros | CLEAR Commands | Macros Dialog Box | RESTORE MACROS Command | SAVE MACROS Command | Editing Macros | Setting a Default Macro Set | Clearing Macro Definitions | Recording Macros


Editing Macros

You can edit existing macros through the Macros dialog box.

To edit a macro

  1. From the Macros dialog box, select a macro from the Individual Macro list and then choose Edit.
  2. Modify the macro contents.
  3. Choose OK.

See Also

Automating Keystroke Tasks with Macros | CLEAR Commands | Macros Dialog Box | SET FUNCTION Command | Recording Macros | Clearing Macro Definitions | Creating, Saving, and Restoring Macro Sets | Setting a Default Macro Set


Recording Macros

You can record keystroke macros in Visual FoxPro through the Macros dialog box.

To record a macro

  1. From the Tools menu, choose Macros.
  2. In the Macros dialog box, choose Record.
  3. Press the key or type the key combination you want to define.
  4. Enter a name for the macro or accept the default and then choose OK.

Visual FoxPro begins recording every keystroke.

Note Macro names cannot contain spaces.

To stop recording a macro

  1. From the Tools menu, choose Macros.
  2. In the Stop Recording Macro dialog box, choose from the following:
    • To save the macro as is, choose OK.
    • To continue recording, choose Continue.
    • To discard the macro, choose Discard.
    • To insert a literal keystroke (the literal meaning of a key instead of any meaning currently assigned to it), choose Insert Literal.
    • To insert a pause, select Seconds, add the amount of time, and choose Insert Pause.

See Also

Automating Keystroke Tasks with Macros | Macros Dialog Box | ON KEY LABEL Command | SET FUNCTION Command | Stop Recording Macro Dialog Box | Clearing Macro Definitions | Editing Macros | Creating, Saving, and Restoring Macro Sets | Setting a Default Macro Set


Setting a Default Macro Set

A default macro set exists when Visual FoxPro starts. You can create and set your own default macro set through the Macros dialog box.

To set a default macro set

  1. From the Macros dialog box, create or restore a macro set.
  2. Choose Set Default.

See Also

Automating Keystroke Tasks with Macros | Creating, Saving, and Restoring Macro Sets | Macros Dialog Box | RESTORE MACROS Command | Clearing Macro Definitions | Editing Macros | Creating, Saving, and Restoring Macro Sets | Recording Macros


Restoring the Visual FoxPro Interactive Environment

If you want to close down all program operations and return Visual FoxPro to its interactive state, issue the following commands in order inside the Command window or in the program called just before you quit Visual FoxPro.

CLEAR ALL
CLOSE ALL
CLEAR PROGRAM

CLEAR ALL removes all objects from memory, which, in turn, closes all private data sessions and cursors.

CLOSE ALL, after CLEAR ALL has completed successfully, closes all databases, tables, and cursors in data session 1, the default Visual FoxPro data session.

CLEAR PROGRAM clears the compiled program buffer of the most recently executed programs. CLEAR PROGRAM forces Visual FoxPro to read the programs from disk, rather than from the program buffer.

Cleaning Up during Transactions If transactions are in progress, use the END TRANSACTION Command for each level of transaction before issuing CLEAR ALL, CLOSE ALL, and CLEAR PROGRAM.

Cleaning Up during Buffered Updates If buffered updates are in progress, use either the TABLEUPDATE( ) Function or TABLEREVERT( ) Function for each cursor with buffered updates before issuing CLEAR ALL, CLOSE ALL, and CLEAR PROGRAM.

See Also

Customizing the Visual FoxPro Environment | Setting Editor Options | CLEAR Commands | CLOSE Commands | END TRANSACTION Command | TABLEUPDATE( ) Function | TABLEREVERT( ) Function | Command Window | Operating the Command Window


Accessibility for People with Disabilities

Microsoft is committed to making its products and services easier for everyone to use. This Help file provides information about how to make Microsoft Windows and Visual FoxPro more accessible as well as other features, products, and services that can help improve accessibility for people with disabilities.

Note The information in this section about Microsoft Windows applies only to users who purchased Microsoft Windows in the United States. If you purchased Microsoft Windows outside the United States, your Windows package contains a subsidiary information card listing Microsoft Support Services telephone numbers and addresses. You can contact your subsidiary to find out whether the type of products and services described in this Help file are available in your area.

For information about technical support services for people who are deaf or hard-of-hearing, see Microsoft Visual FoxPro Technical Support.

You can learn more about Microsoft's commitment to making its products and services more accessible by visiting the Accessiblity Web site at http://www.microsoft.com/enable/.

In This Section

Customizing Microsoft Windows for Accessibility
Provides information about customizing the Microsoft Windows environment to make your computer more accessible.
Customizing Visual FoxPro for Accessibility
Provides information about how to customize Visual FoxPro for accessibility.
Utilities and Resources for Enhancing Accessibility
Provides information about accessibility products, services, and resources available from Microsoft and other organizations.
Microsoft Documentation in Alternative Formats
Provides information about how to obtain alternative and more accessible documentation formats.

See Also

Product Support
Provides information about Microsoft technical support for Visual FoxPro and copyright information.
Using the Accessibility Browser
Provides information about using the Accessibility Browser to help make your Visual FoxPro applications more accessible for other users.


Customizing Microsoft Windows for Accessibility

There are many ways you can customize Microsoft Windows to make your computer more accessible.

  • Windows includes accessibility features that are useful for individuals who have difficulty typing or using a mouse, have moderately impaired vision, or who are deaf or hard-of-hearing. You can install these features during the setup process, or you can add them later from your Windows installation disks. Look up "accessibility" in the Windows Help index for information about installing and using these features.
  • You can add many of the features that make current versions of Windows more accessible to earlier versions of Windows and to MS-DOS via Access Packs. You can download these files by modem, or you can order them on disks from Microsoft.
  • You can use Control Panel and other built-in features to adjust the appearance and behavior of Windows to suit varying vision and motor abilities. These include adjusting colors and sizes, sound volume, and the behavior of the mouse and keyboard.
  • If you have difficulty using the standard QWERTY keyboard layout, Dvorak keyboard layouts make the most frequently typed characters on a keyboard more accessible. You can choose from three Dvorak layouts: two-handed, left-handed only, and right-handed only. You do not have to purchase any special equipment to use these features.

The specific features available, and whether they are built in or must be obtained separately, depend on which operating system you are using.

To Download the Access Packs, Application Notes, and Alternative Keyboard Layouts by Modem

If you have a modem, you can download these files from the following network services:

  • Microsoft's World Wide Web site on the Internet. On the Microsoft home page (http://www.microsoft.com), point to All Products at the top of the page. When the menu appears, click Microsoft Accessibility. Information and downloadable resources are available from this page.
  • Microsoft's Internet server, ftp.microsoft.com, in /Softlib/MSLFiles.
  • MSN, the Microsoft Network online service.
  • CompuServe. Type GO MSL.
  • Various user-group bulletin boards.

To Order the Access Packs, Application Notes, and Alternative Keyboard Layouts on Disks by Phone

If you do not have a modem, you can order the Access Packs, Application Notes, and Alternative Layouts on disks within the United States by calling Microsoft Sales Information Center at (800) 426-9400 (voice) or (800) 892-5234 (TTY).

In Canada, you can call (905) 568-3503 or (905) 568-9641 (text telephone).

See Also

Accessibility for People with Disabilities | Customizing Visual FoxPro for Accessibility | Utilities and Resources for Enhancing Accessibility | Microsoft Documentation in Alternative Formats


Customizing Visual FoxPro for Accessibility

You can use the following steps to enhance accessibility in Visual FoxPro:

Enlarging Toolbar Buttons

To view enlarged toolbar buttons

  1. From the View menu, click Toolbars.
  2. Select the Large buttons check box.

Enlarging Text in the Code Window

To view enlarged text in the Code Window

  • From the Format menu, click Font, and choose the font size you want.

Enlarging Text in the Debugger

To view enlarged text in the Debugger

  1. On the Tools menu, click Options.
  2. In the Options dialog box, click the Debug tab, and then click Font.
  3. Select the font and font size you want.

See Also

Accessibility for People with Disabilities | Customizing Microsoft Windows for Accessibility | Utilities and Resources for Enhancing Accessibility | Microsoft Documentation in Alternative Formats


Utilities and Resources for Enhancing Accessibility

Microsoft and other organizations provide products, services, and resources that make it easier to use personal computers. The following list includes some of the different types of available products:

  • Programs that enlarge or alter the color of information on the screen
  • Programs that describe information on the screen in Braille or synthesized speech
  • Hardware and software utilities that modify the behavior of the mouse and keyboard
  • Programs that make it possible for people to "type" using a mouse or their voice
  • Word or phrase prediction software that makes it possible for people to type more quickly and with fewer keystrokes
  • Alternate input devices, such as single switch or puff-and-sip devices

Microsoft Active Accessibility

Visual FoxPro supports Microsoft Active Accessibility, which is a COM-based Windows developer technology that allows programs and the operating system to work more compatibly with accessibility aids, for example, screen readers such as Microsoft Magnifier. For more information about Microsoft Active Accessibility, visit MSDN at http://msdn.microsoft.com.

Additional Microsoft Products and Services for People with Disabilities

For more information, contact:

Microsoft Sales Information Center
One Microsoft Way
Redmond, WA 98052-6393 		World Wide Web:
Voice telephone:
Teletypewriter (TTY): 		http://www.microsoft.com
(800) 426-9400
(800) 892-5234

Directories of Computer Products That Help People with Disabilities

The Trace R&D Center at the University of Wisconsin–Madison produces a book and a compact disc describing products that help people with disabilities use computers. The book, titled Trace ResourceBook, provides descriptions and photographs of about 2,000 products. The compact disc, titled CO-NET CD, provides a database of more than 18,000 products and other information for people with disabilities. It is issued twice a year.

To obtain these directories, contact:

Trace R&D Center
University of Wisconsin
S-151 Waisman Center
1500 Highland Avenue
Madison, WI 53705-2280 		World Wide Web:
Fax:
 http://trace.wisc.edu
(608) 262-8848

Referrals to Assistive Technology Programs and Trained Evaluators

For general information and recommendations on how computers can help specific requirements, you should consult a trained evaluator. An assistive technology program in your area will provide referrals to programs and services that are available to you.

To locate the assistive technology program nearest you, contact:

National Information System
University of South Carolina
Center for Developmental Disabilities
Columbia, SC 29208 		Voice/text telephone:
Fax: 		(803) 935-5231
(803) 935-5059

See Also

Accessibility for People with Disabilities | Customizing Microsoft Windows for Accessibility | Customizing Visual FoxPro for Accessibility | Microsoft Documentation in Alternative Formats


Microsoft Documentation in Alternative Formats

If you have difficulty reading or handling printed documentation, you can obtain many Microsoft publications and documents for Microsoft products in more accessible formats. Microsoft provides a number of documents for Microsoft products in more accessible formats. For more information, visit the Microsoft Accessiblity Web site at http://www.microsoft.com/enable/.

You can also obtain Microsoft publications from Recording for the Blind & Dyslexic, Inc. Recording for the Blind & Dyslexic distributes these documents to registered eligible members of their distribution service, either on audio cassettes or on disks. The Recording for the Blind & Dyslexic collection contains more than 80,000 titles, including Microsoft product documentation and books from Microsoft Press.

You can contact Recording for the Blind & Dyslexic at the following address or phone numbers for information about eligibility and availability of Microsoft product documentation and books from Microsoft Press:

Recording for the Blind & Dyslexic, Inc.
20 Roszel Road
Princeton, NJ 08540 		Phone:

Fax:
World Wide Web: 		(609) 452-0606 or (800) 221-4792
(609) 987-8116
http://www.rfbd.org

See Also

Accessibility for People with Disabilities | Customizing Microsoft Windows for Accessibility | Customizing Visual FoxPro for Accessibility | Utilities and Resources for Enhancing Accessibility


Using Visual FoxPro

Visual FoxPro provides the environment and tools you need to create and manage high-performance database applications and components. With its robust tools and data-centric, object-oriented language, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.

In This Section

Overview of Visual FoxPro Features
Describes the major features of Visual FoxPro that you expect in a database management system (DBMS) and as a front end for developing client/server applications, such as rapid application and interface creation, powerful object-oriented programming, event handling, testing and debugging capabilities, flexibility in interacting with other applications.
Developing Visual FoxPro Applications
Explains concepts about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Development Productivity Tools
Explains that Visual FoxPro provides developer tools for application development within the FoxPro application and the FoxPro language.

Related Sections

Getting Started with Visual FoxPro
Provides information about where to find the Readme file, installing and upgrading from previous versions, configuring Visual FoxPro, and customizing the development environment.
Reference
Includes Visual FoxPro general, programming language, user interface, and error message reference topics.
Samples
Contains Visual FoxPro class library, server, solutions, and foundation class code samples that you can use for experimenting with and learning Visual FoxPro features.
Walkthroughs
Provides a list of common scenarios in Visual FoxPro and gives step-by-step instructions for each, making it a good place to start learning about features.


Overview of Visual FoxPro Features

Microsoft Visual FoxPro gives you more of everything you have come to expect in a database management system (DBMS) — speed, power, and flexibility. In addition, Visual FoxPro leads you into the next generation by providing object and event models that help you create and modify applications faster than ever before.

The following topics walk you through some of the major features in Visual FoxPro. For information on the newest enhancements in this version of Visual FoxPro, see What's New in Visual FoxPro.

In This Section

Rapid Application Creation
Discusses how you can develop applications rapidly with help from Visual FoxPro wizards, builders, toolbars, and designers, and implement them quickly using the Visual FoxPro object and event models.
Advantages of More Power
Describes how you can take advantage of Visual FoxPro's object-oriented programming capabilities as well as features such as Rushmore Query Optimization technology to improve performance and speed up application development.
User Interface Creation without Programming
Discusses the powerful controls provided by Visual FoxPro that give you interfaces that require little or no coding.
Application Development with Several Developers
Discusses using Visual FoxPro to enable simultaneous access to database components and using source control programs with the Project Manager to track and protect changes to your source code.
Interaction with Other Applications
Provides information about sharing data with other applications, such as Microsoft Excel and Microsoft Word, using objects from other applications, and controlling other applications using automation.
Client/Server Solution Development
Discusses how you can use Visual FoxPro as a front end for developing robust client/server applications. It combines the higher-level support of updateable views of server data with direct access to native server syntax using SQL pass-through.

Related Sections

Getting Started with Visual FoxPro
Provides links to information about installing, upgrading, and customizing Visual FoxPro, as well as accessing the latest readme files.
Using Visual FoxPro
Provides information on Visual FoxPro programming features and productivity tools, as well as sections on development of Visual FoxPro applications.
Walkthroughs
Provides a list of common scenarios and step-by-step guides that enable you to learn how to create different types of applications and components in Visual FoxPro.
Customizing the Visual FoxPro Environment
Discusses settings that enable you to customize your development environment, including the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Development Productivity Tools
Provides information on developer tools for application development within the Visual FoxPro application and the language.


Rapid Application Creation

You can develop applications rapidly with help from Visual FoxPro wizards, builders, toolbars, and designers. In addition, with the Visual FoxPro object and event models, you can create prototypes and implement applications quickly.

Getting Quick Results with Wizards and Builders

Using wizards and builders, you can have any or all of the components of your application completed in a matter of minutes. In addition, if any component you create with a wizard or builder does not fully meet your needs, you can alter the component using a designer.

For quick results, wizards are the answer. They provide step-by-step prompts for common tasks you perform in Visual FoxPro. For example, the Table Wizard guides you through the process of creating a table, the Form Wizard creates a form, and the Web Publishing Wizard helps you create a Web page that searches your tables.

Take a look at what you can do:

  • Develop Instant Applications Using the Application Wizard, you can quickly create an application by using your tables and forms, or by using a sample set of application components.
  • Create an Internet Web Page You can create a Web page that provides Web surfers with search and retrieval access to your tables.
  • Add Page Frames to Forms If you choose more fields than can fit on the form, you can add a page frame to display the additional fields on additional pages.
  • Populate Pivot Tables through ODBC or OLE DB The PivotTable Wizard uses the Visual FoxPro ODBC or OLE DB driver.
  • Show Nulls in a Cross-Tab Report The Cross-Tab Wizard now supports displaying null values.
  • Move Your Data to a Back-End Server You can move Visual FoxPro databases, tables, and views from your system to a back-end server with the SQL Server Upsizing Wizard.

If you are in a hurry, use the table in Wizards Overview to select a wizard, and begin creating your application or component.

If you do not want to experiment with your own data and application components, use the samples provided with Visual FoxPro, located in the ...\Samples\Data directory.

Taking Shortcuts with Toolbars

Like other Microsoft applications, Visual FoxPro includes toolbars containing buttons that represent common tasks you perform or objects you use frequently. To perform a specific task or use a particular object, choose the appropriate button.

You can customize the toolbars that come with Visual FoxPro. You can also define custom toolbars for the applications you write. For more information about toolbars, see Customizing the Visual FoxPro Environment or Designing Menus and Toolbars.

Building Controls Quickly

Just as wizards can help to create reports and forms, builders are visual tools that help you design controls to your specifications. Builders can save you time when you are setting up many forms or prototyping applications. All you do is start the builder and answer a series of questions. Using your answers, the builder sets properties for the control you are adding.

Add a Combo Box to Your Form Suppose you want to enhance a simple form you created by adding the ability to select field values from a list, rather than moving through all the records with VCR buttons and viewing the values in a text box. Just replace the current text box with a combo box and use a builder to set the properties.

Modify Existing Controls with a Builder If you want to change an existing control, you can select the control and use a builder to help you set the control's properties.

For example, the Combo Box Builder is a tabbed dialog box that helps you design a combo box on a form. A combo box gives you the same view of a value as a text box control, but allows you to choose from a list like a list box control. With this builder you can set properties of a combo box. As you set each property, the control on the form changes to match the settings.

Build a Grid Control To display a small spreadsheet-like view of your data, you can use a grid control. Even if you aren't familiar with all the properties of a grid control, you can still take advantage of their functionality using a builder. The builder helps you choose the fields for your grid, select a style and layout, and establish relationships between tables bound to the grid control. As you make changes in the builder, they are reflected in the Form Designer.

For more information, see Builders.

See Also

Overview of Visual FoxPro Features | User Interface Creation without Programming | Form Designer | Wizards Overview | Customizing the Visual FoxPro Environment


Advantages of More Power

Visual FoxPro is much more powerful than its predecessors. Object-oriented programming speeds up application development through features such as subclassing. The Visual FoxPro event model eliminates the need to use a Foundation READ, or to write event handlers. Optimizing your system settings and taking advantage of Rushmore Query Optimization technology improves the performance of Visual FoxPro.

Harnessing the Power of Object-Oriented Programming

Using the Visual FoxPro object model, you can employ all the features of object-oriented programming including inheritance, encapsulation, polymorphism, and subclassing. For details about object-oriented programming with Visual FoxPro, see Object-Oriented Programming.

You can speed up application development by using classes. For example, you can create a basic form, toolbar, or page frame by using the form, toolbar, or page frame base class provided with Visual FoxPro.

Then you can reuse your code and forms by subclassing the classes you defined. For example, you can subclass the Form base class to create a custom class that automatically gives all the forms in your application the look and feel you want.

The Visual FoxPro class model gives you extensive control over the objects in your application. You have as much control of the appearance and behavior of objects on forms at run time as you do in the Form Designer at design time.

With Visual FoxPro, you can create classes visually with the Class Designer or programmatically with the DEFINE CLASS Command. For more information, see Object-Oriented Programming.

Handling Events with Ease

With Visual FoxPro you can create fully event-driven applications. You can access all standard Windows events such as mouse movements that permit dragging or dropping objects. You can control events visually through the Properties window or programmatically through the Visual FoxPro language. For more information about the event model, see Understanding the Event Model.

Testing and Debugging Immediately

Using the debug environment you can test and debug your code at the same time you design each component of your application and write the code. The Visual FoxPro language has been enhanced to include support for debugging capabilities, collection properties, checking the lock status of files and the current record, Value tips, and more. Also, the debugging tools work independently from the main application and do not interfere with the interface you are trying to test.

Test as You Design The enhanced Visual FoxPro development environment gives you more power to test your component design and code. For example, if you are designing a form, you can click the Run button to run the code. If you want to change something, just click the Design button and make your changes.

Catch Syntax Errors Early The editor now features color-coded editing: you can specify colors for syntax, normal text, variables, comments, and more in the Edit Properties Dialog Box. If you mistype a command or keyword, you'll know right away because it's the wrong color.

Debug with Power

You can debug and monitor your application components more easily in this version of Visual FoxPro using the Debugger Window.

  • View Properties of an Object In the debugger you can view the elements within a collection or array using the Watch Window to show a hierarchical display of an object's properties.
  • Trace the Execution Process of Your Code In the Trace Window you can see each line of code as it executes and check the values of all variables, properties, and environment settings.
  • Control Execution with Breakpoints Using breakpoints you can control when execution stops using one of four types of breakpoints. You can stop at a particular line, when a certain value changes, if a condition evaluates to true, or if a condition for a certain line is true.
  • Set Asserts and Display Assert Messages You can use the ASSERT Command to specify conditions that verify that the code is running properly. When an error occurs, the Debug Output Window records the message.
  • Check the Current Value of a Variable To quickly check values you can place the cursor over a variable in the Trace Window to display a Value Tip.
  • Watch and Change Values In the Watch Window and Locals Window you can change values for properties or variables while you run the code.
  • Display Output from Message Requests In the Debug Output Window you can conveniently display interactive or coded information requests in a separate window from the active window or screen.
  • Use a Coverage Log File In the Debugger Window you can use the coverage option to log the execution information about your code such as how long the line took to execute, the line number, and more.
  • Use the Call Stack In the Call Stack Window you can view the program calling path. Reading the Call Stack is one of the most effective techniques for debugging.

For more information about testing and debugging your application, see Testing and Debugging Applications.

Optimizing Your System

Visual FoxPro brings you improved performance across all these product areas:

  • Engine
  • Form/Object
  • OLE
  • Client/Server
  • Wizards/Builders
  • Language

You can also improve performance by enhancing startup speed and optimizing SET commands. For more information about optimizing your system, see Optimizing Your System.

Optimizing Applications with Rushmore Query Optimization Technology

You can dramatically improve the performance of queries by using Rushmore technology. Rushmore Query Optimization is a technology for rapidly selecting sets of records from tables. It can reduce query response times from minutes or hours to seconds. For more information about using the Rushmore technology, see Optimizing Applications.

See Also

Overview of Visual FoxPro Features | Application Development with Several Developers | Object-Oriented Programming | Rapid Application Creation | Debugger Window


User Interface Creation without Programming

Visual FoxPro provides powerful controls that you add with the Form Designer which gives you interfaces that require little or no coding. For example, having the grid control linked to one of your tables makes developing one-to-many forms easy. Just drag a table onto a form to create the grid control. For consistency with other applications you can also create tabbed dialog boxes or your own builder interfaces with the page frame control.

Creating a One-to-Many Form

Visual FoxPro makes it easy to set up forms to display records from related tables. Using the Project Manager Window and the Form Designer you can just "drag and drop" the fields you need to set up a form.

One-to-many forms display data from related tables.

Try setting up a one-to-many form using two related tables, such as the Customers and Orders tables from Testdata.dbc.

After four steps, one-to-many forms are...

...ready to run.

Specify Tables and Views for Your Form in the Data Environment You can use the data environment for your form or a report to specify the tables or views used by your form. After you have added the tables and views that have the records you want to display in your form, you can drag the fields to the Form Designer.

Create Grids by Selecting Multiple Fields You can select multiple fields and drag them to a form to create a grid object. If you select multiple fields and drag them with the right mouse button, you can choose between a grid or multiple controls. You can also click the Fields item in a table and drag it onto a form to create a grid incorporating all fields in the table. If you right-click a single field and drag it onto a form, you can create a different object class than the one that is assigned as the default object class.

Giving Your Form a Professional Look

Be creative and customize your forms with layout, colors, shapes, and graphics.

Align Controls Exactly Use the Layout toolbar to quickly line up controls and space them evenly on the form.

Change the Background Color Use the Color Palette toolbar.

Add Graphics and Pictures Use the Line, Shape, and Image buttons on the Form Controls toolbar.

Control Display and Data Entry in a Combo Box You can set the Format Property and InputMask Property for a Combo Box control.

Remove a Border on a Combo Box or Spinner You can use the BorderStyle Property to remove a border from the control. For example, if you are using combo box or spinner controls in a grid, you can clean up the display by removing the extra lines the border adds to the grid.

Use Current Windows Colors for Form Colors You can set an additional option on the ColorSource Property that lets you set the form colors based on the current Windows color scheme.

Setting the Properties on Controls

You can enhance your user interface with the control properties in Visual FoxPro. Using the Properties Window you can see and set the properties associated with each object in your form to determine how a form control looks and behaves.

Use Data Binding with ActiveX Controls To bind data to ActiveX controls you can use the ControlSource Property (if the control supports it) in the Properties window to specify a field or variable to which the control is bound.

Control Navigation in Page Frames By setting the tab order on your page frame you can control the order that pages are displayed. This also adds the ability to navigate to the different pages in a page frame with the right and left arrow keys.

Control Item Selection in List Box and Combo Box Controls When a list box or combo box is bound to a numeric ControlSource, the list index number of the item is collected, rather than the value. To collect the actual value of the selected item in the control, set the BoundTo Property to True.

Select More Than 60 Items in a List Box You can select an unlimited number of multiple items in a ListBox Control.

Create Hidden Properties and Methods You can set accessibility properties on the properties and methods you create to Public, Protected, or Hidden. To change the accessibility of properties and methods, use the Members Tab, Class Info Dialog Box.

For more information about | See
Creating forms | Creating Forms
Using form wizards | Help by pressing F1 from the wizard.
Using builders | Help by pressing F1 from the builder.
Using controls | Help by searching on the control name or Using Controls
Using forms in applications | Creating Forms

Customizing Your Form Designer

To make your work easier, you can customize the Form Designer to match your work style and needs.

Save Changes Automatically You can set options so Visual FoxPro saves your forms automatically when you quit the Form Designer. In the Forms Tab, Options Dialog Box you can choose the option to Save Changes Before Running Form. If you select this option, you skip the confirmation dialog box, and the changes you made to the current form are saved automatically.

Change the Font in the Properties Window You can choose one of three font settings from the Properties window shortcut menu.

Use the Keyboard in the Property Window The Properties window supports keyboard navigation for scrolling through the hierarchy of objects, controls, and tab orders. Use CTRL+PGUP and CTRL+PGDN to move up and down through the list.

For more information about | See
The Form Designer and form controls | Form Designer
Creating forms | Creating Forms

Add Controls from a Class Library

When you need to add controls to a form so you can navigate through the records in it, you can choose from a library of controls, drag in the controls you need, and run the form. It's that simple.

Adding VCR Controls to a One-to-Many Form

You can use the following example to see how easy it is to streamline your work using controls from class libraries.

Store complicated control sets in a class library for reuse.

Add VCR Controls to a Form By opening the sample button class library (Buttons.vcx) supplied with Visual FoxPro, you can easily add a set of VCR-style navigation control buttons to your form. The sample libraries are in the Visual FoxPro ...\Samples\Classes directory.

A class for VCR controls can be added to your toolbar.

Controls are easy to add to your form.

Set the SkipTable Property Because this is a one-to-many form, you need to specify that the next record in the main table is selected when you choose the Next button. To do this, open the Properties Window and set the SkipTable property so that it refers to the main table.

The SkipTable property adds the final functionality to your control.

Expanding Your Class Libraries

You don't have to wait for someone else to sell you their control classes and libraries; you can make your own.

Create Your Own Classes You can create your own controls and save them in class libraries. You can start with standard Visual FoxPro classes and customize them to create your own version, or you can create your own classes.

Point to Classes in Compiled Applications You can use the SET CLASSLIB Command to point to a class included in a compiled application.

Add and Keep Classes on the Forms Control Toolbar When you add a class to the Forms Control toolbar, the class remains on the toolbar until you click the View Classes button again and select Standard.

View Detailed Information about Your Classes Using the Class Browser Window, you can view the entire hierarchy of classes and objects in a class library or form.

Create Your Own Subclasses of ActiveX Controls You can create subclasses of all the ActiveX controls shipped with Visual FoxPro.

For more information about | See
Using the Class Designer | Help by pressing F1 from the Class Designer.
Setting properties | Creating Forms
Creating classes and using class libraries | Object-Oriented Programming

Creating a Menu Bar and Shortcut Menus

You can use the Menu and Shortcut Designers to add a menu bar and menus to forms in your application. With the Menu and Shortcut Designers you can create shortcut menus and menus for SDI forms.

When you create a menu, you have the option of adding a menu to the menu bar or creating a shortcut menu. The Shortcut Designer presents the familiar Menu Designer interface, but allows you to design shortcut menus rather than menu bars and menus.

After you have generated your shortcut menu, you can attach it to any control by running the menu in the control's RightClick Event.

Creating Reports

When it's time to print out important data, you don't want to spend a lot of time formatting reports. That's why Visual FoxPro provides report wizards to streamline the reporting process. With report wizards you can select the data you want from your tables and views, and present it in your choice of professional looking formats.

It's easy to combine information from two different tables in a one-to-many report.

Using the Visual FoxPro report design features, you can:

Use the Preview Button The last screen of a report wizard has a Preview button so you can quickly see if your report is the way you like it. If not, use the Back button in the wizard and make the necessary adjustments.

Use Quick Report for Fast Results If you're setting up your own report in the Report Designer, choose Quick Report from the Report menu to add selected fields from a table to a report.

Use Query or View Results in a Report Want to print out the results of a query? Choose the Report option in the Query Destination Dialog Box. You can send the query results to a pre-formatted report or send the query to a report wizard.

Create a One-To-Many Report The One-To-Many Report Wizard makes it easy to set up a report that shows fields from two tables joined in a one-to-many relationship. For example, try using the wizard to create a report from two related tables in Testdata.dbc.

Report Wizards retrieve records and format the report layout.

Use Other Report Wizards Try using the other report wizards. For simple one-table reports or summary reports with totals, choose Report Wizard.

Use the Report Designer If you want to customize your wizard-generated report further, just open it in the Report Designer and add the enhancements you need.

For more information about | See
Report Wizards | Help by pressing F1 from the wizard.
Report Designer | Creating Reports and Labels

Providing a Help System

You can add value to your application by creating a Help system. Using the Help compiler included with Visual FoxPro, you can turn your document files into a graphical Help system to distribute with your applications. For more information on creating WinHelp and HTML Help, see Creating Help .

See Also

Overview of Visual FoxPro Features | Rapid Application Creation | Form Designer | Creating Forms


Application Development with Several Developers

If you have several developers working on your applications, you can use Visual FoxPro's ability to allow simultaneous access to database components. Also, for tracking and protecting changes to your source code, you can use source control programs with the Project Manager.

Let Several People Work on Database Objects You can now modify tables and view definitions, without exclusive access to the database. Use the Refresh option on the Database menu – this reloads the database object definition to reflect any changes made by other users.

Use Source Code Control You can use a source code control program such as Microsoft Visual SourceSafe to coordinate and manage changes to applications you develop in Visual FoxPro. The Project Manager provides access to source code control on the Project menu.

For more information about working with several developers, see Planning for Team Development Projects .

See Also

Overview of Visual FoxPro Features | Interaction with Other Applications | Planning for Team Development Projects | Advantages of More Power


Interaction with Other Applications

With Visual FoxPro you can share data with other applications such as Microsoft Excel and Word, use objects from other applications, and control other applications using Automation.

Sharing Data with Other Applications

You can take advantage of all the software tools on your desktop with Visual FoxPro.

Use Your FoxPro Data in Other Applications Sharing data with other applications is easy – for example, you can share Visual FoxPro data with Microsoft Excel by using the PivotTable Wizard, or with Microsoft Word by using the Mail Merge Wizard.

Display or Store Objects from Other Applications You can include objects from another application by linking or embedding them in tables or in forms. Then you can edit the objects directly, without leaving Visual FoxPro.

Editing included objects is easy in Visual FoxPro.

Importing and Exporting Data

You can import and export data between Visual FoxPro and many other applications using a variety of file formats: text, spreadsheets, and tables, to name a few. The data can be appended to or copied from existing tables easily. The Import Wizard helps you make decisions about the structure you want the data to take in Visual FoxPro.

For more information, see Importing and Exporting Data.

Integrating with Automation

With Visual FoxPro you have the power to fully integrate your application with other applications.

Control Other Applications You can extend the power of your application by controlling other applications programmatically. For example, you can direct Microsoft Excel to perform some calculations, instruct Microsoft Graph to chart the results, and then store the chart in a General field of a Visual FoxPro table, all from Visual FoxPro code. Or, you can add ActiveX controls that you or someone else developed.

Optimize Automation Requests You can determine how much time your system uses for requests and how long it takes for messages to appear for your user. For example, you can control how much time your system spends retrying Automation requests before displaying a "server busy" message.

You can also control the number of milliseconds that pass during user input, such as using the mouse or keyboard while an Automation request is pending, and a "busy" message appearing.

Control Visual FoxPro from Other Applications Using Visual FoxPro as an Automation server, you can create references to Visual FoxPro objects, execute Visual FoxPro commands, and run Visual FoxPro programs from other applications.

For more information on Automation, see Sharing Information and Adding OLE.

See Also

Overview of Visual FoxPro Features | Client/Server Solution Development | Importing and Exporting Data | Application Development with Several Developers


Client/Server Solution Development

You can use Visual FoxPro as a front end for developing robust client/server applications. Visual FoxPro combines the higher-level support of updateable views of server data with direct access to native server syntax using SQL pass-through. This gives you a solid foundation on which to build versatile client/server solutions. A full-featured data dictionary, local and remote views, null support, transactions, international application support, and access to ODBC data sources all contribute to the features you need for client/server development.

Increasing Client/Server Performance

You can increase the performance of your client/server application using the properties and ODBC driver provided in Visual FoxPro.

Controlling Performance with Properties

You can increase performance by using the following cursor and remote view properties:

  • CompareMemo
  • FetchAsNeeded
  • Prepared

You can display these properties using the DBGETPROP( ) Function and CURSORGETPROP( ) Function functions, or set the properties with the DBSETPROP( ) Function and CURSORSETPROP( ) Function functions.

Include or Exclude Memo Fields in Update Detection You can use the CompareMemo property to control when memo fields are used to detect update conflicts. This view and cursor property determines whether memo fields (types M or G) are included in the update WHERE clause. The default setting, True (.T.), means that memo fields are included in the WHERE clause. If you set this property to False (.F.), memo fields don't participate in the update WHERE clause, regardless of the settings of UpdateType.

Optimistic conflict detection on Memo fields is disabled when CompareMemo is set to False (.F.). For conflict detection on memo values, CompareMemo should be set to True (.T.).

Fine Tune Record Fetching Use the FetchAsNeeded property to specify if all rows are fetched progressively, or only those within the row set determined by the FetchSize property. If you want to fetch all of the rows in the result set using the Visual FoxPro idle loop, use the default setting, False (.F.). If you want to fetch only when the user scrolls beyond the row set determined by the FetchSize property, set FetchAsNeeded to True (.T.) to fetch the next row set.

Speed Up Re-query Operations on Parameterized Views Using the Prepared property, you can set whether the query for the view is prepared before it is executed. If you set this property to True (.T.), Visual FoxPro sends a request to the ODBC driver to prepare or compile the SQL query that defines the view. If the ODBC driver for your back-end data source supports the use of prepared statements, subsequent re-queries on the open view are executed faster.

Defining Rules with the Data Dictionary

Visual FoxPro databases (.dbc files) provide a data dictionary that allows you to add rules, views, triggers, persistent relationships, and connections to every table in a database.

Within a database you can define:

  • Field-level or record-level rules that Visual FoxPro enforces wherever the table is used in an application.
  • Primary and candidate index keys.
  • Local and remote views.
  • Triggers.
  • Persistent relationships between database tables.
  • Connections to remote data sources.
  • Stored procedures.
  • Default values on fields.
  • Long table and field names.

In addition, you can enforce referential integrity for every persistent relationship by using the Referential Integrity Builder to define rules for inserts, updates, and deletes.

Visual FoxPro also supports null values in tables, greatly improving compatibility and connectivity with other data sources such as Microsoft Access, Visual Basic, and SQL-based servers. For details about null values, search for "null" and "null values".

Each Visual FoxPro database is completely user-extensible, with access through language enhancements and the visual designers. For more information about databases and data dictionaries, see Developing Databases.

View Local, Remote, and Offline Data You can design and test a client/server application on your local computer using data from remote, local, or multiple-table heterogeneous views. Local views use tables on your local computer rather than tables on a remote server, and multiple table views use related data from separate tables. You can create parameterized views to minimize the amount of data you download from the server, take the data on the road, or update remote data from your Visual FoxPro application. For more information about views see Creating Views.

Manage Shared Access with Transactions You can design your application to provide shared access to data. Shared access involves sharing data among users and restricting access when necessary. Transactions and buffering — pessimistic or optimistic, record-level or table-level — mean less programming for you. Built-in batch processing and detailed control over handling update conflicts simplifies updating data in a multiuser environment. For details about designing your application for shared access, see Programming for Shared Access.

Develop International Applications Visual FoxPro provides several areas of support for developing international applications. For example, Visual FoxPro supports several code pages. The code pages for Greek and Russian are supported on MS-DOS, Microsoft Windows, and Macintosh platforms. Visual FoxPro also supports double-byte character sets for languages such as Japanese, Korean, Traditional Chinese, and Simplified Chinese; however, Unicode is not supported. Visual FoxPro supports collation sequences for languages such as Japanese, German, Traditional Chinese, and Icelandic. For more information about international applications, see Developing International Applications.

Implement a Client/Server Application In addition to using views for client/server development, you can send any native server syntax you want directly to a server with Visual FoxPro SQL pass-through functions. These functions permit additional server access and control beyond the capability of views. For details about SQL pass-through see Enhancing Applications using SQL Pass-Through Technology.

After designing your application locally, you can upsize and implement it against a back-end data source. Upsizing applies the benefits of client/server architecture to the local application and allows you to create a remote server database with the same table structure and data as the original Visual FoxPro tables. When you upsize, you choose which tables move to the server and which remain locally for more immediate access. For details about upsizing see Upsizing Visual FoxPro Databases.

See Also

Overview of Visual FoxPro Features | Upgrading from Earlier Versions | Developing Databases | Creating Views | Programming for Shared Access | Interaction with Other Applications


Developing Visual FoxPro Applications

Visual FoxPro provides an extensive set of tools and technologies making it possible to rapidly build flexible solutions with powerful data handling capabilities. The rapid application development environment helps you with all aspects of application development.

To develop applications using Visual FoxPro

  1. Plan your application before starting. Numerous considerations make application development much easier if they are addressed from the start — for example, choosing a data store, security, and schema. For more information, see Application Planning.
  2. Create your application. For more information, see Creating the Application.
  3. Design and build your database to create effective applications with indexes, tables, and databases based on your data requirements. For details, see Working with Data.
  4. Create the user interface for your application. Using Visual FoxPro forms, classes, controls, menus, and toolbars, you can build interfaces that help users gain access to the full potential of your programs. For details, see Creating the User Interface.
  5. Add online Help to your application to reduce the amount of time required to train and support users. For details, see Creating Help.
  6. Build your application by compiling the code. You can create your applications one piece at a time, verifying each component as you go, and then compile them into an application. For details, see Compiling an Application.
  7. Debug your code and create error handlers. The best results come from writing understandable and maintainable code and using the available debugging tools. For more information, see Testing and Debugging Applications.
  8. Prepare your application for distribution by including all required files and creating distribution disks. For more information, see Distributing Applications.

In This Section

Application Planning
Provides links to information to help you carefully plan your applications, including design, architecture, and security considerations.
Creating the Application
Describes the basic steps involved in creating an application and provides links to other information on the process.
Creating Web Services and Components
Provides links to information on extending applications to make them work for multiple users.
Working with Data
Provides information to help you create effective applications by analyzing data requirements and designing your application components to meet those needs.
Enhancing Applications using SQL Pass-Through Technology
Provides links to topics that discuss techniques for implementing client/server technology in a working application that uses remote views.
Compiling an Application
Provides links to information on building applications, referencing modifiable files, and building the application file from your project.
Testing and Debugging Applications
Discusses testing and debugging as necessary stages in the development cycle, and the various levels of robustness that developers look for as they test and debug.
Distributing Applications
Provides information on preparing to distribute your application by including all required files and creating distribution disks.

Related Sections

Using Visual FoxPro
Discusses the Visual FoxPro programming environment and tools that help you create and manage high-performance database applications and components.
Programming in Visual FoxPro
Describes how understanding object-oriented programming and the event-driven model can maximize your productivity and enable you to access the full power of Visual FoxPro.
Optimizing Applications
Provides information on how to get the best performance from your operating system, Visual FoxPro, and your application.


Application Planning

Careful planning saves time, effort, money, and sanity. The more you involve your end users in the planning process, the better. No matter how carefully you plan, though, you'll probably end up refining the specifications as you progress through the project and your end users provide feedback.

In This Section

Design Considerations
Discusses how the design decision you make will impact how you create your application.
Application Architecture
Describes how Visual FoxPro application architecture varies with the type of application you decide to create.
Security Considerations
Shows how you should be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.
Planning for Team Development Projects
Discusses how using source control software, such as Microsoft Visual SourceSafe, to manage the files in a project makes it possible to create complex applications quickly by combining the skills of a team of developers.
Developing International Applications
Shows how to design Visual FoxPro applications so they are as effective internationally as domestically using the international features of Visual FoxPro.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Creating the Application
Discusses how to create Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Creating Web Services and Components
Describes how you can extend your Visual FoxPro application by making it possible for it to work for multiple users, take advantage of Microsoft ActiveX controls and automation-enabled applications.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Data
Discusses how to create effective applications with indexes, tables, and databases based on your data requirements.
Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Provides information on how to use the modular approach to makes it possible for you to verify the functionality of each component you create. Then you can compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Provides information on debugging tools provided by Visual FoxPro to help you find and correct any errors you discover in your applications.
Distributing Applications
Discusses how to prepare to distribute your application after you have completed developing and testing it by including all required files and creating distribution disks.


Design Considerations

Some of the design decisions you make will impact how you create elements of the application. Who will be using the application? What is the center of user activity? How large a data set will you conceivably be working with? Will back-end data servers be used or will the data be exclusively local to a single user or multiple users over a network? Consider these factors before getting too far into the project.

Common User Activities

Even if your end users are working with customers, orders, and parts, how they are working with this information will determine how your application should deal with the data. An order entry form might be necessary for some applications, but would not be a good tool for managing inventory or tracking sales, for example.

Database Size

You'll want to think more about performance if you are dealing with large sets of data. Optimizing Applications explains methods of optimizing performance. You may also want to adjust the way you allow users to move through the data. If you have twenty or thirty records in a table, it's okay to let users move the record pointer in a table one record at a time. If you have twenty or thirty thousand records, you'll have to provide other ways of getting to the desired data: adding search lists or dialogs, filters, custom queries, and so on. Using Controls, explains how to use a list to select specific table records. Creating Views, discusses creating parameterized queries.

Single User vs. Multiple Users

It's a good idea to create your application with the assumption that multiple users will be accessing the database at the same time. Visual FoxPro makes it easy to program for shared access. Programming for Shared Access describes techniques for allowing multiple users to simultaneously access your database.

International Considerations

If you know your application will be used only in a single-language environment, you don't have to worry about internationalization. If, on the other hand, you want to expand your market, or if your users could be dealing with international data or environment settings, you'll want to take these factors into account as you create the application. Developing International Applications discusses the issues you'll need to deal with as you develop applications for international use.

Local vs. Remote Data

If your application deals with remote data, you'll manage it differently than you would manage native Visual FoxPro data. Creating Views explains how to create views to local or remote data.

Backing up Your Source Code

In all application development, it's a good practice to make complete backup copies of your original program files before you build an application. Store the backup copies separately from your compiled applications.

Note Be sure to maintain separate copies of your original source programs for future use. You cannot re-create your source programs from their compiled code.

See Also

Developing International Applications | Programming for Shared Access | Optimizing Applications


Visual FoxPro as an Application Front End

As a Visual FoxPro developer, you probably find it natural to design your applications around the program's visual design tools. For example, you probably think of your application's user interface in terms of Visual FoxPro forms, menus, and reports. In addition, when you develop applications in Visual FoxPro, you most likely think of storing the application's data in Visual FoxPro tables.

One way to integrate Visual FoxPro into an enterprise-wide application is to use the visual design tools in Visual FoxPro, but enhance them with the capabilities of other products. Another way is to create your application's look and feel using Visual FoxPro, but to extend the data storage capabilities of your application by taking advantage of the capabilities of other programs or of non-Visual FoxPro data storage options. You can also upsize your Visual FoxPro data by moving it to a database server.

Extending the Visual Design Tools in Visual FoxPro

The base classes of Visual FoxPro controls were designed to accommodate the vast majority of application interface needs. Visual FoxPro provides all the basic controls and interface elements that are required to create a standard Windows application. However, you will often find that your application requires objects or controls beyond those provided in the base Visual FoxPro classes. If so, you can extend the visual design tools by creating subclasses and by using ActiveX controls.

Creating Subclasses

An extremely powerful feature of Visual FoxPro is the ability to create subclasses of the base controls. By creating one or more subclasses, you can customize the basic Visual FoxPro controls in almost any way that's required for your application. This ability extends to being able to create new objects or controls that combine the features of other controls. For example, the grid control in Visual FoxPro contains not only its own container, properties, and methods, but those of the objects that appear in the grid such as buttons, text boxes, and so on.

Similarly, by subclassing base controls, you can extend the capabilities of Visual FoxPro by creating objects that add new features to existing base classes, or that combine the capabilities of several objects. For example, you can add visual features such as frames or three-dimensional effects to a text box. Or you could combine an image control, buttons, and a text box to create a bitmap-viewing control in which users can move through a series of .bmp files. Creating custom classes in this way can help you manage company-wide development by allowing you to create standardized controls that appear in all your applications. For more information, see Object-Oriented Programming.

Using ActiveX Controls

An alternative to creating a new control using subclasses in Visual FoxPro is to use an ActiveX control (.ocx file). These controls are created independently from Visual FoxPro, and can be integrated not only into Visual FoxPro, but into many other Windows applications as well.

In effect, ActiveX controls are off-the-shelf components that you can integrate seamlessly into your application. Using ActiveX controls provides several benefits:

  • It saves you the time and effort required to create, test, and maintain a Visual FoxPro-specific control to accomplish the same tasks. The more capable the ActiveX control, the more time you save.
  • Many ActiveX controls are already available from third-party suppliers to answer common application requirements. For example, if your application calls for you to display a calendar and allow users to choose dates on it, you can probably find an ActiveX control (perhaps several) that already manages this task.
  • The same control can be used in multiple programs. For example, if it makes sense to do so, you can use the same ActiveX control in Visual FoxPro and Visual Basic. The same properties and methods are used in each case to manage the control, and the control will have the same appearance in all programs, making it easier for users to work with.
  • ActiveX controls often provide access to Windows functionality that can otherwise be awkward or time-consuming to include using only Visual FoxPro tools. For example, you can find ActiveX controls that provide access to electronic mail (using Windows MAPI functions), to low-level Windows graphics functions, and so on. By including an ActiveX control, you can add these types of features to your application in a way that's easy to control using the ActiveX control's properties, methods, and events.

In short, using ActiveX controls enables you to extend your applications not only by integrating Windows-wide functionality, but by adding a common look-and-feel between your application and others in the same enterprise. For more information about using ActiveX controls, see Adding OLE. For information about creating your own ActiveX controls, see Accessing the Visual FoxPro API.

Integrating Functionality from Other Programs

You might find when developing an application that other programs are uniquely suited to accomplishing certain tasks. For example, Microsoft Word has unsurpassed merge letter capabilities, while Microsoft Excel is optimized to calculate complex formulas and easily create charts and graphs from them.

Rather than emulating these capabilities in Visual FoxPro, you can make your application an enterprise-wide solution by integrating them into your application. This way you can match the requirement of your application to the best possible tool to address it.

You can integrate the functionality of other applications into Visual FoxPro in these ways:

  • Run a Visual FoxPro wizard that makes Visual FoxPro data available for use by another application.
  • Write Visual FoxPro programs that use Automation to communicate with, control, and share data with other Windows programs.

The following sections provide details about these methods of extending the capabilities of Visual FoxPro.

Using Wizards

A number of Visual FoxPro wizards allow you to integrate Visual FoxPro data with the functionality of other Windows programs. For example, you can send form letters to your customers by using the Mail Merge Wizard. When you run the wizard, you can specify a table or view that contains the Visual FoxPro data to use, and then either export the data to a suitable file format (such as comma-delimited) or specify that your word processing program use the Visual FoxPro OLE DB provider to access the data. If you use Microsoft Word, the wizard will even start the word processing program, create the blank merge document, and display the Mail Merge toolbar for you to link fields to your Visual FoxPro data.

Similarly, using Microsoft Excel and Microsoft Query, you can analyze your data using a pivot table, which summarizes data in columns and allows you to rearrange it to view it in different ways. By using the PivotTable Wizard in Visual FoxPro, you can use your application data as the source data for Microsoft Excel, and generate the pivot table in Microsoft Excel.

Using Automation

A more powerful way to interact with other applications is to use Automation. Using Visual FoxPro programs, you can access the objects exposed by other applications, and then control them by setting their properties and calling their methods. For example, Microsoft Excel exposes an application object as well as worksheets, columns, rows, and cells within the application object. You can directly manipulate any of these objects, including getting or setting data in them. In addition, you can usually control the application object using the full range of commands available in the program itself. For example, by managing the application object in Microsoft Excel, you can open, save, or print worksheets, invoke the Microsoft Excel chart wizard, and so on.

Automation is a particularly attractive and powerful way to work with Windows programs using Visual FoxPro for several reasons:

  • You have direct access to the other program, including all its objects and commands.
  • You can share data directly with the other program without having to export it or convert it to another format.
  • You can control the other program using the familiar properties and methods model.
  • The other program doesn't necessarily need to be visible to the user when you invoke it. For example, you can invoke Microsoft Excel, place some data into cells, run a complex calculation on the data, read the result, and then display it in Visual FoxPro, all without ever displaying Microsoft Excel. Your user would continue to see only Visual FoxPro, unless you explicitly wanted to display Microsoft Excel.
  • The commands (methods and properties) to control the other program are embedded within familiar Visual FoxPro programs. You don't need to learn a different programming language in order to be able to control the other program.

Automation is particularly powerful because it's an open-ended method for working with other programs. In essence, Automation simply makes available to you the data and commands from other applications for you to use in the way best suited to your application.

A sample scenario illustrates how you can integrate several Windows programs. Imagine that you store your customer and sales data in Visual FoxPro. You'd like to create a sales report that summarizes quarterly sales.

One solution would be to use Automation to copy the Visual FoxPro sales data to cells in a Microsoft Excel worksheet. You can then invoke the Microsoft Excel chart wizard to create a chart of the data and copy it to the Windows Clipboard. Still using Automation, you can invoke Microsoft Word and create or open a sales report document (if you create it as a new document, you can insert standard text that you store in Visual FoxPro), and then paste in the chart you created in Microsoft Excel.

This is just one way you can use Automation to make Visual FoxPro part of an enterprise-wide solution. By becoming familiar with the objects and methods available in programs that you typically use, you can imagine many more ways to make each program enhance the capabilities of the other. For details about Automation, see "Manipulating Objects with Automation" Adding OLE.

Extending Data Storage Capabilities in Visual FoxPro

The data table and indexing capabilities of Visual FoxPro are usually more than adequate to the requirements of an application, whether you're concerned about speed or database size. However, there are times when you might want to extend Visual FoxPro by using data that's stored in some other format. This might be true if:

  • Your application needs access to legacy data that's created and maintained by an existing application. For example, suppose that, as part of your sales application, you need access to data being maintained by an accounting application that was written using a different program, perhaps even on a different platform.
  • You want to optimize data access by using a database server, which can greatly speed data access, particularly in very large databases.
  • You want to share data with other programs, and therefore want to store the data in a format that's accessible to all the programs.
  • The data is best suited to the format of a particular program (such as a spreadsheet). This might be true, for example, if your application required only occasional access to data that was otherwise being maintained by the other program.

If the data you need is in the format of a spreadsheet, word processing document, or other Windows program, you can access it using Automation. For example, you might do this if your application required a collection of form letters. In that case, the letters might be stored as Microsoft Word documents, and your application would use Automation to invoke Word, open the appropriate letter, and insert or substitute text as necessary.

A more common approach to using non-Visual FoxPro data is to use an OLE DB provider to access it. OLE DB providers allow you to connect to data in the format of other programs — typically other database programs — and query or edit the data using standard SQL commands.

For example, you might decide that security and transaction processing capabilities are a vital part of your application, so you decide to store the data using Microsoft SQL Server. To access the data, you define a connection to SQL Server, using the SQL Server OLE DB provider. You can then run queries and other SQL commands using ADO, and retrieve the results into an ADO recordset for further processing in Visual FoxPro.

Other applications can access the same data and take advantage of the same features. For example, a Microsoft Excel worksheet can get its data from the same SQL Server database. Not only will the worksheet enjoy the same performance advantages that your application does, it can also take advantage of the security and transaction processing features of the server, which aren't otherwise available in a Microsoft Excel worksheet.

In some instances, you might want to go further and use SQL commands that are specific to the data source you're accessing with the OLE DB provider. For example, Microsoft SQL Server allows you to create and run stored procedures, which can manipulate data at the server (rather than in your application). To take advantage of stored procedures, you can send "native" SQL statements to the database server. Pass-through SQL commands also allow you to perform system administration tasks on the server, and in some instances they will execute faster than similar SQL statements executed in Visual FoxPro.

For more details about extending data storage capabilities in Visual FoxPro, refer to the documentation in the following table.

For details about | See
Automation | Manipulation of Objects with Automation in Sharing Information and Adding OLE
Using non-Visual FoxPro data | Accessing Remote Data with Views in Creating Views
Using Visual FoxPro in a client/server environment | Planning Client/Server Applications

Upsizing Visual FoxPro Data

You can choose to keep your data in Visual FoxPro tables or on another platform such as a database server. Or you can do both: keep your data in Visual FoxPro tables while you're developing, or until your database grows large, and then move (or upsize) the data to another platform.

For example, you can prototype your application by keeping all the data in local Visual FoxPro tables. This gives you the flexibility to modify your tables, views, and indexes as you develop the application without the complexities of managing tables on a database server. You can keep sample data in the local tables so you can test your forms, reports, and other programs. When the database structure is complete, you can upsize your data to a database server and put the application into production.

Another way to work is to keep your data in Visual FoxPro tables only as long as is practical. When the database grows large, you can upsize it and take advantage of the optimized performance provided by a database server. The exact point at which it makes sense to upsize your database depends on many factors, including the complexity of the database, the performance of your local computer or network, and the demands of your application.

Finally, you can prototype your database in Visual FoxPro, and then upsize it in order to share the data with other applications that can also access a database server. Similarly, you can upsize the database in order to take advantage of the security and server-side transaction processing capabilities of the database server.

For details on upsizing databases, see Upsizing Visual FoxPro Databases.

See Also

Development for the Enterprise | Visual FoxPro as a Data Source | Object-Oriented Programming | Adding OLE | Accessing the Visual FoxPro API | Mail Merge Wizard | PivotTable Wizard


Visual FoxPro as an Application Back End

A different way to integrate Visual FoxPro into an enterprise solution is to use it as one component, but not necessarily as the primary application. In effect, you'd be treating it as a back end for an application written using another product. In this case, the user wouldn't directly see Visual FoxPro. Instead, the application's user interface would be written using tools in the other application, and would communicate with Visual FoxPro in the background to get or manipulate data.

Visual FoxPro works well in this role because it can make available its database engine, which provides rapid data access to other applications. In addition, Visual FoxPro can make its objects and command sets available to other programs, including custom objects that you create.

Making Visual FoxPro Data Available to Other Programs

One way for an enterprise-wide application to take advantage of Visual FoxPro is to use the Visual FoxPro database engine for storing and managing data. This provides high-performance storage and query capability to other programs.

Programs can connect to Visual FoxPro data using the Visual FoxPro OLE DB provider. This provider exposes the Visual FoxPro database engine to standard Visual FoxPro SQL commands.

For example, an application might use Microsoft Excel as a calculation tool for complex data analysis. If the data to be manipulated is highly fluid, it might make sense not to store it in a worksheet, but in a database. The worksheet could then be written to use the Visual FoxPro OLE DB provider to connect to the database, extract the relevant information, and display it in a worksheet for further processing.

Another example might be a kiosk application, such as an information stand at an airport or convention center. You could create the information display using a multimedia authoring program. But if some of the data in the application changed often, it would be cumbersome to change pages in the presentation. Instead, the presentation program could connect to a Visual FoxPro database using the OLE DB provider, and then extract data at run time.

For more information, see the Visual FoxPro OLE DB provider help topics.

Making Visual FoxPro Objects and Commands Available to Other Programs

In addition to making Visual FoxPro data available to other programs as part of an enterprise solution, you can expose Visual FoxPro objects and commands. Other applications can call the methods and set properties of objects in Visual FoxPro, including not only the base objects, but objects defined in custom classes.

For example, you can create an application in Microsoft Excel that stores data in a Visual FoxPro database. In addition to simply reading and writing the data, Microsoft Excel can call Visual FoxPro commands to display a form as a dialog box. One use might be to gather data for a parameterized view.

Another way to expose Visual FoxPro objects is to create an Automation server. This allows you to create application-specific objects that can perform almost any function that you can program Visual FoxPro to accomplish, with the further advantage that you can distribute the server.

One use for a custom server is to create an object that includes a set of business rules that ensure the integrity of data that another application passes to it. For example, you can create an object in Visual FoxPro for storing employee information that not only validates that the application has passed valid employee information, but checks the user's access level to ensure that the user has security access to make the employee changes.

A custom server can also expose an object that incorporates complex logic for updating or reading information. For example, an order entry object might not only be able to store the order, but could also maintain a transaction log of orders, update inventory, calculate a sales commission, and so on.

This type of Automation server is ideal for creating the middle layer of a three-tiered enterprise application. In this model, the data forms the lowest level and the application forms the highest. The functionality is in the middle, and provides a specific, application-independent view of the data that incorporates business rules (or other data processing capabilities) that don't properly belong with the data or with the application alone.

For information about creating custom Automation servers, see Creating Automation Servers in Adding OLE.

Creating a Data Warehouse Using Visual FoxPro

In addition to creating your application in Visual FoxPro, you can use the program to create and maintain a data warehouse, or version of your data that is optimized for reporting. To create a data warehouse, you make a copy of the data required for reporting, and then make it available to users who need it. By maintaining this data separately from your live data, you can:

  • Structure it to make reporting easier or faster than if users created reports from the live data.
  • Place data for reports in a location separate from the live data, which reduces contention for data, improves performance, and can make data available to users who shouldn't see live data for security purposes.

A data warehouse is a snapshot of the data at the time you create it. You refresh the data in the warehouse periodically, scheduling the update according to the reporting needs for your application.

For example, imagine that you're creating an application to manage a library, including an inventory of materials. During the day, the system is in constant use as patrons check materials in and out, and query the system to locate or reserve books. In addition to managing these individual transactions, librarians want to be able to analyze their library, to determine facts such as what materials are the most popular, what books are overdue, and so on.

To help with the analysis, the application can create a data warehouse out of the transaction information. The application can warehouse the data periodically, perhaps every night, and the librarians can create queries without affecting the performance of the system during the day. In addition, the data warehouse can exclude details about the patrons using the library, because this information isn't required for the analysis and might be considered confidential information.

To get the most benefit from a data warehouse, you create it on a server separate from the live data. If the live data and data warehouse are on the same server, you can still get the benefit of having optimized data in the warehouse. However, as users make queries against the warehouse, they can generate a large amount of network traffic, which might affect performance of the live system.

When you create the data warehouse, you can simply copy the live files over to parallel files in the data warehouse. Alternatively, you can restructure the data in the warehouse to optimize it for reporting. For example, you might create indexes for the warehouse data that reduce reporting overheard.

As another example, data in the live application should be normalized in order to avoid data duplication. However, in the data warehouse it might be useful to combine tables that would otherwise be separate; this can eliminate the need to join tables, making it easier for less experienced users to create reports.

You can also match the level of detail in the data warehouse to the reporting requirements of your application. For the most flexibility, you should store the same level of detail in the data warehouse as you have in the live data. However, if users wanted to create only summary reports (such as spreadsheets or charts), you could roll up detail data from the application and store only summary data in the data warehouse.

Using Visual FoxPro as a World Wide Web Search Engine

If your enterprise solution involves creating a World Wide Web server for the Internet, you can incorporate Visual FoxPro into the application as a search engine. This allows you to make the power of your Visual FoxPro database available to anyone who can access your Web server, whether on the Internet or via a company intranet.

For example, imagine that as part of your company-wide intranet you want to make available an employee directory. Employees could point their browsers to a "Search for Employee" page, which would display a page that looks like a Visual FoxPro form, containing text boxes to enter criteria. To perform a search, users would enter the employee's name, phone extension, department, position, or any other information they had available, and then choose a Search Now button. In a moment or two they would see a listing of the employees who met the search criteria. They could then save this listing as a text file that could then be imported into another program, such as a word processor.

Understanding Visual FoxPro as a Web Search Engine

In general, in order to use Visual FoxPro as an information server for the Web, you need these components:

  • An existing Web server with HTTP service, running on Microsoft Windows NT or Windows 2000 operating system.
  • A Visual FoxPro application that can be called as an Automation server. This application can run on any server accessible to the Web server.
  • A means for displaying search results, which usually consists of a Web page template into which you can insert data.

The usual sequence of events that involve a Visual FoxPro search on the Web are these:

  1. The user displays your application's search page by pointing a Web browser to it. The search page includes any text and graphics that you want, plus text boxes in which users can enter search text.
  2. The user chooses a "Search Now" button. The data from the completed form is sent to the Web server for processing, along with the name of your Web page search application.
  3. The Web server calls your application using ISAPI (Internet Server API) protocol, passing to it a parameter containing the search information.
  4. Your application searches the database. When it gets results, it inserts them into a Web page template, and then sends the Web page back to the server as a stream of characters.
  5. The Web server sends the results page to the browser that initiated the search.
  6. The browser displays the results page for the user.

If you've created Web pages, most of the steps in this process are probably familiar. For example, you might already know how to create Web pages. Even if you aren't already familiar with Web page design, you'd probably find the process of creating these pages relatively easy.

For an example of how to use Visual FoxPro as a Web search engine, see the sample Foxisapi.dll in the Visual FoxPro …\Samples\Servers\Foxisapi directory. Refer to the Readme.txt file in that directory for details about how to run the example.

See Also

Visual FoxPro as an Application Front End | Development for the Enterprise | Creating Automation Servers | Adding OLE


Application Architecture

Visual FoxPro application architecture varies with the type of application you decide to create. To design the structure of your application, carefully consider the function each component provides and its relationship to other components.

In This Section

Structure of Visual FoxPro Application
Describes how a typical database application consists of data structures, a user interface, query options, and reporting capabilities.
Planning Client/Server Applications
Discusses the importance of planning in building a successful client/server application. Proper planning will help you build the fastest, most productive application for your users.
Rapid Application Development
Describes the fundamental steps in application development, prototyping, upsizing, implementing, and optimizing.
Application Creation with Accuracy and Data Integrity
Describes how to use Visual FoxPro data validation rules and stored procedures with the data source's data validation rules and stored procedures to build client/server applications that protect data integrity.
Planning Enterprise Applications
Explains how you can use Visual FoxPro as part of a larger-scale application that involves two or more development tools, which makes is possible for you to take advantage of the unique capabilities of each product.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Describes how careful planning saves time, effort, and money. Many of the decisions you make during the planning phase will impact how you create elements of the application.
Design Considerations
Discusses how the design decision you make will impact how you create your application.
Security Considerations
Shows how you should be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.
Planning for Team Development Projects
Discusses how using source control software, such as Microsoft Visual SourceSafe, to manage the files in a project makes it possible to create complex applications quickly by combining the skills of a team of developers.
Developing International Applications
Shows how to design Visual FoxPro applications so they are as effective internationally as domestically using the international features of Visual FoxPro.


Structure of Visual FoxPro Application

A typical database application consists of data structures, a user interface, query options, and reporting capabilities.

An assembled Visual FoxPro application typically presents a user with a menu and one or more forms for entering or displaying data. You provide functionality and maintain data integrity and security by attaching code to certain events. Queries and reports allow your users to extract information from the database.

Structure of a typical Visual FoxPro application

When structuring your application, you need to consider the following tasks:

  • Setting the starting point
  • Initializing the environment
  • Initializing the Environment
  • Controlling the event loop
  • Controlling the Event Loop

The following sections provide details about each of these tasks. Typically you would create an application object to complete these tasks. If you use the Application Wizard to compile your application, it creates an application object. Or, if you want, you can use a program as the main file that handles these tasks. For more information, see Structuring a Program as a Main File.

See Also

Compiling an Application | Setting the Starting Point | Application Framework Files | Application Builder | Initializing the Environment | Planning Client/Server Applications | Planning Enterprise Applications


Planning Client/Server Applications

Microsoft® Visual FoxPro® provides you with the tools to create powerful client/server applications. A Visual FoxPro client/server application combines the power, speed, graphical user interface and sophisticated querying, reporting, and processing of Visual FoxPro with the seamless multiuser access, massive data storage, built-in security, robust transaction processing, logging, and native server syntax of an ODBC data source or server. The synergy of Visual FoxPro and server strengths provides a powerful client/server solution for your users.

The most important step in building a successful client/server application is creating a good design. When you design a client/server application, you're balancing several sets of requirements. You want to build the fastest, most productive application for your users. You also want to ensure the integrity of application data, make the most of existing hardware investments, and build in scalability for the future. In addition, as a Visual FoxPro developer, you want to make the development process as streamlined and cost-efficient as possible.

In This Section

Client/Server Design for High Performance
Building a fast, high-performance client/server application with Microsoft® Visual FoxPro® involves taking advantage of the tremendous speed of the Visual FoxPro engine.
Performance Enhancement through Set-Based Data Access
Explains how you can build a fast, efficient client/server application by minimizing the amount of data you pull down from the server.
Data Location on the Optimal Platform
Learn how to get maximum performance by storing data and other attributes of your database on the optimal platform.

Related Sections

Developing Visual FoxPro Applications
This section includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Architecture
Learn how Visual FoxPro application architecture varies with the type of application you decide to create.
Structure of Visual FoxPro Application
Describes how a typical database application consists of data structures, a user interface, query options, and reporting capabilities.
Rapid Application Development
Describes the fundamental steps in application development, prototyping, upsizing, implementing, and optimizing.
Application Creation with Accuracy and Data Integrity
Learn how to use Visual FoxPro data validation rules and stored procedures with the data source's data validation rules and stored procedures to build client/server applications that protect data integrity.
Planning Enterprise Applications
Explains how you can use Visual FoxPro as part of a larger-scale application that involves two or more development tools, which makes is possible for you to take advantage of the unique capabilities of each product.


Client/Server Design for High Performance

Building a fast, high-performance client/server application with Visual FoxPro involves taking advantage of the tremendous speed of the Visual FoxPro engine. You accomplish this with new techniques such as using set-based data access rather than traditional local navigation, building parameterized queries to download just the data you need, locating tables on the optimal platform, and leveraging both Visual FoxPro and remote stored procedures.

When you design a local or file-server application, you determine the queries, forms, menus, and reports your application will use or create. When you design a client/server application, you perform all the normal system analysis plus additional analysis that relates specifically to client/server applications. You need to think about where the data used by queries, forms, menus and reports will be located, and how you'll access that information. For example, you might ask yourself questions such as:

  • Which tables will be stored on the remote server once the application is implemented?
  • Which tables would be more efficiently stored as local lookup tables?
  • What views will you need to access remote data?
  • What business rules does the server enforce, and how will your application interact with these rules?

Once you've determined the basic components of your client/server application, you can begin to design how your application will access and update data.

See Also

Performance Enhancement through Set-Based Data Access | Client/Server Application Design | Data Location on the Optimal Platform | Selection of the Right Methods | Optimizing Client/Server Performance | Implementing a Client/Server Application


Client/Server Performance Optimization

When you have implemented your client/server application, you might find areas where you'd like to improve performance. For example, you can fine-tune your application to gain maximum performance by speeding up forms and queries and increasing data throughput.

This section discusses optimization strategies for application performance on the client, network, and server.

In This Section

Connection Use Optimization
Establishing a connection uses time and memory on both the client and the server. When you optimize connections, you balance your need for high performance against the resource requirements of your application.
Speeding Up Data Retrieval
You can speed up data retrieval by managing the number of rows fetched during progressive fetching, controlling fetch size, and using delayed Memo fetching.
Query and View Acceleration
You can improve query and view performance by adding indexes, optimizing local and remote processing, and optimizing parameter expressions.
Form Acceleration
When you design a form based primarily on server data, take a minimalist approach for the best performance.
Performance Improvement on Updates and Deletes
You can speed up Update and Delete statements by, adding timestamps to your remote tables, using the CompareMemo property, using manual transaction mode, using server stored procedures, and batching updates.

Related Sections

Creating the Application
Discusses how to create Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Setting the Starting Point
Describes how the main file is the starting point for your application, and can consist of a program or form. When your application is run, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed.
Initializing the Environment
Setting up the application environment is the first task that a main file or application object must accomplish.
Controlling the Event Loop
Learn how to establish an event loop to, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes. This occurs after the environment is set up and you've displayed the initial user interface.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application builder.
Creating the User Interface
Learn how creating forms, classes, controls, and toolbars can provide a rich set of tools for your user interface.
Upsizing Visual FoxPro Databases
Explains how to use the upsizing wizards to move databases, tables, and views from your system to a remote Microsoft SQL Server.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.


Connection Use Optimization

Establishing a connection uses time and memory on both the client and the server. When you optimize connections, you balance your need for high performance against the resource requirements of your application.

The number of connections used by Visual FoxPro depends on whether you force the closing of unused connections, and how you set the length of the connection idle timeout.

Using Shared Connections

You can use connections exclusively or share a connection. Each method has its benefits. When you use a connection exclusively, your application experiences no contentions for connection resources once a connection is established. If each result set uses an exclusive connection, you can also intermingle asynchronous processing on multiple result sets.

When you use a shared connection, you have one connection for multiple result sets. You must serialize data manipulation operations on the result sets sharing the same connection, and design the application to test the connection for busyness any time conflicts might occur. For information on sharing a connection, see Creating Views.

Controlling Connection Timeouts

If your application doesn't take any action for a long time, you can reduce connection use by setting the IdleTimeout property on the connection. The IdleTimeout property controls the interval of time connections are allowed to idle before they're closed by Visual FoxPro. By default, connections wait indefinitely and are not deactivated until specifically closed by the user.

You set the idle time for a connection definition with the IdleTimeout property of the DBSETPROP( ) function; you can set the IdleTimeout property for an active connection with the SQLSETPROP( ) function.

Visual FoxPro closes connections even if Browse windows and forms displaying remote data are still open, and then automatically reconnects when the connection is needed again. However, Visual FoxPro cannot close a connection if:

  • Results of a query from the server are pending.
  • The connection is in manual transaction mode. You must commit or roll back the transaction and switch to automatic transaction mode before the connection can be closed.

You set the transaction mode for a connection definition with the Transactions property of the DBSETPROP( ) function; you can set the transaction mode for an active connection with the SQLSETPROP( ) function.

Releasing Connections

You can improve performance by closing connections that your application is no longer using. Connections are closed automatically for you when you close a view. If the connection is shared by multiple views, Visual FoxPro closes the connection when the last view using the connection is closed.

You can control the connection for a query manually if you don't want to update the data in a cursor. Use a SQL pass-through query to select the data you need into a local cursor and then close the connection.

See Also

Client/Server Performance Optimization | Speeding Up Data Retrieval | Query and View Acceleration | Performance Improvement on Updates and Deletes | Form Acceleration | Implementing a Client/Server Application | Creating Views


Speeding Up Data Retrieval

You can speed up data retrieval by managing the number of rows fetched during progressive fetching, controlling fetch size, and by using delayed Memo fetching.

You can also use the UseMemoSize view property to return character fields as memo fields and then turn FetchMemo off to enable your application to selectively fetch those character fields converted to memo fields.

Using Progressive Fetching

When you query a remote data source, Visual FoxPro retrieves complete rows of data and builds a Visual FoxPro cursor. To speed retrieval of remote data, Visual FoxPro employs progressive fetching of view cursors and cursors created asynchronously with SQL pass-through. Rather than requiring you or your application to wait while an entire data set is retrieved, Visual FoxPro executes a query and fetches only a small subset of the result set rows into the local cursor. The size of this subset is 100 rows by default.

Note Synchronous SQL pass-through statements don't employ progressive fetching. The entire result set requested by a SQLEXEC( ) statement is retrieved before control is returned to your application.

As Visual FoxPro retrieves additional rows of data, the local cursor contains increasingly more of the queried data. Since rows are retrieved at different times from the data source, the information in the rows isn't automatically current. If your connection is operating in asynchronous mode, Visual FoxPro returns control to you or your program as soon as it fetches the first subset of data. During idle time, Visual FoxPro performs a background fetch of the remaining rows in the queried data, one subset at a time, into the local cursor. This scenario allows you to use the already fetched data in the cursor without having to wait for the rest of the data.

Note Increasing the number of rows fetched improves performance, but decreases the responsiveness of the user interface. Decreasing the number of rows fetched has the inverse effect.

Fetching Data On Demand

You can disable progressive fetching and fetch rows only on an as-needed basis by using the FetchAsNeeded database and view cursor property. This can result in more efficient data retrieval for remote views or views retrieving extremely large results sets.

The FetchAsNeeded property is set by default to false (.F.), which means that progressive fetching is employed by default. When you set the FetchAsNeeded property to true (.T.), rows are fetched only when needed. When the FetchAsNeeded property is set to true, you cannot perform an update until you either complete the fetch, call the SQLCANCEL( ) function on the current connection handle, or close the view.

If you want to see the impact of using the FetchAsNeeded property, set the FetchAsNeeded property on a view retrieving a large result set to .T. and then open a browse window on the view and scroll down. The status bar is updated to show the number of rows retrieved as you move through the browse window.

Controlling Cursor Fetching

If you want to fetch the entire cursor, you can issue the GOTO BOTTOM command, or any command requiring access to the entire data set.

Tip While you can use the GOTO BOTTOM command to fetch the entire cursor, it's often more efficient to build a parameterized view that fetches only a single row at a time and requeries as the user changes records. For more information on building high-performance views, see Creating Views.

Programs don't provide idle loop processing. To fetch view cursors programmatically, use the GO nRecordNumber or GOTO BOTTOM commands. To fetch cursors created with SQL pass-through in asynchronous mode, call the SQL pass-through asynchronous function once for each row subset.

Canceling a SQLEXEC( ) Statement

You can use the SQLCANCEL( ) function to cancel a SQLEXEC( ) statement or a view at any time. However, if the server has completed building the remote result set and Visual FoxPro has begun fetching the remote result set into a local cursor, the SQLCANCEL( ) function cancels the SQLEXEC( ) statement and leaves the local cursor. If you want to delete the local cursor you can issue the USE command, which closes the cursor and cancels the fetch.

The USE command will not cancel a SQLEXEC( )statement if the statement hasn't yet created a local cursor. To determine whether Visual FoxPro has created a local cursor, you can call the USED( ) function.

Controlling Fetch Size

You control the number of rows fetched at one time by your application from a remote server by setting the FetchSize property on your view. The FetchSize property specifies how many records are fetched into the local cursor from the remote server at one time, through progressive fetching or asynchronous SQL pass-through calls. The default value is 100 rows.

To control the number of records fetched at one time into a view

  • In the View Designer, choose Advanced Options from the Query menu. In the Data Fetching area of the Advanced Options dialog box, use the spinner to set a value for Number of Records to Fetch at a time.

    -or-

  • Set the FetchSize property with the DBSETPROP( ) function to set the view definition's fetch size.

    -or-

  • Set the FetchSize property with the CURSORSETPROP( ) function to set the active view cursor's fetch size.

    For example, the following code sets the view definition to progressively fetch 50 rows at a time into Customer_remote_view:

    ? DBSETPROP('Customer_remote_view', 'View', 'FetchSize', 50)

Using Delayed Memo Fetching

A well-designed application frequently uses delayed Memo fetching to speed downloading of result sets that contain Memo or General fields. Delayed Memo fetching means that Memo and General field contents are not automatically downloaded when you download a result set. Instead, the rest of the fields in the row are quickly downloaded, and Memo and General field contents aren't fetched until you request them by opening the Memo or General field. Delayed Memo fetching provides the fastest downloading of rows, and allows Memo or General field contents, which can be quite large, to be fetched only if needed by the user.

For example, your form might include a General field that displays a picture. To speed performance, you can use delayed Memo fetching to prevent downloading of the picture until the user chooses a "Preview" button on your form. The code behind the "Preview" button then fetches the General field and displays it on the form.

To control delayed Memo fetching, you use the FetchMemo property on your view or cursor. The FetchMemo property specifies whether to fetch the contents of the Memo or General fields when the row is downloaded. The default value is true (.T.), which means that Memo and General fields are downloaded automatically. If your data contains large amounts of Memo or General field data, you might notice increased performance when you set the FetchMemo property to false (.F.).

Note The view must be updatable to allow delayed Memo fetching to work, because Visual FoxPro uses the key field values established by the update properties to locate the source row on the server when it retrieves the Memo or General field. For information on making a view updatable, see Creating Views.

Use DBSETPROP( ) to set the FetchMemo property on a view, and CURSORSETPROP( ) to set the FetchMemo property on a cursor.

Optimizing Data Fetching Performance

You can use the following recommendations for setting connection and view properties to optimize data fetching. The PacketSize property on your connection has the greatest influence on performance. Also, you can optimize fetch performance using synchronous connections.

Object | Property | Setting
Connection | PacketSize | 4K to 12K1
Connection | Asynchronous2 | .F.
View | FetchSize3 | maximum

1. Set a higher value for rows containing more data; you should experiment to find the best value.
2. Use synchronous connections to increase performance up to 50%, unless you want to be able to cancel SQL statements while executing on the server.
3. The effect of FetchSize is highly dependent on the record size of the fetched result set. In synchronous mode, it does not significantly impact performance, so set it as needed for SQL pass-through asynchronous processing view progressive fetching. FetchSize, if reduced, provides significantly better responsiveness while progressively fetching a view, but slows down the fetch speed. If increased, it increases view fetch performance.

Actual performance depends greatly on your system configuration and application requirements.

See Also

Connection Use Optimization | Query and View Acceleration | Client/Server Performance Optimization | Form Acceleration | Performance Improvement on Updates and Deletes | Implementing a Client/Server Application


Query and View Acceleration

You can improve query and view performance by adding indexes, optimizing local and remote processing, and optimizing parameter expressions.

Adding Indexes to Remote Tables

Remote indexes can make queries significantly faster. Multiple-table queries are faster if the tables are indexed on the joining fields. Having indexes on fields that are included in a query's WHERE clause can also improve performance.

Clustered indexes provide the best performance. On SQL Server, each table can have one clustered index. The SQL Server Upsizing Wizard automatically creates clustered indexes on tables that had a primary key in Visual FoxPro.

Tip While indexes on table fields used in queries can speed processing, indexes on result sets can slow performance. Use indexes on result sets with care.

Optimizing Local and Remote Processing

If you need to process a combination of local and remote data, create a remote view that combines all remote data in a single view. You can then join the remote view with the local data in a local view. Because Visual FoxPro fetches both views completely before joining and filtering the combined view, it's important to limit the size of the view result set.

You gain speed in remote processing by limiting the remote view result set to the minimum amount of data needed by your application. When you retrieve less data into a remote result set, you minimize the time required to download remote data into your local query or view cursor.

Optimizing Parameterized Views

You can speed data retrieval during REQUERY( ) operations on an open, parameterized view by compiling the view before it's executed. To precompile or "prepare" a view, set the Prepared property on the view to true (.T.).

Optimizing Parameter Expressions

View and SQL pass-through parameters are Visual FoxPro expressions and are evaluated in Visual FoxPro before being sent to the remote server. Evaluation time for the expression is important, because it lengthens the query execution time.

See Also

Speeding Up Data Retrieval | Form Acceleration | Client/Server Performance Optimization | Performance Improvement on Updates and Deletes | Implementing a Client/Server Application


Form Acceleration

When you design a form based primarily on server data, take a minimalist approach for the best performance. Determine the data and functionality needed, and delay asking the server for this data and functionality until requested by the user. Requesting data from the server uses processing time and creates network traffic. To request less data in your forms:

  • Request as few records as possible. For example, use a filter or query to limit the size of the record set. Make sure that the server can process any restrictions you use.
  • Use as few remote fields as possible in views underlying your forms.
  • Use as few forms that access remote views as possible in your form set. When you open a form set, all the forms in the form set are opened and populated with data as applicable. By limiting the number of forms in your form set, especially those that must connect to a server and retrieve remote data, you shorten the time the form set takes to load.
  • Use fewer bound controls that access remote data. Each combo box, list box, and grid that's bound to a remote table or query requires a separate query to the server when the form is opened. Avoid controls containing totals, or list boxes and combo boxes that have large row sources.
  • If users need to compare multiple sets of data, consider storing the data returned by the server in temporary local tables. Provide a form in which the user can use the previously stored data, or execute a new query.

Storing Lookup Tables Locally

Often, an application contains several forms that use the same remote table. If the data in the table doesn't change frequently, you can speed up form loading and reduce server load using one of the following techniques:

  • Store tables that never change and aren't too large (such as the names and abbreviations of the regions or states in your country) in the local Visual FoxPro application database. If the table is joined in queries or views with remote tables, you should also keep a copy of it on the server to avoid joining local and remote data.
  • Store tables that rarely change (such as a list of company buildings) both on the server and in the local application database. Provide a way for the user to download the table when the data does change.
  • Store tables that change occasionally but not daily (such as a list of employees in a small company or department) both on the server and in the local application database. Your application should automatically refresh the local version each time it starts. This method uses extra time when the application starts, but speeds up queries when the application is running.

Displaying Fields Only On Request

Display fields that take a long time to retrieve data from the server, such as Memo or General fields, only when requested. You can use the following techniques:

  • If your form is based on a view, place Memo or General fields off screen on another form page. Add a label to the form, such as "Page down to see notes and pictures," that informs the user how to display the information. Set the FetchMemo property on the view or cursor to false (.F.), so that Visual FoxPro doesn't retrieve Memo or General fields until they're displayed on screen.
  • Set the Visible property to false (.F.) for controls bound to Memo or General fields. Add a toggle button or command button that sets the property to true (.T.), so that the user can choose to view the contents of these controls.
  • Display the most important fields on a main form, and provide a button labeled "More Information" that opens another form containing other fields. Base the second form on a view that's parameterized by the primary key field on the main form. For example, suppose you have a main form based on a view whose SQL SELECT statement includes the following code:
    SELECT customer_id, company_name, address, city, region, country
FROM customers

    In the preceding form, cust_id is bound to thisform.txtCust_id. You could base the second form on the following view, which is used only when the user chooses the "More Information" button:

    SELECT orders.order_id, orders.order_date, orders.shipper_id, ;
   employee.emp_id, employee.last_name, employee.first_name ;
FROM orders, employee ;
WHERE orders.cust_id = ?THISFORM.txtCust_id ;
AND orders.employee_id = employees.emp_id

See Also

Query and View Acceleration | Performance Improvement on Updates and Deletes | Client/Server Performance Optimization | Implementing a Client/Server Application


Performance Improvement on Updates and Deletes

You can speed up Update and Delete statements by:

  • Adding timestamps to your remote tables.
  • Using the CompareMemo property.
  • Using manual transaction mode.
  • Using server stored procedures.
  • Batching updates.

Adding Timestamps

You can improve performance when you update, insert, or delete data in a remote table that contains many fields by adding a timestamp field to the remote table, if your server provides the Timestamp field type.

The presence of a timestamp field in a remote table allows you to use the Visual FoxPro SQL WhereType update option DB_KEYANDTIMESTAMP. This option saves processing time because Visual FoxPro compares only two fields in your view, the key field and the timestamp field, against a remote table to detect update conflicts. By comparing only two fields, rather than all the updatable fields (with the DB_KEYANDUPDATABLE option) or all the modified fields (with the DB_KEYANDMODIFIED option), the DB_KEYANDTIMESTAMP option reduces the time it takes to update remote data. For more information on WhereType options, see Creating Views.

Note The DB_KEYANDTIMESTAMP option compares the key and timestamp fields only when your remote table contains a timestamp field. If you use the DB_KEYANDTIMESTAMP option against a remote table that doesn't contain a timestamp field, Visual FoxPro compares the key fields only.

The Upsizing Wizard can automatically add timestamp fields as appropriate to tables you export. For more information, see "Timestamp Columns" in Upsizing Visual FoxPro Databases.

Tip If you do something that alters the structure of a view's base table, such as adding a timestamp field, you might need to re-create the view. The fields in a view definition are stored in the database, and any changes to the base tables for a view after the view is used aren't reflected in the view definition until you re-create the view.

Excluding Memo Fields from the Update WHERE Clause

Whenever appropriate, you can speed updates by preventing view memo fields (fields of type Memo, General, or Picture) from being compared against their base table counterparts. By default, the CompareMemo property is set to true (.T.), which automatically includes memo fields in the SQL WHERE clause generated when you create an updatable view. You can set the CompareMemo property to false (.F.) to exclude memos from the SQL WHERE clause.

Using Transactions

For optimum performance, use manual transaction mode and manage transactions yourself. Manual transaction mode allows you to control when you commit a group of transactions, which enables the server to process more statements quickly.

Automatic transaction mode is more time-consuming, because by default every single update statement is wrapped in a separate transaction. This method provides maximum control over each individual update statement, but also increases overhead.

You can improve performance in automatic transaction mode by increasing the setting of the BatchUpdateCount property on the view or cursor. When you use a large BatchUpdateCount setting, many update statements are batched in a single update statement, which is then wrapped in a single transaction. However, if any statement in the batch fails, the entire batch is rolled back.

Tip The BatchUpdateCount property isn't supported by some servers; you should test this property against each remote server before deploying it in your application.

Using Server-Stored Procedures

You can create stored procedures on the server, which are precompiled and therefore run very quickly. You can execute stored procedures, send parameters with SQL pass-through, and move additional processing to the server as appropriate for your application.

For example, you might want to collect user input locally and then execute a SQL pass-through query to send the data to the server, calling the appropriate stored procedure. To do this, you might want to create a form on a local cursor or array to collect data and then write code that constructs a SQLEXEC( ) statement by using the name of the server-stored procedure and the parameters to be supplied. You could then add this code to the Click event of a command button titled "OK" or "Commit." When the user chooses the button, the SQLEXEC( ) statement runs. Using server stored procedures to update remote data can be more efficient, because the stored procedures are compiled on the server.

Batching Updates

If your application updates a number of records, you might want to batch updates so they're handled more efficiently by the network and server. Update or Insert statements are batched before being sent to the server, according to the setting of the BatchUpdateCount property of the view. The default value is 1, which means that each record is sent to the server with an update statement. You can reduce network traffic by increasing the value to package multiple updates in a statement.

Tip The BatchUpdateCount property isn't supported by some servers; you should test this property against each remote server before deploying it in your application.

To use this feature efficiently, the view connection should be set to Buffering mode 5, for optimistic table buffering, and changes ideally should be confined to the same fields in each row of the cursor. You can use DBSETPROP( ) to set the BatchUpdateCount property for the view definition; to change the value for an active view cursor, use CURSORSETPROP( ).

Optimizing Performance of Updates and Deletes

You can use the following guidelines for setting view and connection properties to optimize performance of updates and deletes. The BatchSize property on your view has the greatest influence on performance.

Object | Property | Setting | Notes
View | BatchUpdateCount | 10 – 30 rows | Set a higher value for smaller-sized updates.1 Set to increase performance by up to 50%. The default is 1.
Connection | Asynchronous | (.F.) | Use synchronous connections to increase performance up to 50%, unless you want to be able to cancel SQL statements while executing on the server. The default is synchronous.
Connection | WaitTime | N/A | To increase performance in asynchronous mode, use a shorter wait time; to reduce network traffic, increase the wait time.
Connection | PacketSize | 4K to 12K | Has little effect on performance.

1 Your best value also depends on the speed of your server.

Actual performance depends greatly on your system configuration and application requirements.

See Also

Form Acceleration | Query and View Acceleration | Client/Server Performance Optimization | Connection Use Optimization | Speeding Up Data Retrieval | Implementing a Client/Server Application


Performance Enhancement through Set-Based Data Access

One of the most important factors in building a fast, efficient client/server application is minimizing the amount of data you pull down from the server. Because client/server applications can access potentially huge amounts of data on a remote server, using traditional local navigation techniques could result in a slow client/server application. To speed performance, you use set-based data access techniques to filter the amount of data you download.

Accessing Set-Based Data Efficiently

Remote data is set-based; you access remote data by selecting a set of data from a large data store using SELECT - SQL statements. The most important difference between building a traditional local application and building a client/server application is the contrast between traditional Visual FoxPro navigational techniques and set-based server data access techniques.

Using Traditional Navigational Techniques

In traditional local database programming, you can access discrete and often large amounts of data by using the GOTO BOTTOM command, which you then query against. You can navigate through data by issuing a SET RELATION command to create a temporary relationship between two tables and then issuing a SKIP command to move through the related records.

While this method of navigating records could be used against remote data, it can be inefficient against large remote data stores. For example, if you create a remote view that accesses a large table on a remote data source and then issue the GOTO BOTTOM command, you must wait while all the data in the view is retrieved from the data source, sent across the network, and loaded into your local system's view cursor.

Using Parameterized Queries

A more efficient approach for accessing remote data is to download just the data you need and then requery to obtain specific additional or new records. Use a SELECT statement based on parameters to download a specific small set of data and then access new records by using the REQUERY( ) function to request a new set of data.

You don't issue the GOTO BOTTOM command against remote server data because this would:

  • Unnecessarily burden network resources by downloading huge amounts of data.
  • Slow performance of your application by handling unneeded data.
  • Potentially reduce accuracy of the data in the local cursor because changes to remote data aren't reflected in the local cursor until you requery.

For example, if you want to create a client/server application that accesses the orders for a particular customer, create a remote view that accesses the Customer table. Create another remote view that accesses the Orders table, but parameterize the view based on the cust_id field. Then use the current customer record as the parameter for the view of the Orders table.

You can use the parameter to scope the downloaded data set to just the right amount of data. If you request too little data, you can lose performance because you'll have to requery the remote server more frequently. If you request too much data, you can waste time downloading data you won't use.

Choosing the Best Client/Server Design

The following examples describe how to gain the benefits of client/server technology and avoid the pitfalls of poor programming techniques. The first method uses traditional programming practices to retrieve all the data from a remote data source into local cursors that are then related with the SET RELATION command. The second, third, and fourth methods adopt progressively smarter data-fetching techniques, effectively limiting the amount of data downloaded with a just-in-time methodology that provides the freshest data and fastest response time over a network.

Using an Unoptimized Client/Server Strategy

A straightforward, unoptimized client/server application uses local data navigation techniques with remote data. For example, if you have 10-million customer records and 100-million order records on a remote data source, you can create an inefficient application that downloads all the Customer and Order records into local cursors. You could then index on 100-million order records, create a temporary relationship between the Customer and Orders tables in your local cursors, and use the SKIP command to navigate through the records.

This method is not optimized for performance, but might, however, be useful if the one side is local and the many side is remote.

Filtering the Many Side

A slightly improved client/server application limits the many side of the relationship, but retrieves all of the one side so you can skip through the records. In this scenario, you create a remote view of the many side of the relationship, the Orders table, parameterized on the customer ID. You then download the entire Customer table.

While creating a parameterized view on the Orders table is an improvement over downloading all of the orders, you still retrieve unnecessary information by continuing to download the entire Customer table. The Customer table is also increasingly out-of-date as changes are made by other users on your system. This method might be beneficial if the one side of the relationship contains a small data set.

Filtering the One Side

A better client/server programming technique creates remote views for all remote data. You limit the number of Customer records downloaded into the remote view of the Customer table by using the SELECT statement in the view to select just the customers for one region. You then create a remote view of the many side of the relationship, the Orders table, parameterized on the customer ID.

This scenario retrieves a smaller set of records. You use the SKIP command to skip on the one side of the relation (the Customer view). You use the REQUERY( ) function to access new data on the many (Orders) side.

In this example, you limit, or filter, both the one side and the many side of the relationship, and can still use the SKIP command to navigate through the filtered data. This method is recommended if the one side of the relationship, even after being filtered, is still sufficient to provide information for a successive set of queries before you requery the remote server.

Using the Primary Key to Access the One-to-Many Relationship

The most efficient client/server programming paradigm gives up the luxury of using the SKIP command, and creates a form that requests input or selection of the customer ID, which is then used as a parameter for a remote view of the Customer table. This parameter is also used as a parameter for a remote view of the Orders table.

For example, you could create a one-to-many form in which the customer information forms the one side, and a Grid control displays the many side of the relationship. The Grid control can be bound to the customer ID chosen in the one side of the form. You can then set the MaxRecords property of CURSORSETPROP( ) to 1, and use the following code to populate the one side of the form:

SELECT * FROM customer WHERE customer.cust_id = ?cCust_id

When users want to view a different customer's record, they input or select a new customer ID. The form requeries the data source for the orders for the new customer ID and refreshes the Grid control with the new order data.

Using these techniques, your application downloads just the data you need, at the time it's needed. You speed response over the network by limiting the amount of data downloaded, and you provide fresher information to the user by requerying the data source just before you display requested information.

This method is recommended when you want to access the one-to-many relationship randomly using any primary key value. You might want to download the primary keys into a control, such as a drop-down list, when you open the form and then provide a control that the user can choose to refresh the list of primary key values on demand.

Using the Data Environment in Client/Server Applications

When you use remote data in a form, include the views in the form's data environment. You can set the AutoOpenTables property for the data environment to false (.F.) so that you can specify when the application refreshes the views with the remote data. Set the ControlSource property for text boxes or other data-bound controls after you call the data environment's OpenTables method, typically in the code associated with the Init event of the form. For more information, see Creating Forms.

See Also

Client/Server Design for High Performance | Data Location on the Optimal Platform | Client/Server Application Design | Selection of the Right Methods | Optimizing Client/Server Performance | Implementing a Client/Server Application


Data Location on the Optimal Platform

You get maximum performance when you store data and other attributes of your database on the optimal platform. The best platform for a particular element depends on how the element is accessed and updated. For example, you might want to store a local copy of a server table, such as a postal code directory that is used as a lookup table, and refresh the local copy only when the back-end table changes.

The following table lists some common application elements and examples of where to locate them for optimal performance.

Locating Elements by Platform

Element | Location | Type | Notes
Tables | Local | Local copies of server lookup tables; small, infrequently changed tables | Use a time stamp, if supported by your remote server, to compare and optionally refresh the local table to match any changes to the back-end source table.
 | Remote | Large or frequently changing tables |
Rules | Local | Rules on remote views | You can use DBSETPROP( ) to store field- and record-level rules on a remote view. Your application can use these local rules to check the validity of data before sending the data to the back-end as an update to remote tables.
 | Remote | Row-level and column-level rules on remote base tables |
Stored procedures | Local | Visual FoxPro stored procedures |
 | Remote | Back-end server stored procedures | Use the SQL pass-through SQLEXEC( ) function to call server stored procedures.
Transactions | Local | Visual FoxPro transactions |
 | Remote | Server transactions |
Triggers | Local views | No triggers on views |
 | Remote | Server triggers |

To reduce network traffic during lookups, you can choose to store not only infrequently changing but also frequently changing lookup tables locally. For example, you can download your company's customer list and refresh it only when customer information changes.

To accomplish this, you can program your application to compare the time stamp on the local copy of the table with the time stamp on back-end data (if your remote server supports time stamps) and update the local copy only if the server table has changed. You can also add a command button to your form that forces an immediate download of the table, allowing users to refresh their copy of the local table on demand.

See Also

Performance Enhancement through Set-Based Data Access | Selection of the Right Methods | Client/Server Application Design | Rapid Application Development | Client/Server Design for High Performance | Optimizing Client/Server Performance | Implementing a Client/Server Application


Rapid Application Development

Regardless of the programming method you choose, you need a good strategy to make developing client/server applications quick and efficient. Because Visual FoxPro makes it easy to quickly prototype and build applications, you can choose to design and build a local prototype of your application and then upsize and implement it in stages against a remote data source. If you have access to a remote data source during the development process, you might choose to prototype your application against the remote data source, using remote views.

Building a Prototype with Views

The first step in developing a Visual FoxPro client/server application can be to build a prototype. By prototyping your application, perhaps module by module, you discover changes and enhancements to your application's design early in the development process. You can then fine-tune your design efficiently against small sample data stores before adding the additional layer of complexity inherent in working with large sets of remote, heterogeneous data. For more information, see Upsizing Visual FoxPro Databases.

Creating a Local Prototype with Local Views

A local prototype for a client/server application is a functioning Visual FoxPro application that uses local views to access local tables. You use views in your client/server prototype because the final client/server application will use remote views to access remote data. By prototyping your application with local views, you're one step closer to the final application.

Building a local prototype is especially practical if you don't have constant access to a remote data source during development, or if you don't want to use remote data to prototype your application. Local views access local Visual FoxPro tables, rather than remote data source tables. You create the local data, however, to mimic the structure of the data on the server. Using local data to represent remote data is one method of quickly developing and testing your application's basic design. You can also speed development by limiting the amount of data selected into the views. For more information, see Creating Views.

Planning for Upsizing

Upsizing is the process that creates a database on the remote server with the same table structure, data, and potentially many other attributes of the original Visual FoxPro database. With upsizing, you take an existing Visual FoxPro application and migrate it to a client/server application. For more information, see Upsizing Visual FoxPro Databases.

When you build an application that you'll eventually upsize, you make choices about the design of your application's architecture and the programming model based on eliciting maximum performance against a remote data source. For more information, see Designing for High Performance.

Prototyping with Remote Views

If you have access to a remote data source and you want to use remote data directly as you develop your client/server application, you can build your prototype using remote views. When you prototype using remote views, you skip the upsizing step because your data is already located on a remote server and you already have remote views to access that data.

Implementing your Client/Server Application

You can simplify testing and debugging your application by implementing your prototyped application in stages. When you implement a prototyped application in stages, you add multiuser enhancements, move the data to the remote data source, and test and debug the application, module by module, in a systematic manner.

As you implement your application, you can use native server syntax and access server-specific functionality, such as server-stored procedures, with SQL pass-through technology. For more information, see Implementing a Client/Server Application.

Optimizing your Application

Once your application is fully implemented against remote data and you've completed the testing and debugging phase, you can fine-tune the speed and performance of the entire application. For more information, see Optimizing Client/Server Performance.

See Also

Selection of the Right Methods | Application Creation with Accuracy and Data Integrity | Client/Server Application Design | Upsizing Visual FoxPro Databases | Data Location on the Optimal Platform


Application Creation with Accuracy and Data Integrity

You can combine the power of Visual FoxPro data validation rules and stored procedures with the data source's data validation rules and stored procedures to build client/server applications that protect data integrity.

Maintaining Data Integrity

You can create local versions of remote server validation rules to provide friendly messages to the user; for example, provide messages about updates that would not be allowed when sent to the remote server because the data entered had violated some server relational integrity or data validation rule.

Using Visual FoxPro Rules on a Remote or Offline View

You can create field- and record-level rules on remote and offline views to validate data entered locally before the data is sent to the remote data source. Because the purpose of these view rules is to prevent sending data to the data source that will be rejected by the server's data integrity rules, you want to replicate the data source's rules in the rules you create for your remote view. You use the DBSETPROP( ) function to create rules for views.

Tip You can create a local validation rule on a remote view that calls a remote server stored procedure and sends the value you want to validate to the server as a parameter. However, using a remote stored procedure adds to processing time during data entry.

Using Server Rules

You can choose to rely on the rules established on the server for data validation. If an error occurs, your error handling routine can call the AERROR( ) function to obtain information, including the error message number, the text of the remote error message, and the connection handle associated with the error.

Using Server Triggers

Though you can create Visual FoxPro triggers on local tables, you can't create them on views. You can, however, use triggers on the remote data source. Server triggers can be used to process secondary data updates, such as cascading updates or deletes. Using server triggers to process secondary updates is more efficient than sending multiple commands to the remote server from your Visual FoxPro application.

Protecting Against Data Loss

Both Visual FoxPro and most remote data sources provide transaction-logging capabilities to protect against data loss. For more information, see Programming for Shared Access.

You can use Visual FoxPro transactions for local prototypes and for processing local data. Use server transactions for remote data updates, inserts, and deletes. For more information, see Optimizing Client/Server Performance.

See Also

Rapid Application Development | Client/Server Application Design | Selection of the Right Methods | Data Location on the Optimal Platform | Implementing a Client/Server Application


Planning Enterprise Applications

Many applications that you create with Visual FoxPro are self-contained solutions to a specific business requirement. For example, you might create a Visual FoxPro application to track your customers, which can include not only database information about the customers, but tools for taking orders, invoicing, and so on. You can create all the features your application needs using the facilities already available in Visual FoxPro, including its database engine, visual design tools, and reporting capabilities.

You can also use Visual FoxPro as part of a larger-scale application that involves two or more development tools. Using Visual FoxPro this way — referred to as "enterprise development" — allows you to take advantage of the unique capabilities of each product. Enterprise development can be as simple as maintaining a customer database in Visual FoxPro and creating a mail merge letter in Microsoft Word, or it can involve creating a complex application using client/server databases, Automation servers, electronic mail, and more.

Visual FoxPro is an ideal tool for creating enterprise-wide business solutions because it features:

  • Powerful, easy-to-use application development tools, including a Form Designer and wizards.
  • A fast database engine.
  • Excellent connectivity with other products, including both other Windows programs such as Microsoft Excel and Word, and client/server systems such as Microsoft SQL Server.
  • Integrated source control and other team development tools.

These features allow you to develop with Visual FoxPro in several roles in an enterprise-wide application. You can use Visual FoxPro:

  • As a front end for other applications. In this scenario, you work primarily with Visual FoxPro; for example, you create the user interface for the application in Visual FoxPro. You then access other applications that contain data needed for the application or that can provide services that enhance those already available in Visual FoxPro. You can also upsize your Visual FoxPro data or move it to another platform.
  • As a data source for other applications. To do so, you would create the user interface for the application using another program, and then access Visual FoxPro data as needed.

The strategy you choose depends on what your application goals are and what programs you want to use.

See Also

Visual FoxPro as an Application Front End | Visual FoxPro as a Data Source | Object-Oriented Programming | Accessing the Visual FoxPro API | Creating Automation Servers


Security Planning

Security is a major concern for both application architects and developers. Applications that store sensitive information need to be protected from malicious attacks and from competitors attempting to steal information or intellectual property. When designing a security model for your application, you must be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.

For general information about security planning for software development, visit the Microsoft Web site about security at http://www.microsoft.com/security/.

In This Section

Security Considerations
Describes general security issues you should be aware of when designing a server application.
Security Risks for Visual FoxPro Developers
Describes specific security issues in Visual FoxPro and how you can avoid them.

Related Sections

Application Planning
Discusses the benefits of careful application planning and provides links to information on application design, team projects, and international considerations.
Programming in Visual FoxPro
Provides links to information on object-oriented programming techniques and the event-driven model to maximize your programming productivity.


Security Considerations

When designing a server application, your design specification should address security issues. You should consider and can address the following items in the application's functional specification:

  • Security goals Define what you need to protect.
  • Security risks Understand the vulnerabilities of your application. You must also understand the significance of potential threats as they relate to your business.
  • Authentication Describes the process of accepting credentials from a user and validating those credentials against a designated authority. The identity of the user, or possibly an application or computer, is referred to as a security principal. The client must provide credentials to allow the server to verify the identity of the principal. After the identity is known, the application can authorize the principal to access resources on the system.
  • Authorization Describes the process of determining whether the proven identity is allowed to access a specific resource.
  • Securing data transmission Ensure that data cannot be viewed or tampered with while in transit by using encrypting when it crosses the network. You must consider the level of security that you data needs while in transit.
  • Impersonation Enables a server process to run using the security credentials of the client. When the server is impersonates the client, any operations performed by the server use the client's credentials. Impersonation does not allow the server to access remote resources on behalf of the client and requires delegation.
  • Delegation Enables a server process to run using the security credentials of the client, similar to impersonation. However, delegation is more powerful and enables the server process to make calls to other computers while acting as the client.
  • Operating system security Refers to the establishment of appropriate Access Control Lists (ACLs) and network security to prevent intruders from accessing secured resources. You must set the appropriate ACLs on the appropriate resources to allow access by only the relevant principals.
  • Securing physical access Refers to storing the server computer in a secure room. You should not overlook this fundamental issue.
  • Code access security Enables code to be trusted to varying degrees depending on where it originates and other aspects of the code's identity. You should be aware of how to create your own access permissions.

See Also

Security Planning | Security Risks for Visual FoxPro Developers


Security Risks for Visual FoxPro Developers

It is important to understand security issues when developing and deploying applications. For general information about developing secure applications, see the Microsoft Web site at http://msdn.microsoft.com/security.

Developers need to be aware of the following specific security issues and best practices when developing Visual FoxPro applications:

  • Validate parameter input values before evaluating them.

    When passing user input values for parameters to commands such as SQL statements, you should include code to check that those values do not contain harmful expressions, such as those that can cause access violations.

    Avoid using simple text boxes for parameter input when possible and choose user interface elements you can more easily control, such as a list boxes, grids as list boxes, or OptionGroup controls. If you must rely on typed user input as parameter input, for example, to execute commands, you should always parse the input for parentheses (()) characters. This ensures that users do not enter input that might be interpreted by Visual FoxPro as an expression. You should also check input for the ampersand (&), which is used as a macro substitution character.

    Caution Use extreme caution when accepting typed user input as parameters and passing it to the following language elements: RUN or ! command, EVALUATE( ) function, EXECSCRIPT( ) function, _VFP.DoCmd method, _VFP.Eval method, and the ampersand (&) character. This practice is recommended only for advanced developers who use strong parameter validation routines for parsing values that might cause harm to the application, the user's computer, or network.
  • Provide less flexibility to users when providing values for SQL SELECT statements.

    When using COM server or SQL Server methods that accept user input values from a SQL SELECT statement, write code that avoids giving the user access to information that should be secured, such as the computer name, or to perform undesirable actions, such as allowing the user to copy over tables and databases.

  • Set database container (DBC) file system attributes to read-only access.

    If a DBC is set to read/write access, users can modify code for DBC Events, such as the DBC_BeforeOpenTables event, to include damaging code, for example, to format a user's hard drive when opening a table in the DBC.

    If the DBC needs to be modified as part of maintenance, a network administrator can temporarily set the DBC with read/write access and then reset it to read-only access when maintenance is finished.

  • Prevent users from viewing source code in your application by encrypting your application and remove debugging information.

    To protect source code and remove debugging information, open your application project in the Project Manager. To encrypt your application project and not include debugging information, select the Encrypted check box and clear the Debug info check box in the Project Information dialog box. You should then select the Recompile All Files check box in the Build Options dialog box and rebuild your project by clicking Build in the Project Manager window. In the setup section of your application, include the SET DEBUG command.

    The _cryptapi class located in the ...\Ffc\_Crypt.vcx foundation class library provides access to the Windows Crypto API routines so you can encrypt strings, data, or files in your Visual FoxPro Applications.

    For more information, see Project Information Dialog Box, Project Manager Window, Build Options Dialog Box, and SET DEBUG Command.

  • It is recommended that you develop applications that use least privilege user settings. It is not necessary for the user to log in as a power user or administrator.
  • Avoid writing to the registry keys, HKEY_LOCAL_MACHINE and HKEY_CLASSES_ROOT. Instead, write only to the HKEY_CURRENT_USER hive.
  • Do not create or update files in the C:\Program Files (%PROGRAMFILES%) or C:\Windows (%SYSDIR%) directories. Instead, you should write user data to the user application folder. You can use the _commonfolder class located in the ...\Ffc\_System.vcx foundation class library to obtain the location of the user application folder.
  • When creating COM Servers in Visual FoxPro, it is recommended that you create COM+ applications to deploy them so you can enforce COM+ role-based security.

See Also

Security Planning | Security Considerations | Developing Visual FoxPro Applications


Planning for Team Development Projects

You can create complex applications quickly by combining the skills of a team of developers. However, team development requires some extra coordination to keep the development effort working smoothly. One strategy is to use source control software, such as Microsoft Visual SourceSafe, to manage the files in a project.

The following topics provide strategies that you can follow to make team development successful. They assume that you're already familiar with creating a Visual FoxPro application, as discussed in other sections.

In This Section

Team Development Concepts
Describes how you can create applications faster and develop more complex applications by working with a team of developers.
Source Control Features
Explains that Visual FoxPro provides a number of features that support team development, a significant feature of which is the use of a source code control system to coordinate access to files in a project.
Management of Visual FoxPro Projects under Source Control
Explains the process for using source control software in Visual FoxPro, including that you put projects under source control, add files to your source-controlled projects, and update the project list for each project.
Management of Files in a Source-Controlled Project
Says that after you have put a Visual FoxPro project under source control, you can work with individual files or manage the project as a whole.
Development and Modification of Databases in Teams
Suggests that in addition to working together with projects and project files, your team must be able to share information in databases.
Development of Class Libraries in Teams
Describes how, because class libraries (.vcx files) are a crucial part of most Visual FoxPro applications, teams must be able to coordinate development efforts when creating them.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Explains how careful planning saves time, effort, and money and many of the decisions you make during the planning phase will impact how you create elements of the application.
Design Considerations
Discusses how the design decisions you make will impact how you create your application.
Application Architecture
Describes how Visual FoxPro application architecture varies with the type of application you decide to create.
Security Considerations
Explains how you need to be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.
Security Considerations
Shows how you should be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.
Developing International Applications
Shows how to design Visual FoxPro applications so they are as effective internationally as domestically using the international features of Visual FoxPro.


Team Development Concepts

By working with a team of developers, you can create applications faster, and can develop more complex applications. You can blend the skills of different developers to create applications that would be difficult or impossible for a single developer to create.

However, team development requires extra effort in the development process. Successful team development depends on:

  • Allowing several developers to work with the same projects and databases at the same time.
  • Coordinating the changes that are made to the same programs, forms, or other application elements, so that one developer's changes don't overwrite those of another developer.
  • Allowing developers to enhance existing application elements (for example, programs or class libraries) without affecting the work of other developers who are currently using these elements.

For example, imagine that your team is developing a complex application. Because the application is large, Visual FoxPro must allow several developers to be working at once on different components of the application. However, you want to be sure that only one developer at a time works on an individual element, such as a form, so that one developer doesn't overwrite the changes made by another developer.

Furthermore, you want that developer to be able to code, test, and debug a form without affecting the other developers (and users) who continue working with an earlier version of the form. When the first developer is finished with the new form, the enhancements can then be integrated into the application.

You can follow the methods recommended in this section for coordinating the work of multiple developers. For example, this section provides information on how you can work with projects and class libraries in a multi-developer environment.

See Also

Developing in Teams | Source Control Features | Management of Visual FoxPro Projects under Source Control | Management of Files in a Source-Controlled Project | Development and Modification of Databases in Teams


Source Control Features

Visual FoxPro provides a number of features that support team development. A significant feature of team development is the use of a source code control system to coordinate who can access and modify files in a project.

Source control is the generic term for tools that manage files in a multi-developer environment. Most source control tools work something like a traditional public library, maintaining a central repository of files — documents, programs, or any other files — in a location accessible to all developers. In addition, source control tools include the ability to track the changes that developers make to files and revert to earlier versions if necessary.

Generally speaking, source control tools provide some or all of these features:

  • Check out, check in Developers check out a file by downloading a copy from the central repository to their local computer before modifying it. As a rule, while a file is checked out, other developers cannot check it out or modify it, but they can usually view it by synchronizing, or getting a read-only copy of it. (If the file is a text file, such as program source code, it's possible for several developers to check out the same file, and then merge others' changes with their local copy.) When developers are done with a file, they can check in their changes by checking in, or uploading, their local copy to the central repository. As part of the file check-in process, most source control tools prompt the developer to enter any comments about changes made to the file.
  • Merging To allow several developers to work concurrently on the same file, source control software allows multiple developers to check out the file at the same time. (This can usually be done only with text files such as program source code.) If another developer has changed the file, the source control system can integrate those changes into your version of the file.
  • Project control Developers can organize files into projects or other work-specific categories. Files can often be shared between projects if necessary.
  • Change tracking Most source control systems keep track of the changes made in a file when it's checked in. This allows developers to reconstruct earlier versions of the file, which is useful for recovering earlier work.
  • Difference checking Source control software allows developers to compare versions of a file and review the differences between them.
  • History Developers can examine the check-in history for each file, including the comments made by each developer when checking in the file.
    Tip If your source control software supports comments, take advantage of it. Comments can greatly aid in the process of tracking changes and provide a useful history of application development.

To use source code control, users must join a source-controlled project (sometimes referred to as "enlisting" in a project). When users have joined a project, they can check out and check in the files that belong to that project.

Note You must enable your source control system's option to check out the same file multiple times in order for several developers to work in a project concurrently. For details, refer to the documentation for your source code control software.

See Also

Team Development Concepts | Source Control Software in Visual FoxPro | Enabling Source Control | Management of Visual FoxPro Projects Under Source Control | Developing in Teams


Source Control Software in Visual FoxPro

One of the most critical aspects of developing in teams is the ability to control who is allowed to change files. For example, if there are no controls on files, and if more than one developer is changing a program at the same time, there is a strong likelihood that one set of changes will end up being overwritten or discarded, wasting time and effort.

Visual FoxPro helps your team manage files in your projects by allowing you to integrate a source code control system into the Visual FoxPro Project Manager. By doing so, you can manage project files in a team development environment and ensure that development efforts proceed smoothly.

Integrating Source Control with Visual FoxPro Projects

Visual FoxPro supports source code control tools by allowing you to integrate commercially-available source control software directly into your projects. You can use many of the version control systems currently available. (Contact the software vendor to find out if the software can be integrated with Microsoft development tools.) For example, if your development team already uses Microsoft Visual SourceSafe, you can specify that as the source control software to use with Visual FoxPro.

Note If you add a project to Visual SourceSafe, for proper mapping to the project, all files contained in the project must be in the project directory or path.

All source control in Visual FoxPro is managed through the Project Manager. When you set up a project in Visual FoxPro, you have the option of creating a corresponding source code control project, which is referred to as "putting the project under source control." After you've put a project under source control, Visual FoxPro helps you manage the files in the source-controlled project. When you want to modify a file — for example, if you edit a program or modify a form — Visual FoxPro prompts you to check out that file.

In Visual FoxPro, source control is used to manage files of all types, not just .prg files, but .scx, .frx, .lbx, .mnx, and .vcx files, and others as well. Although individual files can be shared between different Visual FoxPro projects, all source control operations are conducted on files within the context of a particular project.

Note Visual FoxPro doesn't prompt you to put data tables such as .dbf and .dbc files under source control when you create them, but you can add them manually to your source-controlled project.

When you work in the Project Manager with a project that's under source control, Visual FoxPro displays icons next to files that are under source control to indicate their status.

The following table summarizes the icons used in the Project Manager to indicate source control status.

Icon | Meaning
 | The file is checked out to you.
 | The file is checked out to you and to one or more other developers.
 | The file is checked out to another developer.
 | The file is not checked out; you cannot change the file until you check it out.
 | The file has been merged. After examining the changes, you can check the file in.
 | The file has been merged and there are conflicts that need to be resolved.
 | Visual FoxPro cannot determine the source control status of the file.

If a file isn't under source control, no icon appears next to it.

See Also

Source Control Features | Enabling Source Control | Developing in Teams | Management of Visual FoxPro Projects Under Source Control | Team Development Concepts


Enabling Source Control

To enable source control, first install your source control program according to the documentation provided with it. Typically, you install an administrator version on a server where the source code will be maintained, and then install the client version of the product on local machines.

Note All developers on a project must use the same source code control software.

After installing the source control software, you can set options so that Visual FoxPro will recognize it, and to specify defaults for your projects.

To enable source control in Visual FoxPro

  1. From the Tools menu, choose Options.
  2. In the Options dialog box, choose the Projects tab.
  3. In the Source control options area, select the name of your source control program in the Active source control provider list.
  4. To have Visual FoxPro prompt you to add new projects to source control, select Automatically add new projects to source control.

Each time you start Visual FoxPro, it checks for a source control provider. If one is found, you can put or manage projects under source control.

See Also

Source Control Software in Visual FoxPro | Management of Visual FoxPro Projects Under Source Control | Developing in Teams | Source Control Features |


Management of Visual FoxPro Projects Under Source Control

To use source control software in Visual FoxPro, you put projects under source control, add files to your source-controlled projects, and update the project list for each project.

Working with the Project File and Project List File

In Visual FoxPro, project information is maintained in a set of table and memo files with the extensions .pjx and .pjt. For example, if you've created a project called "MyProj," the information about the project, including the list of files, their location, and whether they're compiled into the application file (.app or .exe file), is stored in the files called Myproj.pjx and Myproj.pjt.

When working in a team development environment, developers don't share the same project files (.pjx and .pjt files). Instead, developers maintain their own local copies of the .pjx and .pjt files.

To coordinate changes that individual developers make to a project under source control, Visual FoxPro maintains a project file list (or .pjm file, short for "project metafile"). The file containing the project file list is a text file that stores the same information as the .pjx and .pjt files, such as which files are currently included in the project.

The source code control software maintains a central project file list file stored with the other files in the central repository. In addition, each developer has a local copy of the project file list checked out that reflects his or her current version of the project.

Imagine you're working with a project, and that you're adding a new program (.prg file). When you add the new file (and assuming that you put this file under source control), Visual FoxPro updates your local copy of the project and shows the file when you use the Project Manager on your computer. Other developers aren't initially aware of your change, and their local copies of the project don't show the file you have added. Even though you haven't updated the project file list, you can still check in the new file for safekeeping and check it back out again as needed.

When you're finished with the new file — for example, when you've finished testing your new program — you can update the project file list. When you do, Visual FoxPro merges the information in your local project file list with that in the central project file list.

Visual FoxPro in turn updates your local project file list with changes it finds in the central project file list. If other developers have added files to the project, your local project file list is updated, local copies of the new files are placed on your computer, Visual FoxPro rebuilds your project (.pjx and .pjt files), and the Project Manager displays the added files for you to work with.

Managing project files using the project list

Note The project file list tracks only the project files that are explicitly under source control. If your project includes files that aren't under source control, they will not appear in the project file list, and Visual FoxPro will not add these files to other developers' projects when they update their own project lists.

See Also

Enabling Source Control | Putting Projects Under Source Control | Adding Files to a Source-Controlled Project | Joining an Existing Source-Controlled Project | Updating the Project List | Detaching a Project from Source Control | Removing Files from a Source-Controlled Project | Sharing Files Between Source-Controlled Projects | Developing in Teams


Putting Projects Under Source Control

You must specify that a Visual FoxPro project will be source-controlled before you can take advantage of your source control software. You do this by adding a project to your source control system.

If source control software is enabled, you can specify that any new projects you create be automatically put under source control.

To create a new source-controlled project

  1. In the Options dialog box, choose the Projects tab, and then select a source code control provider if you haven't already done so.
  2. Make sure Automatically add new projects to source control is selected, and then choose OK. To make this setting the default, choose Set as Default, and then choose OK.
  3. From the File menu, choose New, and then start a new Visual FoxPro project.

    After you've named the new project, Visual FoxPro will prompt you to create the new source-controlled project. The default name for the new project will be the same as the name of the Visual FoxPro project.

After you create the new source-controlled project, Visual FoxPro finishes creating the Visual FoxPro project. Before other developers can use the file, they must enlist in the project.

If you're working with an existing project that isn't already under source control, you can create a new source-controlled project for it, and then put its files under source control.

To put an existing project under source control

  1. Open your Visual FoxPro project in the Project Manager.
  2. From the Project menu, choose Add Project to Source Control.

    Visual FoxPro displays the dialog box for your source control system that allows you to create a new project. By default, the name of the source-controlled project is the same as that of the Visual FoxPro project.

  3. Create the source-controlled project as you normally do with your source control software.

When you add an existing project to source control, Visual FoxPro prompts you to add the project's files to the source-controlled project.

See Also

Adding Files to a Source-Controlled Project | Management of Visual FoxPro Projects Under Source Control | Updating the Project List | Joining an Existing Source-Controlled Project | Developing in Teams


Adding Files to a Source-Controlled Project

After you put a Visual FoxPro project under source control, you can add individual files to the source-controlled project. If the Visual FoxPro project already contains files when you put it under source control, you can add them to the source-controlled project.

Note If the source control software supports it, Visual FoxPro allows you to keep the file checked out when you add it to the source-controlled project. If not, the file is checked in and you must check it out again in order to work with it. For details about checking files out and in after they're added to a project, see Management of Files in a Source-Controlled Project.

To add existing files to a controlled project

  1. From the Project menu, choose Source Control and then choose Add Files to Source Control.
  2. In the Add Files to Source Control dialog box, select the files you want to add.
    Note Keep checked out and Comment appear only if your source code control software supports these options.
  3. Choose OK.

    Visual FoxPro generates the control files necessary for the source control software, and then adds the files to the project. If you've selected many files, this process can take some time.

You can set it up so that when you add a file to a project, Visual FoxPro will prompt you to put it under source control.

To specify that Visual FoxPro prompts you to put new files under source control

  • In the Projects tab of the Options dialog box, make sure Automatically add new projects to source control is selected, and then choose OK.

    To make this setting the default, choose Set as Default, and then choose OK.

After you've added files to a project, you must update the project list before other developers can work with the new files.

See Also

Updating the Project List | Developing in Teams | Management of Visual FoxPro Projects Under Source Control | Detaching a Project from Source Control | Joining an Existing Source-Controlled Project


Joining an Existing Source-Controlled Project

If you are a new developer on a project that's already under source control, you must join the project before you can check files out and in. When you join a project, Visual FoxPro creates a local project list file and generates a current project file (.pjx file) for you.

To join an existing project

  1. From the File menu, choose Join Source Control Project.
  2. In the Open Project dialog box, select the server and directory that contains the Visual FoxPro project file you want to join.
  3. Set the working directory on your local machine; this specifies where the source control system will place files when you check them out and where it will look when you check them back in. For example, if you're using Visual SourceSafe as your source control provider, choose Browse from the Directory area and select an existing directory, or type the name of a new directory.
    Tip All developers on a project must use the same directory structure for the files in a project, although the names of individual subdirectories can differ.

See Also

Developing in Teams | Management of Visual FoxPro Projects Under Source Control | Detaching a Project from Source Control | Updating the Project List


Updating the Project List

Even after files have been added to the source-controlled project, other developers will not be able to work with them. Developers will be able to manually use their source control system to check files out and in if they need to, but the added files will not be displayed in the Project Manager for any developer except the developer who added the files. To make the files available to other developers, update the project list.

When you update the project list, Visual FoxPro:

  • Generates a new local project file list (.pjm file).
  • Checks in the new project file list (with the option set to keep the file checked out).
  • Merges the local and central project file lists if there are differences. If a merge conflict occurs, Visual FoxPro displays a dialog box to help you resolve the merge conflicts.
  • Rebuilds the local project (.pjx) file based on the merged project file list.
  • Gets local copies of files added to the project by other developers.
  • Prompts you to get the latest versions of the project files.
  • Refreshes the display in the Project Manager to reflect changes.

To update the project list

  • From the Project menu, choose Source Control, and then choose Update Project List.

As part of the update procedures, Visual FoxPro prompts you to get the latest versions of files. If you have a file already checked out, as a general rule you shouldn't get the latest version, because your version is almost certainly more current than the one on the network.

If you're getting the latest version of a text file (such as a program), the source control software can attempt to merge the latest changes with your version. For more information about merging text files, see Checking In Files.

When you're finished, other developers should also then update their project list (using the same procedure) in order to be able to work with the files you've added.

See Also

Developing in Teams | Management of Visual FoxPro Projects Under Source Control | Detaching a Project from Source Control | Joining an Existing Source-Controlled Project


Detaching a Project from Source Control

If you no longer want to control the files in a project, you can detach the project from source control. When you do so, files remain in the source control project so that other developers can continue to use them and so you can examine their history or use them with other projects.

If you have project files on your computer that are tagged as read-only — that is, you have copies of files, but they're not checked out — you can remove their read-only attribute when the project is detached from source control.

Note When you detach a project from source control, you break the link between your local project files and the source-controlled project, and your local files become read/write. Be sure to institute manual version control procedures after detaching the project, or you run the risks inherent in working with files that are not under source control.

To detach a project from source control

  1. Check in all the files under source control.
  2. From the Project menu, choose Detach Project from Source Control.

See Also

Updating the Project List | Removing Files from a Source-Controlled Project | Developing in Teams | Management of Visual FoxPro Projects Under Source Control


Removing Files from a Source-Controlled Project

You can remove individual files from source control if you no longer want them to be part of your source-controlled project. You might do this, for example, if a program or form becomes obsolete and is no longer part of your project

To remove a file from source control

  1. In the Project Manager, select the file to remove.
  2. From the Project menu, choose Source Control, and then choose Remove Files from Source Control.
  3. In the Remove Files from Source Control dialog box, select the files to remove, and then click OK.

If you remove a file from a Visual FoxPro project that's under source control, Visual FoxPro prompts you whether you want only to remove the file from the project or to delete it from disk. A setting in the Options dialog box determines whether Visual FoxPro also prompts you to remove the file from the source-controlled project.

  • If Remove files from source control upon removal from project is checked, Visual FoxPro also prompts you to remove the file from the source-controlled project.
  • If Remove files from source control upon removal from project isn't checked, you're not prompted, and the file is left under source control.

After a file has been removed from source code control, copies of it might still exist on other developers' computers. If so, the file is treated as a local file only for those developers.

See Also

Detaching a Project from Source Control | Sharing Files Between Source-Controlled Projects | Developing in Teams | Management of Visual FoxPro Projects Under Source Control


Sharing Files Between Source-Controlled Projects

You can set up a file so that it's a member of two or more source-controlled projects at the same time. This is useful if you use common files, such as standard programs, libraries, or dialog boxes, in more than one project. When you share files between projects, changes you check in to a file are reflected in all the projects that share the file.

The specific method for sharing files between source-controlled projects depends on your source control software. If file sharing options aren't supported by your source control provider, file sharing commands will not be available on the menu.

The first step of the following procedure applies to all source control systems that support file sharing. The subsequent steps might differ, depending on your source control software.

To share files between controlled projects

  1. From the Project menu, choose Source Control and then choose Share Files.
  2. In the dialog box that appears, indicate what files you want to share with your current project, and what project they currently belong to.

    The specific options available from this menu command depend on your source control system. For details, choose Help in the Share dialog box or refer to the documentation for your source control system.

    Tip In Microsoft Visual SourceSafe, you can see what projects a file is a member of by using the Project Properties command and choosing the Links tab. If you add a project to Visual SourceSafe, for proper mapping to the project, all files contained in the project must be in the project directory or path.

See Also

Removing Files from a Source-Controlled Project | Management of Files in a Source-Controlled Project | Developing in Teams | Management of Visual FoxPro Projects Under Source Control


Management of Files in a Source-Controlled Project

After you have put a Visual FoxPro project under source control, you can work with individual files or manage the project as a whole.

Working with Multi-File Components

Some project components in Visual FoxPro actually consist of multiple files: a primary file and one or more implicit files. For example, when you create a form, Visual FoxPro creates an .scx file (the primary file) and an .sct file (the implicit file). The following components have multiple files:

Component | Primary file type | Implicit file type(s)
Form | .scx | .sct
Report | .frx | .frt
Label | .lbx | .lbt
Class Library | .vcx | .vct
Menu | .mnx | .mnt
Table | .dbf | .fpt, .cdx, .idx
Database | .dbc | .dct, .dcx

When a developer checks out a component file, such as a form, Visual FoxPro also manages the corresponding implicit file or files. Likewise, when a file is checked back in, or a new file added, Visual FoxPro manages the implicit file or files automatically.

Note If you generate and compile a menu, you create local .mpr and .mpx files as well. These aren't initially under source control, but you can add them as files to your project, and then put them under source control as you would other files.

See Also

Sharing Files Between Source-Controlled Projects | Checking Out Files | Checking In Files | Discarding Changes | Getting the Latest Versions of Files | Comparing Files or Projects | Checking for Differences in Forms, Reports, and Other Table Files | Developing in Teams | Management of Visual FoxPro Projects Under Source Control


Checking Out Files

When you're working in a source-controlled project, Visual FoxPro can prompt you to check files out when you modify them by opening the appropriate editor. For example, if you select a form and choose Modify to open the Form Designer, Visual FoxPro can first prompt you to check out the files for the form. (If you don't check out the files, the form is displayed in the Form Designer, but is read-only.)

However, you can also check out files manually, which is useful if you want exclusive access to the file, but don't want to open the editor for the file just at the moment. You might do this, for example, if you intend to work with a file offsite.

To specify Visual FoxPro to prompt you to check out files being modified

  • In the Projects tab of the Options dialog box, make sure the option Check out files upon modify is checked, then choose OK.

    To make this setting the default, choose Set as Default, and then choose OK.

To check out a file manually

  1. In the Project Manager, select the file to work with.
  2. From the Project menu, choose Source Control, and then choose Check Out.
  3. In the Check Out Files dialog box, select the file or files you want to work with, and then click OK.

See Also

Management of Files in a Source-Controlled Project | Checking In Files | Developing in Teams | Options


Checking In Files

You must always check in files manually. Visual FoxPro doesn't automatically check in a file; for example, it doesn't check in a form when you close the Form Designer. Instead, it leaves the file checked out so you can continue to edit it, take it offsite, or work with it in some other fashion.

The exact result of the check-in process depends on the file you're checking in and on your source control software. For forms, menus, labels, class libraries, and other types of files, the file is treated as a binary file, and the source control software makes your new version of the file into the current one for other developers to check out.

Tip Always remember to check in files when you're done editing them. If you keep them checked out for long periods, you might prevent other developers from working with them, and you'll prevent the latest version of the file from being backed up during the course of your network backup.

To check in a file

  1. In the Project Manager, select the file to work with.
  2. From the Project menu, choose Source Control, and then choose Check In.
  3. Enter a comment describing the changes you've made.
  4. In the Check In Files dialog box, select the file, and then click OK.

Checking In Text Files

When you check in a text file such as a .prg file, and if multiple versions of the file are checked out, the source control software doesn't simply overwrite the central version. Instead, it checks whether there have been changes to the file since you last checked it out. If so, it attempts to merge those changes with your file. To do so, it adds, deletes, and changes lines in your copy of the file.

When it's finished merging, the source control software might also give you the opportunity to check in your file. Don't check in your file right away. Instead, test your application using the new version of the file that incorporates both your changes and those of other developers. Only when you're satisfied that the application works correctly, check in your file. If other developers have made further changes to the same file, you might have to merge, test, and check in again.

In some instances, the source control software might report a merge conflict, which indicates that it cannot resolve changes between your changes and those of other developers. This can occur, for example, if you and another developer have been updating the same lines of the same program. If the source control software cannot merge successfully, it creates a version of the file that contains the original text plus your changes, marks the conflicts, and writes that file to your computer. (The exact means by which the conflicts are marked depends on the source control software you're using.) The file then appears in the Project Manager with a merge conflict icon:

To resolve the merge conflict, you must edit the file again, make your changes, and remove the merge conflict markers. When you're finished editing, Visual FoxPro prompts you to confirm that you've resolved all conflicts. The file is then marked with the merge icon:

Test your application to be sure that the changes are working properly. You can then attempt to check the file in again. If no more merge conflicts occur, your file becomes the current version.

See Also

Checking Out Files | Discarding Changes | Developing in Teams | Management of Files in a Source-Controlled Project


Discarding Changes

If you've checked out a file, but decide to discard any changes you've made, you can undo the checkout. This has the effect of checking the file back in (that is, other users can then check the file out), but doesn't update it with changes. For example, if you mistakenly checked out a file instead of simply getting the latest version, undo the checkout instead of checking the file back in. This prevents the source code control system from having to create another version of the file, thus saving time and space.

Tip If you want to view a file but don't need to check it out, you can get the latest version of it.

To undo a checkout

  1. In the Project Manager, select the file to work with.
  2. From the Project menu, choose Source Control, and then choose Undo Check Out.
  3. In the Undo Check Out of Files dialog box, make sure the file you want is selected, and then click OK.

See Also

Checking In Files | Getting the Latest Versions of Files | Developing in Teams | Management of Files in a Source-Controlled Project


Getting the Latest Versions of Files

If you want to view the latest version of a file, you can check it out. However, if the file is already checked out, or if you only want to view the file (not modify it), you can get the latest version of a file. When you do, Visual FoxPro copies the most current checked-in version of a file to your computer, but leaves it as a read-only file. You can get the latest version of a file even if it's currently checked out.

If the file you're getting is a text file, the source control software will merge the most current one with your version instead of simply overwriting it.

Note To merge files when getting the latest version, you might need to enable this as an option in your source control software. For details, see the documentation for your source control software.

To get the latest version of a file

  1. In the Project Manager, select the file for which you want the latest version.
  2. From the Project menu, choose Source Control, and then choose Get Latest Version. If the file is currently checked out, you're prompted to replace or merge your checked-out version with the current version from the source control project.
    Note If you already have the file checked out, Visual FoxPro prompts you to overwrite it. If you've made changes to the file since last checking it out, choose No when prompted to replace the file.

See Also

Discarding Changes | Comparing Files or Projects | Developing in Teams | Management of Files in a Source-Controlled Project


Comparing Files or Projects

When working with files and with a project, you might need to compare the current local copy in your working directory with the current master copy in the source-controlled project. This can help you determine whether another user has changed a file, or it can help you pinpoint where you've made changes since you checked out the file.

Most source control systems can only compare and display differences between files if they're in text format. When Visual FoxPro compares forms, reports, menus, labels, and class libraries, it uses the text representations of those files.

Note If your source control provider doesn't support file comparison options, they aren't available on the menu.

To see differences between projects

  • From the Project menu, choose Source Control, and then choose Show Project Differences.

    The resulting report is produced by your source control software, so the specific information provided can vary. In general, however, the source control system will display a window with two panes, and will highlight or otherwise mark the differences between the local and master copies of the file.

To see differences between files or the project list

  1. If you're viewing differences for a single file, in the Project Manager, select the file for which you want to see differences.
  2. For a single file, from the Project menu, choose Source Control, and then choose Show Differences. For the project list, from the Project menu, choose Source Control, and then choose Show Project List Differences.

    The resulting report is produced by your source control software, so the specific information provided can vary. In general, however, the source control system will display the two versions side-by-side, and will highlight or otherwise mark new, deleted, and changed lines.

See Also

Getting the Latest Versions of Files | Checking for Differences in Forms, Reports, and Other Table Files | Developing in Teams | Management of Files in a Source-Controlled Project


Checking for Differences in Forms, Reports, and Other Table Files

In Visual FoxPro, only a few types of files are treated as text files by the source control software. These include program source code (.prg) files and the project file list (.pjm file). Forms, reports, and other types of files are actually stored as tables of information about their components. For example, a form's .scx file is a table of the controls in that form, plus information about the form itself. Table-type files are used to store information about forms (.scx files), reports (.frx files), menus (.mnx files), labels (.lbx files), and class libraries (.vcx files).

Because these files are stored as Visual FoxPro tables, source control systems cannot treat them as text files (the source control system treats them as "binary" files). As a result, tools for viewing differences between versions of these files cannot pinpoint the differences, nor can you see a history of changes.

In order to allow you to use source control to view differences in forms, reports, and similar files, Visual FoxPro creates text representations of them. Then, when you put one of these files under source control, Visual FoxPro creates a text version of the file, which it maintains automatically as you make changes.

Text representation of Visual FoxPro file

To support the capability to generate text representations of table-type files, Visual FoxPro includes the utility program Scctext.prg, or you can use a different program that you obtain from another source or write yourself.

To specify a text conversion utility

  1. In the Options dialog box, choose the Projects file.
  2. In the Text generation box, enter the name of the conversion program.
  3. Choose Set as Default, and then choose OK

Visual FoxPro automatically calls the text conversion program whenever you add a form, report, menu, label, or visual class file to a source-controlled project. The utility generates a text file that has the same name as the primary file, but uses "A" as the last letter of the extension. For example, for a form called Myform.scx, the utility generates a text file called Myform.sca. When you check in the form (or other file) after changing it, the source control software automatically creates and checks in the text file.

If you specify a text conversion utility when you already have forms, reports, and similar files in your source-controlled project, you must temporarily remove them from the project, and then re-add them with text generation enabled.

To generate text representations for existing files in a project

  1. Back up all the files that will be affected: forms, reports, menus, labels, and class libraries.
  2. Verify that the files aren't already checked out.
  3. From the Project menu, choose Source Control, and then choose Remove Files from Source Control.
  4. Select the files to remove from the project, and then choose OK.
  5. Enable text generation, following the steps described earlier.
  6. From the Project menu, choose Source Control, and then choose Add Files to Source Control.
  7. Select the files to add, and then choose OK.

As it puts the each file under source control, Visual FoxPro also creates the corresponding text representation for the file.

See Also

Comparing Files or Projects | Displaying File and Project Information | Developing in Teams | Management of Files in a Source-Controlled Project


Displaying File and Project Information

You can display information about individual files and about the project as a whole. For example, you can display the checkout history for an individual file or for the project list file. Information typically available includes:

  • The version number, which indicates how many times a new version of the file or project list has been checked in.
  • Who checked in the file or project file each time.
  • The date and time it was checked in.
  • What comments the developer added when checking in the file or project list.

To view checkout history for a file or the project list

  1. If you're viewing the history of a single file, in the Project Manager, select the file for which you want to see the history.
  2. For an individual file, from the Project menu, choose Source Control, then choose Show History. For the project list, from the Project menu, choose Source Control, and then choose Show Project List History.

    The specific options available from this menu command depend on your source control system. For details, choose Help in the dialog box that's displayed or refer to the documentation for your source control system.

You can also view the information about an individual or about the project that's being maintained by the source control system. This usually includes information such as the checkout status of the file or project list, whether the file is a text or binary file (which determines if you can merge your changes with the centrally-stored file), and so on.

To view source control information for a file or the project list

  1. If you're viewing the history of a single file, in the Project Manager, select the file for which you want to see the history.
  2. For an individual file, from the Project menu, choose Source Control, and then choose Source Control Properties. For the project list, from the Project menu, choose Source Control, and then choose Project Properties.

    The specific options available from this menu command depend on your source control system. For details, choose Help in the dialog box that's displayed or refer to the documentation for your source control system.

See Also

Checking for Differences in Forms, Reports, and Other Table Files | Development and Modification of Databases in Teams | Developing in Teams | Management of Files in a Source-Controlled Project


Development and Modification of Databases in Teams

In addition to working together with projects and project files, your team must be able to share information in databases. Working with databases as a team involves not only the issues of ordinary concurrency control for data in tables, but the need to be able to share database control information as well.

For several developers to work with a database at the same time, they must be able to share the database (.dbc) file. In Visual FoxPro, the .dbc file can be shared between developers as an ordinary data table. The .dbc file must therefore be stored centrally with the tables making up the database. Developers shouldn't keep local copies of a .dbc file because changes that they make to the database will not be reflected in other developers' versions of the file.

If you do need to change the .dbc file, note the following restrictions:

  • Developers cannot modify the same database element (such as a table structure, view, or connection) at the same time. When a developer modifies a database element, Visual FoxPro locks its entry in the .dbc file; other users can read the entry (that is, they can issue a USE command), but they cannot modify it (MODIFY STRUCTURE).
  • If a database element is in use, you cannot modify its structure. For example, if one developer has a table open, no other developer can modify its structure.
  • If you call the DBSETPROP( ) function to change the properties of a database, the function puts a write lock on the object being updated. If there's a lock conflict, DBSETPROP( ) follows the rules established with SET REPROCESS.

Working with Views and Connections

Views and connections work somewhat differently than tables. When you're first defining the view, Visual FoxPro uses the tables in a database, but doesn't lock them. However, because the tables are in use, other developers cannot modify their structures.

From the time you first save a new view or connection definition, Visual FoxPro locks it exclusively until you close the View or Connection Designer. In other words, as long as you have the view or connection open in a designer, it's locked exclusively. While the view is locked, no one else can modify it.

When you use a view, its structure is cached locally. This ensures that if the view is modified while you're using it — for example, if you call REFRESH( ) or REQUERY( ) — your form or report continues to run correctly.

See Also

Displaying File and Project Information | Development of Class Libraries in Teams | Developing in Teams | Management of Files in a Source-Controlled Project


Development of Class Libraries in Teams

Because class libraries (.vcx files) are a crucial part of most Visual FoxPro applications, teams must be able to coordinate development efforts when creating them. Working with class libraries in a team involves many of the same coordination issues that any set of application components does, but adds some issues unique to classes:

  • Changes to classes are propagated not just to applications that use those classes, but to all subclasses derived from them.
  • Multiple classes are often stored in a single library file, the minimum unit that can be managed by a source control system.

As with complex forms and programs, it's good practice to isolate development in a class library, so that one developer can make changes to the library without affecting the work of other developers. Ideally, the team of developers can work with a class library while it's being enhanced by another developer, without having to worry about whether changes to the libraries will cause problems in the application.

When a class is used, Visual FoxPro caches it on the user's computer, even after a form that uses the class has been released. You must explicitly release the class before Visual FoxPro will recognize it as no longer in use. If you've used a class during the current session (and it's therefore cached), but want to load a new version of the class, be sure to release the class to force Visual FoxPro to reload it from the changed library.

Putting Class Libraries Under Source Control

When you put a class library under source control, only one developer can check the library out at a time. The library becomes read-only for other developers. As a rule, this doesn't interfere with application development, because developers can use and subclass a library even if it's read-only. While the application developers work with the read-only version of the library, the class library developer can modify all the classes in the library.

If you use this approach, the developer who is updating the library shouldn't check in the file until it has been finished and tested. Otherwise, other developers will get the incomplete version of the file when they update their project file lists or get the latest versions of files.

If the library is very complex, you can also consider breaking it into smaller libraries for development. Another advantage of this approach is that smaller library files load faster. However, this means that different classes might be finished and available at different times.

Because each approach has its advantages, you should examine the requirements of your development team and choose the strategy that best fits how you work.

See Also

Development and Modification of Databases in Teams | Developing in Teams | Management of Files in a Source-Controlled Project | Displaying File and Project Information


Developing International Applications

To move into the world market, you must design your Visual FoxPro applications so they are as effective internationally as domestically. This section describes how to use the international features of Visual FoxPro to produce applications for selected locales.

In This Section

Preparation of an International Application
Preparing an international application usually involves three steps: creating data, writing code, and designing a user interface.
Design of the Interface
Because text tends to increase when you localize an application, it is important to be careful when designing the user interface components.
Entering International Data
An important aspect of developing international applications is understanding how to enter data into your application.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Design Considerations
Discusses how the design decisions you make will impact how you create your application.
Application Architecture
Describes how Visual FoxPro application architecture varies with the type of application you decide to create.
Security Considerations
Shows how you should be aware of security requirements from a business perspective and the implications that a chosen security model can have on performance, scalability, and deployment.
Planning for Team Development Projects
Discusses how using source control software, such as Microsoft Visual SourceSafe, to manage the files in a project makes it possible to create complex applications quickly by combining the skills of a team of developers.


Preparation of an International Application

Preparing an international application usually involves three steps: creating data, writing code, and designing a user interface. Before you take these steps, however, you need to consider the following questions:

  • What data is acceptable?
  • How do you write code for an international application?
  • What should you consider when designing a user interface?

The following sections address these questions and pose others you need to consider before you prepare your application.

Tip You can reduce the cost of developing an international application and bring it to market more quickly by designing it as an international application initially rather than modifying it for international use later on.

Preparing the International Data

To create international data for an application, you can enter it manually, import it from other applications, or append it to existing files and memo fields. For more information, see Importing and Exporting Data.

What Data Is Acceptable?

To decide what data is acceptable, first consider the locales in which the application will be used. The locales will determine the cultural content of the data as well as the languages in which the data is prepared.

In addition, the languages will affect the code page with which the data is prepared. A code page is a character set that a computer uses to display data properly, often to handle international characters. International characters include characters that have diacritical marks. Diacritical marks are placed over, under, or through letters to indicate sound changes from the unmarked form. The most common diacritical marks are the grave accent (` as in à), acute accent (´ as in á), circumflex (^ as in â), tilde (~ as in ã ), umlaut (¨ as in ä ), ring (° as in å), and slash (/ as in ø), all used in conjunction with vowels.

Ordinarily, data is automatically marked with the appropriate code page when you work with it. However, if you manually assign a code page to a table, or if you otherwise cause the code page to change, users might not recognize some or all of the data displayed. For more information, see Code Pages in Visual FoxPro.

Some languages, such as Chinese, Korean, and Japanese, use DBCS (double-byte character sets) to represent their data. If your application might run in these environments, you might need to use special string-handling functions and collation sequences for the application to work properly. For more information, see Application Creation with Double-Byte Character Sets.

How Do You Write Code?

An application consists of a user interface component and an application component. The user interface component contains graphics, text strings, and settings related to various locales, such as dates, currencies, numeric values, and separators. The application component contains the code that is run for all locales, including code that processes the strings and graphics used in the user interface.

The components of an application

When designing your application, keep the application and user interface components separate, because independent components make the application easier to localize and maintain. For example, with separate components, you don't have to browse the source code to localize interface elements. For more information, see Creating or Modifying Programs.

How Do You Design a User Interface?

The menus, forms, controls, toolbars, and bitmaps used in the user interface must serve the locales for which you're designing the application. For example, if you design the application for users in Germany and France, dialog boxes must be large enough to display instructions properly when the instructions are localized in German and French. In addition, the images used in icons and bitmaps must be culturally correct so that they're understood in the target locales. For more information, see Design of the Interface.

Testing the Application

To test an international application, you need to check the country and language dependencies of the locale for which the application is designed. Testing involves checking the application's data and user interface to ensure that they conform to the locale's standards for date and time, numeric values, currency, list separators, and measurements.

See Also

Developing International Applications | Design of the Interface | Importing and Exporting Data | Entering International Data | Code Pages in Visual FoxPro | Code Pages Supported by Visual FoxPro


Design of the Interface

Because text tends to increase when you localize an application, be careful when designing the following user interface components:

  • Application messages
  • Menus and forms
  • Icons and bitmaps

Creating Application Messages

When you create messages in your application, English text strings are usually shorter than equivalent text strings in other languages. The following table shows the additional average growth for strings, based on their initial length.

English length (in characters) | Additional growth for localized strings
1 to 4 | 100%
5 to 10 | 80%
11 to 20 | 60%
21 to 30 | 40%
31 to 50 | 20%
over 50 | 10%

Designing Menus and Forms

As with messages, menus and forms can grow when the application is localized. For instance, consider the following forms, which are part of an Automated Teller Machine sample application. The first figure shows the English form, and the second figure shows the Spanish equivalent. You can see that extra space was allocated for text to increase in the form.

Tip If you allow room for text to increase in an interface, localizers need less time to resize controls and to redesign the interface.

Text needs more room when localized

In menus and forms, avoid crowding status bars. Also, avoid abbreviations, because they might not exist in other languages.

Using Icons and Bitmaps

Used properly, icons and bitmaps can be an important part of a user interface. However, the meaning of icons and bitmaps can be more ambiguous than the meaning of words. Therefore, consider the following guidelines when using icons and bitmaps:

  • Use images that are universally recognized. For example, use an envelope to represent mail, but don't use a mailbox because it's not a universal symbol.
  • Use culturally sensitive images. For example, avoid using images of religious symbols and animals.
  • Avoid using text in bitmaps, because text growth can become a problem, just as it can in other parts of the interface.
  • Avoid jargon, slang, humor, extravagant language, and ethnic stereotypes.
  • Use ToolTips to help explain icons, which have the added advantage of expanding automatically to the size of the text they display.
  • If you portray men and women, ensure that their gender roles are suitable, and that gestures and images of the human body are appropriate in the target culture.
  • Use color appropriately. For example, avoid using color combinations associated with national flags or political movements.

If you're not sure whether an icon or bitmap is appropriate, consult someone in the locale for which you're designing the application.

See Also

Preparation of an International Application | Entering International Data | Developing International Applications | Code Pages in Visual FoxPro | Code Pages Supported by Visual FoxPro


Entering International Data

An important aspect of developing international applications is knowing how to enter data into your application. Data can come into your application in two ways:

  • Users enter the data.
  • You or your users import the data from existing files.

The following sections discuss these two methods.

Entering International Characters

You can enter international characters into Visual FoxPro using your keyboard. The exact method you use depends on the language you're working with. In single-byte character environments, you can enter the characters directly, or by pressing a combination of keys on the keyboard. On the other hand, double-byte character set (DBCS) environments often provide an Input Method Editor (IME), which is an application you can use to enter characters.

Entering Characters Using the Keyboard

With an international keyboard you can display international characters by simply pressing the keys dedicated to those characters. If your keyboard doesn't have keys for international characters, you can enter such characters by using the character map provided with Windows or by pressing the ALT key in conjunction with keys on the numeric keypad.

The easiest way to enter an international character is to copy it from the character map, which is available from the Accessories menu.

Alternatively, you can enter an international character by pressing ALT combined with a four-digit number beginning with zero that you enter from the numeric keypad.

Note You cannot enter international characters in FoxFont. For example, if you open the Command window, switch to FoxFont, and then press a dedicated key, the result isn't the character on the key. For best results, avoid FoxFont in international applications.

To create an international character

  • Copy the character from the character map, and then paste it into your document.

    -or-

  • Hold down ALT and then type a zero followed by the appropriate three-digit ASCII code.
    Tip The status bar on the character map shows the key combination that corresponds to each character selected on the map.

For instance, to type ö (ANSI code 246), press NUM LOCK on the numeric keypad, and then press ALT+0246. Be sure to use a standard Windows font — not FoxFont or FoxPrint.

Troubleshooting

If characters don't transport correctly, see if you're using FoxFont. For example, FoxFont is the default for user-defined windows created with DEFINE WINDOW (if the FONT clause is omitted). Be sure to use the FONT clause to specify a font other than the standard Windows font when creating user-defined windows so that international characters display correctly.

Entering Characters Using an IME

If you're working in an IME environment, you can use an Input Method Editor to enter characters into Visual FoxPro. The IME is an application provided with your environment that makes it possible for you to type characters on the keyboard to display a selection of international characters and then choose the specific character you want. For example, an IME for Chinese might make it possible for you to enter a Pinyin representation of a Chinese word and then display a list of characters that match the representation. When you select the character you want, the IME pastes it into Visual FoxPro.

You can control when Visual FoxPro displays an IME by setting the IMEMode property or calling the IMESTATUS( ) function. If you turn the IME window on, Visual FoxPro automatically displays the IME when you're editing in a system window such as the Browse or Edit windows. If you turn the IME window off, you can invoke the IME by pressing the appropriate keys on your keyboard.

Appending and Copying International Data

If you're importing or copying data from delimited files using the APPEND FROM or COPY TO commands, you can specify what character is being used in the file to separate fields. For example, it's common in many European countries to use a semicolon (;) as a field delimiter, whereas the common delimiters in the United States are comma (,), tab, or space.

To import or copy files and specify a delimiter, add the DELIMITED WITH CHARACTER clause to the APPEND FROM or COPY TO commands:

COPY TO mytxt.txt DELIMITED WITH _ WITH CHARACTER ";"

See Also

Design of the Interface | Code Pages in Visual FoxPro | Developing International Applications | DEFINE WINDOW | Code Pages Supported by Visual FoxPro


Creating the Application

A Microsoft Visual FoxPro application typically includes one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, reports, and menus.

To create an application using Visual FoxPro

  1. Create a project. For more information, see Working with Projects.
  2. Configure your application by setting a starting point, initializing the environment, and starting the event loop. For more information, see Configuring an Application.
  3. Create a user interface for your application. For more information see, Creating the User Interface.
  4. Create reports and labels for your application. For more information, see Creating Reports and Labels.
  5. Create help files for your application. For more information, see Creating Help.

Note The Application Framework can create applications automatically that include all required, and many optional, elements that make an application effective and easy to use. For more information, see Creating Applications with the Application Framework.

In This Section

Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Configuring an Application
Explains the steps involved in configuring a Visual FoxPro application.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application builder.
Creating the User Interface
Discusses how creating forms, classes, controls, and toolbars can provide a rich set of tools for your user interface.
Creating Reports and Labels
Describes how to implement Visual FoxPro reports and labels in your applications. Learn how to collect and organize your data to print or display on screen.
Creating Help
Describes how to implement professional help into your application using HTML Help or WinHelp 4.0.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Describes how careful planning saves time, effort, and money. Many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating Web Services and Components
Explains how you can extend your Visual FoxPro application by making it possible for it to work for multiple users, take advantage of Microsoft ActiveX controls and automation-enabled applications.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Data
Describes how to create effective applications with indexes, tables, and databases based on your data requirements.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Teaches how to use the modular approach to makes it possible to verify the functionality of each component you create. Then you can compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Explains that when you develop an application, you must test for errors within and across components. Visual FoxPro provides debugging tools to help you find and correct any errors you discover in your applications.
Distributing Applications
Prepares you to distribute your application by including all required files and creating distribution disks, after you have completed developing and testing your application.


Working with Projects

A project is defined as a configuration and a group of files that produce a program or final binary file or files. In Visual FoxPro, you can manage a project using the Project Manager window, allowing you to visually see and manipulate items in your project. Projects make it easier and faster to develop large applications.

In This Section

Creating a Project
Explains how to use the Project Manager to create a project and to organize and work with tables, forms, databases, reports, queries, and other files when you are managing tables and databases or creating an application.
Adding Files to a Project
Explains how you easily add files to a project using the Application Wizard and/or Project Manager.
Structuring a Program as a Main File
Describes how you can use a program file, which includes commands to handle the tasks associated with major application tasks, as the main file in your application.
Project Manager Hooks
Describes actions that access a project programmatically so you can manipulate a project as an object.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Describes how careful planning saves time, effort, and money and how many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating the Application
Discusses how to create a Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Creating Web Services and Components
Describes how you can extend your Visual FoxPro application to make it work for multiple users, and to take advantage of Microsoft ActiveX controls and automation-enabled applications.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Data
Describes how to create effective applications with indexes, tables, and databases based on your data requirements.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Describes how to use the modular approach to verify the functionality of each component you create and then compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Explains that Visual FoxPro provides debugging tools to help you find and correct any errors you discover in your applications.
Distributing Applications
Describes how to prepare to distribute your application by including all required files and creating distribution disks, after you have completed developing and testing your application.


Creating a Project

Using the Project Manager, you can quickly familiarize yourself with Visual FoxPro. The Project Manager provides an easy, visual way to organize and work with tables, forms, databases, reports, queries, and other files when you are managing tables and databases or creating an application.

If you have your own set of tables from earlier versions of FoxPro, you can add them to a project immediately to see how Visual FoxPro works. If you have other data you want to organize (be it in spreadsheets, text files, or tables from other applications), you can import it into Visual FoxPro and add it to a project.

You can create a new project at any time by choosing the New option from the File menu.

To create a new project

  1. From the File menu, choose New.
  2. Select Project and choose New File.
  3. In the Create dialog box, select where to save the project and type the name you want to assign to the new project.
  4. Choose Save.

To help you become familiar with Visual FoxPro, you can also use the sample files that are provided. These samples are in folders within the Visual FoxPro ...\Samples directory.

See Also

Upgrading from Earlier Versions | Installing Visual FoxPro | Importing and Exporting Data | Visual FoxPro Start Page


Adding Files to a Project

A Visual FoxPro project consists of separate components that are stored as individual files. For example, a simple project might consist of forms (.scx files), reports (.frx files), and programs (.prg and .fxp files). In addition, a project usually has one or more databases (.dbc files), tables (stored in .dbf and .fpt files) and indexes (.cdx and .idx files). To be included in an application, a file has to be added to your project. That way, when you compile your application, Visual FoxPro can include the files for that component in the finished product.

You can easily add files to a project in a number of ways:

  • To create a project and add existing files, use the Application Wizard.
  • To automatically add new files to a project, open a project, then create the new files from within the Project Manager.
  • To add existing files to a project, open a project and add them using the Project Manager.

If you've used the Application Wizard or Project Manager to create the files, you usually don't need to do anything else — the file is automatically included in the project. One exception, however, is if your application includes a file that will be modified by the user. Because included files are read-only, you must mark the file as excluded. For more information, see Referencing Modifiable Files.

Tip For a list of file types and extensions used in Visual FoxPro, see File Extensions and File Types.

Creating and Modifying Files with Project Manager

The Project Manager simplifies creating and modifying files. Just select the type of file you want to create or modify and choose the New or Modify button. Visual FoxPro displays the design tool appropriate to the type of file you selected.

To create a file to add to the Project Manager

  1. Select the element you want to create.
  2. Choose New.

With some items, you have the option to use a wizard to help you create the file.

To modify a file

  1. Select an existing file.
  2. Choose Modify.

For example, to modify a table, select the name of the table and choose Modify to display the table in the Table Designer.

Adding a Description to a File

When you create or add a new file, you can add a description to the file. This description is shown at the bottom of the Project Manager when the file is selected.

To add a description to a file

  1. In the Project Manager, select the file.
  2. From the Project menu, choose Edit Description.
  3. In the Description dialog box, type a description for the file.
  4. Choose OK.

Adding an Existing File to a Project

If an existing file is not already part of your project, you can add it manually.

To add a file to a project manually

  1. In the Project Manager Window, choose the type of component you want to add by selecting it in the hierarchy.
  2. Choose Add.
  3. In the Open dialog box, select the file you want to add.
  4. Choose OK.

To remove a file from a project

  1. Select the element you want to remove.
  2. Choose Remove.
  3. In the confirmation prompt, choose Remove.

If you want to delete the file from your computer, choose Delete.

Visual FoxPro also adds files to your project if you reference them in a program or form. For example, if a program in your project includes the following line, Visual FoxPro adds the file Orders.scx to your project:

DO FORM ORDERS.SCX

If a file is referenced in this way, it is not immediately included in a project. Later, when you build the project, Visual FoxPro resolves references to all files and automatically includes implicit files in the project. Additionally, if any other file is referenced through user-defined code within the new file, building the project will also resolve that reference and include the file. The referenced files appear in the Project Manager the next time you view the project.

Caution Visual FoxPro might not be able to resolve references to picture (.bmp and .msk) files, depending on how they are used in code. Therefore, add pictures to your files manually. In addition, Visual FoxPro cannot automatically include files that are referenced using macro substitution, because the name of the file is not known until the application is running. If your application references files using macro substitution, include the referenced files manually.

See Also

Structuring a Program as a Main File | Referencing Modifiable Files | Compiling an Application | Application Wizard


Structuring a Program as a Main File

If you use a program (.prg) file as the main file in your application, you must be sure that it includes commands to handle the tasks associated with major application tasks. The main file doesn't have to issue commands directly to accomplish all the tasks. For example, it is common to call procedures or functions to handle tasks such as initializing the environment and cleaning up.

Note If you used the Application Wizard and allowed it to create the program Main.prg, you can modify the program the wizard created instead of creating a new one. The wizard uses a special class to define an object for the application. The main program includes sections to instantiate and configure the object.

To build a simple main program

  1. Initialize the environment by opening databases, declaring variables, and so on.
  2. Establish the initial user interface by calling a menu or form.
  3. Establish the event loop by issuing the READ EVENTS command.
  4. Issue CLEAR EVENTS command from a menu (such as an Exit command) or a button (such as an Exit command button). The main program shouldn't issue this command.
  5. Restore the environment when the user quits the application.

For example, your main program might look like this:

Code Comments
DO SETUP.PRG
 Call program to set up environment (store values in public variables)
DO MAINMENU.MPR
 Display menu as initial interface
READ EVENTS
 Establish event loop. A different program (such as Mainmenu.mpr must issue a CLEAR EVENTS command)
DO CLEANUP.PRG
 Restore environment before quitting

See Also

Controlling the Event Loop | Adding Files to a Project | Compiling an Application | Application Architecture | Setting the Starting Point | Initializing the Environment


Project Manager Hooks

In previous versions of Visual FoxPro, the only access to a project was through direct table manipulation of the project's .pjx file. In Visual FoxPro, you can access a project programmatically and therefore manipulate a project as an object. A project can be manipulated at design time while the project is open in the Project Manager, or at design time and run time without the Project Manager visible.

The following are some of the actions you can perform programmatically on a project:

  • Add or delete files from a project.
  • Add files in the project to source code control applications (such as Microsoft Visual SourceSafe) and check files in and out of source code control.
    Note If you add a project to Visual SourceSafe, for proper mapping to the project, all files contained in the project must be in the project directory or path.
  • Determine the number of files in a project and their types.
  • Open and modify files in the project.
  • Change properties of the project.
  • Change properties of files in the project.
  • Change properties of Automation servers (.dll dynamic-link libraries or .exe executable files) built from the project.
  • Execute code when events occur in the project.
  • Rebuild the project, or build .app, .exe, or .dll files from the project.

With the project manager hooks, advanced developers can create their own project managers with unique customized user interfaces.

In This Section

Project Object Hierarchy
Illustrates the object hierarchy for a project, a project object, and its associated ProjectHook object.
Project Object Architecture
Describes the language elements, such as clauses and project events, that make up the project object architecture.
Running the Project Manager Hooks Sample
Provides instructions on how to locate and run the Visual FoxPro Solutions Sample application.

Related Sections

Development Productivity Tools
Provides information on developer tools provided for application development within the Visual FoxPro application and the language.
IntelliSense Overview
Provides information on IntelliSense, which displays information in popup windows and drop-down lists that assist you with statement and function completion syntax.
Coverage Profiler Application
Discusses a coverage application, which writes information about which lines of code in a file were run, and a profiler application, which provides information about which lines actually run, how many times a line is run, duration, and so on.
Automating Keystroke Tasks with Macros
Describes how you can record and save keystrokes in macros by using the Macros dialog box.
Productivity Tools
Describes the different tools available to help make creating Visual FoxPro applications easier and faster.


Project Object Hierarchy

The object hierarchy for a project consists of the project, a project object, and its associated ProjectHook object. A project object contains a files collection, consisting of files in the project, and a servers collection, consisting of Automation servers created from the project. The following diagram illustrates the project object hierarchy within the Visual FoxPro object model:

Projects Collection

The projects collection gives direct access to a project object, allowing you to manipulate the project and the files and servers the project contains. A project object is added to the projects collection whenever a project is created, opened or an .app, .dll, or .exe is built from the project.

Like other OLE collections, you can obtain information about a project from the projects collection. For example, the following code uses the projects collection Count and Item properties to display the names of all the projects in the projects collection, and then uses the FOR EACH command to display the same information:

nProjectCount = Application.Projects.Count

FOR nCount = 1 TO nProjectCount
   ? Application.Projects.Item(nCount).Name
NEXT

FOR EACH oProj IN Application.Projects
   ? oProj.Name
ENDFOR

This line of code uses the ActiveProject property to add a program, Main.prg, to the currently active project:

Application.ActiveProject.Files.Add('Main.prg')

This line of code adds Main.prg to the first project added to the projects collection:

Application.Projects[1].Files.Add('Main.prg')

A projects collection has the following property and method:

Properties
Count
Methods
Item

The Project Object

The project object is instantiated whenever a project is opened from the File menu or with the CREATE PROJECT, MODIFY PROJECT, BUILD APP, BUILD DLL, BUILD EXE, or BUILD PROJECT commands. The project object allows you to programmatically manipulate the project, and can be accessed through the Visual FoxPro Application object. Note that the Application object supports a new ActiveProject property that provides a project object reference to the project open in the currently active Project Manager.

A project object has the following properties and methods:

Properties |
Application | AutoIncrement
BaseClass | BuildDateTime
Debug | Encrypted
HomeDir | Icon
MainFile | Name
Parent | ProjectHook
ProjectHookClass | ProjectHookLibrary
SCCProvider | ServerHelpFile
ServerProject | TypeLibCLSID
TypeLibDesc | TypeLibName
VersionComments | VersionCompany
VersionCopyright | VersionDescription
VersionLanguage | VersionNumber
VersionProduct | VersionTrademarks
Visible |
Methods |
Build | CleanUp
Refresh | SetMain

The ProjectHook Object

A ProjectHook object is a Visual FoxPro base class that is instantiated by default whenever a project assigned to the ProjectHook object is opened. (You can include the NOPROJECTHOOK clause in CREATE PROJECT and MODIFY PROJECT to prevent a ProjectHook object from being instantiated for the project.)

The ProjectHook object allows programmatic access to events that occur in a project. For example, you can execute code whenever a file is added to a project. This optional object differs from the Project Object, which contains all the properties and methods available in the Project Information dialog box.

You can specify a default ProjectHook class for new projects in the Projects tab of the Options dialog box. If a default ProjectHook class isn't specified in the Projects tab, new projects aren't assigned a ProjectHook class. You can specify a project hook class for an individual project (overriding the default ProjectHook class) in the Project Information dialog box. At run time, you can use the ProjectHook property to specify a project hook class for a project. If you change the ProjectHook class for a project, the new ProjectHook class doesn't take effect until the project is closed and opened again.

A ProjectHook object has the following properties, events, and methods:

Properties |
BaseClass | Class
ClassLibrary | Comment
Name | OLEDropEffects
OLEDropHasData | OLEDropMode
Parent | ParentClass
Tag |
Events |
AfterBuild | BeforeBuild
Destroy | Error
Init | OLEDragDrop
OLEDragOver | OLEGiveFeedBack
QueryAddFile | QueryModifyFile
QueryRemoveFile | QueryRunFile
Methods |
AddProperty | ReadExpression
ReadMethod | ResetToDefault
SaveAsClass | WriteExpression

Project Object and the ProjectHook Object Interaction

When you open the Project Manager from the File menu, or with the CREATE PROJECT or MODIFY PROJECT commands, the Project Manager window appears and a project object is instantiated with its associated ProjectHook object. Project build commands (BUILD PROJECT, BUILD APP, BUILD DLL, and BUILD EXE) also instantiate the project and ProjectHook objects.

When an event occurs in a project, the project object passes the event to the ProjectHook object. User code in the event in the ProjectHook object is executed and control is passed back to the Project object. The value returned to the project object from the ProjectHook object determines if the project object finishes the operation. Placing NODEFAULT in the event code prevents the default action from being performed. For example, placing NODEFAULT in the QueryAddFile event prevents a file from successfully being added to a project.

Files Collection

The files collection gives direct access to a file object, allowing you to manipulate file objects in a project while the project is open. Like other OLE collections, you can obtain information about a file in a project from the files collection. For example, the following code uses the files collection Count and Item properties to display the names of all the files in the files collection, and then uses the FOR EACH command to display the same information:

nFileCount = Application.ActiveProject.Files.Count

FOR nCount = 1 TO nFileCount
   ? Application.ActiveProject.Files.Item(nCount).Name
NEXT

FOR EACH oProj IN Application.ActiveProject.Files
   ? oProj.Name
ENDFOR

This line of code uses the ActiveProject property to add a file, Main.prg, to the currently active project:

Application.ActiveProject.Files.Add('Main.prg')

This line of code adds Main.prg to the first project added to the projects collection:

Application.Projects[1].Files.Add('Main.prg')

The files collection has the following properties and methods:

Properties
Count
Methods
Add
Item

File Object

The file object allows you to manipulate individual files in a project.

A file object has the following properties and methods:

Properties |
CodePage | Description
Exclude | FileClass
FileClassLibrary | LastModified
Name | ReadOnly
SCCStatus | Type
Methods |
AddToSCC | CheckIn
CheckOut | GetLatestVersion
Modify | Remove
RemoveFromSCC | Run
UndoCheckOut |

Servers Collection

The servers collection gives direct access to a server object, allowing you to manipulate the servers that a project contains. A server object is added to the servers collection whenever a dynamic-link library (.dll) or executable (.exe) file containing an Automation server is built from the project. For more information about creating Automation servers, see Creating Automation Servers in Adding OLE.

A servers collection has the following property and method:

Properties
Count
Methods
Item

Server Object

The server object lets you determine information (including type library information) about Automation servers contained in a project. This information is also available in the Servers tab of the Project Information dialog box. Note that a server object isn't created until the project containing the OLEPUBLIC class (specified in the DEFINE CLASS command) is built.

A server object has the following properties and methods:

Properties |
CLSID | Description
HelpContextID | Instancing
ProgID | ServerClass
ServerClassLibrary |

See Also

Project Manager Hooks | Project Object Architecture | Running the Project Manager Hooks Sample | Development Productivity Tools | Application Object


Project Object Architecture

A Visual FoxPro project object exposes an IDispatch interface so that Automation clients, ActiveX controls, and other COM objects can access the project object through standard OLE interfaces. Because a project object now exposes an IDispatch interface, the errors that can be generated when manipulating projects are OLE errors.

Language Enhancements

Two new clauses have been added to the CREATE PROJECT and MODIFY PROJECT commands. The first clause, NOPROJECTHOOK, prevents the ProjectHook object from being instantiated for a project. The second clause, NOSHOW, opens a project without displaying it in the Project Manager, allowing you to programmatically manipulate the project without displaying it. You can use the Visible property to later display the Project Manager. For more information about these new clauses, see CREATE PROJECT and MODIFY PROJECT.

Project Events

The following sections describe events and the order in which they occur when projects are created, modified, closed, built, and so on.

Creating a New Project

The following events occur when you execute CREATE PROJECT, create a new project from the File menu, or click the New toolbar button and specify to create a new project:

  1. The project object is created.
  2. The ProjectHook object is instantiated.
  3. The Init event for the ProjectHook object occurs. If the Init event returns true (.T.), the default, the project is created and the project is displayed in the Project Manager.

    If the Init event returns false (.F.), the project isn't created, the project and ProjectHook objects are released, and the Project Manager isn't displayed.

Modifying an Existing Project

The following events occur when you execute MODIFY PROJECT, modify an existing project from the File menu, or click the Open toolbar button and specify an existing or new project:

  1. The project object is created. The project object obtains its values from the project's .pjx file.
  2. The ProjectHook object is instantiated.
  3. The Init event for the ProjectHook object occurs. If the Init event returns true (.T.) (the default), the project is opened for modification in the Project Manager.

    If the Init event returns false (.F.), the project isn't opened for modification, the project and ProjectHook objects are released, and the Project Manager isn't displayed.

Closing a Project

The following events occur when an open project is closed:

  1. The ProjectHook Destroy event occurs and the ProjectHook object is released.
  2. The Project object is released.

Issuing BUILD APP, BUILD DLL, or BUILD EXE

The following events occur when BUILD APP, BUILD DLL, or BUILD EXE is issued:

  1. The project object is created. The project object obtains its values from the project's .pjx file.
  2. The ProjectHook object is instantiated.
  3. The Init event for the ProjectHook object occurs. If the Init event returns true (.T.), the default, the ProjectHook BeforeBuild event occurs. If NODEFAULT is included in the BeforeBuild event, the .app, .dll, or .exe isn't built. Otherwise, the build process continues.

    If any files are added to the project during the build process, the ProjectHook QueryAddFile event occurs before each file is added. If NODEFAULT is included in the QueryAddFile event, a file isn't added to the project. Otherwise, the file is added to the project. When the .app, .dll, or .exe is successfully built, the ProjectHook AfterBuild event occurs, and then the ProjectHook Destroy event occurs.

    If the Init event returns false (.F.), the app, .dll, or .exe isn't built, and the project and ProjectHook objects are released.

Issuing BUILD PROJECT

The following events occur when BUILD PROJECT with the FROM clause is issued. If the FROM clause is omitted, the events occur in the order described above when BUILD APP, BUILD DLL, or BUILD EXE is issued.

  1. The project object is created. The project object obtains its values from the project's .pjx file.
  2. The ProjectHook object is instantiated.
  3. The Init event for the ProjectHook object occurs. If the Init event returns true (.T.), the default, the files specified in the FROM clause are added individually to the project. The ProjectHook QueryAddFile event occurs before each file is added to the project. If NODEFAULT is included in the QueryAddFile event, the file isn't added to the project. Otherwise, the file is added to the project.

    The ProjectHook BeforeBuild event then occurs. If NODEFAULT is included in the BeforeBuild event, the project isn't built. Otherwise, the project is built.

  4. When the project build is complete, the ProjectHook AfterBuild event occurs, and then the ProjectHook Destroy event occurs.

    If the ProjectHook Init event returns false (.F.), the project isn't built. The project and ProjectHook objects are released and a new .pjx file isn't created.

Using a Drag and Drop Operation

The following events occur when you drag a file or a set of files over the outline section (treeview) of the Project Manager:

  1. When the mouse pointer is positioned over the outline section of the Project Manager, the ProjectHook OLEDragOver event occurs with the nState parameter set to 0 (DRAG_ENTER in Foxpro.h). The OLEDragOver event then occurs repeatedly with the nState parameter set to 2 (DRAG_OVER in Foxpro.h). If the mouse pointer moves outside of the outline section of the Project Manager, the OLEDragOver event occurs with the nState parameter set to 1 (DRAG_LEAVE in Foxpro.h).
  2. The ProjectHook OLEDragDrop event occurs if you release the mouse button while the mouse pointer is positioned over the outline section of the Project Manager. By default, Visual FoxPro adds each file dropped on the Project Manager to the project. The ProjectHook QueryAddFile event occurs before each file is added to the project.

Adding a File with the Add Button

The following events occur when you add a file to a project by clicking the Add button in the Project Manager:

  1. The Open dialog box appears.
  2. If you select a file and choose OK, a file object is created for the file you select.
  3. The ProjectHook QueryAddFile event occurs and the name of the file object is passed to the event. If NODEFAULT is included in the QueryAddFile event, the file isn't added to the project. Otherwise, the file is added to the project.

Adding a File with the New Button

The following events occur when you add a new file to a project by clicking the New button in the Project Manager:

  1. The appropriate designer or editor for the file is displayed.
  2. When the new file is saved, the Save As dialog box is displayed. Clicking Save creates a file object for the new file.
  3. The ProjectHook QueryAddFile event occurs and the name of the file object is passed to the event. If NODEFAULT is included in the QueryAddFile event, the file isn't added to the project. Otherwise, the file is added to the project.

Modifying a File with the Modify Button

The following events occur when you modify a file in a project by clicking the Modify button in the Project Manager:

  1. The ProjectHook QueryModifyFile event occurs before the appropriate designer or editor for the file is displayed.
  2. The file object for the file to modify is passed as a parameter to the QueryModifyFile event. If NODEFAULT is included in the QueryModifyFile event, the appropriate designer or editor for the file isn't displayed and the file isn't modified. Otherwise, the file is opened in the appropriate designer or editor for modification.

Removing a File with the Remove Button

The following events occur when you remove a file in a project by clicking the Remove button in the Project Manager:

  1. The ProjectHook QueryRemoveFile event occurs.
  2. The file object for the file to be removed is passed as a parameter to the QueryRemoveFile event. If NODEFAULT is included in the QueryRemoveFile event, the file isn't removed from the project. Otherwise, the file is removed from the project.

Executing a File with the Run Button

The following events occur when you execute a file in a project by clicking the Run button in the Project Manager:

  1. The ProjectHook QueryRunFile event occurs.
  2. The file object for the file to be executed is passed as a parameter to the QueryRunFile event. If NODEFAULT is included in the QueryRunFile event, the file isn't executed. Otherwise, the file is executed.

Rebuilding a Project or Building a File with the Build Button

The following events occur when you rebuild the project or build an .app, .dll, or .exe from a project by clicking the Build button in the Project Manager:

  1. The Build Options dialog box is displayed.
  2. You can choose Rebuild Project, Build Application, Build Executable, or Build COM DLL, and specify additional build options. If you click Cancel, the build doesn't occur.
  3. The ProjectHook BeforeBuild event occurs if you click OK, and the build process begins.
  4. When the build is completed, the ProjectHook AfterBuild event occurs.

See Also

Project Object Hierarchy | Running the Project Manager Hooks Sample | Development Productivity Tools


Running the Project Manager Hooks Sample

The Visual FoxPro Solutions Sample application includes a sample named "Track activities in a project" that demonstrates many of the new Project Manager hooks.

To run the Solutions Sample application

  • Enter the following in the Command window:
    DO (HOME(2) + 'solution\solution')

    -or-

  1. From the Program menu, choose Do.
  2. Choose the ...\Samples\Solution folder.
  3. Double-click Solution.app.

To run the "Track activities in a project" sample

  1. After starting Solution.app, double-click Projects.
  2. Click Track activities in a project and then click Run Sample.

The Track activities in a project sample allows you to open a project and then manipulate the project in any manner. Any changes you make to the project are stored in a table. When you close the project, you can view the changes you made to the project in a Browse window.

For more information about how the Track activities in a project sample works and to take a closer look at the code behind the sample, you can open the form used to create the sample.

To open the Track activities in a project form

  1. After starting Solution.app, double-click Projects.
  2. Click Track activities in a project and then click See Code.

Acttrack.scx, the form used to create the Track activities in a project sample, opens in the Form designer.

You might also want to take a closer look at the ProjectHook class library, Project_hook.vcx, that is assigned to the project you open in the Track activities in a project sample. Most of the code that is executed when project events occur is in the event procedures in this class library. Project_hook.vcx is located in the ...\Samples\Solution\Tahoe directory.

See Also

Project Object Architecture | Development Productivity Tools | Project Object Hierarchy


Configuring an Application

A Visual FoxPro application must be configured properly so that it performs per your specifications set during the application planning.

In This Section

Setting the Starting Point
Explains how to set the file that is to be the starting point for your application.
Initializing the Environment
Describes how to configure your application environment.
Controlling the Event Loop
Describes how to start and stop your application's event loop.

Related Sections

Developing Visual FoxPro Applications
Explains concepts about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed for Visual FoxPro applications.
Application Planning
Describes the various steps involved in properly planning an application.
Application Architecture
Describes how Visual FoxPro application architecture varies with the types of applications you decide to create.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application Builder.
Structuring a Program as a Main File
Provides information on the structure a main file should have.
Customizing the Visual FoxPro Environment
Describes ways to configure Visual FoxPro and your applications for optimal use.
Creating the User Interface
Explains features such as forms, controls, toolbars, classes, and menus that Visual FoxPro contains to create a rich user interface.
Creating Reports and Labels
Explains how to create and modify reports and labels.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.
Optimizing Applications
Describes concepts on how to maximize the performance of your Visual FoxPro application.
System Variables Overview
Describes what system variables are and how they are used in Visual FoxPro applications.


Setting the Starting Point

Main files link each component together and set the starting point for your application. The main file serves as the execution starting point for your application, and can consist of a program or form. When users run your application, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed. All applications must have a main file. Usually, the best choice is to create a main program in your application. However, you can combine the functionality of the main program and the initial user interface by using a form as the main program.

If you use the Application Wizard to create your application, you can allow the wizard to create a main file program for you. You don't need to specify a main file yourself unless you want to change the main file after the wizard is done.

To set the starting point for an application

  1. In the Project Manager Window, select the file.
  2. From the Project menu, choose Set Main.
    Note The file that you set as the application's main file is automatically marked as included so that it is treated as read-only after you compile the application.

Only one file in the project can be set as the main file. The main file is displayed in bold type, as shown in the following illustration.

Setting a main file in the Project Manager

See Also

Application Architecture | Compiling an Application | Initializing the Environment | Application Framework Files | Application Builder


Initializing the Environment

The first task that a main file or application object must accomplish is to set up your application's environment. The default Visual FoxPro development environment establishes certain values of SET commands and system variables when Visual FoxPro opens. However, these settings might not be the best environment for your application.

Tip To see the default values of the Visual FoxPro development environment, start Visual FoxPro without a configuration file by typing VFP -C and then issue the DISPLAY STATUS COMMAND.

It is always a good idea to save the initial environment settings and set up a specific environment for your application in your setup code.

To capture commands for the current environment

  1. From the Tools menu, choose Options.
  2. Press Shift and select OK to display the environment SET commands in the Command window.
  3. From the Command window, copy and paste into your program.

In an environment specific to your application, you might want to include code to:

  • Initialize variables.
  • Establish a default path.
  • Open any needed databases, free tables, and indexes. If your application requires access to remote data, the initialization routine can also prompt the user for the necessary login information.
  • Reference external library and procedure files.

For example, if you wanted to test the default value of the SET TALK command, store the value, and set TALK to OFF for your application, you could place the following code in your setup procedure:

IF SET('TALK') = "ON"
   SET TALK OFF
   cTalkVal = "ON"
ELSE
   cTalkVal = "OFF"
ENDIF

Displaying the Initial Interface

The initial user interface can be a menu, form, or any other user component. Often, an application will display a sign-on screen or logon dialog box before displaying the opening menu or form.

You can initiate the user interface in the main program by using a DO command to run a menu or a DO FORM command to run a form.

DO FORM STARTUP.SCX

Restoring the Original Environment

It is usually a good idea to save default settings in public variables, in a custom class, or as properties of an application object so that you can restore these values when quitting the application. For example, if you saved the SET TALK setting into the public variable cTalkVal, issue the following command:

SET TALK &cTalkVal
Note Variable names used with macro substitution should not contain the "m." prefix because the period assumes a variable concatenation and will produce a syntax error.

If you initialize the environment in a different program than the one in which you are restoring it — for example, if you initialize by calling one procedure, but restore the environment by calling another — be sure you can access the values you stored. For example, store the values to restore in public variables, custom classes, or as properties of an application object.

See Also

Setting the Starting Point | Controlling the Event Loop | Compiling an Application | Structuring a Program as a Main File | Optimizing Visual FoxPro Startup Speed | SET Command Overview | DISPLAY STATUS COMMAND


Controlling the Event Loop

Once the environment is set up and you've displayed the initial user interface, you're ready to establish an event loop to wait for user interaction.

To control the event loop

  • Issue the READ EVENTS command, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes.

It is important to place the READ EVENTS command correctly in your main file, because all processing in the main file is suspended from the time the READ EVENTS command is executed until a subsequent CLEAR EVENTS command is issued. For example, you might issue a READ EVENTS command as the last command in an initialization procedure, executed after the environment has been initialized and the user interface displayed. If you don't include the READ EVENTS command, your application will return to the operating system after running.

After the event loop has been started, the application is under the control of the user interface element that was last displayed. For example, if the following two commands are issued in the main file, the application displays the form Startup.scx:

DO FORM STARTUP.SCX
READ EVENTS

If you don't include a READ EVENTS command or its equivalent in your main file, your application will run properly from the Command window within the development environment. However, when you run it from your menu or main screen, the application will appear briefly, then quit.

Your application must also provide a way to end the event loop.

To terminate the event loop

  • Issue the CLEAR EVENTS command.

Typically, you issue the CLEAR EVENTS command from a menu or a button in a form. The CLEAR EVENTS command suspends the event processing for Visual FoxPro and returns control to the program that issued the READ EVENTS command that started the event loop.

For a simple program example, see Structuring a Program as a Main File.

Caution You need to establish a way to exit the event loop before you start it. Make sure your interface has a mechanism (such as an Exit button or menu command) to issue the CLEAR EVENTS command.

See Also

Initializing the Environment | Structuring a Program as a Main File | Compiling an Application | READ EVENTS COMMAND | Adding Files to a Project


Creating Applications with the Application Framework

The Application Framework is designed to include all required, and many optional, elements that make an application effective and pleasurable to use. Though the framework itself provides a great deal of flexibility and power to create applications the way that works best for you, this section discusses the ways using the Application Wizard and the Application builder ease your application development.

In This Section

Creating a Framework
Learn how to create an Application Framework by using the Application Wizard or by using the New Application item in the Component Gallery.
Application Framework Files
Provides a list and description of files that are included in the Application Framework.
Data Selection with Application Builder
Describes how to select the data sources you want in developing your application after you plan your application.
Managing Documents with Application Builder
Discusses how to plan and choose the documents that you want to add to your application once you have selected data sources.
Specifying a Builder Application with Builder.dbf
Provides the Builder.dbf table, which you can use to specify a builder application. The table contains fields that represent the name of a builder, a description of the builder, and a field called Type that identifies the Class or Base Class property that invokes the custom builder.

Related Sections

Creating the Application
Discusses how to create Visual FoxPro applications, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Setting the Starting Point
Describes how the main file is the starting point for your application, and can consist of a program or form. When your application is run, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed.
Initializing the Environment
Discusses how setting up the application environment is the first task that a main file or application object must accomplish.
Controlling the Event Loop
Describes how to establish an event loop, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes. This occurs after the environment is set up and you've displayed the initial user interface.
Client/Server Performance Optimization
Discusses how you can fine-tune your application to gain maximum performance by increasing data throughput.
Creating the User Interface
Covers how creating forms, classes, controls, and toolbars can provide a rich set of tools for your user interface.
Upsizing Visual FoxPro Databases
Explains how to use the upsizing wizards to move databases, tables, and views from your system to a remote Microsoft SQL Server.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.


Creating a Framework

You can create an Application Framework by using the Application Wizard or by using the New Application item in the Component Gallery. When you use the Component Gallery, a new project folder item is added to your Favorites folder.

Whichever method you use, Visual FoxPro displays an Application Builder so you can add information to be stored in a meta table.

To create an application

  1. From the Tools menu, point to Wizards, and then click Application.

    -or-

    In the Catalogs folder of the Component Gallery, double-click the New Application item.

  2. In the Application Wizard dialog box:
    • Specify the project name.
    • Accept or locate the project file.
    • Choose your options to Create project directory structure (default) and Add to Favorites catalog (default).

For more information, see Creating Applications with the Application Framework in Help.

You can also use the Component Gallery to add forms, reports, data, and service objects to your new application framework and controls to forms. When you use the Component Gallery to add a form to an application, you can create a new form or subclass from an existing class.

See Also

Application Framework Files | Development Productivity Tools | Running the Project Manager Hooks Sample


Application Framework Files

An application framework includes the project file and a starter class library subclassed from the Visual FoxPro base classes, ready for you to populate with new or existing tables and documents.

Master Include File
This common #INCLUDE file is used by components with settings and strings. The file also includes the APP_GLOBAL value, the name used by components for referencing.
Configuration File
An optional Config.fpw used for applications such as top-level forms in order to implement settings such as SCREEN=OFF.
Project Hook Class
Controls events related to the project such as adding new files. It also can access Application Builder for setting actions and properties of file interaction within the application.
Application Meta Table
Contains information such as project settings made or used by the Application Builder and Project Hooks.
Application Builder
Facilitates adding components to the project and setting properties such as navigation options.

The framework allows you to specify whether to create a complete application or just an application framework. If you choose to create a complete application, you can either include in the application a database and forms or reports you have already created, or you can create a new application from scratch using a database template. If you choose to create a framework, you can go back later and add components to the framework.

See Also

Creating a Framework | Development Productivity Tools


Data Selection with Application Builder

After you plan your application, you need to select the data sources you need in developing your application. You can use the Application Builder Data Tab, Application Builder to add databases and tables to your application and project.

Adding Data Using the Data Tab

If you already have existing data, you can use the Data tab to create a data environment for your application by adding free tables or tables from a database to the application. As soon as you specify a table, the Application Builder displays it in the grid and prepares to create both a form and a report for the table. At this point, you have selected only which data sources to include. They are not actually added to the framework until you select the Generate button. If you want to add only the data source and not have new forms or reports, uncheck the options next to the table entry. If you have a form or report check box marked when you click the Generate button, the appropriate wizard creates a new document for that datasource. You can select a visual style for these documents from the Style drop-down lists.

You can later edit these documents in the Form tab or Report tab of the Application Builder. If you have datasources listed in the Data tab grid and you click the OK button to exit the Application Builder, Visual FoxPro prompts you to add the tables, forms and reports to your project and application. Clicking the Generate button performs the same function.

The documents generated by the Application Builder contain all the fields for the selected datasource. If you want more control over the layout of your document, run the Form Wizard or Report Wizard directly from the Wizards menu and add the newly created document in the Form tab or Report tab. You can also add or edit forms or reports from the Application Builder.

When you use the Application Builder to add data, it is marked in the project as Excluded, meaning that it is not bound into the built application. This enables you to edit the added table. A table built into an application is read-only and cannot be edited. If you want to include a table in the project and thereby make it read-only (for example, a special lookup table where data will not change), right-click on the table in the Project Manager, and select the Include menu item.

Creating Data Using the Data Tab

You can also use the Database Wizard or the Database Wizard buttons on the Data tab to create new tables to add to the project and application. These wizards create new data structures for your application in the appropriate data folder and allow you to generate new documents in the same manner discussed previously.

The basic documents that the Application Builder creates contain all fields in the tables on which they are based. These documents are excellent for basic data input and reporting, but you might want to create documents for other unique purposes in your application. The Form Wizard and Report Wizard offer more flexibility and the foundation classes included with the Component Gallery offer added functionality to forms and reports.

Locating Data

If you use the Application Builder to add data and documents to your application, data-binding is handled automatically. The Application Builder does, however, offer a Default Data Directory option on the Advanced Tab, Application Builder if you are manually coding documents to bind to data and need the application framework to handle data path resolution. Use this setting to specify a folder that contains your datasources to provide appropriate path information for this data.

Importing Data

With many applications, you may already have data that you wish to use, but it's not necessarily in the proper format. It might be in plain text or spreadsheet format. In these cases, you can use the Import Wizard to migrate your data into FoxPro tables. You can then easily add these tables to your application.

Upsizing Data

Visual FoxPro includes an upsizing wizard that allows you to move your FoxPro data to a SQL Server database. If the demands of your application require use of one of these databases, you can easily migrate your existing data and still keep the application intact.

The SQL Server Upsizing Wizard allows you to Create remote views on tables. If you select this option, the tables in your database will be changed to remote views. Since the documents (forms or reports) in your application are bound solely to the datasource name, you can still run your application, but the data being used will be SQL Server data instead of FoxPro tables.

If you have existing SQL Server data that you want to use in your application, you can easily set up a Visual FoxPro database containing remote views pointing to these datasources. The application framework will handle these just like they were native FoxPro tables.

See Also

Managing Documents with Application Builder


Managing Documents with Application Builder

Once you have selected data sources, you need to plan and choose the documents that you want to add to your application. The Application Builder is particularly effective for this task since it not only adds the document to your project, but also integrates it with the framework. Because the framework uses extended document information stored in a meta-table, the Application Builder automatically handles this integration. The meta-table is stored in the same folder as the application project and is given the same name as the project plus an "_app.dbf" suffix. The extended document information that is stored in the framework meta-table specifies the following:

  • A friendly name to display in the Open or New dialog box.
  • Whether a form appears in the New dialog box.
  • Whether a form appears in the Open dialog box.
  • Whether a form uses a navigation toolbar.
  • Whether a form uses a navigation menu.
  • Whether a form allows for opening of multiple instances.

You can have the builder automatically create new forms and reports when you add data to the application. These documents are generated from the associated wizards.

Once a document has been added to the application framework, it will automatically appear in the Forms tab or Reports tab.

When you open the Forms tab you will find a list that contains the forms you have already added to your application manually or from entries in the Data tab.

Note It's possible that a form in your project does not appear in the Forms tab. This is because that form is not registered in the application meta-table. You can register it by choosing the form using the Add button on the Forms Tab page. In addition, the Cleanup button on the Advanced Tab, Application Builder will synchronize the documents in your project with those registered in the meta-table. You can also edit or remove any of these documents from the appropriate tab.

To add documents in the Application Builder

  1. Click the Add button on the appropriate document tab (Form or Report) and select a document. The application framework automatically handles a variety of document types. With forms, you can select a form (.scx) file, a form class from a class library, (.vcx), or a program (.prg) file that contains code that runs a form. With reports, you can choose a report (.frx) file, label (.lbx) file, or program (.prg) file that has code to run a report.
  2. Once you add the file to the document list, you can choose various settings in terms of how that document functions in the application.

    The Forms tab enables you to manage the following options:

    • The form's friendly name.
    • Whether the form is limited to a single instance.
    • Whether the form uses a navigation toolbar.
    • Whether the form uses a navigation menu.
    • Whether the form appears in the New dialog box.
    • Whether the form appears in the Open dialog box.

      The Reports tab enables you to manage the following options:

    • The report's friendly name.
    • Whether your report appears in the Print Reports dialog box.

To edit documents in the Application Builder

  1. Open any listed form or report by highlighting the document and then clicking the Edit button. In the case of a form, you may be prompted with the following message:

    "Would you like to add a mediator object to this form to fully enable it for use with the application framework?"

    If you answer "Yes", the Application Builder adds to your form an object that automatically communicates directly with the application object used by the framework. This object provides additional functionality to forms in your application. For example, when you close a form, the object can detect if there is buffered data that has not been saved and prompt you to save changes. Also, the object will differentiate between a form launched using the New dialog box versus the Open dialog box.

  2. In the designer, edit your document to your liking. You might want to use the Component Gallery to add a background or foundation class. You can use the Component Gallery to add special characteristics and functionality to your document.

To remove documents in the Application Builder

  • You can remove any document from the meta-table by highlighting the document and then clicking the Remove button. After the document is removed from your application, it remains in the project file.
    Note Your application will run regardless of whether a form or report is stored in the meta-table. As long as you provide code that specifies how to run this document, the application will handle it just fine. The advantage of using the Application Builder is that you would not need to worry about the application handling running forms and reports. This is done automatically.

See Also

Data Selection with Application Builder | Developing Applications with the Application Framework


Specifying a Builder Application with Builder.dbf

You can use the Builder.dbf table to specify a builder application. Each record contains fields that represent the name of a builder, optionally, a description of the builder, and a field called Type that identifies the Class or Base Class property that invokes the custom builder. For instance, the Type entry for a Command Button is Commandbutton and the Type entry for the Autoformat builder is Multiselect because it runs against multiple selected controls.

The following table describes a BUILDER table record.

Field Name | Field Type | Width (comment)
NAME | Character | 45 (Builder name)
DESCRIPT | Memo | 4
BITMAP (unused) | Memo | 4
TYPE | Character | 20
PROGRAM | Memo | 4 (Builder application)
CLASSLIB | Memo | 4 (Class Library name)
CLASSNAME | Memo | 4 (Builder Class)
PARMS | Memo | 4 (passed parameter list)

The named builder application compares the value in the Type field and the Class of the object and starts if there is a match. If more than one match is found, a selection dialog displays.

By default, the Builder.app application passes three parameters, listed in the PARMS field of Builder.dbf, to a builder program:

PARMS Entry | Description
wbReturnValue | Variable containing a value to be returned to the Builder.app.
<character string> | A literal string to pass to Register table.
<optional value> | A keyword or other value to pass to Builder.app

To create a custom builder

  1. Write an application that provides an interface and modifies the selected control or controls.
  2. Save the application in the Wizards folder.
  3. Open the Builders.dbf table and append a new record.
  4. Enter values for the Name, Descript, Type, and Program fields.

    If your custom builder uses additional values, you can also enter values for the remaining fields.

After you complete all entries and close the Browse, the new builder is registered. For example, if you create a program that changes the fonts of selected controls, then save the program in a file called Chgfont.prg, the following table shows the entries for Builder.dbf.

Field Name | Value
NAME | The Builder That Changes Fonts
DESCRIPT | This builder modifies the font of all selected controls
TYPE | MULTISELECT
PROGRAM | Chgfont.prg

When you use the builder, Visual FoxPro displays the Builder Selection dialog box because there are now two builders of the Multiselect type. When you choose The Builder that Changes Fonts , Builder.app runs the program you saved as Chgfont.prg.

See Also

Builders | Application Builder | _BUILDER System Variable | AutoFormat Builder | Combo Box Builder | Command Group Builder | Edit Box Builder | Form Builder | Grid Builder | List Box Builder | Option Group Builder


Creating the User Interface

A well-designed interface can guide users through your application. Forms, classes, controls, menus, and toolbars provide a rich set of tools for designing a great user interface.

In This Section

Creating Forms
Your application must have forms to make it possible for users to view and enter data. However, you can customize standard forms visually and programmatically to create a specialized environment for your users.
Working with Forms
After creating your form, you can run, hide, or alter it in different ways.
Using Controls
Controls manage the interactions between users and your application. Microsoft Visual FoxPro offers a variety of controls to enhance your application interface.
Designing Menus and Toolbars
A good menu system tells your users a lot about the design and structure of your application. Planning menus and toolbars carefully can improve the usability of your application and provide immediate access to common tasks.

Related Sections

Developing Visual FoxPro Applications
This section includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Creating the Application
Discusses how to create Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Setting the Starting Point
Describes how the main file is the starting point for your application, and can consist of a program or form. When your application is run, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed.
Initializing the Environment
Setting up the application environment is the first task that a main file or application object must accomplish.
Controlling the Event Loop
Learn how to establish an event loop to, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes. This occurs after the environment is set up and you've displayed the initial user interface.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application builder.
Client/Server Performance Optimization
Learn how you can fine-tune your application to gain maximum performance by increasing data throughput.
Upsizing Visual FoxPro Databases
Explains how to use the upsizing wizards to move databases, tables, and views from your system to a remote Microsoft SQL Server.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.


Creating Forms

You can use forms to give your users a familiar interface for viewing and entering data into a database, but forms provide far more than just an interface. Forms provide a rich set of objects that can respond to user (or system) events, so you can make it possible for your users to accomplish their information management tasks as easily and as intuitively as possible.

In This Section

Designing Forms
Provides background on the capabilities of the Form designer, with links to topics on creating forms and setting the data environment.
Creation of Single- and Multiple-Document Interfaces
Describes the two types of applications possible in Visual FoxPro and the types of forms that support both types of interfaces. Includes links to topics dealing with the various form types.
Extending Forms with Form Sets
Explains the benefits of including multiple forms as a group in a form set and describes how to create and work with form sets.
Addition of Objects to Forms
Lists the types of objects you can add to a form and offers background on the two categories of objects in Visual FoxPro: containers and controls. Provides links to topics on adding containers and controls to forms.
Adding Properties and Methods to a Form
Includes instructions on how to add a new property to a form, create an array property, create a new method for a form, and include a file in a form. Provides links to topics on manipulating objects, defining form behavior, and editing event and method code.
Saving Forms
Contains directions on how to save a form in the Form designer and save a form or selected controls as a class definition.

Related Sections

Creating the User Interface
Using Visual FoxPro forms, classes, controls, menus, and toolbars, you can build interfaces that help users gain access to the full potential of your programs.
Working with Forms
After creating your form, you can run, hide, or alter it in different ways.
Using Controls
Controls manage the interactions between users and your application. Visual FoxPro offers a variety of controls to enhance your application interface.
Designing Menus and Toolbars
A good menu system tells your users a lot about the design and structure of your application. Planning menus and toolbars carefully can improve the usability of your application and provide immediate access to common tasks.


Designing Forms

Visual FoxPro provides you with a powerful Form Designer to make form design fast and easy. You can have:

  • Various types of objects on the forms.
  • Data bound to objects on the form.
  • Top-level or child forms.
  • Multiple forms that can be manipulated together.
  • Forms based on your own custom templates.

Forms and form sets are objects with their own properties, events, and methods that you can set in the Form Designer. A form set consists of one or more forms that can be manipulated as a unit. If you have four forms in your form set, for example, you can display or hide them as a unit with a single command at run time.

See Also

Creating Forms | Creating a New Form | Setting the Data Environment | Creation of Single- and Multiple-Document Interfaces | Specifying a Form Type


Creating a New Form

Forms display the fields and records in your tables and views, and usually include navigation controls to help you move from record to record.

You can create forms in Visual FoxPro in any of these ways:

  • Use form wizards to create ready-to-use forms.
  • Choose Quick Form on the Form menu to create a simple form that you can customize by adding your own controls.
  • Use the Form Designer to modify existing forms or create your own forms.

Using a Form Wizard

Whenever you want to create a new form, you can use a form wizard to help you set it up. The wizard will ask you a series of questions and build a form for you based on your answers. You can choose from several different style options and preview your form before creating it.

To create a new form with a wizard

  1. In the Project Manager, select the Documents tab and select Forms.
  2. Choose New.
  3. Choose Form Wizard.
  4. Select the type of form you want to create.
  5. Follow the instructions on the wizard screens.

You can also access the form wizards from the menu by choosing the Wizards command from the Tools menu, and selecting Form.

Visual FoxPro provides two different form wizards to help you create forms:

  • To create a basic form based on one table, choose the Form Wizard.
  • To create a form that incorporates data from two tables linked in a one-to-many relationship, choose the One-to-Many Form Wizard.

Forms you create with the form wizards have a standard set of navigation buttons so you can display different records in the form, edit records, search for records, and so on. If you create a form within a database, the Form Wizard can use input mask and format settings stored in the database.

Starting the Form Designer

If you want to create your own form without using a wizard, use the Form Designer. With the Form Designer, you can add fields and controls to your form, and customize it by adjusting and aligning the controls.

The Quick Form command is provided to make it easier to get started creating a form. The Quick Form command displays the Form Builder, which adds selected fields from tables or views to your form.

To create a new form

  1. In the Project Manager, choose the Documents tab.
  2. Select the Forms icon.
  3. Choose New.
  4. Select New Form. The Form Designer window appears so you can begin creating your form.

    -or-

  • From the File menu, choose New, select Form, and choose New File.

    -or-

  • Use the CREATE FORM command.

Modifying a Form

If the wizard- or builder-generated forms don't quite fit your needs, you can modify them with the Form Designer. Using the Form Designer, it's easy to move and resize controls, copy or delete controls, align controls, and modify the tab order.

To modify a generated form

  1. In the Project Manager, select the Documents tab.
  2. Choose the Forms icon and select the name of the form.
  3. Choose Modify.

Adding Fields Quickly

When you want to quickly place the fields from a table or view into a form, choose Quick Form on the Form menu. Quick Form starts the Form Builder, which adds selected fields from a table or view to your form, using the field style you choose. The Form Builder creates a form without navigation controls, so you can add your own. You can use a control builder to add navigation controls to your form, or choose from the predefined library of navigation controls provided with Visual FoxPro.

To add fields to a form

  1. In the Project Manager, open the form.
  2. In the Form Designer go to the Form menu and choose Quick Form. The Form Builder appears.
  3. In the Style tab, select the style you want for the new control.
  4. In the Field Selection tab, select the source of the fields, and the fields you want to add.
  5. Choose OK to generate the form.

    -or-

  6. In the Form Controls toolbar, choose a data control and drag in the Form Designer window to create the control.
  7. In the Properties window, choose the Data tab and select the ControlSource property.
  8. Enter a field name.

    -or-

    Select a field from the list of available fields.

Using the Form Designer Toolbars

The Form Designer toolbars give you quick access to frequently used commands and the layout, alignment, and color controls you need when designing or modifying forms. For more information about the purpose of each button on each toolbar, you can use the ToolTips feature or search for "Toolbars".

See Also

Setting the Data Environment | Creating Forms | Creation of Single- and Multiple-Document Interfaces | Designing Forms | Adding Visual FoxPro Controls to a Form


Setting the Data Environment

Each form or set of forms includes a data environment. The data environment is an object that includes the tables or views the form interacts with and the relationships between tables that the form expects. You can visually design the data environment in the Data Environment Designer and save it with the form.

The data environment can automate opening and closing tables and views when the form is run. In addition, the data environment helps you set the ControlSource property for controls by populating the ControlSource property-setting box in the Properties window with all the fields in your data environment.

To open the Data Environment Designer

  1. From the View menu, choose Data Environment.
  2. From the Shortcut menu, choose Add.
  3. In the Open dialog box, choose a table or view to add to the data environment.

Common Data Environment Properties

The following data environment properties are commonly set in the Properties window:

Property | Description | Default Setting
AutoCloseTables | Controls whether tables and views are closed when the form is released. | True (.T.)
AutoOpenTables | Controls whether tables and views in the data environment are opened when the form is run. | True (.T.)
InitialSelectedAlias | Specifies the table or view that is selected when the form is run. | "" at design time. If not specified, at run time the first cursor added to the DataEnvironment is initially selected.

Adding a Table or View to the Data Environment Designer

When you add tables or views to the Data Environment Designer, you can see the fields and indexes that belong to the table or view.

To add a table or view to the Data Environment Designer

  1. From the View menu, choose Data Environment.
  2. From the Data Environment menu, choose Add.
  3. In the Add Table or View dialog box, select a database in the Database box.
  4. In the Select area, choose Tables or Views.

    Your selection determines which fields list appears in the Tables in database box.

  5. In the Tables in Database box, select a table or view.
  6. Choose OK.

    -or-

    If no database or project is open, choose Other to select a table.

You can also drag a table or view from an open project or the Database Designer into the Data Environment Designer.

Setting an Index for the Data Environment Designer

You can set the order your records appear in your report by setting an index for the data environment.

To set an index for the Data Environment Designer

  1. From the View menu, choose Data Environment.
  2. From the shortcut menu, choose Properties.
  3. In the Properties Window, choose Cursor1 in the Object box.
  4. Choose the Data tab and select the Order property.
  5. Enter an index name.

    -or-

    Select an index from the list of available indexes.

When the Data Environment Designer is active, the Properties window displays objects and properties associated with the data environment. Each table or view in the data environment, each relationship between tables, and the data environment itself is a separate object in the Object box of the Properties window.

Removing a Table from the Data Environment Designer

When you remove a table from the data environment, any relationships that the table is involved in are also removed.

To remove a table or view from the Data Environment Designer

  1. In the Data Environment Designer, select the table or view.
  2. From the DataEnvironment menu, choose Remove.

Setting Relationships in the Data Environment Designer

If you add tables to the Data Environment Designer that have persistent relationships set in a database, the relationships are automatically added in the data environment. If the tables don't have persistent relationships, you can still relate them in the Data Environment Designer.

To set relationships in the Data Environment Designer

  • Drag a field from the primary table onto the matching index tag in the related table.

You can also drag a field from the primary table to a field in the related table. If there is no index tag in the related table corresponding to the field in the primary table, you're prompted to create the index tag.

Editing Relationships in the Data Environment Designer

When you set a relation in the Data Environment Designer, a line between the tables indicates the relationship.

To edit the properties of the relation

  • In the Properties window, select the relation from the Object box.

The properties of the relation correspond to clauses and keywords in the SET RELATION and SET SKIP commands.

The RelationalExpr property is set by default to the name of the primary key field in the primary table. If the related table is indexed on an expression, you need to set the RelationalExpr property to this expression. For example, if the related table is indexed on UPPER(cust_id), you need to set RelationalExpr to UPPER(cust_id).

If the relation is not a one-to-many relationship, set the OneToMany property to false (.F.). This corresponds to using the SET RELATION command without issuing SET SKIP.

Setting the OneToMany property of a relation to true (.T.) corresponds to issuing the SET SKIP command. When you skip through the parent table, the record pointer remains on the same parent record until the record pointer moves through all related records in the child table.

Note If you want a one-to-many relationship in the form, set the OneToMany property to true (.T.), even if a persistent one-to-many relationship has been established in a database.

See Also

Creating a New Form | Creation of Single- and Multiple-Document Interfaces | Creating Forms | Specifying a Form Type | Displaying a Child Form Inside a Top-Level Form | Add Table or View | Properties Window | Designing Forms


Creation of Single- and Multiple-Document Interfaces

Visual FoxPro allows to you to create two types of applications:

  • Multiple-document interface (MDI) applications consist of a single main window, and the application's windows are contained within or float on top of the main window. Visual FoxPro is primarily an MDI application, with the command window, edit windows, and designer windows contained within the main Visual FoxPro window.
  • Single-document interface (SDI) applications consist of one or more independent windows, each of which appears separately on the Windows desktop. Microsoft Exchange is an example of an SDI application, in which each message you open appears in its own independent window.

An application consisting of single window is usually an SDI application, but some applications mix SDI and MDI elements. For example, Visual FoxPro displays its debugger as an SDI application, which in turn contains MDI windows of its own.

To support both types of interfaces, Visual FoxPro allows you to create several types of forms:

  • Child form. A form contained within another window, used in creating MDI applications. Child forms cannot be moved outside the bounds of their parent form (the main form), and when minimized appear at the bottom of their parent form. If their parent form is minimized, they are minimized along with it.
  • Floating form. A form that belongs to a parent (main) form, but is not contained within it. Instead, floating forms can be moved anywhere on the screen. They cannot be moved behind their parent window. If minimized, a floating form appears at the bottom of the desktop. If their parent form is minimized, floating forms are minimized along with it. Floating forms are also used in creating MDI applications.
  • Top-level form. An independent form without parent form, used to create an SDI application, or to serve as the parent for other child forms in an MDI application. Top-level forms work at the same level as other Windows applications, and can appear in front of or behind them. They appear on the Windows taskbar.

Child, floating, and top-level forms

See Also

Setting the Data Environment | Creating Forms | Specifying a Form Type | Displaying a Child Form Inside a Top-Level Form | Hiding the Main Visual FoxPro Window


Specifying a Form Type

You create all types of forms in much the same way, but you set specific properties to indicate how the form should behave.

If you're creating a child form, you specify not only that it should appear inside another form, but also whether it is an MDI-compliant child form, which indicates how the form behaves when maximized. If the child form is MDI-compliant, it combines with the parent form, sharing the parent form's title bar and caption, menus, and toolbars. A child form that is not MDI-compliant maximizes into the full client area of the parent, but retains its own caption and title bar.

To specify a child form

  1. Create or edit the form using the Form Designer.
  2. Set the form's ShowWindow property to one of the following values:
    • 0 — In Screen. The child form's parent will be the main Visual FoxPro window.
    • 1 — In Top-Level Form. The child form's parent will be the top-level form that is active when the child window is displayed. Use this setting if you want the child window to appear inside any top-level window other than the main Visual FoxPro window.
  3. Set the form's MDIForm property to .T. (true) if you want the child form to be combined with the parent when maximized, or to .F. (false) if the child window should be retained as a separate window when maximized.

A floating form is a variation of a child form.

To specify a floating form

  1. Create or edit the form using the Form Designer.
  2. Set the form's ShowWindow property to one of the following values:
    • 0 — In Screen. The floating form's parent will be the main Visual FoxPro window.
    • 1 — In Top-Level Form. The floating form's parent will be the top-level form that is active when the floating window is displayed.
  3. Set the form's Desktop property to .T. (true).

To specify a top-level form

  1. Create or edit the form using the Form Designer.
  2. Set the form's ShowWindow property to 2 — As Top-Level Form.

See Also

Creation of Single- and Multiple-Document Interfaces | Displaying a Child Form Inside a Top-Level Form | Creating Forms | Hiding the Main Visual FoxPro Window | Adding a Menu to a Top-Level Form


Displaying a Child Form Inside a Top-Level Form

If you've created a child form in which the ShowWindow property is set to 1 — In Top-Level Form, you don't directly specify the top-level form that acts as the child form's parent. Instead, Visual FoxPro assigns the child form to a parent at the time the child window is displayed.

To display a child form inside a top-level form

  1. Create a top-level form.
  2. In the event code of the top-level form, include the DO FORM command, specifying the name of the child form to display.

    For example, create a button in the top-level form, and then in the Click event code for the button, include a command such as this one:

    DO FORM MyChild
    Note The top-level form must be visible and active when the child form is displayed. Therefore, you cannot use the Init event of the top-level form to display a child form, because the top-level form will not yet be active.
  3. Activate the top-level form, and then if necessary, trigger the event that displays the child form.

See Also

Creation of Single- and Multiple-Document Interfaces | Specifying a Form Type | Hiding the Main Visual FoxPro Window | Creating Forms | Adding a Menu to a Top-Level Form | Extending Forms with Form Sets


Hiding the Main Visual FoxPro Window

If you're running a top-level form, you might not want the main Visual FoxPro window to be visible. You can use the Visible property of the Application object to hide and show the main Visual FoxPro window as needed.

To hide the main Visual FoxPro window

  1. In the Init event of the form, include the following line of code:
    Application.Visible = .F.
  2. In the Destroy event of the form, include the following line of code:
    Application.Visible = .T.

Make sure that you also provide a way to close the form by using THISFORM.Release in some method or event.

Note You can also include the following line in a configuration file to hide the main Visual FoxPro window: SCREEN = OFF

See Also

Creation of Single- and Multiple-Document Interfaces | Customizing the Visual FoxPro Environment | Displaying a Child Form Inside a Top-Level Form | Adding a Menu to a Top-Level Form | Creating Forms | Extending Forms with Form Sets | Addition of Objects to Forms


Adding a Menu to a Top-Level Form

Menus on top-level forms not only provide form navigation, they can provide initial clues about the design of your application.

To add a menu to a top-level form

  1. Create a top-level form menu. For more information about creating menus for top-level forms, see Designing Menus and Toolbars.
  2. Set the form's ShowWindow property to 2 – As Top-Level Form.
  3. In the Init event of the form, run the menu program and pass it two parameters:

    DO menuname.mpr WITH oForm, lAutoRename

    oForm is an object reference to the form. In the Init event of the form, pass THIS as the first parameter.

    lAutoRename specifies whether or not a new unique name is generated for the menu. If you plan to run multiple instances of the form, pass .T. for lAutoRename.

    For example, you can call a menu called mySDImenu with this code:

    DO mySDImenu.mpr WITH THIS, .T.

See Also

Creation of Single- and Multiple-Document Interfaces | Hiding the Main Visual FoxPro Window | Extending Forms with Form Sets | Creating Forms | Addition of Objects to Forms | Adding Visual FoxPro Containers


Extending Forms with Form Sets

You can manipulate multiple forms as a group by including them in a form set. A form set has these benefits:

  • You can show or hide all the forms in a form set at one time.
  • You can visually arrange multiple forms at once to control their relative positions.
  • Because all the forms in a form set are defined in a single .scx file with a single data environment, you can automatically synchronize record pointers in multiple forms. If you change the record pointer in a parent table in one form, the child records in another form are updated and displayed.
    Note All the forms and all the objects on the forms are loaded when you run the form set. Loading many forms with a number of controls might take several seconds.

Creating a New Form Set

A form set is a parent container for one or more forms. When you are in the Form Designer, you can create a form set.

To create a form set

  • From the Form menu, choose Create Formset.

If you don't want to work with multiple forms as a group of forms, you don't need to create a form set. Once you've created a form set, you can add forms to it.

Adding and Removing Forms

Once you've created a form set, you can add new forms and remove forms.

To add additional forms to a form set

  • From the Form menu, choose Add New Form.

To remove a form from a form set

  1. In the Form box at the bottom of the Form Designer, select the form.
  2. From the Form menu, choose Remove Form.

If you have a single form in a form set, you can remove the form set so that you have only the form.

To remove a form set

  • From the Form menu, choose Remove Formset.

Forms are saved in table format to a file with an .scx extension. When you create a form, the .scx table contains a record for the form, a record for the data environment, and two records for internal use. A record is added for each object you add to the form or to the data environment. If you create a form set, an additional record is added for the form set and for each new form. The parent container of each form is the form set. The parent container of each control is the form that it is placed on.

Tip When you run a form set, you may not want all forms in the form set initially visible. Set the Visible property to false (.F.) for forms you don't want displayed when the form set runs. Set the Visible property to true (.T.) when you want the forms displayed.

See Also

Adding a Menu to a Top-Level Form | Addition of Objects to Forms | Creating Forms | Adding Visual FoxPro Containers | Form Designer


Addition of Objects to Forms

To design the functionality you want in a form, you add the appropriate controls, set form and control properties, and write event code.

You can add the following types of objects to a form:

  • Controls
  • Containers
  • User-defined classes
  • Sharing Information and Adding OLE

Understanding Container and Control Objects

Objects in Visual FoxPro belong in one of two categories, depending on the nature of the class they are based on:

  • Containers can hold other containers or controls. They can act as the parent object for other objects. For example, a form, as a container, is the parent object of a check box on that form.
  • Controls can be placed in containers, but cannot be the parent for other objects. For example, a check box cannot contain any other object.

The Form Designer allows you to design both containers and controls.

Container | Can contain
Column | Headers, and any objects except form sets, forms, toolbars, timers, and other columns
Command button group | Command buttons
Form set | Forms, toolbars
Form | Page frames, grids, any controls
Grid | Columns
Option button group | Option buttons
Page frame | Pages
Page | Grids, any controls

See Also

Extending Forms with Form Sets | Adding Visual FoxPro Containers | Creating Forms | Adding Visual FoxPro Controls to a Form | Adding User-Defined Objects to a Form | Adding Controls to a Form with the Component Gallery | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Adding Visual FoxPro Containers

In addition to form sets and forms, Visual FoxPro provides four base container classes.

Visual FoxPro Container Classes |
Command button group | Option button group
Grid | Page frame

To add container objects to a form

  • In the Form Controls toolbar, select the desired container object (button group, grid, option button group, or page frame) button and drag it to size in the form.

When you add a command button group or an option button group to a form in the Form Designer, the group contains two buttons by default. When you add a page frame to a form, the page frame contains two pages by default. You can add more buttons or pages by setting the ButtonCount property or the PageCount property to the number you want.

When you add a grid to a form, the ColumnCount property is set to – 1 by default, which indicates AutoFill. At run time, the grid will display as many columns as there are fields in the RowSource table. If you don't want AutoFill, you can specify the number of columns by setting the grid's ColumnCount property.

For more information about these container objects, see Using Controls.

Collection and Count Properties

All container objects in Visual FoxPro have a count property and a collection property associated with them. The collection property is an array referencing each contained object. The count property is a numeric property indicating the number of contained objects.

The collection and count properties for each container are named according to the type of object that can be contained in the container. The following table lists the containers and the corresponding collection and count properties.

Container | Collection Property | Count Property
Application | Objects Forms | Count FormCount
FormSet | Forms | FormCount
Form | Objects Controls | Count ControlCount
PageFrame | Pages | PageCount
Page | Controls | ControlCount
Grid | Columns | ColumnCount
CommandGroup | Buttons | ButtonCount
OptionGroup | Buttons | ButtonCount
Column | Controls | ControlCount
ToolBar | Controls | ControlCount
Container | Controls | ControlCount
Control | Controls | ControlCount

These properties allow you to use a loop to programmatically manipulate all or specific contained objects. For example, the following lines of code set the BackColor property of columns in a grid to alternating green and red:

o = THISFORM.grd1
FOR i = 1 to o.ColumnCount
   IF i % 2 = 0 && Even-numbered column
      o.Columns(i).BackColor = RGB(0,255,0) && Green
   ELSE
      o.Columns(i).BackColor = RGB(255,0,0) && Red
   ENDIF
ENDFOR

See Also

Addition of Objects to Forms | Adding Visual FoxPro Controls to a Form | Creating Forms | Adding User-Defined Objects to a Form | Extending Forms with Form Sets | Adding Controls to a Form with the Component Gallery | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Adding Visual FoxPro Controls to a Form

You can easily add any of the standard Visual FoxPro controls to your form by using the Controls toolbar.

Standard Visual FoxPro Controls

Check box
Hyperlink
List box
Spinner
Combo box
Image
OLE Bound Control
Text box
Command button
Label
OLE Container Control
Timer
Edit box
Line
Shape

You add new controls by selecting them from the Form Controls toolbar, and placing them in the Form Designer window. For example, you might want to add new labels for fields on the form, add new controls such as buttons, edit boxes, list boxes, and so on, or add pictures or lines and shapes to enhance the appearance of your form.

To add a control to a form

  1. Choose a control in the Form Controls toolbar.
  2. In the Form Designer window, drag to create a rectangle where you want the control to be, or click to create a control of default size.

The new control appears where you placed it. You can then move it to its final location on the form, and resize it as needed.

Adding Multiple Controls at One Time

When you choose the Button Lock button, you can add multiple controls of the same type without having to click the control button on the toolbar more than once. For example, if you want to add five text boxes to a form, make sure the Button Lock button is selected, and then click the text box control button in the Form Controls toolbar once and add all five text boxes to the form.

Button lock is automatically engaged if you double-click on a control button on the Form Controls toolbar. To turn button locking off, click the Button Lock button again or click the Selection Pointer button on the Form Controls toolbar.

Adding a Control with a Builder

If you want help adding a control, you can use a builder to add the controls and make them work with the form, or you can add the controls using the Form Controls toolbar and the Properties window.

Just as wizards can be used to construct forms quickly, builders can be used for adding controls to a form. The builder asks a series of questions related to the control you are adding to your form, and sets the appropriate properties to make the control work as desired.

For example, if you want to add a new text box to a form, the builder asks which style of text box you prefer and which table's field it should display.

Builders can be accessed in one of two ways: from the Form Designer shortcut menu, or by activating the Builder Lock button on the Form Controls toolbar when you add controls to a form.

To add a control with a builder

  1. In the Form Controls toolbar, select the Builder Lock button.
  2. Select the control you want from the Form Controls toolbar, and draw it on the form.
  3. Fill in the information on the builder tabs.

Using Builders for All Controls

By setting the Builder Lock button on the Form Controls toolbar, you can automatically use a control builder each time you add a control to a form.

To turn on the Builder Lock

  • In the Form Controls toolbar, click the Builder Lock button.

For more information about which control to choose, see Using Controls. For details on valid image control sources, see Graphics Support in Visual FoxPro

Adding Data-Bound Controls to a Form

You can bind controls to data in a table, view, table field, or view field by setting the ControlSource property of a control to a field or the RecordSource property of a grid to a table or view. But you can also create data-bound controls by dragging fields or tables to the form directly from:

  • The Project Manager
  • The Database Designer
  • The Data Environment Designer

The class of control created this way depends on the Field Mappings settings in the Properties tab of the Table Designer or the Field Mapping tab of the Options dialog box.

By placing the tables or views associated with your form in the data environment for your form, you make it easy to bind new controls to the fields in the tables or views.

The ControlSource property field displays the fields available in the Data Environment Designer so you can select the one you want to bind to a control.

Displaying the Properties Window

The Properties window displays all the properties for the controls you add to a form. You use the ControlSource property in the Properties window to bind the control you have added to your form to a specific field in the table in your Data Environment Designer.

To display the Properties window

  • From the View menu, choose Properties.
    Note If you want to use the Properties window to set control properties, make sure Builder Lock is turned off.

See Also

Adding Visual FoxPro Containers | Adding User-Defined Objects to a Form | Creating Forms | Addition of Objects to Forms | Adding Properties and Methods to a Form | Table Designer | Field Mapping | Adding Controls to a Form with the Component Gallery | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls | Setting the Data Environment


Adding Controls to a Form with the Component Gallery

You can use the Component Gallery to quickly add custom controls and objects to a form. The Component Gallery contains dozens of custom controls and objects that greatly reduce the amount of coding required to create specialized forms.

To open the Component Gallery

  • From the Tools menu, choose Component Gallery.

When the Component Gallery is open, you can drag custom controls and objects from the Component Gallery and drop them on a form.

See Also

Component Gallery | Adding Visual FoxPro Containers | Adding User-Defined Objects to a Form | Creating Forms | Addition of Objects to Forms | Adding Properties and Methods to a Form | Table Designer | Field Mapping | Adding Visual FoxPro Controls to a Form | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Adding Controls to a Wizard-Generated Form

If you create a form with one of the form wizards and then want to add controls to it, you can match the style of the existing controls by using the controls in the wizard controls library, Wizstyle.vcx.

When you open the wizards control library, wizard-style controls (such as chiselfield, embossedmemo, and so on) are available in the Form Controls toolbar. To find out which control to use, select an existing control and note its class and class library. For example, a standard wizard field would be in the Standardfield class, found in Wizstyle.vcx.

Tip Use ToolTips on the Form Controls toolbar to help you identify class names.

To match controls in a wizard-generated form

  1. In the Form Designer, open the form.
  2. From the Form Controls toolbar, choose the View Classes button and choose Add.
  3. In the Open dialog box, locate Wizstyle.vcx in the Wizards subdirectory and choose OK.
  4. In the Form Controls toolbar, select the control that corresponds to an existing control in the form and drag in the form to add it.
    Note If you move a form to a new directory or another system, you should move the control library associated with the form along with it.

See Also

Addition of Objects to Forms | Adding Controls to a Form with the Component Gallery | Creating a New Form | Creating Forms with Local and Remote Data | Adding Visual FoxPro Controls to a Form | Creating Forms | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Selecting, Moving, and Resizing Form Controls

After creating a form, you may need to adjust the placement or size of the controls on the form. For example, you might want to move a memo field, or make a text box longer.

To select a control

  • Using the pointer, click anywhere on the control.

To select adjacent controls

  1. Choose the select arrow in the Form Controls toolbar.
  2. By dragging the pointer, draw a box around the controls you want to select.

To move a control

  1. Select the control by clicking it.
  2. Drag the control to the new position in the form window.

    -or-

    Select the control and use the arrow keys to reposition it.

To resize a control

  1. Select the control.
  2. Drag one of the sizing handles to increase the length, width, or overall size of the control.

See Also

Addition of Objects to Forms | Adding Controls to a Form with the Component Gallery | Setting Control Properties | Creating a New Form | Creating Forms with Local and Remote Data | Adding Visual FoxPro Controls to a Form | Creating Forms | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Aligning Controls in Forms | Setting Tab Order for Controls


Copying and Deleting Form Controls

When designing or modifying a form, you may want to make a copy of a control that is already on the form. You can copy an existing control and paste the copy onto your form.

To copy a control

  1. Using the pointer, select a control.
  2. From the Edit menu, choose Copy.
  3. From the Edit menu, choose Paste.
  4. Use the pointer to reposition the control as needed.

If you create a control and then decide you don't need it, or don't want a control created by a wizard, you can remove the control.

To delete a control

  • Select the control and choose Cut from the Edit menu.

See Also

Addition of Objects to Forms | Adding Controls to a Form with the Component Gallery | Setting Control Properties | Creating a New Form | Creating Forms with Local and Remote Data | Adding Visual FoxPro Controls to a Form | Creating Forms | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Aligning Controls in Forms

The buttons on the Layout toolbar make it easy to accurately line up controls in relation to each other in your forms. For example, you might want to align controls horizontally or vertically or make sure that a related set of controls has the same width or height. To align controls, select a group of controls, and then choose one of the layout buttons on the Layout toolbar.

Adjusting Control Placement

If you need to place controls precisely on the screen, you can use Show Position on the View menu. When checked, Show Position displays the coordinates and dimensions of a selected control in the status bar at the bottom of the Form Designer window.

Controlling the Grid Display

The grid display helps you align controls on your forms. You can adjust the size of the grid with Set Grid Scale on the Format menu. You can turn display of the grid on and off by using the Grid Lines command on the View menu, or setting the Grid Lines option on the Forms tab of the Options dialog box.

You can also adjust the size or position of controls in relation to the grid with Snap to Grid on the Format menu. When Snap to Grid is checked on the Form menu, controls placed on a Form are automatically aligned to the guidelines on the grid. You can override the grid by:

  • Clearing Snap to Grid on the Format menu. By default, this option is checked.
  • Using the arrow keys to align controls.
  • Pressing CTRL before clicking on a control and holding the CTRL key down while dragging the object to another position.
  • Choosing alignment options from the Layout toolbar or the Format menu.

See Also

Aligning Controls in Forms | Adding Visual FoxPro Containers | Adding User-Defined Objects to a Form | Creating Forms | Addition of Objects to Forms | Adding Properties and Methods to a Form | Adding Visual FoxPro Controls to a Form | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls | Setting Tab Order for Controls


Setting Tab Order for Controls

The tab order of a form determines the sequence in which the controls are selected when a user presses the TAB key to move through the form.

You can choose two different methods for setting tab order: interactively, by clicking the controls in the order you want them to be selected when the form is used; or by arranging a list of controls in a dialog box.

To choose a tab-ordering method

  1. From the Tools menu, choose Options.
  2. In the Options dialog box choose the Forms tab.
  3. Under the Tab Ordering option, select Interactive or By List.

Setting Tab Order Interactively

In interactive mode, you set tab order by double-clicking the control you want to be first in the tab order, and then single-clicking on the rest of the controls in the order in which you want them to be selected in the form. The last control selected is indicated with a highlighted tab order number.

To change the tab order interactively

  1. From the View menu, choose Tab Order.
  2. Double-click the tab order box beside the control you want to be the first control in the tab order.
  3. Click the tab order box for each of the other controls.
  4. Click anywhere on the form to save your changes and exit Tab Order mode, or press ESC to exit Tab Order mode without saving your changes.

Setting Tab Order by List

In list mode, you set tab order by rearranging the control names in the Tab Order dialog box. You can set order by row (down the form) or by column (across the form).

To set the tab order using a list

  1. From the View menu, choose Tab Order.
  2. Choose By Row or By Column.
  3. In the Tab Order dialog box, use the pointer to rearrange the list.
  4. Choose OK.

See Also

Addition of Objects to Forms | Tab Order dialog box | Adding Visual FoxPro Containers | Adding User-Defined Objects to a Form | Creating Forms | Addition of Objects to Forms | Adding Properties and Methods to a Form | Adding Visual FoxPro Controls to a Form | Adding Controls to a Wizard-Generated Form | Adding User-Defined Objects to a Form | Selecting, Moving, and Resizing Form Controls


Adding User-Defined Objects to a Form

One of the most powerful features of Visual FoxPro is the ability to create classes that can easily be used and reused in various pieces of your applications. Once you've created classes, you can add them to your forms.

To add an object based on a custom class

  • In the Project Manager, drag the class onto the container.

You can also add your classes directly from the Form Controls toolbar when you add them to your toolbar.

Adding Class Libraries to the Controls Toolbar

You need to register your class libraries before they can be displayed in the Form Controls toolbar.

To register a class library

  1. From the Tools menu, choose Options.
  2. In the Options dialog box, choose the Controls tab.
  3. Choose Add.
  4. In the Open dialog box, choose a class library to add to the Selected list and choose Open.
  5. Repeat steps 3 and 4 until you've added all the libraries you want to register.

Classes in the class libraries in the Selected list can be used in the Form Designer as easily as Visual FoxPro base classes can be used.

Tip If you want the class libraries to be available from the Form Controls toolbar every time you run Visual FoxPro, choose Set as Default in the Options dialog box.

You can also register libraries directly in the Form Designer.

To register a class library in the Form Designer

  1. In the Form Controls toolbar, choose the View Classes button.
  2. From the submenu, choose Add.
  3. In the Open dialog box, choose a class library to add to the Form Controls toolbar and choose Open.

Adding Objects to a Form from a Class Library

Once you've added class libraries in the Classes tab of the Options dialog box or from the View Classes submenu, you can access them in the Form Designer.

To add a custom object from the Controls toolbar

  1. In the Form Controls toolbar, choose the View Classes button.
  2. From the list of registered class libraries, select the library that contains the control you want to add to the form.

    The toolbar is populated with the controls in the library you selected.

  3. Click the control you want and drag it to size in the form.
    Note You can remove a visual class library from the View Classes toolbar menu by selecting the library in the Selected list in the Controls tab of the Options dialog box, and choosing Remove.

When you add objects to a form based on anything other than the Visual FoxPro base classes, a relative path to the class library (.vcx file) is stored in the form's .scx file. If you move either the form or the class library to a different location, Visual FoxPro displays a dialog box when you try to run the form so that you can manually locate the class library.

Determining What Controls Are on a Form

To determine how many controls are on the form, you can use the ControlCount property. The Controls[n] property of the form allows you to reference each control on the form. The following program prints the Name property of all the controls on the currently active form.

ACTIVATE SCREEN  && to print to the main Visual FoxPro window
FOR nCnt = 1 TO Application.ActiveForm.ControlCount
   ? Application.ActiveForm.Controls[nCnt].Name
ENDFOR

See Also

Adding User-Defined Objects to a Form | Adding Properties and Methods to a Form | Creating Forms | Addition of Objects to Forms | Project Manager | Adding Controls to a Form with the Component Gallery | Adding Controls to a Wizard-Generated Form | Selecting, Moving, and Resizing Form Controls | Aligning Controls in Forms | Setting Tab Order for Controls


Adding Properties and Methods to a Form

You can add as many new properties and methods as you want to a form set or to a form that isn't part of a form set. Properties hold a value; methods hold procedural code to be run when you call the method. The new properties and methods are scoped to the form and you reference them the same way you reference other properties or methods of the form.

Creating New Properties

If you have a form set, properties and methods that you add in the Form Designer are scoped to the form set. If you don't have a form set, the properties and methods are scoped to the form.

To add a new property to a form

  1. From the Form menu, choose New Property.
  2. In the New Property dialog box, type the name of the property. You can also include a description of the property that can be displayed at the bottom of the Properties window.

Creating an Array Property

An array property is scoped to the form like any other property, but can be manipulated with the Visual FoxPro array commands and functions.

To create an array property

  1. Add a new property to the form.
  2. In the Name box of the New Property dialog box, type the name of the array property and include the size and dimensions of the array.

    For example, to create a two-dimensional array with 10 rows, you could type arrayprop[10,2] in the Name box of the New Property dialog box.

Array properties are read-only in design mode, but you can manage, redimension, and assign values to the elements of the array property at run time. For an example of using an array property, see Managing Multiple Instances of a Form".

Creating New Methods

You can add methods to the form that can be called the same way the form class methods can be called.

To create a new method for a form

  1. From the Form menu, choose New Method.
  2. In the New Method dialog box, type the name of the method. You can optionally include a description of the method.

You call a user-defined method the same way you call base class methods, using the following syntax:

ObjectName.MethodName

Your method can also accept parameters and return values. In this case, you call the method in an assignment statement:

cVariable = ObjectName.MethodName(cParameter, nParameter)

Including Predefined Constants

To use predefined constants in your methods or events (not to properties), you can include a header file in a form or a form set using #INCLUDE. A header file typically contains compile-time constants defined with the #DEFINE preprocessor directive.

To include a file in a form

  1. From the Form menu, choose Include File.
  2. In the Include File dialog box, specify the file in the Include File text box.

    -or-

    Choose the dialog button to open the Include dialog box and choose the file.

  3. Choose OK.

See Also

Addition of Objects to Forms | Adding User-Defined Objects to a Form | Manipulating Objects | Creating Forms | Defining Form Behavior | Editing Event and Method Code


Manipulating Objects

There are several ways you can manipulate and work with objects on a form at design time:

  • Set the size and position of objects in the Form Designer by expanding, shrinking, or dragging them.
  • Align controls by choosing options on the Format menu or using the alignment tools on the Layout toolbar. For more information about the Layout toolbar, see Aligning Controls in Forms.
  • Set colors using the Palette toolbar. For more information about using the Palette toolbar, see Customizing Forms.
  • View object property settings, display inherited code for objects, events, and methods, set values for properties, and restrict your view to only modified properties using the Properties window.

Properties Window

The primary point of control for all objects in your form is the Properties window. The Properties window displays the properties, events, and methods and their settings for a selected form, data environment, cursor, relation, or control.

Properties window

For more information about the Properties window, see Properties Window.

Viewing Properties for Objects

To view properties for an object, open the Properties window.

To open the Properties window

  • On the Window menu, click Properties Window.

You can also open the Properties window by right-clicking the Form Designer or Data Environment Designer and choosing Properties from the shortcut menu.

To view properties for an object

  • Click the form or an object on the form.

The Properties window displays the properties, methods, and events for the selected object. You can also select the object from the object list in the Properties window.

To view properties that multiple objects have in common, press and hold SHIFT while you select several objects on the form. The properties list shows common properties for the objects you select.

To view settings for properties, events, and methods that appear truncated in the properties list, expand the Properties window or display the value tip by moving the mouse over the property, event, or method in the properties list. Value tips show the visual class libraries, if they exist, from which methods and events are inherited and settings for read-only properties.

Displaying Inherited Code for Objects, Events, and Methods

You can view code inherited from parent classes for objects, events, and methods, making it easier to decide whether you want to use or override the inherited code.

Note The View Parent and View Inherited Code features support only the viewing of parent code, not editing. To edit parent class code if using a subclass, use the Class Browser. For more information, see Viewing Class Definition Code and Managing Classes with the Class Browser.

You can choose to view inherited or parent code from inside the code window or the properties list in the Properties window.

To view inherited code using the code window

  1. Choose an object from the form.

    -or-

    Choose an event or method from the properties list in the Properties window.

  2. To open the code window, double-click the object, event, or method.
  3. In the code window, click the View Parent Code button to display the list of all parent classes.
  4. Select the parent class.

An editing window opens and displays the parent code. You can also choose the View Parent Code button in the code window by pressing ALT+I.

Note The View Parent Code button is available in the code window only when there is at least one parent class that contains code. When source code exists, parent classes appear in bold.

Visual FoxPro displays only those parent classes for the selected control. If a list of parent classes is available, the parent classes appear in order from the most immediate or top parent class to the one closest to the base class, traversing the parent tree. The base class does not appear.

If code inherited from the immediate parent class exists, and the parent class is a member of a container class, Visual FoxPro displays the container class followed by a separator and then the classes in the parent tree. Other classes that traverse the container hierarchy might contain code but are not displayed in the list.

Viewing inherited code using the properties list in the Properties window traverses the parent or container tree to reach the inherited parent class.

Viewing Inherited Code using the Properties Window

If inherited code exists for a method or event, the parent class name and class libraries from which the method or event inherits code appear in the properties list of the Properties window as follows:

Inherited cClassname ClassLibrary

To view inherited code using the properties list

  1. Select an object on the form.
  2. In properties list in the Properties window, right-click the event or method.
  3. From the shortcut menu, select View Inherited Code.

An editing window opens and displays the inherited parent code.

Setting Properties for Objects

You can set or change properties at design time or programmatically.

Note Some properties are evaluated at design time, so any memory variables or arrays used in expressions for these properties must be in scope at design time. Properties that are read-only at design time, such as the Class property of an object, are displayed in italics in the properties list of the Properties window.

To set or edit the value for a property

  1. Click an object on the form.
  2. From the properties list in the Properties window, select a property.
  3. In the property settings box, type or choose the desired setting for the selected property.

You can also select an object from the object box in the Properties window.

If the property requires a character value, you do not have to include the value in quotation marks. For example, if you want the caption of a form to display as Customer, type Customer in the property settings box. However, if you want the caption to display as "Customer" with quotation marks (""), type "Customer" in the property settings box.

Setting Properties to Expressions

You can set certain properties to the results of expressions or functions in the Properties window. Visual FoxPro evaluates the expression for a property when you enter it in the Properties window and when the object is initialized at design or run time. Once the object is created, the property setting does not change until you or the user explicitly changes it.

Caution If you set a property to the result of a user-defined function, Visual FoxPro evaluates the function when you set the property, or when you modify or run the form. If an error exists in the user-defined function, you might not be able to open your form.

You can also set the property to the user-defined function in the Init event of the object as in the following example:

THIS.Caption = myfunction( )

However, if an error exists in the user-defined function, you will still be unable to run the form, but you can modify it.

To set a property to an expression

  1. From the properties list, select the property for which you want to enter an expression.
  2. In the property settings box, type an equal sign (=) followed by the expression.

For example, you can indicate the currently active table when the form runs by selecting the Caption property of the form and typing =ALIAS( ) in the property settings box.

You can also specify expressions for properties by using the Expression Builder. To open the Expression Builder, select the desired property and click the Function button in the Properties window.

Showing Properties with Modified Settings

In the Properties window, you can choose to list only those properties for which the default settings have been changed.

To view properties with modified settings

  1. Right-click the Properties window outside the properties list.
  2. From the shortcut menu, select Non-Default Properties Only.

The properties list shows only those properties, events, and methods whose settings have been changed.

See Also

Adding Properties and Methods to a Form | Defining Form Behavior | Creating Forms | Editing Event and Method Code | Form Designer


Defining Form Behavior

When you are designing a form in the Form Designer, the form is live: except for setting the Visible property to false (.F.), visual and behavioral changes you make are immediately reflected in the form. If you set the WindowState property to 1 – Minimized or 2 – Maximized, the form in the Form Designer immediately reflects this setting. If you set the Movable property to false (.F.), a user will not be able to move the form at run time and you won't be able to move the form at design time either. You might want to design the functionality of your form and add all the appropriate controls before you set some of the properties that determine form behavior.

The following form properties are commonly set at design time to define the appearance and behavior of the form.

Property | Description | Default
AlwaysOnTop | Controls whether a form is always on top of other open windows. | False (.F.)
AutoCenter | Controls whether the form is automatically centered in the main Visual FoxPro window or on the desktop when the form is initialized. | False (.F.)
BackColor | Determines the color of the form window. | 255,255,255
BorderStyle | Controls whether the form has no border, a single-line border, a double-wide border, or a system border. If the BorderStyle is 3 - System, the user will be able to resize the form. | 3
Caption | Determines the text displayed in the title bar of the form. | Form1
Closable | Controls whether the user can close the form by double-clicking the close box. | True (.T.)
DataSession | Controls whether the tables in the form are opened in work areas that are globally accessible or private to the form. | 1
MaxButton | Controls whether or not the form has a maximize button. | True (.T.)
MinButton | Controls whether or not the form has a minimize button. | True (.T.)
Movable | Controls whether or not the form can be moved to a new location on the screen. | True (.T.)
ScaleMode | Controls whether the unit of measurement in object size and position properties is foxels or pixels. | Determined by settings in the Options dialog box.
Scrollbars | Controls the type of scroll bars a form has. | 0 - None
TitleBar | Controls whether a title bar appears at the top of the form. | 1 - On
ShowWindow | Controls whether the window is a child (in screen), floating, or top-level window. | 0 - In Screen
WindowState | Controls whether the form is minimized (in Windows only), maximized, or normal. | 0 - Normal
WindowType | Controls whether the form is modeless (the default) or modal. If the form is modal, the user must close the form before accessing any other elements of your application's user interface. | 0 – Modeless

You can use the LockScreen property to make run-time adjustment of control layout properties appear cleaner.

Assigning Icons to Forms

In Visual FoxPro, you can assign an icon to the form; the icon is displayed on a forms taskbar button and in the title bar of the form. To assign an icon to a form, set the form's Icon property to the name of an .ico file.

To assign an icon to a form

  1. Open the form.
  2. Open the Properties window.
  3. Set the Icon property to the .ico file that you want to display.

See Also

Manipulating Objects | Editing Event and Method Code | Creating Forms | Form Designer | Visible | Saving Forms


Editing Event and Method Code

Events are user actions, such as clicks and mouse movements, or system actions, such as the progression of the system clock. Methods are procedures that are associated with the object and that are specifically invoked programmatically. For a discussion of events and methods, see Object-Oriented Programming. You can specify the code to be processed when an event is triggered or a method is invoked.

To edit event or method code

  1. From the View menu, choose Code.
  2. Select the event or method in the Procedure box.
  3. In the Edit window, write the code you want to be processed when the event is triggered or the method is invoked.

    For example, you could have a command button on a form with the caption "Quit." In the Click event for the button, include the line:

    THISFORM.Release
    Tip To move between procedures in the Code Editing window, press PAGE DOWN or PAGE UP.

When the user clicks the command button, the form is removed from the screen and from memory. If you don't want to release the form from memory, you could instead include the following line in the click event:

THISFORM.Hide
Note If code associated with the Init event of a form set, a form, or any object on any form in a form set returns false (.F.), the form will not be created.

See Also

Defining Form Behavior | Saving Forms | Creating Forms | Running a Form | Setting Properties at Run Time


Saving Forms

You need to save your form before you can run it. If you try to close the Form Designer when the form has not been saved, Visual FoxPro prompts you to save or discard the changes you've made.

To save a form

  • In the Form Designer, choose Save from the File menu. Forms are saved as files with an .scx extension.

Saving Forms and Controls as Classes

You can also save a form, or a subset of the controls on a form, as a class definition. If you intend to create subclasses based on the form or reuse the controls in other forms, save the form as a class definition.

To save a form or selected controls as a class definition

  1. From the File menu, choose Save As Class.
  2. In the Save As Class dialog box, choose Current form or Selected controls.
  3. In the Name box, enter a name for the class.
  4. In the File box, enter a filename for the class to be stored to.
  5. Choose OK.

If you don't give the filename an extension, the default extension of .vcx is added when the file is saved. Once a form has been saved as a class definition, you can modify it with the MODIFY CLASS command. For more information about creating classes, see Object-Oriented Programming.

See Also

Saving a Form as HTML | Editing Event and Method Code | Creating Forms | Running a Form | Setting Properties at Run Time | Example of Manipulating Objects


Saving a Form as HTML

You can use the Save As HTML option on the File menu when you're creating a form to save the contents of a form as an HTML (Hypertext Markup Language) file.

To save a form as HTML

  1. Open the form.
  2. Choose Save As HTML on the File menu. (You will be asked to save the form if it has been modified.)
  3. Enter the name of the HTML file to create and choose Save.

See Also

Saving Forms | Passing Parameters to a Form | Managing Multiple Instances of a Form | Creating Forms | Setting the Design Area for a Form | Creating Forms with Local and Remote Data


Working with Forms

When you have created a form, you can manipulate it in various ways. You can run or hide it using the interface or programmatically. You can alter your form through its objects, by passing parameters, or setting the design area and templates. Local and remote data can be incorporated into your form, and you can manage multiple instances of your form.

In This Section

Running a Form
Provides instructions on how to run a form, name a form object, and make it possible for a user to close the active form.
Setting Properties at Run Time
Provides instructions on how to set properties to expressions at run time and set multiple properties at the same time.
Example of Manipulating Objects
Contains an example with two forms in a formset. The example illustrates how to set properties and call event code from a number of objects inside a formset.
Hiding a Form
Explains how to hide and release a form. When you hide a form, it is invisible to the user, and the user cannot manipulate it. However, you still have complete programmatic control of the form.
Passing Parameters to a Form
Details the steps required to pass a parameter to a form created in the Form designer and to return a value from a form.
Returning a Value from a Form
Provides steps for using forms throughout your application to allow users to specify a value.
Managing Multiple Instances of a Form
Outlines the important issues to consider when you have multiple instances of a form and provides examples of multiple instances of a form.
Customizing Forms
Provides instructions on how to change text fonts and sizes, add shapes and lines to a form, add graphics to a form, and set the foreground and background colors of a form.
Setting the Design Area for a Form
Explains how to set the maximum design area for the Form designer in the Options dialog box.
Creating Forms with Local and Remote Data
Describes the creation of forms that can be switched easily between using local and remote data.
Setting Form Templates
Contains an explanation of how to specify a form class from a registered class library for your form template and presents the various ways you can specify form set templates.

Related Sections

Creating the User Interface
Using Microsoft® Visual FoxPro® forms, classes, controls, menus, and toolbars, you can build interfaces that help users gain access to the full potential of your programs.
Creating Forms
Your application must have forms to make it possible for users to view and enter data. However, you can customize standard forms visually and programmatically to create a specialized environment for your users.
Using Controls
Controls manage the interactions between users and your application. Microsoft® Visual FoxPro® offers a variety of controls to enhance your application interface.
Designing Menus and Toolbars
A good menu system tells your users a lot about the design and structure of your application. Planning menus and toolbars carefully can improve the usability of your application and provide immediate access to common tasks.


Running a Form

You can run a form directly from the interface or in program code.

Running a Form Interactively

There are several ways to run the form you've designed.

If you're working in the Form Designer, you can test the form by clicking the Run button on the Form Designer toolbar. To reopen the form in the Form Designer, close the form or choose the Modify Form button on the toolbar.

You can also run a form from a project or programmatically.

To run a form

  • In the Project Manager, select the select the name of the form under the Documents tab and choose Run.

    -or-

  • Type DO FORM in the Command window.

    -or-

  • From the Form menu, choose Run Form. You can also choose the Run button on the Standard toolbar.

You can also run the form by choosing Do from the Program menu, choosing Form in the List Files of Type box, selecting the form, and choosing Do.

Tip When running a form, you can quickly switch to Design mode by clicking the Modify Form button on the Standard toolbar.

Running a Form from a Program

To programmatically run a form, include the DO FORM command in the code associated with an event, in method code, or in a program or procedure.

Naming the Form Object

By default, when you use the DO FORM command, the name of the form object is the same as the name of the .scx file. For example, the following line of code runs Customer.scx. Visual FoxPro automatically creates an object variable for the form named customer:

DO FORM Customer

To name a form object

  • Use the NAME clause of the DO FORM command.

For example, the following commands run a form, creating two form object variable names:

DO FORM Customer NAME frmCust1
DO FORM Customer NAME frmCust2

Manipulating the Form Object

If you issue the DO FORM command from the Command window, the form object is associated with a public variable. You can access the form object through the variable name. For example, the following commands, issued in the Command window, open a form named Customer and change its caption.

DO FORM Customer
Customer.Caption = "Hello"

If you then issue the following command in the Command window, O is displayed in the active output window, indicating that Customer is an object:

? TYPE("Customer")

If you issue the DO FORM command in a program, the form object is scoped to the program. If the program or procedure completes, the object is gone, but the form remains visible. For example, you could run the following program:

*formtest.prg
DO FORM Customer

After you run the program, the form remains visible and all of the controls on the form are active, but TYPE("Customer") returns U indicating that Customer is an undefined variable. The following command, issued in the Command window, would generate an error:

Customer.Caption = "Hello"

You can, however, access the form by using the ActiveForm, Forms, and FormCount properties of the application object.

Scoping the Form to the Form Object Variable

The LINKED keyword of the DO FORM command allows you to link the form to the form object. If you include the LINKED keyword, when the variable associated with the form object goes out of scope, the form is released.

For example, the following command creates a form linked to the object variable frmCust2:

DO FORM Customer NAME frmCust2 LINKED

When frmCust2 is released, the form is closed.

Closing an Active Form

To allow users to close the active form by clicking the close button or by choosing Close from the form's Control menu, set the Closable property of the form.

To allow a user to close the active form

  • In the Properties window, set the Closable property to true (.T.).

    -or-

  • Use the RELEASE command.

For example, you can close and release the frmCustomer form by issuing the following command in a program or in the Command window:

RELEASE frmCustomer

You can also allow a user to close and release a form by including the following command in the Click event code for a control, such as a command button with a caption of "Quit":

THISFORM.Release

You can also use the RELEASE command in the code associated with an object on the form, but any code you've included in the Release method will not be executed.

Caution When you release a form, you release from memory the object variable created for the form. There is a single variable for a form set, so you can't release forms in a form set without releasing the form set. If you want to release the form set, you can use RELEASE THISFORMSET. If you want to remove a form from the screen so that a user can no longer see it or interact with it, you can use THISFORM.Hide.

See Also

Saving Forms | Setting Properties at Run Time | Creating Forms | Example of Manipulating Objects | Hiding a Form


Setting Properties at Run Time

The object model in Visual FoxPro gives you a great deal of control over properties at run time.

Referencing Objects in the Object Hierarchy

To manipulate an object, you need to identify it in relation to the container hierarchy. At the highest level of the container hierarchy (the form set or form) you need to reference the object variable. Unless you use the NAME clause of the DO FORM command, the object variable has the same name as the .scx file.

Properties are manipulated by referencing the object variable, the control, and the property, separated by dots (.):

objectvariable.[form.]control.property = Setting

The following table lists properties or keywords that make it easier to reference an object in the object hierarchy:

Property or keyword | Reference
ActiveControl | The control on the currently active form that has the focus
ActiveForm | The currently active form
ActivePage | The active page on the currently active form
Parent | The immediate container of the object
THIS | The object or a procedure or event of the object
THISFORM | The form that contains the object
THISFORMSET | The form set that contains the object

For example, to change the caption of a command button on the form frmCust in a form set stored in Custview.scx, use the following command in a program or in the Command window:

CustView.frmCust.cmdButton1.Caption = "Edit"

Use the THIS, THISFORM, and THISFORMSET keywords to reference objects from within a form. For example, to change the Caption of a command button when the command button is clicked, include the following command in the Click event code for the command button:

THIS.Caption = "Edit"

The following table gives examples of using THISFORMSET, THISFORM, THIS, and Parent to set object properties:

Command Where to include the command
THISFORMSET.frm1.cmd1.Caption = 'OK'
 In the event or method code of any control on any form in the form set except for frm1.
THISFORM.cmd1.Caption = 'OK'
 In the event or method code of any control except for cmd1 on the same form that cmd1 is on.
THIS.Caption = 'OK'
 In the event or method code of the control whose caption you want to change.
THIS.Parent.BackColor = RGB(192,0,0)
 In the event or method code of a control on a form. The command changes the background color of the form to dark red.

Setting Properties at Run Time with Expressions

You can also set properties at run time using expressions or functions.

To set properties to expressions at run time

  • Assign an expression to the property.

    -or-

  • Assign the result of a user-defined function to the property.

    For example, you could set the caption of a button to be Edit or Save, depending on the value of a variable. Declare the variable in the calling program for your form:

    PUBLIC glEditing
glEditing = .F.

    Then use an IIF expression in the Caption setting:

    frsSet1.frmForm1.cmdButton1.Caption = ;
   IIF(glEditing = .F., "Edit", "Save")

You could determine the size of a button and set the caption using expressions with fields in a table:

* set button width to length of 'Call ' + first and last names
frmForm1.cmdButton1.Width = 5 + ;
   LEN(ALLTRIM(employee.first_name    + " " + employee.last_name))
* set button caption to 'Call ' + first and last names
frmForm1.cmdButton1.Caption = "Call " + ;
   ALLTRIM(employee.first_name + " " + employee.last_name)

You could also set the caption using a user-defined function:

frsSet1.frmForm1.cmdButton1.Caption = setcaption()

Setting Multiple Properties

You can set multiple properties at once.

To set multiple properties

  • Use the WITH ... ENDWITH structure.

    For example, to set multiple properties of a column in a grid in a form, you could include the following statement in any event or method code in the form:

    WITH THISFORM.grdGrid1.grcColumn1
   .Width = 5
   .Resizable = .F.
   .ForeColor = RGB(0,0,0)
   .BackColor = RGB(255,255,255)
   .SelectOnEntry = .T.
ENDWITH

Calling Methods at Run Time

The syntax for calling methods of an object is:

Parent.Object.Method

Once an object has been created, you can call the methods of that object from anywhere in your application. The following commands call methods to display a form and set the focus to a command button:

* form set saved in MYF_SET.SCX
myf_set.frmForm1.Show
myf_set.frmForm1.cmdButton1.SetFocus

To hide the form, issue this command:

myf_set.frmForm1.Hide

Responding to Events

The code you include in an event procedure is executed when the event takes place. For example, the code you include in the Click event procedure of a command button runs when the user clicks the command button.

Calling the procedural code associated with an event does not cause the event to occur. For example, the following statement causes the code in the Activate event of frmPhoneLog to be executed, but it doesn't activate the form:

frmPhoneLog.Activate

Calling the Show method of a form causes the form to be displayed and activated, at which point the code in the Activate event is executed:

frmPhoneLog.Show

See Also

Running a Form | Example of Manipulating Objects | Creating Forms | Hiding a Form | Passing Parameters to a Form | Saving a Form as HTML


Example of Manipulating Objects

The following example sets properties and calls event code from various objects within a form set. The example includes two forms, frmLeft and frmRight, in a formset.

Sample form set in the Form Designer

The two check boxes and the command button on frmLeft have event code associated with them. The name of the text box on frmLeft is txtInput.

Event Code for Objects in LeftForm

Object Event Code
chkItalic Click
THISFORM.txtInput.FontItalic = ;
   THIS.Value
chkBold Click
THIS.txtInput.FontBold = THIS.Value
cmdClear Click
THISFORM.txtInput.Value = ""

THISFORM.txtInput.FontBold = .F.
THISFORM.txtInput.FontItalic = .F.
THISFORM.chkItalic.Value = .F.
THISFORM.chkBold.Value = .F.

Setting a Property of Another Control on the Same Form

You can set the properties of one control from within the event code of another by using the THISFORM keyword or the Parent property. The following two commands are executed when a user initially clicks on the Italic and the Bold check boxes, setting the appropriate text box properties:

THISFORM.txtInput.FontItalic = .T.
THIS.Parent.txtInput.FontBold = .T.

In this case, THISFORM and THIS.Parent can be used interchangeably.

Sample form set at run time

The code in the click event for cmdClear uses THISFORM to reset the values of the other controls on the form.

Setting Another Form's Properties

You can also set properties of one form from another. Form2 contains five command buttons. The first button on the form has this code in its Click event:

THISFORMSET.frmLeft.Caption = ;
 ALLTRIM(ThisFormSet.frmLeft.txtInput.Value)

Notice that the form set and the form need to be referenced when setting properties from within a different form.

User clicks "Change Left Form Caption" command button on Right Form

The click event code of the second command button on frmRight demonstrates setting a property of a form from within an object on the form:

THISFORM.Caption = ;
 ALLTRIM(ThisFormSet.frmLeft.txtInput.Value)

If the user chooses this button, the caption of frmRight changes to the value in the text box on frmLeft.

Accessing Objects on Different Forms

The following code in the Click event of the Change Bold Setting command button changes the value of the Bold check box on frmLeft and calls the event code associated with this control.

THISFORMSET.frmLeft.chkBold.Value = ;
   NOT THISFORMSET.frmLeft.chkBold.Value
THISFORMSET.frmLeft.chkBold.InteractiveChange

The last line of the example calls the InteractiveChange event of chkBold. You could also call this procedure with the following command:

THISFORMSET.frmForm1.chkBold.InteractiveChange( )

If this procedure call is omitted, the value of the check box changes, but the FontBold property of the text box is never changed.

User clicks "Change Bold Setting" command button on Right Form

Checking Properties and Calling Method Code of Another Form

The following code in the Click event of the Hide Left Form command button hides or shows frmLeft, depending on the value of the Visible property, and changes the button caption as appropriate:

IF ThisFormSet.frmLeft.Visible
   ThisFormSet.frmLeft.Hide
   THIS.Caption = "Show Left Form"
ELSE
   ThisFormSet.frmLeft.Show
   THIS.Caption = "Hide Left Form"
ENDIF

Notice that the THIS keyword is used within event code of a control to reference properties of the control.

User clicks Hide Left Form command button on Right Form

The following command in the Click event of the Quit command button releases the form set, causing both forms to close:

RELEASE ThisFormSet

See Also

Setting Properties at Run Time | Hiding a Form | Creating Forms | Passing Parameters to a Form | Saving a Form as HTML


Hiding a Form

You can hide a form so that it is not visible to a user. When the form is hidden, the user cannot interact with the form, but you still have full programmatic control of them.

To hide a form

  • Use the Hide method.

    For example, in the code associated with the Click event of a command button, you could include the following line of code:

    THISFORM.Hide

When the user clicks the command button, the form remains in memory, but is not visible.

Releasing a Form

You can allow a user to release a form when he or she is finished interacting with it. When you release a form, you can no longer access properties and methods of the form.

To release a form

  • Call the Release method.

For example, in the code associated with the Click event of a command button, you could include the following line of code:

THISFORM.Release

When the user clicks the command button, the form closes.

See Also

Example of Manipulating Objects | Creating Forms | Passing Parameters to a Form | Saving a Form as HTML | Managing Multiple Instances of a Form


Passing Parameters to a Form

Sometimes you want to pass parameters to forms when you run them to set property values or specify operational defaults.

To pass a parameter to a form created in the Form Designer

  1. Create properties on the form to hold the parameters, such as ItemName and ItemQuantity.
  2. In the Init event code for the form, include a PARAMETERS statement such as:
    PARAMETERS cString, nNumber
  3. In the Init event code for the form, assign the parameters to the properties, as in this example:
    THIS.ItemName = cString
THIS.ItemQuantity = nNumber
  4. When running the form, include a WITH clause in the DO FORM command:
    DO FORM myform WITH "Bagel", 24

See Also

Hiding a Form | Saving a Form as HTML | Creating Forms | Managing Multiple Instances of a Form | Setting the Design Area for a Form | Returning a Value from a Form


Returning a Value from a Form

You can use forms throughout your application to allow users to specify a value.

To return a value from a form

  1. Set the WindowType property of the form to 1 to make the form modal.
  2. In the code associated with the Unload event of the form, include a RETURN command with the return value.
  3. In the program or method that runs the form, include the TO keyword in the DO FORM command.

    For example, if FindCustID is a modal form that returns a character value, the following line of code stores the return value to a variable named cCustID:

    DO FORM FindCustID TO cCustID

For more information, see RETURN and DO FORM.

Note If you get an error, make sure the WindowType is set to 1 (Modal).

See Also

Unload Event | Passing Parameters to a Form | RETURN | DO FORM


Managing Multiple Instances of a Form

You can have multiple instances of a class definition active at a time. For example, you can design one order form but have several open orders in your application. Each uses the same form definition but is displayed and manipulated individually.

When you have multiple instances of a form, the key points to remember are:

  • Create an array property in the launching form to hold the object variables associated with each instance of the multiple instance form. The easiest way to keep track of instance variables when you don't know ahead of time how many there will be is to use an array.
  • For the form that is to have multiple instances, set the DataSession property to 2 – Private Data Session. A private data session provides a separate set of work areas for each instance of the form so that selected tables and record pointer positions are all independent.

The following example provides code that demonstrates creating multiple instances of a form. For the sake of brevity, this code is not optimized; it is intended only to present the concepts.

The following form launches multiple instances:

Property Setting for Launch.scx

Object Property Setting
frmLaunch aForms[1]
" "

Event Code for Launch.scx

Object Event Code
cmdQuit Click
RELEASE THISFORM
cmdLaunch Click
nInstance = ALEN(THISFORM.aForms)
DO FORM Multi ;
  NAME THISFORM.aForms[nInstance] ;

  LINKED
DIMENSION ;
  THISFORM.aForms[nInstance + 1]

In refining the code in this example, you could manage the array of form objects so that empty array elements reused as forms are closed and new forms are opened, rather than always redimensioning the array and increasing the number of elements by one.

The form that can have multiple instances is Multi.scx. The data environment for this form contains the Employee table.

Multiple instances of Multi.scx

Property Setting for Multi.scx

Object | Property | Setting
txtFirstname ControlSource
Employee.first_name
txtLastName ControlSource
Employee.last_name
frmMulti | DataSession | 2 - Private Data Session

When you choose Launch Form in the Launcher form, an instance of the Multi form is created. When you close the Launcher form, the property array aForms is released and all instances of Multi are destroyed.

Visual FoxPro provides some functions and properties to help you manage multiple instances of objects. For more information, see AINSTANCE( ), AUSED( ), and DataSessionID.

See Also

Saving a Form as HTML | Setting the Design Area for a Form | Creating Forms | Creating Forms with Local and Remote Data | DataSession


Customizing Forms

You can add enhancements to your forms to make them more interesting visually and easier to use. For example, you might want to group similar controls together visually by drawing a box around them, or use images to give the forms a more professional appearance.

Using the Form Designer, you can customize your forms by:

  • Changing text fonts and sizes
  • Adding shapes and lines to a form
  • Adding graphics to a form
  • Setting the foreground and background colors of a form

Changing Text Fonts and Sizes

Using the font properties in the Properties window, you can modify the style and size of the text that appears in controls you have added to your forms. You can choose from the available font styles and sizes supported by your system. To change the text in your form, change the font properties, such as FontName, FontSize, and FontBold, shown in the Properties window.

To change the text in your forms

  1. In the Form Designer, select the control you want to change.
  2. In the Properties window, drop down the Object list, and select the object you want to change.
  3. Locate the font property you want to change, and set its value.

Adding Shapes and Lines to Forms

You can add shapes and lines to forms to customize them. For example, you may want to separate groups of controls with a dividing line, or enclose related controls within a box to set them apart.

To add a line to a form

  1. In the Form Controls toolbar, choose the Line button.
  2. Drag in the form to create a line.

You can size and move the line like other controls, or change the slant of the line with the LineSlant property in the Properties window.

To add a shape to a form

  1. In the Form Controls toolbar, choose the Shape button.
  2. Drag in the form to create a shape.

You can change the type of shape drawn with the Curvature property in the Properties window.

Adding Graphics to a Form

You can add an image to the background of your form, or add an image to a box inside the form.

To add a graphic to your form

  1. Choose one of the following:
    • To change the background of the form, select the form.

      -or-

    • To add a picture to your form, select an Image control from the Form Controls toolbar and place it on the form.
  2. In the Properties window, select the Picture property.
  3. Choose the dialog button to display the Open dialog box.
  4. Locate the image or other file you want to use.
  5. Choose OK.

Setting Form Colors

You can control a form's colors by using the ColorSource property to base the colors on an existing color scheme, or you can use the Color Palette toolbar to change the foreground or background color of your forms and the controls within them.

To set form colors using the ColorSource property

  • On the Layout tab in the Properties window, choose ColorSource and select a value.

To set the foreground or background color of a form or control

  1. From the View menu, select Color Palette toolbar.
  2. Choose Foreground Color or Background Color.
  3. Select the control or form you want to change.
  4. In the Color Palette toolbar, select the color you want to use.
  5. To see more color choices, choose Other Colors on the toolbar.

To create a custom color

  1. In the Color Palette toolbar, choose Other Colors.
  2. In the Color dialog box, choose Define Custom Colors to display the Custom Color Selector.
  3. Select one of the Custom Colors boxes, and then click in the Custom Color Selector to select the custom color you want.
  4. Choose Add to Custom Colors to add the new color to your palette.
  5. Choose OK.

    Visual FoxPro applies the custom color to the current selection.

See Also

Creating Forms | Form Designer | Properties window | ColorSource property | Creating Forms | Setting the Design Area for a Form | Managing Multiple Instances of a Form | LineSlant Property


Creating Forms with Local and Remote Data

You can create forms that can be easily switched between using local data and data that is stored remotely (for example, on a database server). This allows you to create a prototype application using local or test data, then switch to remote or live data without substantial changes to your forms.

For example, if your Visual FoxPro application is a front end for a large customer table stored on a database server, you can create a local .dbf file that contains a small but representative sampling of the data. You can then create, test, and debug your forms based on this small set of data. When you're ready to distribute your application, you can link your form to the large data set.

The key to being able to switch between local and remote data is to make sure that you use views instead of directly linking your form (and its controls) to a table. To access remote data, you must use a view in any event. Therefore, to facilitate switching between local and remote data, create a view for the local data as well. When you create the form, you can add both views to its data environment, then switch between them as needed.

To create a form that can switch between local and remote data

  1. Create two views of the data, one that points to the remote data, and another that points to the local data.
  2. Create a new form.
  3. Open the Data Environment Designer for the form, and then add both views.
  4. Right-click the Data Environment Designer, and then choose Properties.
  5. In the Properties window, set the Alias property for both cursors to the same name.
  6. Set the data environment's OpenViews property to either 1 — Local Only or 2 — Remote Only, depending on which view you wanted to use when running the form.
    Note Because you are using the same alias for both views, do not choose 0 — Local and Remote (the default).
  7. On the form, add the controls you need and set their ControlSource properties to the appropriate fields in the view. Because both views have the same alias, the controls will respond automatically to whichever view is active when the form is run.

After the form is created, you can switch the views alias by changing the data environment's OpenViews property. You can do this in the Data Environment while using the Form Designer. Alternatively, you can write code and attach it to an event, which is useful if you want to switch views at run time. For example, you could put this code in the form's Activate event:

THISFORM.DataEnvironment.OpenViews = 2 && Use remote view

If you create a form that can be switched between local and remote data, you must also design your navigation code to accommodate both views, particularly if you are designing forms with one-to-many relationships. For example, if your form only accesses a local table or view, you might use code such as the following in a Next command button to move to the next record in a cursor:

SKIP 1
THISFORM.Refresh()

However, this code is inefficient when you're navigating in a remote view, because it assumes that the cursor contains all the data required by the form. As a rule, you want to minimize the amount of data that you download from the remote data source.

The solution is to use a parameterized view. For example, the definition for a view used to edit customer information could be:

SELECT * FROM CUSTOMERS WHERE ;
 CUSTOMERS.COMPANY_NAME = ?pCompanyName

When the form runs, it can prompt the user for a customer name using a dialog box or by allowing the user to enter a name in a text box. The code for a Display button would then be similar to the following:

pCompanyName = THISFORM.txtCompanyName.Value
REQUERY("customer")
THISFORM.Refresh()

For more information about parameterized views, see "Creating a Parameterized View" in Creating Views.

See Also

Setting the Design Area for a Form | Setting Form Templates | Creating Forms | Data Environment Designer | Properties window | OpenViews


Setting the Design Area for a Form

You can set the maximum design area for the Form Designer in the Options dialog box.

To set the maximum design area for a form

  1. From the Tools menu, choose Options.
  2. In the Options dialog box, choose the Forms tab.
  3. In the Maximum design area box, choose the pixel coordinates for the maximum design area.
    Tip If you select None, the Form Designer does not impose a limit on the size of form you design.

For more information, see Forms Tab, Options Dialog Box

When you set the maximum design area, the background of the Form Designer is white within the design area boundaries and gray in areas beyond the maximum design area. If you develop applications on a monitor with a resolution of 1024 x 768, for example, you can set your design resolution to 640 x 480 and know that the forms you design will always fit on 640 x 480 screens.

Within the design area, be sure to account for standard window attributes such as toolbars. For example, in a 640 x 480 screen, a form with a status bar and one toolbar docked at the top or the bottom of the screen can have a maximum height of 390 pixels.

Main Visual FoxPro window attribute | Required pixels (Non-Themed Windows)
Title and menu | 38
Status bar | 23
Docked toolbar | 29
Note The required pixel amounts above will vary if themed windows are used.

See Also

Managing Multiple Instances of a Form | Creating Forms with Local and Remote Data | Creating Forms | Setting Form Templates | Form Designer


Setting Form Templates

You can create your own form class to use a template for all your new forms, or you can use one of the sample classes that ship with Visual FoxPro.

When you create a new form, it is based on the template form that is set in the Options dialog box. If no template is specified, the new form is based on the Visual FoxPro Form base class. For more information about Visual FoxPro classes, see Object-Oriented Programming.

Advantages of Using Form Templates

Form templates allow you to set default properties for your forms so that you can easily give all the forms in your application a consistent look and feel. You could include a company logo, for instance, and use a consistent color scheme in all your forms by designing a template form class with these attributes. If the company logo changes, you could change the picture in the template form class and all the forms you created based on the template would automatically inherit the new logo.

You can add custom properties and methods to the Visual FoxPro form class so that these properties and methods are available to each form in your application. If you are used to creating variables and user-defined procedures that are scoped to a form, using custom properties and methods provides this functionality, and also allows you to have a cleaner encapsulation model.

Specifying the Default Form Template

You can specify a form class from a registered class library for your form template.

To specify a default form template

  1. From the Tools menu, choose Options.
  2. In the Options dialog box, choose the Forms tab.
  3. In the Template classes area, select the Form check box.

    If no form template has been selected, the Open dialog box opens so that you can choose a form class. If a form template has been selected, you can change it by choosing the dialog button and selecting another class.

  4. Choose Set as Default if you want the template to be used in subsequent sessions of Visual FoxPro.
  5. Choose OK.

Using Form Templates

You can specify form set templates the same way you set form templates. The following combinations are possible:

  • Both form set and form templates are specified.

    Choosing Form in the New dialog box (and all the other ways to create a new form) will automatically create a form set based on the template form set class. When you choose Add New Form from the Form menu in the Form Designer, a form based on your form template is added to the form set.

  • Only the form set template is specified.

    Choosing Form in the New dialog box (and all the other ways to create a new form) will automatically create a form set based on the template FormSet class. When you choose Add New Form from the Form menu in the Form Designer, a form based on the Visual FoxPro Form base class is added to the form set.

  • Only the form template is specified.

    Choosing Form in the New dialog box (and all the other ways to create a new form) will automatically create a form based on the template Form class.

  • No templates are specified.

    Choosing Form in the New dialog box (and all the other ways to create a new form) will automatically create a form based on the Visual FoxPro Form base class.

See Also

Creating Forms with Local and Remote Data | Creating Forms | Options | Saving a Form as HTML | Setting the Design Area for a Form | Managing Multiple Instances of a Form


Using Controls

Controls are the primary medium of user interaction. By typing and clicking and by moving through controls on the forms in your application, users can manipulate their data and accomplish the tasks they want to do.

In This Section

Control Selection for Particular Tasks
Explains the flexibility of Visual FoxPro controls and how to correctly select the proper control for your application.
Controls for Displaying Lists
Describes the common uses, methods, and properties of list boxes and drop-down list boxes.
Controls for Accepting Input
Describes the common uses, methods, and properties of Visual FoxPro controls that accept user input that cannot be predetermined.
Controls for Displaying Information
Explains various Visual FoxPro controls and objects that can display and order information.
Controls for Manipulating Rows of Data
Describes the common uses, methods, and properties of the Visual FoxPro grid control.
Controls for Allowing Specific Actions
Describes the Visual FoxPro controls that allow users to take specific preprogrammed actions either by user interaction or by timed delay.
Controls for Extending Forms
Describes how the Page Frame object and the use of ActiveX controls can expand the workable area and use of Visual FoxPro forms.
Controls and Data Concepts
Explains the difference between the two kinds of controls you can have on your forms and lists the effects of a ControlSource property setting on different controls.
Creating Drag-and-Drop Controls
Describes the two types of drag-and-drop functionality that can be included in your Visual FoxPro application, OLE drag-and-drop and control drag-and-drop.
Making Controls Easier to Use
Offers instructions on how to use access keys, tab order, ToolTip text, and selective disabling to create a more design that is easier to use.

Related Sections

Creating the Interface
Using Visual FoxPro forms, classes, controls, menus, and toolbars, you can build interfaces that help users gain access to the full potential of your programs.
Creating Forms
Your application must have forms to make it possible for users to view and enter data. However, you can customize standard forms visually and programmatically to create a specialized environment for your users.
Working with Forms
After creating your form, you can run, hide, or alter it in different ways.
Designing Menus and Toolbars
A good menu system tells your users a lot about the design and structure of your application. Planning menus and toolbars carefully can improve the usability of your application and provide immediate access to common tasks.


Control Selection for Particular Tasks

Visual FoxPro controls are flexible and versatile. Though there are multiple controls you could use to accomplish any particular task, you need to have a consistent approach to the controls you use so that users can tell what to expect when they see the interface you provide. For example, a label has a Click event in the same way that a command button does, but users familiar with graphical interfaces expect to click on command buttons to perform actions.

Most of the functionality you will want to build into your forms will fall under one of the following categories:

  • Providing users with a set of predetermined choices
  • Accepting user input that cannot be predetermined
  • Accepting user input in a given range
  • Allowing users to perform specific actions
  • Performing specific actions at given intervals
  • Displaying information

Providing a Set of Predetermined Choices

One of the most straightforward ways to ensure the validity of the data in a database is to give users a predetermined set of options. By controlling user choices, you can make sure that no invalid data is stored in the database. The following controls make it possible for you to provide users with a set of predetermined choices:

  • Option button groups
  • List boxes and drop-down lists
  • Check boxes

Option button groups are containers that contain option buttons. Typically, option buttons make it possible for users to specify one of a number of operational options in a dialog box rather than data entry.

See Also

Controls and Data Concepts | Setting the Number of Option Buttons in an Option Button Group | Using Controls | Controls and Objects | Setting Option Button Properties


Controls for Displaying Lists

List boxes and drop-down list boxes (combo box controls with the Style property set to 2 - Dropdown List) provide a user with scrollable lists that contain a number of options or pieces of information. In a list box, multiple items can be visible at all times. In a drop-down list box, only one item is visible, but a user can click the down button to display a scrolling list of all the items in the drop-down list box.

Run Solution.app in the Visual FoxPro ...\Samples\Solution directory to see several examples that demonstrate using list boxes and drop-down list boxes, including the following:

  • Add pictures to a list.
  • Multiselect items in a list.
  • Fill a list with values from different sources.
  • Display multiple columns in a list.
  • Sort list items.
  • Move items between lists.
    Tip If you have room on the form and if you want to emphasize the choices a user has, use a list. To conserve space and emphasize the currently selected item, use a drop-down list box.

Common List Properties and Methods

The following list box properties are commonly set at design time.

Property | Description
ColumnCount | The number of columns in the list box.
ControlSource | Where the value that a user chooses from the list is stored.
MoverBars | Whether mover bars are displayed to the left of list items so that a user can easily rearrange the order of items in the list.
Multiselect | Whether the user can select more than one item in the list at a time.
RowSource | Where the values displayed in the list come from.
RowSourceType | Whether the RowSource is a value, a table, a SQL statement, a query, an array, a list of files, or a list of fields.
Note The Value property of a list can be numeric or character. The default is numeric. Set the Value property to an empty string if the RowSource is a character value and if you want the Value property to reflect the character string of the selected item in the list. You can press the SPACEBAR and then the BACKSPACE key to enter an empty string for a property in the Properties window.

The following list box methods are commonly used.

Method | Description
AddItem | Adds an item to a list with a RowSourceType of 0.
RemoveItem | Removes an item from a list with a RowSourceType of 0.
Requery | Updates the list if the values in the RowSource have changed.

Filling a List Box or a Combo Box

You can fill a list box with items from a variety of sources by setting the RowSourceType and RowSource properties.

See Also

Storing User Choices to a Table Using Option Buttons | Choosing the Type of Data for a List or Combo Box | Creating Multicolumn List Boxes | Using Controls | Controls and Objects


Choosing the Type of Data for a List or Combo Box

The RowSourceType property determines what kind of source populates the list box or combo box — for example, an array or a table. When you have set the RowSourceType, specify the source of the list items by setting the RowSource property.

RowSourceType | Source of the List Items
0 | None. Programmatically add items to the list.
1 | Value
2 | Alias
3 | SQL Statement
4 | Query (.qpr)
5 | Array
6 | Fields
7 | Files
8 | Structure
9 | Popup. Included for backward compatibility.

The following sections describe the various RowSourceType settings.

None If you set the RowSourceType property to 0, the default, the list is not populated automatically. You can add items to the list by using the AddItem method:

frmForm1.lstMyList.RowSourceType = 0
frmForm1.lstMyList.AddItem("First Item")
frmForm1.lstMyList.AddItem("Second Item")
frmForm1.lstMyList.AddItem("Third Item")

The RemoveItem method makes it possible for you to remove items from the list. For example, the following line of code removes "Second Item" from the list:

frmForm1.lstMyList.RemoveItem(2)

Value If you set the RowSourceType property to 1, you can specify multiple values in the RowSource property to be displayed in the list. If you set the RowSource property through the Properties window, include a comma-delimited list of items. If you set the RowSource programmatically, include the comma-delimited list in quotation marks:

Form1.lstMyList.RowSourceType = 1
Form1.lstMyList.RowSource = "one,two,three,four"

Alias If you set the RowSourceType property to 2, you can include values from one or more fields in an open table.

If the ColumnCount property is 0 or 1, the list displays values in the first field of the table. If you set the ColumnCount property to 3, the list displays values in the first three fields of the table. To display fields in a different order than they are stored in the table, set the RowSourceType property to 3 - SQL Statement or 6 - Fields.

Note If the RowSourceType is 2 - Alias or 6 - Fields, when a user chooses a new value in the list, the table record pointer moves to the record with the value of that item.

SQL Statement If you set the RowSourceType property to 3 - SQL Statement, include a SELECT - SQL statement in the RowSource property. For example, the following statement selects all fields and all records from the Customer table into a cursor:

SELECT * FROM Customer INTO CURSOR mylist

If you set the RowSource programmatically, remember to enclose the SELECT statement in quotation marks.

Note By default, Visual FoxPro SELECT statements without INTO clauses immediately display the resulting cursor in a Browse window. Because you rarely want this behavior in a RowSource SQL statement, include an INTO CURSOR clause in your SELECT statement.

Query If you set the RowSourceType property to 4, you can populate your list box with the results of a query you designed in the Query Designer. When RowSourceType is set to 4, set RowSource to the .qpr file. For example, the following line of code sets the RowSource property of a list to a query.

THISFORM.List1.RowSource = "region.qpr"

If you do not specify a file extension, Visual FoxPro assumes an extension of .qpr.

Array If you set the RowSourceType property to 5, the list is populated with the items in an array. You can create an array property of the form or form set for the RowSource or use an array created elsewhere in your application.

For information about creating array properties, see Creating Forms.

Tip The RowSource setting of a list is evaluated by Visual FoxPro as needed in your application, not just in the method in which you set the RowSource. You need to keep this scope in mind. If you create a local array in a method, that array will be scoped to the method and will not be available in all cases when Visual FoxPro needs to evaluate the property setting. If you set the RowSource of a list to an array property of the form or form set, you need to reference the property relative to the list, not relative to the method in which you set the property. For example, if you have a form array property named arrayprop, the following lines of code in the Init of the form produce different results:
THIS.lst1.RowSource = "THIS.arrayprop"   && Error
THIS.lst1.RowSource = "THISFORM.arrayprop" && No error.

To populate a list with the elements in a multi-dimensional array

  1. Set the RowSourceType property to 5.
  2. Set the RowSource property to the multi-dimensional array.
  3. Set the ColumnCount property to the number of columns to display.
  4. Set the ColumnWidths property to the desired widths for each column.
  5. To make the List or Combo box display the entire array contents, call its Requery() method. Add code, such as the following, in the Init() of the ListBox or ComboBox:
    This.Requery()

Fields If you set the RowSourceType property to 6, you can specify a field or comma-delimited list of fields to populate the list, such as:

contact,company,location

You can include the following types of information in the RowSource property of a list with a RowSourceType of 6 - Fields:

  • field
  • alias.field
  • alias.field, field, field, ...

If you want to have fields from multiple tables in the list, set the RowSourceType property to 3 - SQL Statement.

Unlike a RowSourceType of 2 - Alias, a RowSourceType of 6 - Fields makes it possible for you to display fields independent of their actual positions in the table.

Files If you set the RowSourceType property to 7, the list is populated with files in the current directory. Additionally, options in the list make it possible for you to choose a different drive and directory for file names to be displayed in the list.

Set RowSource to the skeleton of the type of files you want to be displayed in the list. For example, to display Visual FoxPro tables in the list, set the RowSource property to *.dbf.

Structure If you set the RowSourceType property to 8, the list is populated with the fields in the table that you specify when you set the RowSource property. This RowSourceType setting is useful if you want to present the user with a list of fields to search for values in or a list of fields to order a table by.

Popup If you set the RowSourceType property to 9, you can fill the list from a previously defined popup. This option is included for backward compatibility.

See Also

Application of List Boxes and Drop-Down List Boxes | Creating Multicolumn List Boxes | Using Controls | Controls and Objects | RowSourceType | RowSource


Creating Multicolumn List Boxes

Although the default number of columns in a list box is one, a list box in Visual FoxPro can contain as many columns as you want. A multicolumn list box differs from a grid in that you select a row at a time in a multicolumn list box while you can select individual cells in a grid, and data in the list cannot be directly edited.

To display multiple columns in a list box

  1. Set the ColumnCount property to the number of desired columns.
  2. Set the ColumnWidths property. For example, if there are three columns in the list box, the following command would set the column widths to 10, 15, and 30, respectively:
    THISFORM.listbox.ColumnWidths = "10, 15, 30"
  3. Set the RowSourceType property to 6 - Fields.
  4. Set the RowSource property to the fields to be displayed in the columns.
    Note For the columns to align correctly, you need to either set the ColumnWidths property or change the FontName property to a monospaced font. The FirstElement property of ListBoxes and ComboBoxes is not effective in multi-column lists.

When the RowSourceType of the list is set to 0 - None, you can use the AddListItem method to add items to a multicolumn list box. For example, the following code adds text to specific columns in a list box:

THISFORM.lst1.ColumnCount = 3
THISFORM.lst1.Columnwidths = "100,100,100"
THISFORM.lst1.AddListItem("row1 col1", 1,1)
THISFORM.lst1.AddListItem("row1 col2", 1,2)
THISFORM.lst1.AddListItem("row1 col3", 1,3)
THISFORM.lst1.AddListItem("row2 col2", 2,2)

See Also

Choosing the Type of Data for a List or Combo Box | Allowing Users to Select Multiple Items in a List Box | Using Controls | Allowing Users to Add Items to a List Box | Controls and Objects


Allowing Users to Select Multiple Items in a List Box

The default behavior of a list allows one item at a time to be selected. You can, however, make it possible for a user to select multiple items in a list.

To allow multiple selected items in a list

  • Set the MultiSelect property of the list to true (.T.).

To process the selected items — to copy them to an array or incorporate them elsewhere in your application — loop through the list items and process those for which the Selected property is true (.T.). The following code could be included in the InteractiveChange event of a list box to display the selected items in a combo box, cboSelected, and the number of selected items in a text box, txtNoSelected:

nNumberSelected = 0  && a variable to track the number
THISFORM.cboSelected.Clear && clear the combo box
FOR nCnt = 1 TO THIS.ListCount
   IF THIS.Selected(nCnt)
      nNumberSelected = nNumberSelected + 1
      THISFORM.cboSelected.Additem (THIS.List(nCnt))
   ENDIF
ENDFOR
THISFORM.txtNoSelected.Value = nNumberSelected

See Also

Creating Multicolumn List Boxes | Allowing Users to Add Items to a List Box | Using Controls | Refreshing a One-to-Many Display Based on a List Value | Controls and Objects


Allowing Users to Add Items to a List Box

In addition to allowing users to select items from a list box, you can make it possible for users to interactively add items to a list.

To add items to a list interactively

  • Use the AddItem method.

In the following example, when the user presses ENTER, the code in the KeyPress event of a text box adds the text in the text box to the list box and clears the text in the text box:

LPARAMETERS nKeyCode, nShiftAltCtrl
IF nKeyCode = 13   && Enter Key
   THISFORM.lstAdd.AddItem(This.Value)
   THIS.Value = ""
ENDIF

Allowing Users to Enter Data into a Table from a List

If the ControlSource property is set to a field, whatever the user selects in the list is written to the table. This is an easy way to help ensure the integrity of the data in your table. While the user can still enter the wrong data, an illegal value cannot be entered.

For example, if you have a list of states or counties for a user to choose from, the user cannot enter an invalid state or county abbreviation.

Allowing Users to Go to a Record by Picking a Value in a List

Often, you want to let users select the record they want to view or edit. For example, you could provide users with a list of customer names. When the user selects a customer from the list, you select that customer's record in the table and display customer information in text boxes on the form. You can do this several ways, depending on the source of data in your form.

RowSourceType Selecting the appropriate record
2 - Alias
6 - Fields 		When the user chooses a value in the list, the record pointer is set automatically to the desired record. Issue THISFORM.Refresh in the InteractiveChange event of the list to show the new values in other controls on the form.
0 - None
1 - Value
3 - SQL Statement
4 - QPR
5 - Array 		In the InteractiveChange event, select the table that has the record with the desired values, and then search for the desired value. For example, if the RowSource holds customer identification numbers from the customer table, use this code:
SELECT customer
LOCATE FOR THIS.Value = cust_id
THISFORM.Refresh

See Also

Allowing Users to Select Multiple Items in a List Box | Refreshing a One-to-Many Display Based on a List Value | Using Controls | Displaying Child Records in a List | Controls and Objects


Refreshing a One-to-Many Display Based on a List Value

When the user chooses to go to a record by picking a value in a list, you might have a one-to-many relationship that needs to reflect the changed record pointer in the parent table. You can implement this functionality with both local tables and local or remote views.

Local Tables

If the RowSourceType of the list is 2 - Alias or 6 - Fields and the RowSource is a local table with a relationship set in the form's data environment, issue THISFORM.Refresh in the InteractiveChange event when the user chooses a new value. The many sides of the one-to-many relationship automatically displays only the records that match the expression of the parent table involved in the relation.

Views

Refreshing a one-to-many display is a little different if the RowSource of the list box is a local or remote view. The following example describes creating a form with a list box and a grid. The list box displays the values from the cust_id field in the TESTDATA!Customer table. The grid displays the orders associated with the cust_id field selected in the list box.

First, in the View Designer create a parameterized view for the orders. When you create the view in the View Designer, set the selection criterion for the foreign key to a variable. In the following example, the variable is called m.cCust_id.

Parameterized view using a variable

Then, when you design the form, follow the steps in the following procedure. Note that the view requires a value for the parameter that is not available when the form is loaded. By setting the NoDataOnLoad property of the view cursor object to true (.T.), you prevent the view from being run until the REQUERY( ) function is called, at which time the user would have selected a value for the variable used in the parameterized view.

To design a one-to-many list based on local or remote views

  1. Add the table and the parameterized view to the data environment.
  2. In the Properties window for the view cursor object in the Data Environment, set the NoDataOnLoad property to true (.T.).
  3. Set the RowSourceType property of the list box to 6 — Fields, and set its RowSource property to the field referenced as the foreign key in the view's parameter.

    In the example, you would set the RowSource property to customer.cust_id.

  4. Set the RecordSource property of the grid to the name of the view you created earlier.
  5. In the InteractiveChange event code of the list box, store the value of the list box to the variable, and then requery the view, as in this example:
       m.cCust_id = THIS.Value
   *assuming the name of the view is orders_view
   =REQUERY("orders_view")

For more information about local and remote views, see Creating Views.

See Also

Allowing Users to Add Items to a List Box | Displaying Child Records in a List | Adding Pictures to Items in a List | Using Controls | Controls and Objects


Displaying Child Records in a List

You can display records from a one-to-many relationship in a list so that the list displays the child records in the relationship as the record pointer moves through the parent table.

To display child records in a list

  1. Add a list to the form.
  2. Set the ColumnCount property of the list to the number of columns you want to display.

    For example, if you want to display the Order_id, Order_net, and Shipped_on fields in the list, set the ColumnCount property to 3.

  3. Set the ColumnWidths property to the appropriate widths for displaying your selected fields.
  4. Set the RowSourceType of the list to 3 — SQL Statement.
  5. Set the RowSource to the SELECT statement. For example, the following statement selects three fields from the orders table for the current record in the customer table:
    SELECT order_id, order_net, shipped_on from orders ;
   WHERE order.cust_id = customer.cust_id ;
   INTO CURSOR temp
  6. In the Init event of the form and in the code that moves the record pointer through the table, requery the list:
    THISFORM.lstChild.Requery

See Also

Refreshing a One-to-Many Display Based on a List Value | Adding Pictures to Items in a List | Using Check Boxes | Using Controls | Controls and Objects


Adding Pictures to Items in a List

You can set the Picture property of the list to the graphic file you want displayed next to the items in the list. For details on valid file types, see Graphic Support in Visual FoxPro

For example, you could have a list box populated with files. You might want to have a different bitmap next to the file if it is a table, a program, or some other file type.

List box with pictures

The following code is associated with the Click event of the list box:

FOR iItem = 5 TO THIS.ListCount      && files start at the 5th item
   cExtension = UPPER(RIGHT(THIS.List(iItem),3))
   DO CASE
      CASE cExtension = "DBF"
         THIS.Picture(iItem) = "tables.bmp"
      CASE cExtension = "BMP"
         THIS.Picture(iItem) = "other.bmp"
      CASE cExtension = "PRG"
         THIS.Picture(iItem) = "programs.bmp"
      CASE cExtension = "SCX"
         THIS.Picture(iItem) = "form.bmp"
      OTHERWISE
         THIS.Picture(iItem) = IIF("]" $ cExtension, ;
            "", "textfile.bmp")
   ENDCASE
ENDFOR

See Also

Displaying Child Records in a List | Using Check Boxes | Accepting Input That Cannot Be Predetermined | Using Controls | Controls and Objects


Controls for Accepting Input

It is not always possible to anticipate all the possible values that a user might need to enter into a control. The following controls make it possible for you to accept user input that cannot be predetermined:

  • Text boxes
  • Edit boxes
  • Combo boxes

The text box is the basic control that makes it possible for users to add or edit data stored in a non-memo field in a table.

To see examples of using text boxes

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Text boxes.

To programmatically reference or change the text displayed in the text box

  • Set or reference the Value property.

If you set a ControlSource for the text box, the value displayed in the text box is stored in the Value property of the text box and in the variable or field specified in the ControlSource property.

Validating the Data in a Text Box

To check or verify the value in the text box, include code in the method associated with the Valid event. If the value is invalid, return False (.F.) or 0. If the Valid returns False (.F.), an "Invalid input" message is displayed. If you want to display your own message, include the WAIT WINDOW command or the MESSAGEBOX( ) function in the Valid code and return 0.

If the Valid event returns False (.F.) or 0, the control does not lose focus.

For example, if you have a text box that makes it possible for a user to type an appointment date, you could check to make sure that the date is not already past by including the following code in the Valid event of the text box:

IF CTOD(THIS.Value) < DATE( )
   = MESSAGEBOX("You need to enter a future date",1)
   RETURN 0
ENDIF

Selecting Text When the Text Box Gets the Focus

To select all text when the user enters the text box with the keyboard, set the SelectOnEntry property to True (.T.).

Formatting the Text in a Text Box

You can use the InputMask property to determine the values that can be typed in the text box and the Format property to determine the way values are displayed in the text box.

See Also

Using Check Boxes | Using the InputMask Property | Using Controls | Value | Accepting Numeric Input in a Given Range | Controls and Objects


Accepting Input with a Combo Box Control

The combo box control has the functionality of a list box and a text box. There are two styles for a combo box: Drop-down combo and Drop-down list. Specify which one you want by changing the Style property of the control. Drop-down lists are discussed in Controls for Displaying Lists.

Drop-Down Combo Box

A user can click the button on a drop-down combo box to see a list of choices or enter a new item directly in the box beside the button. The default Style property of a combo box is 0 — Dropdown Combo.

Adding User Items to Drop-Down Combo Box Lists

To add the new user value to the drop-down combo box, you can use the following line of code in the method associated with the Valid event of the combo box:

THIS.AddItem(THIS.Text)

Before adding an item, however, it would be a good idea to check to make sure that the value is not already in the combo box drop-down:

lItemExists = .F. && assume the value isn't in the list.
FOR i = 1 to THIS.ListCount
   IF THIS.List(i) = THIS.Text
      lItemExists = .T.
      EXIT
   ENDIF
ENDFOR

IF !lItemExists
   THIS.AddItem(THIS.Text)
ENDIF

Common Combo Box Properties

The following combo box properties are commonly set at design time.

Property | Description
ControlSource | Specifies the table field where the value that the user chooses or enters is stored.
DisplayCount | Specifies the maximum number of items displayed in the list.
InputMask | For drop-down combo boxes, specifies the type of values that can be typed in.
IncrementalSearch | Specifies whether the control tries to match an item in the list as the user types each letter.
RowSource | Specifies the source of the items in the combo box.
RowSourceType | Specifies the type of the source for the combo box. The RowSourceType values for a combo box are the same as for a List.
Style | Specifies whether the combo box is a drop-down combo or a drop-down list.

See Also

Controls for Accepting Input | ComboBox Control | Using Controls


Editing Text Using an Edit Box

You can make it possible for users to edit text from long character fields or memo fields in edit boxes. Edit boxes allow automatic wordwrapping and the ability to move through the text using the arrow keys, page up and page down keys, and scrollbars.

To see examples of using edit boxes

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Edit boxes.

Allowing Users to Edit a Memo Field in an Edit Box

All you have to do to make it possible for a user to edit a memo field in an edit box is set the ControlSource property of the edit box to the memo field. For example, if you have a memo field named comments in a table named log, you can set the ControlSource property of an edit box to log.comments to make it possible for a user to edit the memo field in the edit box.

Allowing Users to Edit a Text File in an Edit Box

You also can make it possible for a user to edit a text file in an edit box. The following form demonstrates this.

Example form for editing a text file in an edit box

An OK button on the form closes the form with the following command in the Click event code:

RELEASE THISFORM

The other two buttons in this example, cmdOpenFile and cmdSave, make it possible for a user to open a text file and save the file after edits.

Code Associated with the Click Event of cmdOpenFile

Code Comments
CREATE CURSOR textfile ;
  (filename c(35), mem m)

APPEND BLANK
Create a cursor with a character field to hold the name of the text file and a memo field to hold the contents of the text file.

Add a blank record to the cursor.
REPLACE textfile.FileName WITH ;
  GETFILE("TXT")
 Use the GETFILE( ) function to return the name of the file to open. Store the name in the FileName field of the cursor.
IF EMPTY(textfile.FileName)

   RETURN
ENDIF
If the user chooses Cancel in the Get File dialog box, the FileName field will be empty and there will be no file to open.
APPEND MEMO mem FROM ;

  (textfile.FileName) OVERWRITE
Fill the memo field with the text in the file.
THISFORM.edtText.ControlSource = ;

  "textfile.mem"
THISFORM.Refresh
Set the ControlSource of the edit box on the form.
THISFORM.cmdSave.Enabled = .T.
 Enable the Save button.

When the file has been opened and edited, the Save button makes it possible for a user to write changes back out to the file.

Code Associated with the Click Event of cmdSave

Code Comments
COPY MEMO textfile.mem TO ;

  (textfile.filename)
Overwrites the old value in the file with the text in the memo field.

Manipulating Selected Text in an Edit Box

Edit boxes and text boxes have three properties that make it possible for you to work with selected text: SelLength, SelStart, and SelText.

You can select text programmatically using the SelStart and SelLength properties. For example, the following lines of code select the first word in an edit box.

Form1.edtText.SelStart = 0
Form1.edtText.SelLength = AT(" ", Form1.edtText.Text) - 1
Tip When you change the SelStart property, the edit box scrolls to display the new SelStart. If you change the SelStart in a loop, for example when searching for text, your code will execute faster if you include THISFORM.LockScreen = .T. before processing and THISFORM.LockScreen = .F. after processing.

You can access selected text in an edit box or text box with the SelText property. For example, the following line of code makes the selected text all uppercase:

Form1.edtText.SelText = UPPER(Form1.edtText.SelText)

Common Edit Box Properties

The following edit box properties are commonly set at design time.

Property | Description
AllowTabs | Whether the user can insert tabs in the edit box instead of moving to the next control. If you allow tabs, be sure to indicate that users can move to the next control by pressing CTRL+TAB.
HideSelection | Whether selected text in the edit box is visibly selected when the edit box does not have the focus.
ReadOnly | Whether the user can change the text in the edit box.
ScrollBars | Whether there are vertical scrollbars.

See Also

Using Controls | EditBox Control | Controls for Accepting Input


Using the InputMask Property to Control User Input

The InputMask property determines the characteristics of each character typed into the text box. For example, you could set the InputMask property to 999,999.99 to limit user input to numeric values less than 1,000,000 with two decimal places. The comma and the period would be displayed in the text box before the user entered any values. If the user pressed a character key, the character would not be displayed in the text box.

If you have a logical field and want a user to be able to type "Y" or "N" but not "T" or "F", set the InputMask property to "Y".

Accepting User Passwords in a Text Box

Often in an application, you want to obtain secure information from a user, such as a password. You can use a text box to get this information without making the information visible on the screen.

To accept user input without displaying the actual value

  • Set the PasswordChar property of the text box to * or some other generic character.

If you set the PasswordChar property to anything other than an empty string, the Value and Text properties of the text box contain the actual value that the user typed in the text box, but the text box displays a generic character for every key the user pressed.

Entering Dates in a Text Box

Text boxes have several properties that you can set to make it easy for your users to enter date values.

Property | Description
Century | Sets whether the first two digits of the year are displayed or not.
DateFormat | Formats the date in the text box to one of fifteen predetermined formats, such as German or Japanese.
StrictDateEntry | Sets StrictDateEntry to 0 - Loose. This makes it possible for a user to enter dates in more flexible formats than the default 99/99/99.

Common Text Box Properties

The following text box properties are commonly set at design time.

Property | Description
Alignment | Sets whether the contents of the text box are left justified, right justified, centered, or automatic. Automatic alignment depends on the data type. Numbers, for example, are right justified and characters are left justified.
ControlSource | Specifies the table field or variable whose value is displayed in the text box.
InputMask | Specifies the data entry rule each character entered must follow. For specific information about InputMask, see Help.
SelectOnEntry | Sets whether the contents of the text box are selected automatically when the text box receives the focus.
TabStop | Specifies whether the user can tab to the control. If TabStop is set to .F., a user can still select the text box by clicking it.

See Also

Accepting Input That Cannot Be Predetermined | Accepting Numeric Input in a Given Range | Using Controls | Allowing Specific Actions | Controls and Objects | Click Event


Accepting Numeric Input in a Given Range

Although you can set the InputMask property and include code in the Valid event to make sure that numeric values entered into text boxes fall within a given range, the easiest way to check the range of values is to use a spinner.

Using Spinners

You can use spinners to make it possible for users to make choices by "spinning" through values or directly typing the values in the spinner box.

Setting the Range of Values that Users Can Choose

Set the KeyboardHighValue and the SpinnerHighValue properties to the highest number you want users to be able to enter in the spinner.

Set the KeyboardLowValue and the SpinnerLowValue properties to the lowest number you want users to be able to enter in the spinner.

Decrementing a Spinner When the User Clicks the Up Button

Sometimes, if your spinner reflects a value like "priority," you want the user to be able to increase the priority from 2 to 1 by clicking the Up button. To cause the spinner number to decrement when the user clicks the Up button, set the Increment property to -1.

Spinning Through Non-Numeric Values

While the value of a spinner is numeric, you can use the Spinner control and a text box to make it possible for users to spin through multiple types of data. For instance, if you want a user to be able to spin through a range of dates, you could size the spinner so that only the buttons are visible and position a text box beside the spinner buttons. Set the Value property of the text box to a date and in the UpClick and DownClick events of the spinner, increment or decrement the date.

Tip You can use the Windows API function GetSystemMetrics to set the width of your spinner so that only the buttons are visible and the buttons are the best width for the up and down arrow bitmap display.
  • Set the spinner's BorderStyle property to 0.
  • Include the following code in the Init of the spinner:
    DECLARE INTEGER GetSystemMetrics IN Win32api INTEGER
THIS.Width = GetSystemMetrics(2) && SM_CXVSCROLL

Common Spinner Properties

The following spinner properties are commonly set at design time.

Property | Description
Increment | How much to increment or decrement the value each time the user clicks the Up or Down buttons.
KeyboardHighValue | The highest value that can be entered into the spinner text box.
KeyboardLowValue | The lowest value that can be entered into the spinner text box.
SpinnerHighValue | The highest value that the spinner will display when the user clicks the Up button.
SpinnerLowValue | The lowest value that the spinner will display when the user clicks the Down button.

See Also

Using the InputMask Property | Allowing Specific Actions | Using Controls | Performing Specific Actions at Given Intervals | Controls and Objects


Setting the Number of Option Buttons in an Option Button Group

When you create an option button group on a form, two option buttons are included by default. You can determine how many option buttons are in a group by changing the ButtonCount property.

To set the number of option buttons in a group

  • Set the ButtonCount property to the desired number of option buttons.

    For example, to have a group of six option buttons, set the ButtonCount property of the option button group to 6.

The Value property of the group indicates which of the buttons has been chosen. For example, if you chooses the fourth option button in a group of six option buttons, the value of the option button group is 4.

If the group's ControlSource property is a character field, or if the Value property is set to a character value before the form is run, the group's Value property is the caption of the selected option button.

See Also

Control Selection for Particular Tasks | Setting Option Button Properties | Using Controls | Controls and Objects | Controls and Data Concepts | Storing User Choices to a Table Using Option Buttons


Setting Option Button Properties

To manually adjust individual elements of an option button or command button group in the Form Designer, choose Edit from the group's shortcut menu.

You can set properties on individual buttons in the Properties window. You also can set these properties at run time by specifying the name of the option button and the desired property setting. For example, the following line of code, included in the method or event code of some object on the same form as the option button group, sets the caption of optCust in the option button group opgChoices:

THISFORM.opgChoices.optCust.Caption = "Sort by Customer"

You also can set these properties at run time by using the Buttons property and specifying the index number of the option button in the group. For example, if optCust is the third button in the group, the following line of code also sets the caption of optCust:

THISFORM.opgChoices.Buttons(3).Caption = "Sort by Customer"

To set properties on all buttons in a group

  • Use the SetAll method of the group.

    For example, the following line of code disables all the buttons in an option button group named opgMyGroup on a form:

    THISFORM.opgMyGroup.SetAll("Enabled",.F., "OptionButton")

Enabling and Disabling Buttons in a Group

The previous example shows how to programmatically disable all option buttons in a group. When the buttons are disabled, they are displayed in the colors specified in the DisabledForeColor and DisabledBackColor properties of the option buttons. You could also set the Enabled property of the option button group to false (.F.) to disable the group; however, there would be no visual clue for the user.

Determining Which Option Button Is Currently Selected

You can use the Value property of the option button group to determine which option button in the group is selected. If the control source for the button is numeric, you have five option buttons in a group. If the third button is selected, the Value property of the option button group is 3; if no option buttons are selected, the Value property of the option button group is 0.

You also can determine the caption of the selected option button by using the Value and Buttons properties of the group. For example, the following line of code stores the Caption property of the selected option button to a variable cSelected.

oGroup = THISFORM.opg1
cSelected = oGroup.Buttons(oGroup.Value).Caption

Filtering Lists with Option Buttons

If you have a small set of predetermined table filters, you could use option buttons to make it possible for users to switch between the filters.

The following example assumes a form with a list box (lstCustomers) and an option button group that contains three option buttons.

Property Settings for the List Box

Object | Property | Setting
lstCustomers | RowSourceType | 2 - Alias
lstCustomers | RowSource | Customer

The filters are set in the Click event code of the option buttons.

Event Code for Filtering a List when Users Choose an Option Button

Object Event Code
optAll Click
SET FILTER TO
GO TOP
THISFORM.lstCustomers.Requery
optCanada Click
SET FILTER TO customer.country = "Canada"
GO TOP
THISFORM.lstCustomers.Requery
optUK Click
SET FILTER TO customer.country = "UK"
GO TOP
THISFORM.lstCustomers.Requery

When the user closes the form, do not forget to reset the filter by including SET FILTER TO in the Click event of the closing button or in the Destroy event.

Tip To refresh a list when the list source might have changed, use the Requery method.

See Also

Setting the Number of Option Buttons in an Option Button Group | Storing User Choices to a Table Using Option Buttons | Using Controls | Controls and Objects | Form Designer


Storing User Choices to a Table Using Option Buttons

While it is not as common, you can use option buttons to get information from a user to be stored in a table by saving the Caption property. If you have a standardized testing application, for example, you could use option buttons to make it possible for a user to choose among multiple choice options A, B, C, or D. You could also use option buttons to indicate gender in an employee table.

To store the Caption property of an option button to a table

  1. Set the Value property of the option button group to an empty string.
  2. Set the Control property of the option button group to a character field in a table.

For example, if the captions of the option buttons in a group are "A", "B", "C", and "D", and the ControlSource of the option button group is a character field, when a user chooses the button with the caption "B", "B" is stored in the field.

To see an example of a multiple-choice test using option buttons

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Options buttons.
  3. Click Present a user with multiple choices.

See Also

Setting Option Button Properties | Application of List Boxes and Drop-Down List Boxes | Using Controls | Controls and Objects | Choosing the Type of Data for a List or Combo Box


Controls for Displaying Information

One of the principles of good design is to make relevant information visible. You can use the following controls to display information to your users:

  • Images
  • Labels
  • Text Boxes
  • Edit Boxes
  • Shapes

Using Images

The Image control makes it possible for you to add pictures (.bmp and other graphics files) to your form. An Image control has the full range of properties, events, and methods that other controls have, so an Image control can be changed dynamically at run time, Users can interact with images by clicking, double-clicking, and so on. For details on valid graphic file types, see Graphics Support in Visual FoxPro.

The following table lists some of the key properties of an Image control.

Property | Description
Picture | The picture (.bmp file) to display.
BorderStyle | Whether there is a visible border for the image.
Stretch | If Stretch is set to 0 – Clip, portions of the picture that extend beyond the dimensions of the Image control are not displayed. If Stretch is set to 1 - Isometric, the Image control preserves the original dimensions of the picture and displays as much of the picture as the dimensions of the Image control will allow. If Stretch is set to 2 - Stretch, the picture is adjusted to exactly match the height and width of the Image control.

Using Labels

Labels differ from text boxes in that they:

  • Cannot have a data source.
  • Cannot be directly edited.
  • Cannot be tabbed to.

You can programmatically change the Caption and Visible properties of labels to tailor the label display to the situation at hand.

Common Label Properties

The following label properties are commonly set at design time.

Property | Description
Caption | The text displayed by the label.
AutoSize | Whether the size of the label is adjusted to the length of the Caption.
BackStyle | Whether the label is Opaque or Transparent.
WordWrap | Whether the text displayed on the label can wrap to additional lines.

Using Text and Edit Boxes to Display Information

Set the ReadOnly property of text and edit boxes to display information that the user can view but not edit. If you only disable an edit box, the user will not be able to scroll through the text.

Using Shapes and Lines

Shapes and lines help you visually group elements of your form together. Research has shown that associating related items helps users to learn and understand an interface, which makes it easier for them to use your application.

The following Shape properties are commonly set at design time.

Property | Description
Curvature | A value between 0 (90 degree angles) and 99 (circle or oval).
FillStyle | Whether the shape is transparent or has a specified background fill pattern.
SpecialEffect | Whether the shape is plain or 3D. This only has an effect when the Curvature property is set to 0.

The following Line properties are commonly set at design time.

Property | Description
BorderWidth | How many pixels wide the line is.
LineSlant | When the line is not horizontal or vertical, the direction of the slant. Valid values for this property are a slash ( / ) and a backslash ( \ ).

Using Form Graphics to Display Information

You can graphically display information on a form by using the following form methods.

Method | Description
Circle | Draws a circular figure or arc on a form.
Cls | Clears graphics and text from a form.
Line | Draws a line on a form.
Pset | Sets a point on a form to a specific color.
Print | Prints a character string on a form.

To see examples that demonstrate form graphics

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Forms, and then click Form graphics.

See Also

Performing Specific Actions at Given Intervals | Enhancing Control Display | Using Controls | Caption | Controls and Objects


Enhancing Control Display

Command buttons, check boxes, and option buttons can display pictures in addition to captions. These controls all have properties that make it possible for you to specify pictures to be displayed on the controls.

Property | Description
DisabledPicture | Display picture on button when button is disabled. If you do not specify a value, Visual FoxPro displays a dimmed picture when the control is disabled.
DownPicture | Display picture on button when button is pressed. If you do not specify value, Visual FoxPro displays the picture with the background colors changed so that the button appears pressed when the button is pressed.
Picture | Display picture displayed on button when button is enabled and not pressed.
PicturePosition | Display picture relative to its caption.
PictureSelectionDisplay | Display picture in the text box of a combo box.

If you do not want a caption displayed with the picture, set the Caption property to an empty string by deleting the default caption in the property settings box of the Properties Window.

Using Picture Masks

Often, a .bmp picture contains white space you do not want to appear on your controls. A white border around an irregularly shaped image could make your control look bad. To avoid this problem, Visual FoxPro creates a temporary default mask for your picture. White areas are given a transparent attribute so that the underlying color of the button or background shows through. To keep certain white areas of your .bmp white, create a mask for it that will override the default.

To create a mask for a .bmp

  1. Open the .bmp file in Paint or another bitmap utility.
  2. Blacken all areas of the picture that you want to be displayed exactly as they are in the .bmp file. Leave the areas you want to be transparent as white.
  3. Save the file in the same directory and with the same name as the .bmp file but with an .msk extension.

When Visual FoxPro loads a .bmp file specified by the Picture property for a command button, option button, or check box, it looks in the same directory for a matching .msk file. If an .msk file with the same name as the .bmp is in the directory, Visual FoxPro uses it as a mask for the picture. All white areas in the .msk picture are made transparent in the .bmp. All black areas in the .msk picture are displayed exactly as they are in the .bmp.

Note The .bmp picture and the .msk picture must have the same dimensions for the mask to be able to represent the area of the .bmp.

See Also

Displaying Information | Manipulating Multiple Rows of Data | Using Controls | Manually Adjusting Grid Display at Design Time | Controls and Objects


Controls for Manipulating Rows of Data

Visual FoxPro provides a very powerful tool — the grid object — for displaying and manipulating multiple rows of data.

Using Grids

The grid is a container object. Just as a form set can contain forms, a grid can contain columns. In addition, the columns contain headers and controls, each with their own sets of properties, events, and methods, giving you a great deal of control over the elements of the grid.

Container | Can contain
Grid | Columns
Column | Headers, controls

The Grid object makes it possible for you to present and manipulate rows and columns of data in a form or page. A particularly useful application of the Grid control is creating one-to-many forms, such as an invoice form.

To see examples of using grids

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Grid.

To add a Grid control to a form

  • In the Form Controls toolbar, choose the Grid button and drag to size in the Form window.

If you do not specify a RecordSource value for the grid and there is a table open in the current work area, the grid will display all the fields in that table.

Setting the Number of Columns in a Grid

One of the first properties you might want to set for the Grid control is the number of columns.

To set the number of columns in a grid

  1. Select the ColumnCount property in the Property and Methods list.
  2. In the Property box, type the number of columns you want.

If the ColumnCount property is set to - 1 (the default), the grid will contain, at run time, as many columns as there are fields in the table associated with the grid.

See Also

Enhancing Control Display | Manually Adjusting Grid Display at Design Time | Using Controls | Setting the Source of the Data Displayed in the Grid | Controls and Objects


Manually Adjusting Grid Display at Design Time

When you have added columns to the grid, you can change the width of the columns and the height of the rows. You can manually set the height and width properties of the column and row objects in the Properties window or visually set these properties in grid design mode.

To switch to grid design mode

  • Choose Edit from the grid's shortcut menu.

    -or-

  • In the Object box of the Properties window, select a column of the grid.

When you are in grid design mode, a thick border is displayed around the grid. To switch out of grid design mode, select the form or another control.

To adjust the width of the columns in a grid

  1. In grid design mode, position the mouse pointer between grid column headers so that the pointer changes to a bar with arrows pointing left and right.
  2. Select the column and drag until the column is the desired width

    -or-

    Set the column's Width property in the Properties window.

To adjust the height of the rows in a grid

  1. In grid design mode, position the mouse pointer between the first and second buttons on the left side of the Grid control so that the pointer changes to a bar with arrows pointing up and down.
  2. Select the row and drag until the row is the desired height.

    -or-

  • Set the column's Height property in the Properties window.
    Tip You can prevent a user from changing the height of the grid rows at run time by setting AllowRowSizing to false (.F.).

See Also

Manipulating Multiple Rows of Data | Setting the Source of the Data Displayed in the Grid | Using Controls | Setting Up a One-to-Many Form Using the Grid Control | Controls and Objects


Setting the Source of the Data Displayed in the Grid

You can set the data source for the grid and for each column individually.

To set the data source for a grid

  1. Select the grid, and then click the RecordSourceType property in the Properties window.
  2. Set the RecordSourceType property to 0 - Table, if you want Visual FoxPro to open the table for you, or 1 - Alias if you want the grid to be populated with the fields in a table that is already open.
  3. Click the RecordSource property in the Properties window.
  4. Type the name of the alias or table to serve as the data source for the grid.

If you want to specify particular fields to be displayed in particular columns, you also can set the data source for a column.

To set the data source for a column

  1. Select the column, and then click the ControlSource property in the Properties window.
  2. Type the name of the alias or table and the field to serve as the source for the values displayed in the column. For example, you can type:
    Orders.order_id

Adding Records to a Grid

You can make it possible for users to add new records to a table displayed in a grid by setting the AllowAddNew property of the grid to true (.T.). When the AllowAddNew property is set to true, new records are added to the table when the last record is selected and the user presses the DOWN ARROW key.

If you want more control over when a user adds new records to a table, you can set the AllowAddNew property to false (.F.), the default, and use the APPEND BLANK or INSERT commands to add new records.

See Also

Manually Adjusting Grid Display at Design Time | Setting Up a One-to-Many Form Using the Grid Control | Displaying Controls in Grid Columns | Using Controls | Controls and Objects


Setting Up a One-to-Many Form Using the Grid Control

One of the most common uses for a grid is to display the child records for a table while text boxes display the data for the parent records. When the user moves through the records in the parent table, the grid displays the appropriate child records.

If you have a data environment for your form that includes a one-to-many relationship between two tables, displaying the one-to-many relationship in the form is very easy.

To set up a one-to-many form with a data environment

  1. Drag desired fields from the parent table in the Data Environment Designer to your form.
  2. Drag the related table from the Data Environment Designer to the form.

In almost all cases, you will want to create a data environment for your form or form set. However, it is not much more complicated to create a one-to-many form without using the Data Environment Designer.

To set up a one-to-many form without creating a data environment

  1. Add text boxes to your form to display the desired fields from the primary table.
  2. Set the ControlSource property of the text boxes to the primary table.
  3. Add a grid to the form.
  4. Set the RecordSource property of the grid to the name of the related table.
  5. Set the LinkMaster property of the grid to the name of the primary table.
  6. Set the ChildOrder property of the grid to the name of the index tag in the related table that corresponds to the relational expression of the primary table.
  7. Set the RelationalExpr property of the grid to the expression that joins the related table to the primary table. For example, if the ChildOrder tag is indexed on "lastname + firstname", set RelationalExpr to the same expression.

Either way you set up the one-to-many form, you can add navigation controls to move through the parent table and refresh the form objects. For example, the following code could be included in the Click event of a command button:

SELECT orders && if orders is the parent table
SKIP
IF EOF( )
   GO BOTTOM
ENDIF
THISFORM.Refresh

See Also

Setting the Source of the Data Displayed in the Grid | Displaying Controls in Grid Columns | Using Controls | Making Controls Easier to Use | Controls and Objects


Displaying Controls in Grid Columns

In addition to displaying field data in a grid, you can have controls in the columns of a grid so that you can present a user with embedded text boxes, check boxes, drop-down list boxes, spinners, and other controls. For example, if you have a logical field in a table, when you run the form, a user can tell which record values are true (.T.) and which record values are false (.F.) by seeing whether the check box is set. Changing the value is as easy as setting or clearing the check box.

You can add controls to grid columns interactively in the Form Designer or write code to add the controls to the columns at run time.

To interactively add controls to a grid column

  1. Add a grid to a form.
  2. In the Properties window, set the ColumnCount property of the grid to the number of desired columns.

    For example, type 2 for a two-column grid.

  3. In the Properties window, select the parent column for the control from the Object box.

    For example, select Column1 to add a control to Column1. The border of the grid changes to indicate that you are editing a contained object when you select the column.

  4. Select the desired control on the Form Controls toolbar and click in the parent column.

    The new control will not be displayed in the grid column in the Form Designer, but it will be visible at run time.

  5. In the Properties window, make sure the control is displayed indented under the parent column in the Object box.

    If the new control is a check box, set the Caption property of the check box to " " and the Sparse property of the column to false (.F.).

  6. Set the ControlSource property of the parent column to the desired table field.

    For example, the ControlSource of the column in the following illustration is products.discontinu from Testdata.dbc in the Visual FoxPro ...\Samples\Data directory.

  7. Set the CurrentControl property of the parent column to the new control.

When you run the form, the control is displayed in the grid column.

Tip If you want to be able to center a check box in a grid column, create a container class, add a check box to the container class, and adjust the position of the check box in the container class. Add the container class to the grid column and set the ControlSource of the check box to the desired field.

To remove controls from grid columns in the Form Designer

  1. In the Object box of the Properties window, select the control.
  2. Activate the Form Designer.

    If the Properties window is visible, the control name is displayed in the Object box.

  3. Press the DELETE key.

You also can add controls to a grid column using the AddObject method in code.

To programmatically add controls to a grid column

  • In the Init event of the grid, use the AddObject method to add the control to the grid column and set the CurrentControl property of the column.

For example, the following lines of code in the Init event of a grid add two controls to a grid column and specify one of them as the current control:

THIS.grcColumn1.AddObject("spnQuantity", "SPINNER")
THIS.grcColumn1.AddObject("cboQuantity", "COMBOBOX")
THIS.grcColumn1.CurrentControl = "spnQuantity"
* The following lines of code make sure the control is visible
* and is diplayed in every row in the grid
THIS.grcColumn1.spnQuantity.Visible = .T.
THIS.grcColumn1.Sparse = .F.

In this example, Column1 has three possible current control values:

  • spnQuantity
  • cboQuantity
  • Text1 (the default control)
    Note Properties set on the Grid level are not passed on to the columns or headers. In the same way, you must set properties of the headers and contained controls directly; they do not inherit their properties from settings at the Column level.
    Tip For the best display of combo boxes in grid columns, set the following combo box properties:
    BackStyle = 0      && Transparent
Margin = 0
SpecialEffect = 1 && Plain
BorderStyle = 0      && None

Using Conditional Formatting in Grids

Special formatting in a grid can make it easier for a user to scan through the records in the grid and locate certain information. To provide conditional formatting, use the dynamic font and color properties of a column.

For example, you can add a grid to a form and set the ColumnCount property to 2. Set the ControlSource property of the first column to orders.to_name and the ControlSource property of the second column to orders.order_net. To display order totals less than 500.00 with a forecolor of black and order totals greater than or equal to 500.00 with a foreground color of red, include the following line in the grid's Init event code:

THIS.Column2.DynamicForeColor = ;
   "IIF(orders.order_net >= 500, RGB(255,0,0), RGB(0,0,0))"

Common Grid Properties

The following grid properties are commonly set at design time.

Property | Description
ChildOrder | The foreign key of the child table that is joined with the primary key of the parent table.
ColumnCount | Number of columns. If ColumnCount is set to - 1, the grid has as many columns as there are fields in the grid's RecordSource.
LinkMaster | The parent table for child records displayed in the grid.
RecordSource | The data to be displayed in the grid.
RecordSourceType | Where the data displayed in the grid comes from: a table, an alias, a query, or a table selected by the user in response to a prompt.

Common Column Properties

The following column properties are commonly set at design time.

Property | Description
ControlSource | The data to be displayed in the column. This is often a field in a table.
Sparse | If Sparse is set to true (.T.), controls in a grid are displayed as controls only when the cell in the column is selected. Other cells in the column display the underlying data value in a text box. Setting Sparse to true (.T.) allows faster repainting if a user is scrolling through a grid with a lot of displayed rows.
CurrentControl | Which control in the grid is active. The default is Text1, but if you add a control to the column, you can specify it as the CurrentControl.
Note The ReadOnly property of a control inside the column is overridden by the ReadOnly property of the Column. If you set the ReadOnly property of the control in a column in the code associated with the AfterRowColChange event, the new setting will be valid while you are in that cell.

See Also

Setting Up a One-to-Many Form Using the Grid Control | Making Controls Easier to Use | Using Controls | Extending Forms | Form Designer | Controls and Objects


Controls for Allowing Specific Actions

Frequently, you want to make it possible for users to take specific actions that have nothing to do with manipulating values. For example, you can make it possible for a user to close a form, open another form, move through a table, save or cancel edits, run a report or query, jump to an address of a destination on the Internet or an intranet, or any number of other actions.

Using Command Buttons and Command Button Groups

One of the most common places to put the code for specific actions is the Click event of a command button.

Making a Command Button the Default Choice

Set the Default property to true (.T.) to make the command button the default choice. The default choice has a thicker border than other command buttons. If a command button is the default choice, when the user presses ENTER, the Click event of the command button executes.

Note If the selected object on a form is an edit box or a grid, the code associated with the Click event of the default choice is not executed when the user presses ENTER. Pressing ENTER in an edit box adds a carriage return and line feed to the value in the edit box. Pressing ENTER in a grid selects an adjacent field. To execute the Click event of the default button, press CTRL+ENTER.

Common Command Button Properties

The following command button properties are commonly set at design time.

Property | Description
Cancel | Specifies that the code associated with the Click event of the command button executes when a user presses ESC.
Caption | Text displayed on the button.
DisabledPicture | The .bmp file displayed when the button is disabled.
DownPicture | The .bmp file displayed when the button is pressed.
Enabled | Whether the button can be chosen.
Picture | The .bmp file displayed on the button.

You also can include command buttons in a group so that you can manipulate them individually or as a group.

Managing Command Button Choices at the Group Level

If you want to work with a single method procedure for all the code for the Click events of command buttons in a group, you can attach the code to the Click event of the command button group. The Value property of the command button group indicates which of the buttons was clicked, as demonstrated in the following code example:

DO CASE
   CASE THIS.Value = 1
      WAIT WINDOW "You clicked " + THIS.cmdCommand1.Caption NOWAIT
      * do some action
   CASE THIS.Value = 2
      WAIT WINDOW "You clicked " + THIS.cmdCommand2.Caption NOWAIT
      * do some other action
   CASE THIS.Value = 3
      WAIT WINDOW "You clicked " + THIS.cmdCommand3.Caption NOWAIT
      * do a third action
ENDCASE
Note If the user clicks in the command button group but not on a particular button, the Value property still reflects the last command button that was selected. If you have written code for the Click event of a particular button in the group, that code is executed rather than the group Click event code when the user chooses that button.

Common Command Button Group Properties

The following command button group properties are commonly set at design time.

Property | Description
ButtonCount | Number of command buttons in the group.
BackStyle | Whether the command button group has a transparent or opaque background. A transparent background appears to be the same color that the underlying object, usually the form or a page, is.

Using the Hyperlink Object

You can use the Hyperlink object to jump to an address of a destination on the Internet or an intranet. The Hyperlink object can be used to start a hyperlink aware application, typically an Internet browser such as the Microsoft Internet Explorer, and open the page specified in the address. The Hyperlink NavigateTo( ) method makes it possible for you to specify the address of the destination that you jump to.

For example, to navigate to the Microsoft Internet site on the World Wide Web from a form, first add the Hyperlink control to the form. Add a command button to the form, and then add the following code to the Click event for the command button:

THISFORM.Hyperlink1.NavigateTo('www.microsoft.com')

When the form is run, you can click the command button to jump to the Microsoft Web site.

See Also

Accepting Numeric Input in a Given Range | Performing Specific Actions at Given Intervals | Using Controls | Controls and Objects | Displaying Information


Performing Specific Actions at Given Intervals

The Timer control makes it possible for you to perform actions or check values at specific intervals.

Using the Timer Control

Timer controls respond to the passage of time independent of user interaction, so you can program them to take actions at regular intervals. A typical use is checking the system clock to see if it is time to do a particular task. Timers are also useful for other kinds of background processing.

To see examples of using timers

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Timer.

Each timer has an Interval property, which specifies the number of milliseconds that pass between one timer event and the next. Unless disabled, a timer continues to receive an event (appropriately named the Timer event) at roughly equal intervals of time. The Interval property has a few limitations to consider when you are programming a timer:

  • The interval can be between 0 and 2,147,483,647, inclusive, which means that the longest interval is about 596.5 hours (over 24 days).
  • The interval is not guaranteed to elapse exactly on time. To ensure accuracy, the timer should check the system clock when it needs to, rather than try to keep track of accumulated time internally.
  • The system generates 18 clock ticks per second, so even though the Interval property is measured in milliseconds, the true precision of an interval is no more than one-eighteenth of a second.
  • If your application or another application is making heavy demands on the system — such as long loops, intensive calculations, or disk, network, or port access — your application might not get timer events as often as the Interval property specifies.

Placing a Timer Control on a Form

Placing a Timer control on a form is like drawing any other control: you choose the timer tool on the Form Controls toolbar and click and drag on the form.

A Timer control

The timer appears on the form at design time so you can select it, view its properties, and write an event procedure for it. At run time, a timer is invisible and its position and size are irrelevant.

Initializing a Timer Control

A Timer control has two key properties.

Property | Setting
Enabled | If you want the timer to start working as soon as the form loads, set to true (.T.). Otherwise, leave this property set to false (.F.). You can choose to have an outside event (such as a click of a command button) start operation of the timer.
Interval | Number of milliseconds between timer events.

Note that the Enabled property for the timer is different than for other objects. With most objects, the Enabled property determines whether the object can respond to an event caused by the user. With the Timer control, setting Enabled to false (.F.) suspends timer operation.

Remember that the Timer event is periodic. The Interval property does not determine "how long" as much as it determines "how often." The length of the interval should depend on how much precision you want. Because there is some built-in potential for error, make the interval one-half the desired amount of precision.

Note The more often a timer event is generated, the more processor time is consumed in responding to the event. This can slow down overall performance. Do not set a particularly small interval unless you need it.

Responding to the Timer Event

When a Timer control's interval elapses, Visual FoxPro generates the Timer event. Typically, you respond to this event by checking some general condition, such as the system clock.

A digital clock is a very simple but highly useful application involving a Timer control. When you understand how the application works, you can enhance it to work as an alarm clock, stopwatch, or other timing device.

The digital clock application includes a timer and a label with a border. At design time, the application looks like this:

The digital clock application

At run time, the timer is invisible.

Control | Property | Setting
lblTime | Caption |
Timer1 | Interval | 500 (half a second)
Timer1 | Enabled | True

The sole procedure in the application is the Timer event procedure:

IF THISFORM.lblTime.Caption != Time()
   THISFORM.lblTime.Caption = Time()
ENDIF

The Interval property for the timer is set to 500, following the rule of setting the Interval to half of the shortest period you want to distinguish (one second in this case). This might cause the timer code to update the label with the same time twice in one second. This could cause some visible flicker, so the code tests to see if the time is different from what is displayed in the label before it changes the caption.

See Also

Displaying Information | Using Controls | Enhancing Control Display | Controls and Objects


Controls for Extending Forms

Page frames make it possible for you to extend the surface area of your forms, and ActiveX controls make it possible for you to extend the functionality of your forms.

Using Page Frames

A page frame is a container object that contains pages. Pages in turn contain controls. Properties can be set at the page frame, page, or control level.

To see examples of using page frames

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Page frame.

You can think of the page frame as a three-dimensional container that presents layered pages. Only controls on the top page (or on top of the page frame) can be visible and active.

The page frame defines the location of the pages and the amount of the page that is visible. The upper-left corner of a page is anchored to the upper-left corner of the page frame. Controls can be placed on pages that are beyond the dimensions of the page frame. These controls are active, but are not visible unless you programmatically change the Height and Width properties of the page frame to make the controls visible.

Using Pages in an Application

With page frames and pages, you can create tabbed forms or dialog boxes with the same kind of interface capabilities that you see in the Project Manager.

In addition, page frames make it possible for you to define a region of the form where you can easily swap controls in and out. For example, in Wizards, most of the form remains constant, but an area of the form changes with each step. Instead of creating five forms for the wizard steps, you could create one form with a page frame and five pages.

Solution.app, in the Visual FoxPro ...\Samples\Solution directory, contains two page frame examples that demonstrate using frames with and without tabs.

Adding Page Frames to a Form

You can include one or more page frames on any form.

To add a page frame to a form

  1. In the Form Controls toolbar, choose the Page Frame button and drag to size in the Form window.
  2. Set the PageCount property to indicate the number of pages to include in the frame.
  3. From the frame's shortcut menu, choose Edit to activate the frame as a container. The page frame border widens to indicate that it is active.
  4. Add controls the same way you would add them to a form.
    Note Like other container controls, you must select the page frame and choose Edit from the right mouse menu, or select the container in the Object drop-down list in the Properties window, so that the container is selected (has a wider border) before you add controls to the page you are designing. If you do not activate the page as a container before adding controls, the controls will be added to the form instead of the page, even though they might appear to be on the page.

To select a different page in the page frame

  1. Activate the page frame as a container by right-clicking it and choosing Edit.
  2. Select the tab of the page you want to use.

    -or-

  • Select the page in the Object box in the Properties window.

    -or-

  • Select the page in the Page box at the bottom of the Form Designer.

Adding Controls to a Page

When you add controls to a page, they are visible and active only when their page is active.

To add controls to a page

  1. In the Object box of the Properties window, select the page. A border appears around the page frame indicating that you can manipulate contained objects.
  2. In the Form Controls toolbar, choose the control button you want and drag to size in the page.

Managing Long Captions on Page Tabs

If the captions on your tabs are longer than can be displayed on the tab given the width of the page frame and the number of pages, you have two options:

  • Set the TabStretch property to 1 - Single Row to show only the characters of the captions that will fit on the tabs. Single Row is the default.
  • Set the TabStretch property to 0 - Multiple Rows to stack the tabs so that the entire caption on all the tabs is visible.

Changing Pages Programmatically

Whether a page frame is displayed with tabs or not, you can programmatically make a page active by using the ActivePage property. For example, the following code in the Click event procedure of a command button on a form changes the active page of a frame page on the form to the third page:

THISFORM.pgfOptions.ActivePage = 3

Common Page Frame Properties

The following page frame properties are commonly set at design time.

Property | Description
Tabs | Whether tabs are visible for the pages.
TabStyle | Whether or not the tabs are all the same size and together the same width as the page frame.
PageCount | The number of pages in the page frame.

See Also

Making Controls Easier to Use | Manipulating Objects with OLE Container Control and OLE Bound Control | Using Controls | ActiveX Controls Overview | Controls and Objects


ActiveX Controls Overview

ActiveX controls (.ocx files) are installed by default when you install Visual FoxPro. You can distribute ActiveX controls with your applications. ActiveX controls are added to a form in an application by using the Visual FoxPro OLE container control.

The following table lists the .ocx files that are installed with Visual FoxPro and the ActiveX controls contained in each file.

File | Controls | Help file
MSCOMCTL2.ocx | Animation control Datetimepicker control Monthview control Updown control | Cmctl298.chm
MCI32.ocx | Multimedia MCI control | Mmedia.chm
MSChrt20.ocx | MsChart control | Mschrt98.chm
MSComctl.ocx | ImageCombo control ImageList control ListView control ProgressBar control Slider control StatusBar control TabStrip control Toolbar control TreeView control | Cmctl198.chm
MSComm32.ocx | MSComm control | Comm98.chm
MSInet.ocx | Microsoft Internet Transfer control | Inet98.chm
MSMapi32.ocx | MAPI Message control MAPI Session control | Mapi98.chm
MSMask32.ocx | Masked Edit control | Masked98.chm
MSWinsck.ocx | Winsock control | Mswnsk98.chm
Picclp32.ocx | PicClip control | Picclp98.chm
Richtx32.ocx | Rich Textbox control | Rtfbox98.chm
Sysinfo.ocx | SysInfo control | Sysinf98.chm

In earlier versions of Visual FoxPro, the file containing the ActiveX controls was renamed from Comctl32.ocx to Mscomctl.ocx.

Even though Visual FoxPro upgraded to the new Mscomctl.ocx file, older forms with these controls will still reference the older file since the ActiveX control is bound by its OleClass property. ActiveX controls from the older Comctl32.ocx file have a version of 1.

For example, the OleClass property for a ListView control on an earlier form would say:

   COMCTL.ListViewCtrl.1

Newer ActiveX controls in the Mscomctl.ocx file have a version 2 (or higher). For example:

   COMCTL.TreeViewCtrl.2

Visual FoxPro will not automatically upgrade your control, so it is important to know which version of an ActiveX control a form uses when distributing your applications.

See Also

Adding OLE | Controls Tab, Options Dialog Box | OLE Container Control


Manipulating Objects with OLE Container Control and OLE Bound Control

You add an OLE object to a form by clicking the OLE Container Control tool and dragging it to size in the Form window. This tool can represent a server object such as Microsoft Excel or Word, or it can represent an ActiveX control if your Windows SYSTEM directory contains ActiveX controls (files with an .ocx extension). For general information about ActiveX controls, see Adding OLE.

OLE Bound Control

You can create a bound OLE object on a form by clicking this tool and dragging it to size in the Form window. After creating the object, you connect it to a General field in a table. Then, you use the object to display the contents of the field. For example, if you store Word documents in a General field, you can display the contents of these documents by using a bound OLE object on a form.

To create a bound OLE object

  1. Create or open a form.
  2. In the Form Controls toolbar, choose the OLE Bound Control button and drag it to size on the form.
  3. Bind the OLE object to a General field by setting the object's ControlSource property.

For an example of using the OLE Bound control, see Adding OLE.

See Also

Extending Forms | Making Controls Easier to Use | Displaying Controls in Grid Columns | Using Controls | Controls and Objects


Controls and Data Concepts

You can have two types of controls on your forms: controls that are bound to data and controls that are not. When users interact with bound controls, the values that they enter or choose are stored in the data source, which can be a table field, a cursor field, or a variable. You bind a control to data by setting its ControlSource property, or, in the case of grids, its RecordSource property.

If you do not set the ControlSource property of a control, the value that the user enters or chooses in the control is only stored as a property setting. The value is not written to disk or stored in memory beyond the lifetime of the control.

Effect of a ControlSource Property Setting on Controls

Control | Effect
Check box | If the ControlSource is a field in a table, then NULL values, logical values true (.T.) or false (.F.), or numeric values 0, 1, or 2 in the ControlSource field cause the check box to be selected, cleared, or grayed as the record pointer moves through the table.
Column | If the ControlSource is a table field, the user is directly editing the field when editing values in the column. To bind an entire grid to data, set the RecordSource property of the grid.
List box or
combo box 		If the ControlSource is a variable, the value the user chooses in the list is stored in the variable. If the ControlSource is a field in a table, the value is stored in the field at the record pointer. If an item in the list matches the value of the field in the table, the item is selected in the list when the record pointer moves through the table.
Option button If the ControlSource is a numeric field, 0 or 1 is written to the field, depending on whether or not the button is chosen.

If the ControlSource is logical, .T. or .F. is written to the field, depending on whether the button is chosen. If the record pointer moves in the table, the value of the option button is updated to reflect the new value in the field.

If the ControlSource of the option button's OptionGroup control (not the option button itself) is a character field, the caption of the option button is stored to the field if the option button is chosen. Note that the control source for an option button (as distinct from an OptionGroup control) cannot be a character field, or Visual FoxPro will report a data type mismatch when the form is run.
Spinner | The spinner reflects and writes numeric values to the underlying field or variable.
Text box or
edit box 		The value in the table field is displayed in the text box. Changes the user makes to this value are written back to the table. Moving the record pointer affects the Value property of the text box.

Some of the tasks you want to accomplish with controls require having data bound to the control. Other tasks will not. For additional information, see Controls and Objects.

See Also

Using Controls | Control Selection for Particular Tasks | Controls and Objects | Setting the Number of Option Buttons in an Option Button Group | Setting Option Button Properties


Creating Controls by Dragging and Dropping Fields or Tables

You can specify the type of control that is created when you drag a field or table onto a form. For example, you can create a text box control any time a Character field is dragged onto a form.

To map field types to classes

  1. From the Tools menu, choose Options.
  2. Select the Field Mapping tab.
  3. To change a field type mapping, select a line in the Map fields to classes for drag and drop area and choose Modify.
  4. In the Modify Field Mapping dialog box, select a field type from the Type list.

    To set the class that is created whenever you drag a table or multiple fields, select Multiple from the Type list.

  5. To select the class library (.vcx file) that contains the control you want to associate with the selected field type, choose Browse.
  6. Select a class name from the Name list. The class you specify here will be created any time a field of the selected type is dragged onto a form.
  7. Choose OK to accept the mapping.
  8. Set options in the Database options area:
    To... | Select...
    Create a label in addition to the bound control when you drag a field or table to a form or container | Drag and drop field caption
    Set the Comment property of the bound control to the text specified in the Field Comment box in the Fields tab of the Table Designer | Copy field comment
    Set the InputMask property of the bound control to the input mask specified in the Fields tab of the Table Designer | Copy field input mask
    Set the Format property of the bound control to the format specified in the Fields tab of the Table Designer | Copy field format
Note You also can specify classes for dragging and dropping in the Display Class box in the Fields tab of the Table Designer. The settings in the Table Designer override the settings you specify here.

Quickly Creating a Single Control

You can quickly create a single control based on the field type mapping you specified on the Field Mapping tab in the Options dialog box. You also can override the default mapping and create a different class type.

To create a single control

  • Click on any field in the Data Environment and drag it onto a form.
    Note The ControlSource property of the newly created control is set to the Name property of the field.

To create a single control and override the current field mapping

  1. Right-click on any field in the Data Environment and drag it onto a form.
  2. From the shortcut menu, select Create Other Control Here.
  3. In the Open dialog box, choose a Visual Class Library (.vcx) file.
  4. Select the type of control you want to create from the Class Name box and choose Open.

Quickly Creating Multiple Controls

You can drag an entire table onto a form. By default, a grid control is created when you drag a table onto a form. You can override the default and create multiple controls corresponding to the default field type mappings specified for each field in the table.

To create a grid control

  • Choose any table in the Data Environment, Database Designer, or Project Manager and drag it onto a form.

To create multiple controls

  1. Right-click any table, or two or more highlighted fields in a table, in the Data Environment, Database Designer, or Project Manager, and drag it onto a form.
  2. From the shortcut menu, select Create Multiple Controls Here.

See Also

Adding Controls to a Wizard-Generated Form | Creating a New Form | Creating Forms with Local and Remote Data | Adding Visual FoxPro Controls to a Form | Data Environment Designer | Creating Forms


Creating Drag-and-Drop Controls

When you design Visual FoxPro applications, you can drag text, files, and objects from the Component Gallery, Project Manager, the Database Designer, and the Data Environment Designer to desired locations on forms and reports. The drag-and-drop features in Visual FoxPro make it possible for you to extend this ability to the user at run time.

This drag-and-drop capability extends to multiple-form operations. The user can drag text, files, and controls anywhere on the screen, including other forms.

Two types of drag-and-drop functionality are supported in Visual FoxPro: OLE drag-and-drop and control drag-and-drop. OLE drag-and-drop makes it possible for you to move data between other applications that support OLE drag-and-drop (such as Visual FoxPro, Visual Basic, the Windows Explorer, Microsoft Word and Excel, and so on). In a distributed Visual FoxPro application, you can move data between controls in the application, or between controls and other Window applications that support OLE drag-and-drop.

Control drag-and-drop makes it possible for you to drag Visual FoxPro controls within your Visual FoxPro applications. Control drag-and-drop is also supported in earlier versions of Visual FoxPro. As the user drags a control, Visual FoxPro provides a gray outline that is the same size as the object and moves with the mouse pointer. You can override this default behavior by specifying a cursor file (.cur) for the DragIcon property of a control.

This section describes control drag-and-drop. For more information about OLE drag-and-drop, see OLE drag-and-drop in "Interoperability and the Internet."

To see examples of control drag-and-drop

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click General.
    Note Run-time dragging of a control does not change its location automatically. You can do this, but you must program the relocation yourself, as described in the section, "Causing Control Movement in a Drag-and-Drop Operation." Often, dragging is used only to indicate that some action should be performed; the control retains its original position after the user releases the mouse button.

Using the following drag-and-drop properties, events, and method, you can specify both the meaning of a drag operation and how dragging can be initiated (if at all) for any given control.

To | Use this feature
Enable automatic or manual dragging of a control. | DragMode property
Specify what icon is displayed when the control is dragged. | DragIcon property
Recognize when a control is dropped onto the object. | DragDrop event
Recognize when a control is dragged over the object. | DragOver event
Start or stop manual dragging. | Drag method

All visual controls can be dragged at run time and all controls share the properties listed in the preceding table. Forms recognize the DragDrop and DragOver events, but they do not have DragMode and DragIcon properties.

Enabling Automatic Drag Mode

To make it possible for the user to drag a control whenever the user clicks the control, set its DragMode property to 1. This enables automatic dragging of the control. When you set dragging to Automatic, dragging is always on.

Note While an automatic drag operation is taking place, the control being dragged does not recognize other mouse events.

Responding When the User Drops the Object

When the user releases the mouse button after dragging a control, Visual FoxPro generates a DragDrop event. You can respond to this event in many ways. You can relocate the control at the new location (indicated by the last position of the gray outline). Remember that the control does not move automatically to the new location.

Two terms are important when discussing drag-and-drop operations — source and target.

Term | Meaning
Source | The control being dragged.
Target | The object onto which the user drops the control. This object, which can be a form or control, recognizes the DragDrop event.

A control becomes the target if the mouse position is within its borders when the button is released. A form is the target if the pointer is in a blank portion of the form.

The DragDrop event receives three parameters: oSource, nXCoord, and nYCoord. The parameter oSource is a reference to the control that was dropped onto the target. The parameters nXCoord and nYCoord contain the horizontal and vertical coordinates, respectively, of the mouse pointer within the target.

Because oSource is an object, you use it just as you would a control — you can refer to its properties or call one of its methods. For example, the following statements in the code associated with the DragDrop event checks to see whether the user has dropped a control on itself:

LPARAMETERS oSource, nXCoord, nYCoord
IF oSource.Name != THIS.Name
   * Take some action.
ELSE
   * Control was dropped on itself.
   * Take some other action.
ENDIF

All possible control types for oSource have a Visible property. Therefore, you can make a control invisible when it is dropped on a certain part of a form or on another control. The following line in the code associated with the DragDrop event of an Image control causes a dragged control to disappear when it is dropped on the image:

LPARAMETERS oSource, nXCoord, nYCoord
oSource.Visible = .F.

Indicating Valid Drop Zones

When you enable drag-and-drop functionality, you can help your users by including visual clues about where a user can and cannot drop a control. The best way to do this is to change the DragIcon of the source in the code associated with the DragOver event.

The following code in the DragOver event of a control indicates to a user that the control is not a valid drop target. In this example, cOldIcon is a user-defined property of the form.

LPARAMETERS oSource, nXCoord, nYCoord, nState
DO CASE
   CASE nState = 0 && Enter
      THISFORM.cOldIcon = oSource.DragIcon
      oSource.DragIcon = "NODROP01.CUR"
   CASE nState = 1 && Leave
      oSource.DragIcon = THISFORM.cOldIcon
ENDCASE

Controlling When Dragging Starts or Stops

Visual FoxPro has a setting of Manual for the DragMode property that gives you more control than the Automatic setting. The Manual setting makes it possible for you to specify when a control can and cannot be dragged. (When DragMode is set to Automatic, the control can always be dragged as long as the setting is n'ot changed.)

For instance, you might want to enable dragging in response to MouseDown and MouseUp events, or in response to a keyboard or menu command. The Manual setting also makes it possible for you to recognize a MouseDown event before dragging starts, so that you can record the mouse position.

To enable dragging from code, leave DragMode in its default setting (0 - Manual). Then use the Drag method whenever you want to begin or stop dragging an object:

container.control.Drag(nAction)

If nAction is 1, the Drag method initiates dragging of the control. If nAction is 2, the control is dropped, causing a DragDrop event. The value 0 for nAction cancels the drag. The effect is similar to giving the value 2, except that no DragDrop event occurs.

Note To enable a drag and drop operation from a list box, the best place to call the Drag method is in the code associated with the MouseMove event of the source list box, after determining that the mouse button is down. For an example, see Lmover.scx in the Visual FoxPro ...\Samples\Solution\Controls\Lists directory.

Causing Control Movement in a Drag-and-Drop Operation

You might want the source control to change position after the user releases the mouse button. To make a control move to the new mouse location, use the Move method. For example, the following code in the DragDrop event of a form moves the control that is dragged to the location of the drop:

LPARAMETERS oSource, nXCoord, nYCoord
oSource.Move(nXCoord, nYCoord)

This code might not produce precisely the effects you want, because the upper-left corner of the control is positioned at the mouse location. The following code positions the center of the control at the mouse location:

LPARAMETERS oSource, nXCoord, nYCoord
oSource.Move ((nXCoord – oSource.Width / 2), ;
   (nYCoord – oSource.Height / 2))

The code works best when the DragIcon property is set to a value other than the default (the gray rectangle). When the gray rectangle is being used, the user normally wants the control to move precisely into the final position of the gray rectangle. To do this, record the initial mouse position within the source control. Then use this position as an offset when the control is moved. For an example, see Ddrop.scx in the Visual FoxPro...\Samples\Solution\Forms directory.

To record the initial mouse position

  1. Specify manual dragging of the control.
  2. Declare two form-level variables, nDragX and nDragY.
  3. Turn on dragging when a MouseDown event occurs. Also, store the value of nXCoord and nYCoord in the form-level variables in this event.
  4. Turn dragging off when the MouseUp event occurs.

See Also

OLE Drag-and-Drop | Implementing Intrinsic and Manual OLE Drag-and Drop Modes | Design-Time OLE Drag-and-Drop Support | Allow Users to Drag-and-Drop Controls | Using Controls


Making Controls Easier to Use

You want to make it as easy as possible for users to understand and use your controls. Access keys, tab order, ToolTip text, and selective disabling all contribute to a more usable design.

Setting Access Keys

An access key makes it possible for a user to choose a control from anywhere in the form by pressing ALT and the key.

To specify an access key for a control

  • Precede the desired letter in the Caption property for the control with a backslash and a less than sign (\<).

For example, the following property setting for the Caption of a command button makes O the access key.

\<Open

A user can choose the command button from anywhere in the form by pressing ALT+O.

To specify an access key for a text box or edit box

  1. Create a label with a backslash and less than sign (\<) in front of the desired letter, such as C\<ustomer.
  2. Make sure the label is the control in the tab order immediately preceding the text box or edit box you want to receive the focus.

Setting the Tab Order of Controls

The default tab order of controls on your form is the order in which you added the controls to the form.

Tip Set the tab order of controls so that the user can easily move through your controls in a logical order.

To change the tab order of controls

  1. In the Form Designer toolbar, choose Set Tab Order.
  2. Double-click the box next to the control you want to have the initial focus when the form opens.
  3. Click the box next to the other controls in the order you want them to be tabbed to.
  4. Click anywhere outside the tab order boxes to finish.

You also can set the tab order for the objects on your form by list, depending on the setting in the Form Design tab of the Options dialog box.

You can set the selection order for the option and command buttons within a control group. To move to a control group with the keyboard, a user tabs to the first button in the control group and then uses the arrow keys to select other buttons in the group.

To change the selection order of buttons within a control group

  1. In the Properties window, select the group in the Object list. A thick border indicates that the group is in edit mode.
  2. Select the Form Designer window.
  3. From the View menu, choose Tab Order.
  4. Set the selection order as you would the tab order for controls.

Setting ToolTip Text

Each control has a ToolTipText property that makes it possible for you to specify the text displayed when the user pauses the mouse pointer over the control. Tips are especially useful for buttons with icons instead of text.

To specify ToolTip text

  • In the Properties window, select the ToolTipText property and type the desired text.

The form's ShowTips property determines whether ToolTip text is displayed.

Change the Mouse Pointer Display

You can change the mouse pointer display to provide visual clues to your users about different states your application might be in.

For example, in the tsBaseForm class of the Tasmanian Traders sample application, a WaitMode method changes the mouse pointer to the default wait state cursor. Before running any code that might take a while to process, the Tasmanian Traders application passes a value of true (.T.) to the WaitMode method to change the pointer and let the user know that processing is going on. After the processing is completed, a call to WaitMode with false (.F.) restores the default mouse pointer.

* WaitMode Method of tsBaseForm class
LPARAMETERS tlWaitMode

lnMousePointer = IIF(tlWaitMode, MOUSE_HOURGLASS, MOUSE_DEFAULT)
THISFORM.MousePointer = lnMousePointer
THISFORM.SetAll('MousePointer', lnMousePointer)

If you want to change the mouse pointer to something other than one of the default pointers, set the MousePointer Property to 99 - Custom and set the MousePointer Property to your own cursor (.cur) or icon (.ico) file.

Enabling and Disabling Controls

Set a control's Enabled property to false (.F.) if the functionality of the control is not available in a given situation.

Enabling and Disabling Buttons in a Group

You can enable or disable individual option buttons or command buttons in a group by setting the Enabled property of each button to either true (.T.) or false (.F.). You also can disable or enable all the buttons in a group by setting the Enabled property of the group, as in the following line of code:

frmForm1.cmgCommandGroup1.Enabled = .T.

When you set the Enabled property of an option button group or a command button group to false (.F.), all the buttons in the group are disabled, but will not be displayed with the disabled ForeColor and BackColor. Setting the Enabled property of the group does not change the Enabled property of the individual buttons in the group. This makes it possible for you to disable a group of buttons with some of the buttons already disabled. When you enable the group, buttons that were originally disabled remain disabled.

If you want to disable all the buttons in a group so that they appear disabled, and if you do not want to preserve information about which buttons were originally disabled or enabled, you can use the SetAll method of the group, like this:

frmForm1.opgOptionGroup1.SetAll("Enabled", .F.)

See Also

Displaying Controls in Grid Columns | Extending Forms | Using Controls | Caption property | Properties window | Controls and Objects


Designing Menus and Toolbars

Menus and toolbars provide a structured and accessible route for users to leverage the commands and tools contained in your applications. Proper planning and design of menus and toolbars will make sure the key functionality of your applications is exposed, and users will not become frustrated as they try to use your applications. For information about customizing Visual FoxPro toolbars, see Customizing the Visual FoxPro Environment.

Users often browse menus before looking elsewhere for information about your application. If your menus are well designed, users can organize their understanding of the application by developing a mental model based on the menu organization and content alone. With the Visual FoxPro Menu designer, you can create menus that enhance the quality of your applications.

Each part of a Visual FoxPro application can have its own menu system or set of menus. The following topics describe how to create a menu system. For details about adding menus to an application, see Compiling an Application.

In This Section

Menu System Creation
Much of the work involved in creating a menu system is done in the Menu designer, where you create the actual menus, submenus, and menu options.
Including Menus in an Application
When you create a menu system, you can include it in your application.
Adding Setup Code to a Menu System
You can customize a menu system by adding setup code to it.
Adding Cleanup Code to a Menu System
You can tailor your menu system by adding cleanup code to it.
Controlling Menus at Run Time
Each Visual FoxPro menu has two names, and each menu item has a name and a number. Visual FoxPro uses one name in the user interface and the other name or number in the generated menu program (.mpr).
Creating Custom Toolbars
If your application includes repetitive tasks that users perform frequently, you can add custom toolbars to simplify or speed up the tasks.
Testing and Debugging a Menu System
You can preview a menu system as you design it, or you can test and debug it after generating the menu program.
Customizing a Menu System
After creating a basic menu system, you can customize it. For example, you can create status bar messages, define menu locations, or define default procedures.

Related Sections

Creating the Interface
Using Visual FoxPro forms, classes, controls, menus, and toolbars, you can build interfaces that help users gain access to the full potential of your programs.
Creating Forms
Your application must have forms to make it possible for users to view and enter data. However, you can customize standard forms visually and programmatically to create a specialized environment for your users.
Working with Forms
After creating your form, you can run, hide, or alter it in different ways.
Using Controls
Controls manage the interactions between users and your application. Visual FoxPro offers a variety of controls to enhance your application interface.


Menu System Creation

Much of the work involved in creating a menu system is done in the Menu Designer, where you create the actual menus, submenus, and menu options.

Creating a menu system involves several steps. Regardless of the size of your application and the complexities of the menus you plan to use, you should:

  • Plan and design the system.

    Decide what menus you need, where they appear in the interface, which ones need submenus, and so on.

  • Create the menus and submenus.

    Define the menu titles, menu items, and submenus using the Menu Designer.

  • Assign tasks to the system so that it does what you want.

    Specify tasks for the menus to perform, such as displaying forms and dialog boxes. Additionally, include setup code and cleanup code if appropriate. Setup code executes before the menu system is defined and can include code for opening files, declaring variables, or placing the menu system on a stack so that it can be retrieved later. Cleanup code contains code to be executed after the menu definition code, and makes menus and menu items available or unavailable for selection.

  • Generate the menu program.
  • Run the program to test the system.

See Also

Designing Menus and Toolbars | Creating Menus, Shortcut Menus, Menu Items, and Submenus | Compiling an Application | Menu System Design Guidelines


Menu System Design Guidelines

The usefulness of an application can depend on the quality of its menu systems. If you invest planning time in your menus, users will accept them readily and learn them quickly.

While designing your menu system, consider the following guidelines:

  • Organize the system according to the tasks users will perform, not according to the hierarchy of programs in the application.

    Users can form a mental model of how the application is organized by looking at the menus and menu items. To design these menus and menu items effectively, you should know how your users will think about and accomplish their work.

  • Give each menu a meaningful title.
  • Organize menu items according to their expected frequency of use, their logical sequence, or their alphabetical order.

    If you can't predict the frequency and can't determine a logical order, then organize menu items alphabetically. Alphabetical ordering is particularly effective when a menu contains more than eight items. With so many items, the user spends time scanning them; alphabetical ordering facilitates scanning.

  • Put separator lines between logical groups of menu items.
  • Limit the number of items on a menu to one screen.
  • If the number exceeds the length of a screen, create submenus for appropriate menu items.
  • Choose access keys and keyboard shortcuts for menus and menu items.

    For example, ALT+F could be an access key for a File menu.

  • Use words that clearly describe the menu items.

    Use common words rather than computer jargon, and use simple, active verbs to indicate what actions will result from choosing each menu item. Don't use nouns as verbs. Additionally, describe the menu items using parallel construction. For example, if you use single words for all the items, then use the same part of speech for all of them.

  • Use mixed upper and lowercase letters in menu items.

See Also

Menu System Creation | Creating Menus, Shortcut Menus, Menu Items, and Submenus | Designing Menus and Toolbars | Grouping Menu Items | Compiling an Application


Creating Menus, Shortcut Menus, Menu Items, and Submenus

After planning your menu system, you can create it with the Menu Designer. You can create menus, shortcut menus, menu items, submenus of menu items, lines that separate groups of related menu items, and so on. The following sections provide the details.

Creating Menus

You can create menus by customizing the existing Visual FoxPro menu system or by developing your own menu system. To start with the existing Visual FoxPro menu system, use the Quick Menu feature.

To create a menu system with Quick Menu

  1. From the Project Manager, select the Other tab, select Menus, and then select New.
  2. Select Menu.

    The Menu Designer appears.

  3. From the Menu menu, choose Quick Menu.

    The Menu Designer now contains information about the main Visual FoxPro menus.

  4. Customize the menu system by adding or changing menu items.

    For example, insert a Customer menu before the Help menu by choosing the mover button associated with the Help menu, choosing the Insert button, and then typing Customer in the Prompt column. The result looks like this:

    A customized menu system

Tip Drag mover buttons to change the location of menus on the menu bar. If you need a Help menu, make it the last menu on the menu bar so that users can find it quickly.

Before you can use your menu in an application, you must generate it.

To generate a menu

  • From the Menu menu, choose Generate.

Visual FoxPro prompts you to save the menu system in a file with an .mnx extension. This file is a table that will store all the information about the menu system. After you save the menu system, Visual FoxPro prompts for an output file with an .mpr extension. This file will contain the generated menu program.

Creating Shortcut Menus

Shortcut menus appear when you click the right mouse button on a control or object, and provide a quick way to expose all of the functions that apply to just that object. You can use Visual FoxPro to create shortcut menus, then attach these menus to controls. For example, you can create a shortcut menu containing the commands Cut, Copy, and Paste that will appear when a user right-clicks on data contained in a Grid control.

To create a shortcut menu

  1. From the Project Manager, select the Other tab, select Menus, and then choose New.
  2. Choose Shortcut.

    The Shortcut Designer appears.

When you are in the Shortcut Menu designer, the process for adding menu items is the same as it is for creating menus.

For an example of shortcut menus, run Solution.app in the Visual FoxPro ...\Samples\Solution\Solution directory.

Creating SDI Menus

SDI menus are menus that appear in single-document interface (SDI) windows. To create an SDI menu you must indicate that the menu will be used on an SDI form while you're designing the menu. Other than that, the process of creating an SDI menu is the same as that for creating a normal menu.

To create an SDI menu

  • While the Menu Designer is open, choose General Options from the View menu, and select Top-Level Form.

Creating Menu Items

After creating menus, you can place menu items on the menus. Menu items can represent Visual FoxPro commands or procedures that you want the user to execute, or menu items can contain submenus that offer additional menu items.

To add menu items to a menu

  1. In the Prompt column, select the menu title to which you want to add menu items.
  2. In the Result box, select Submenu.

    A Create button appears to the right of the list.

  3. Choose the Create button.

    An empty design window appears. In this window, you enter the menu items.

  4. In the Prompt column, type the names of the new menu items.

Creating Submenus

For each menu item, you can create a submenu containing additional menu items.

To create a submenu

  1. In the Prompt column, select the menu item to which you want to add a submenu.
  2. In the Result box, select Submenu.

    A Create button appears to the right of the list. If a submenu already exists, an Edit button appears instead.

  3. Select Create or Edit.
  4. In the Prompt column, type the names of the new menu items.

Adding Menus Programmatically

Though you typically create menus and menu items using the Menu Designer, you can also create them using Visual FoxPro commands. For example, you can create a menu using DEFINE PAD, a submenu using DEFINE POPUP, and items on the submenu using a series of DEFINE BAR commands. You can also use DEFINE BAR to customize menus in such ways as adding pictures, assigning fonts, and displaying messages to the user.

See Also

Menu System Creation | Menu System Design Guidelines | Grouping Menu Items | Designing Menus and Toolbars | Compiling an Application


Grouping Menu Items

For readability, separate groups of similar menu items with dividing lines. For example, in Visual FoxPro, the Edit menu has a line separating the Undo and Redo commands from the Cut, Copy, Paste, Paste Special, and Clear commands.

To group menu items

  1. In the Prompt column, type \-. This creates a dividing line.
  2. Drag the button to the left of the \- prompt to move the dividing line until it appears where you want it.

See Also

Menu System Creation | Creating Menus, Shortcut Menus, Menu Items, and Submenus | Saving a Menu as HTML | Designing Menus and Toolbars | Compiling an Application


Saving a Menu as HTML

You can use the Save As HTML option on the File menu when you're creating a menu to save the contents of a menu as an HTML (Hypertext Markup Language) file.

To save a form as HTML

  1. Open the menu.
  2. Choose Save As HTML on the File menu. (You will be asked to save the menu if it has been modified.)
  3. Enter the name of the HTML file to create and choose Save.

See Also

Menu System Creation | Grouping Menu Items | Including Menus in an Application | Designing Menus and Toolbars | Creating Menus, Shortcut Menus, Menu Items, and Submenus, | Compiling an Application


Adding Cleanup Code to a Menu System

You can tailor your menu system by adding cleanup code to it. Cleanup code typically contains code that initially enables or disables menus and menu items. When you generate and run the menu program, setup code and menu definition code is processed before cleanup code.

To add cleanup code to a menu system

  1. From the View menu, choose General Options.
  2. In the Menu Code area, select Cleanup and then choose OK.
  3. In the code window, type the appropriate cleanup code.

    Your changes are saved when you close the Menu Designer.

    Tip If your menu is the main program in an application, include a READ EVENTS command in the cleanup code and assign a CLEAR EVENTS command to the menu command used to exit the menu system. This prevents your run-time applications from terminating prematurely.

See Also

Adding Setup Code to a Menu System | Controlling Menus at Run Time | Creating Custom Toolbars | Designing Menus and Toolbars | Compiling an Application


Adding Setup Code to a Menu System

You can customize a menu system by adding setup code to it. Setup code can include code for creating the environment, defining variables, opening necessary files, and saving or restoring menu systems with the PUSH MENU and POP MENU commands.

To add setup code to a menu system

  1. From the View menu, choose General Options.
  2. In the Menu Code area, select Setup and then choose OK.
  3. In the setup code window, type the appropriate setup code.

    Your changes are saved when you close the Menu Designer.

See Also

Performing Tasks with Commands | Adding Cleanup Code to a Menu System | Controlling Menus at Run Time | Designing Menus and Toolbars | Compiling an Application


Assigning Access Keys and Keyboard Shortcuts

As you create a menu system, you should consider ease of access to the system, and you must assign tasks to the system. You must give menus and menu items tasks to perform, such as displaying forms, toolbars, and other menu systems. You should define access keys to permit entry to the menu system. You can also add keyboard shortcuts and enable or disable menu items for more control.

Assigning Access Keys

Well-designed menus have access keys for quick keyboard access to the menu functionality. The access key is represented by the underlined letter in the menu title or menu item. For instance, the Visual FoxPro File menu uses "F" as its access key.

If you don't assign an access key to a menu title or menu item, Visual FoxPro automatically assigns the first letter as the access key. For example, the Customer menu created previously didn't have a defined access key. Accordingly, Visual FoxPro assigned the first letter (C) as the access key.

To specify the access key for a menu or menu item

  • Type \< to the left of the letter you want as the access key.

    For example, to set the access key to "u" in the Customer menu title, replace Customer with C\<ustomer in the Prompt column.

    Note If an access key for your menu system doesn't work, look for duplicate access keys.

Assigning Keyboard Shortcuts

In addition to assigning access keys, you can specify keyboard shortcuts for menus or menu items. As with access keys, keyboard shortcuts let you choose a menu or menu item by holding down one key while pressing another. The difference between access keys and keyboard shortcuts is that you can use a keyboard shortcut to choose a menu item without first displaying its menu.

Keyboard shortcuts for Visual FoxPro menu items are combinations of the CTRL or ALT key and another key. For instance, you can create a new file in Visual FoxPro by pressing CTRL+N.

To specify a keyboard shortcut for a menu or menu item

  1. In the Prompt column, select the appropriate menu title or menu item.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. In the Key Label box, press a key combination to create a keyboard shortcut.

    If a menu item doesn't have a keyboard shortcut, Visual FoxPro displays "(press the key)" in the Key Label box.

  4. In the Key Text box, add the text you want to appear beside the menu item.

    By default, Visual FoxPro repeats the keyboard shortcut from the Key Label box in the Key Text box. However, you can change the text in the Key Text box if you want your application to display different text. For example, if both the Key Label and Key Text were CTRL+R, you could change the Key Text value to ^R.

    Note CTRL+J is an invalid keyboard shortcut because it is used to close certain dialog boxes in Visual FoxPro.

See Also

Including Menus in an Application | Enabling and Disabling Menu Items | Creating Menus, Shortcut Menus, Menu Items, and Submenus, | Designing Menus and Toolbars | Compiling an Application


Controlling Menus at Run Time

Each Visual FoxPro menu has two names, and each menu item has a name and a number. Visual FoxPro uses one name in the user interface and the other name or number in the generated menu program (.mpr). You can use these names or numbers to reference and control menus and menu items at run time. If you don't provide a name or number when creating menus and menu items, Visual FoxPro creates one when you generate the menu program.

For an example of adding and removing menu items at run time, see Solution.app in the Visual FoxPro ...\Samples\Solution directory.

Caution Avoid using Visual FoxPro-generated names and numbers in code, because they change each time you generate the menu program. If you refer to a generated name or number, your code might fail.

In the Menu Designer, the Prompt column shows what appears in the user interface, and the column to the right of the Result box shows what appears in the generated program.

To specify a name for a menu pad

  1. In the Prompt column, select the appropriate menu title.
    Note The Result column must show Command, Submenu, or Procedure — not Pad Name.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. In the Pad Name box, type the name of your choice.
  4. Choose OK to return to the Menu Designer.

To specify a number for a menu item

  1. In the Prompt column, select the appropriate menu item.
    Note The Result column must show Command, Submenu, or Procedure — not Bar #.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. In the Bar # box, type the number of your choice.
  4. Choose OK to return to the Menu Designer.
    Tip If you use the Quick Menu feature, don't change the names or numbers that Visual FoxPro provides for system menus or menu items; otherwise, you might get unpredictable results when you run the generated menu program.

See Also

Adding Cleanup Code to a Menu System | Designing Menus and Toolbars | Creating Custom Toolbars | Creating Menus, Shortcut Menus, Menu Items, and Submenus, Compiling an Application


Enabling and Disabling Menu Items

You can enable or disable a menu or menu item based on a logical condition.

To enable or disable a menu or menu item

  1. In the Prompt column, select the appropriate menu title or menu item.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. Select Skip For.

    The Expression Builder appears.

  4. In the Skip For box, type the expression that determines whether the menu or menu item is enabled or disabled.

    If the expression evaluates to false (.F.), the menu or menu item is enabled. If the expression evaluates to true (.T.), the menu or menu item is disabled and cannot be selected or chosen. For details, see DEFINE BAR and DEFINE PAD.

    Note After the menu system has been displayed, you can enable and disable menus and menu items by using the SET SKIP OF command.

Marking the State of a Menu Item

On a menu, a check mark next to a menu item indicates that it is in effect. For example, if you put a check mark next to the Credit item on the Customer menu created earlier, Credit is in effect.

At run time, you can place a check mark next to a menu item by using the SET MARK OF command.

For an example of disabling and marking the state of menu items, run Solution.app in the Visual FoxPro ...\Samples\Solution directory.

Assigning Tasks to Menus or Menu Items

When a menu or menu item is selected, it performs a task, such as displaying a form, a toolbar, or another menu system. To perform a task, a menu or menu item must execute a Visual FoxPro command. The command can be contained in one line, or it can be a procedure call.

Tip If you expect to use a set of commands in several places, write a procedure. The procedure should be explicitly named and written in the menu cleanup code, or somewhere where it can be referenced by any menu or object.

See Also

Assigning Access Keys and Keyboard Shortcuts | Performing Tasks with Commands | Performing Tasks with Procedures | Designing Menus and Toolbars | Compiling an Application


Including Menus in an Application

When you create a menu system, you can include it in your application.

To include a menu system in your application

  • Add the .mnx file to your project, and then build the application from the project. For more information about building your application, see Compiling an Application.

Attaching Shortcut Menus to Controls

When you create and generate a shortcut menu, you can attach it to a control. Shortcut menus typically appear when a user right-clicks on a control. You can attach a shortcut menu to a particular control by entering a small amount of code in the right-click event of the control.

  1. Select the control to which you want to attach the shortcut menu.
  2. In the Properties window, choose the Methods tab and select Right Click Event.
  3. In the code window, type DO menu.MPR, where menu is the name of the shortcut menu.
    Note Be sure to use the .mpr extension when referencing shortcut menus.

Attaching SDI Menus to Forms

When you create an SDI menu, you can attach it to an SDI form. In addition, you must:

  • Set the form's ShowWindow property.
  • Add a DO statement to the form's Init event.

To attach an SDI menu to a form

  1. In the Form Designer, set the form's ShowWindow property to 2 – As Top Level Form.
  2. In the Init event of the form, call the menu.

    For example, if your menu is called SDIMENU.MPR, add this code:

    DO SDIMENU.MPR WITH THIS,.T.

See Also

Saving a Menu as HTML | Assigning Access Keys and Keyboard Shortcuts | Designing Menus and Toolbars | Creating Menus, Shortcut Menus, Menu Items, and Submenus, | Compiling an Application |


Performing Tasks with Commands

To perform a task, you can assign a command to a menu or menu item. A command can be any valid Visual FoxPro command, including a call to a program that exists on your path or a procedure defined in the Cleanup option of the General Options dialog box. For more information, see Creating a Default Procedure for a Menu System.

To assign a command to a menu or menu item

  1. In the Prompt column, select the appropriate menu title or menu item.
  2. In the Result box, select Command.
  3. In the box to the right of the Result box, type the appropriate command:

If the command calls a procedure in the menu's cleanup code, use the DO command with the following syntax:

DO procname IN menuname

In this syntax, menuname specifies the location of the procedure. This is the name of the menu file and must have the .mpr extension. If you don't specify the location in menuname, you must specify it with SET PROCEDURE TO menuname.mpr, if the procedure is in the menu cleanup code.

Displaying Forms and Dialog Boxes

From a menu or menu item, you can display a compiled form or dialog box by calling it with a command or procedure. For example, to display a form named "Orders," use the following command:

DO FORM Orders
Tip When you create a menu or menu item that displays a form or dialog box, put three dots at the end of the prompt to indicate that more user input is required.

Displaying Toolbars

If you create a custom toolbar for an application, you can display it by calling it from a menu or menu item. For details, see Creating Custom Toolbars.

See Also

Enabling and Disabling Menu Items | Performing Tasks with Procedures | Adding Setup Code to a Menu System | Designing Menus and Toolbars | Compiling an Application


Performing Tasks with Procedures

You can assign a procedure to a menu or menu item. The way you assign a procedure depends on whether the menu or menu item has submenus.

To assign a procedure to a menu or menu item without submenus

  1. In the Prompt column, select the appropriate menu title or menu item.
  2. In the Result box, select Procedure.

    A Create button appears to the right of the list. If a procedure has been defined previously, an Edit button appears instead.

  3. Select Create or Edit.
  4. Type the appropriate code in the window.
    Note You don't need to type the PROCEDURE command in the procedure editing window because Visual FoxPro generates this statement for you. The only place you need the PROCEDURE statement is in the cleanup code.

To assign a procedure to a menu or menu item with submenus

  1. In the Menu level box, select the level that includes the appropriate menu or menu item. For example, suppose your menu system includes the Customer menu created earlier. To assign a procedure to the Customer menu, select the "Menu Bar" level in the Menu Level box. Similarly, to assign a procedure to an item on the Customer menu, select the "Customer" level in the list.
  2. From the View menu, choose Menu Options.

    Visual FoxPro displays the Menu Options dialog box.

  3. Assign the procedure by doing one of the following:
    • Write or call a procedure in the Procedure box.

      -or-

    • Choose Edit and then OK to open a separate editing window and write or call a procedure.

See Also

Performing Tasks with Commands | Adding Setup Code to a Menu System | Adding Cleanup Code to a Menu System | Designing Menus and Toolbars | Compiling an Application


Creating Custom Toolbars

If your application includes repetitive tasks that users perform frequently, you can add custom toolbars to simplify or speed up the tasks. For example, if users typically print a report by choosing a menu command, you can simplify the task by providing a toolbar with a print button.

In This Section

Defining a Toolbar Class
Explains how to create a custom toolbar class.
Adding Objects to a Custom Toolbar Class
Describes the steps involved in editing a custom toolbar class.
Adding Custom Toolbars to Form Sets
Provides information on how to add a custom toolbar class to your form as another form in a form set.
Coordinating Toolbars and Forms Using Code
Provides information on how to programmatically add a toolbar to a form.
Defining Toolbar Actions
Explains how to define actions associated with the toolbar and its objects.
Creating the Coordinated Menu
Explains how to coordinate a menu with a toolbar.
Adding a Coordinated Toolbar and Menu to a Form Set
Explains how to add a coordinated menu and toolbar to a form.

Related Sections

Customize Toolbar Dialog Box
Explains how to customize toolbars that come with Visual FoxPro.


Defining a Toolbar Class

If you want to create a toolbar that contains buttons not already found on existing toolbars, you can do so by defining a custom toolbar class. Visual FoxPro provides a Toolbar base class from which you can create the class you need.

After defining a toolbar class, you can add objects to the toolbar class, and then define the properties, events, and methods for the custom toolbar. Finally, you can add the toolbar to a form set.

To define a custom toolbar class

  1. From the Project Manager, select Classes and then choose New.
  2. In the Class Name box, type the name of your class.
  3. From the Based On box, select Toolbar to use the Toolbar base class.

    -or-

    Choose the dialog button to choose another toolbar class.

  4. In the Store In box, type the name of the library in which you want to save the new class.

    -or-

    Choose the dialog button to select an existing library.

  5. Add objects to the new toolbar class.

For example, you could store a printing class based on the Toolbar base class in an inventory library.

When you complete the New Class dialog box, the Class Designer appears.

You can also define a toolbar class by doing one of the following:

  • Choosing New from the File menu and then choosing Class.
  • Using the CREATE CLASS or MODIFY CLASS command.
  • Defining the class programmatically with the DEFINE CLASS command.

See Also

Adding Objects to a Custom Toolbar Class | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Adding Objects to a Custom Toolbar Class

After creating a custom toolbar class, you can add objects to it, including any objects supported by Visual FoxPro, except grids. For example, you can add objects from the Controls toolbar.

To add objects to your custom toolbar class

  1. Open the class library containing the custom toolbar class, and then open the class.
  2. On the Form Controls toolbar, choose an object you want to add.
  3. Place the object on the custom toolbar by selecting the custom toolbar.
  4. Repeat steps 2 and 3 until the custom toolbar is complete.
  5. Reorganize the objects on the custom toolbar, if appropriate.

    For example, you can size objects, move them by dragging them, delete them by pressing the DELETE key, or add extra space between them by inserting Separator objects from the Form Controls toolbar.

    Note You can move only one object at a time.
  6. Set properties of the toolbar in the Properties window.
  7. Save the custom toolbar class.
    Tip You can add a bitmap or icon to a toolbar button by setting its Picture property.

See Also

Defining a Toolbar Class | Adding Custom Toolbars to Form Sets | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Adding Custom Toolbars to Form Sets

After defining a toolbar class, you can create a toolbar from it. You can coordinate toolbars and forms by using the Form Designer or writing code.

Coordinating Toolbars and Forms in the Form Designer

You can add a toolbar to a form set so that the toolbar opens along with the forms in the form set. You cannot add the toolbar directly to the form.

To add a toolbar to a form set using the Form Designer

  1. Register and select the library containing the toolbar class.
  2. Open the form set with which you want to use the toolbar class, click the View Classes button on the Form Controls toolbar, and then select the toolbar class from the list displayed.
  3. From the Form Controls toolbar, choose the toolbar class.
  4. Click in the Form Designer to add the toolbar, and then drag the toolbar to its appropriate location.

    Visual FoxPro adds the toolbar to the form set. If a form set isn't open, Visual FoxPro prompts you for one.

  5. Define the actions of the toolbar and its buttons.
    Tip To determine an object's class, look at its ToolTip in the Form Controls toolbar.

See Also

Adding Objects to a Custom Toolbar Class | Coordinating Toolbars and Forms Using Code | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment | Defining Toolbar Actions | Object-Oriented Programming


Coordinating Toolbars and Forms Using Code

In addition to using the Form Designer, you can add toolbars to form sets by using code.

To add a toolbar to a form set using code

  • In the form set's Init event, use the SET CLASSLIB command to specify the library containing the toolbar class, and then create a toolbar from that class in the form set.

For example, to add and display the toolbar tbrPrint, which is based on the printing class in the inventory class library, add the following code to the form set's Init event:

SET CLASSLIB TO inventory
THIS.AddObject("tbrPrint","printing")
THIS.tbrPrint.Show
Note If the toolbar class does not define the actions of the toolbar and its buttons, you must define the actions in the event procedures associated with the toolbar and its buttons.

Example:

You can define all aspects of a toolbar in code. For example, if you add the following code to a form set's Init event, when the form set is loaded Visual FoxPro creates and displays the toolbar defined in the code. This toolbar contains two buttons.

When chosen, these buttons change the font attributes of the form frmForm1 in the form set.

Form Set Init Event Code

Code Comments
THIS.AddObject("tbrTool1","mytoolbar")
THIS.tbrTool1.Show
 Adds a toolbar of the class mytoolbar to the current form set and makes the toolbar visible. This code is in the form set's Init event.

Class definition code

Code Comments
DEFINE CLASS myToolBar AS TOOLBAR

ADD OBJECT cmdBold AS COMMANDBUTTON
ADD OBJECT sep1    AS SEPARATOR
ADD OBJECT cmdItalic AS COMMANDBUTTON
 Start of the class definition: one toolbar with a command button, a separator, and another command button.
Left = 1
Top  = 1
Width = 25
Caption = "Form Attributes"
 Sets properties of the toolbar object.
cmdBold.Caption = "B"
cmdBold.Height = 1.7
cmdBold.Width = 10

cmdItalic.Caption = "I"
cmdItalic.Height = 1.7
cmdItalic.Width = 10
cmdItalic.FontBold = .F.
 Sets properties of the controls. Notice that there are no Top or Left property settings for controls on a toolbar. Controls on a toolbar are automatically positioned in the order they are added.

The FontBold property of cmdItalic is set to false (.F.) because FontBold is true (.T.) by default.
PROCEDURE Activate
   THIS.cmdBold.FontBold = ;
    THISFORMSET.frmForm1.FontBold
   THIS.cmdItalic.FontItalic = ;
    THISFORMSET.frmForm1.FontItalic
ENDPROC
 When the toolbar is activated, the font attributes of the two command buttons are set to reflect the Bold and Italic font settings of frmForm1.
PROCEDURE cmdBold.CLICK
   THISFORMSET.frmForm1.FontBold = ;
    !THISFORMSET.frmForm1.FontBold
   THIS.FontBold = ;
    THISFORMSET.frmForm1.FontBold
ENDPROC
 When the user clicks cmdBold, the FontBold setting of frmForm1 is reversed, and the FontBold setting of cmdBold is set to match it.
PROCEDURE cmdItalic.CLICK
   THISFORMSET.frmForm1.FontItalic = ;
    !THISFORMSET.frmForm1.FontItalic
   THIS.FontItalic = ;
    THISFORMSET.frmForm1.FontItalic
ENDPROC
 When the user clicks cmdItalic, the FontItalic setting of frmForm1 is reversed, and the FontItalic setting of cmdItalic is set to match it.
ENDDEFINE
 End of the class definition.

Setting Properties of Custom Toolbars

While designing a custom toolbar, you can set its properties. For example, you can set the Movable property to allow the user to move the toolbar.

Additionally, you can use methods and events to control custom toolbars. For example, you can use the Dock method to dock or float a toolbar, and you can use the BeforeDock event and AfterDock event to control what happens before and after a toolbar is docked.

See Also

Adding Custom Toolbars to Form Sets | Defining Toolbar Actions | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment | Defining Toolbar Actions


Defining Toolbar Actions

After creating a toolbar, you must define the actions associated with the toolbar and its objects. For example, you must define what happens when the user clicks the toolbar or one of its buttons.

To define a toolbar action

  1. Select the object for which you want to define an action: the toolbar or one of its buttons.
  2. In the Properties window, choose the Methods tab.
  3. Edit the appropriate event.
  4. Add the code that specifies the action.

Additionally, you can set properties and methods of the toolbar and its objects.

Coordinating Menus and Custom Toolbars

If you create a toolbar, you should synchronize menu commands with their corresponding toolbar buttons. For example, if you enable a toolbar button, you should enable its corresponding menu command.

You should design and create your application to:

  • Perform the same actions when the user chooses associated toolbar buttons and menu items.
  • Coordinate the enabling and disabling of associated toolbar buttons and menu items.

Follow these general steps when coordinating menu items and toolbar buttons:

  1. Create a toolbar by defining a toolbar class, add command buttons, and include the operational code in the methods associated with the Click events of the command buttons.
  2. Create the coordinated menu.
  3. Add the coordinated toolbar and menu to a form set.

See Also

Coordinating Toolbars and Forms Using Code | Creating the Coordinated Menu | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Creating the Coordinated Menu

When you coordinate a menu with a toolbar, the menu items accomplish the same tasks as the associated toolbar buttons, and the menu items are automatically disabled when the associated toolbar button is disabled.

To create a menu that is coordinated with a toolbar

  1. In the Menu Designer, create a submenu with a descriptive prompt for every button on the toolbar.
  2. In the result column for each submenu item, choose Command.
  3. For each submenu item, call the code associated with the Click event of the appropriate toolbar command button.

    For example, if the name of the button on the toolbar is cmdA, add the following line of code in the edit box for the submenu item command:

    Formset.toolbar.cmdA.Click
  4. Choose the button in the Options column to open the Prompt Options dialog box and choose Skip For.
  5. In the Expression Builder, enter an expression that indicates that the menu option should be skipped when the toolbar command button is not enabled.

    For example, if the name of the button on the toolbar is cmdA, enter the following expression in the Skip For box:

    NOT formset.toolbar.cmdA.Enabled
  6. Generate the menu.
  7. Add the menu to the form set with the toolbar and run the form set.

When the user opens the menu, Visual FoxPro evaluates the Skip For condition, disabling the menu item if the associated toolbar command button is disabled. When the user chooses an item on the menu, the code in the Click event of the associated toolbar command button is executed.

See Also

Defining Toolbar Actions | Adding a Coordinated Toolbar and Menu to a Form Set | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Adding a Coordinated Toolbar and Menu to a Form Set

When you have created a toolbar class and a menu that are designed to work together, it is easy to incorporate them in a form set.

To incorporate a coordinated toolbar and menu in a form set

  1. Add the toolbar to the form set in one of three ways:
    • Drag the toolbar class from the Project Manager into the Form Designer.
    • Register the toolbar class library and add the toolbar to the form set from the Form Controls toolbar.
    • In the Init event of the form set, include code with the AddObject method to add the toolbar.
  2. In the Load event of the form set, save the existing menu and run your menu program.

    For example, if your menu name is mymenu, include the following lines of code using the PUSH MENU and DO commands:

    PUSH MENU _MSYSMENU
DO mymenu.mpr
  3. In the Unload event of the form set, restore the original menu with the POP MENU command:
    POP MENU _MSYSMENU

If some menu commands are used more than others, you can create custom toolbars containing buttons for those commands. Then, users can simply press the buttons whenever they need the commands. However, if you create a toolbar, you should synchronize the menu commands with their corresponding buttons. For example, if you enable a button, you should enable its corresponding menu command.

See Also

Creating the Coordinated Menu | Testing and Debugging a Menu System | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Testing and Debugging a Menu System

You can preview a menu system as you design it or you can test and debug it after generating the menu program.

To preview a menu system as you design it

  • In the Menu Designer, choose Preview.

When you choose Preview, the menu system you've defined appears at the top of the screen. Additionally, the Preview dialog box displays the file name (or a temporary file name) of the menu system.

If you select a menu title or menu item, it also appears in the Preview dialog box, along with the command assigned to it, if there is one.

To test a menu system

  1. From the Menu menu, choose Generate.

    If you've changed the menu, Visual FoxPro prompts you to save the changes.

  2. In the Generate Menu dialog box, enter a name for the generated menu program by typing the name in the Output File box or by choosing the dialog button.
  3. Choose Generate to produce a menu program file with an .mpr extension.
  4. From the Program menu, choose Do to run the program.
    Caution If you modify the generated menu program (the .mpr file), you'll lose the changes when you modify the menu using the Menu Designer and then regenerate the menu program.

If the menu program doesn't work as intended, use the diagnostic tools provided with Visual FoxPro. For more information, see Testing and Debugging Applications.

Tip If you run an application (.exe file) in which the main program is a menu and the application terminates as soon as the menu is displayed, include the READ EVENTS command in the cleanup code. You must also assign a CLEAR EVENTS command to the menu command that allows the user to exit the menu system.

See Also

Adding a Coordinated Toolbar and Menu to a Form Set | Customizing a Menu System | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Customizing a Menu System

After creating a basic menu system, you can customize it. For example, you can create status bar messages, define menu locations, or define default procedures.

Displaying Status Bar Messages

When a menu or menu item is selected, you can display a status bar message describing the choice. Such a message helps the user by adding information about the menu choice.

To display a message when a menu or menu item is selected

  1. In the Prompt column, select the appropriate menu title or menu item.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. Select Message.

    The Expression Builder dialog box appears.

  4. In the Message box, type the appropriate message.
    Tip Enclose character strings in quotation marks.

Defining the Location of Menu Titles

You can customize the location of user-defined menu titles in your applications. You can customize the location relative to the active menu system by choosing options in the General Options dialog box. Additionally, you can specify the location of menu titles when the user edits an object visually.

To specify a relative location for user — defined menu titles

  1. From the View menu, choose General Options.
  2. Choose the appropriate Location option: Replace, Append, Before, or After.

Visual FoxPro relocates all of the menu titles you've defined. If you want to relocate some but not all of them, drag the mover buttons next to the appropriate menu titles in the Menu Designer.

Additionally, you can specify the location of menu titles when the user edits an object in your application. If you include an object and the user activates it, your menu titles will not appear on the resulting menu bar unless you indicate that you want them there.

To control menu title location during object visual editing

  1. In the Prompt column, select the appropriate menu title.
  2. Choose the button in the Options column to display the Prompt Options dialog box.
  3. Set the Negotiate check box.
  4. Choose one of the following option buttons:
    • None does not place the menu title on the menu bar. Choosing None is the same as not choosing any option.
    • Left places the menu title in the left group of menu titles on the menu bar.
    • Middle places the menu title in the middle group of menu titles on the menu bar.
    • Right places the menu title in the right group of menu titles on the menu bar.

If you don't choose Left, Middle, or Right, the menu title will not appear on the menu bar when the user edits an object. For more information about editing objects visually, see Sharing Information and Adding OLE.

Saving and Restoring Menus

You can save and restore menus on the stack with the PUSH MENU and POP MENU commands. Pushing and popping is useful when you want to remove a menu temporarily, replace it with another, and then restore the original later on.

The number of menus you save in memory is limited only by the amount of available memory.

Tip Check the available memory with the SYS(1016) function. For example, to check how much memory your menu system uses, call SYS(1016), push the menu on the stack, and then call SYS(1016) again.

Creating a Default Procedure for a Menu System

You can create a global procedure that applies to your entire menu system. Such a procedure runs whenever a menu without an assigned procedure is chosen.

For example, suppose you're developing an application for which some menus do not yet have submenus, procedures, and so on. For these menus, you can create a code stub that executes when the menus are chosen. For instance, you could create a general procedure that includes this function:

MESSAGEBOX("Feature not available")

To create a default procedure

  1. Open the menu system you're designing.
  2. From the View menu, choose General Options.
  3. Assign the procedure by doing one of the following:
    • Write or call a procedure in the Procedure box.

      -or-

    • Select Edit and then OK to open a separate editing window and write or call a procedure.

Setting the System Menu

You can manipulate menus that use the Visual FoxPro menu system by using the SET SYSMENU command. With SET SYSMENU, you can disable your menus, add and remove items from your menus, restore the default Visual FoxPro menus, and control access to your menus during program execution.

See Also

Testing and Debugging a Menu System | General Options dialog box | Creating Custom Toolbars | Customize Toolbar Dialog Box | Designing Menus and Toolbars | Customizing the Visual FoxPro Environment


Creating Reports and Labels

After you collect and organize your data, you can add reports or labels to your application to print the data or display it on the screen.

In this section

Creating a Report Layout
Explains the various ways to create report layouts in Visual FoxPro.
Controlling Data Sources
Describes how to control the use of data in your report.
Protecting a Report's Data Session
Explains how to protect your report's data session from being affected by the global data session.
Modifying Layouts
Describes how to change the layout of your report.
Defining the Report Page
Describes how to set up a report using the tools provided in the Report Designer.
Adding, Copying, Deleting Report Controls
Explains how to use report controls in your Visual FoxPro report or label.
Setting Print Options for Controls
Explains how to adjust when and where a report control will print.
Saving a Report as HTML
Explains how to save a report in HTML format.
Integrating Queries and Reports
Describes how to implement a query in your Visual FoxPro report.
Generating Forms and Reports
Explains how to generate a report or label without writing any code.

Related Sections

Working with Data
Learn how to create effective applications with indexes, tables, tables and databases based on your data requirements.
Creating the Application
Discusses how to create a Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Working with Projects
Defines a project configuration and a group of files that produce a program or final binary file or files.
Application Planning
Describes how careful planning saves time, effort, and money, and how many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.


Creating a Report Layout

You can create report layouts three ways in Visual FoxPro:

  • Create simple single or multiple table reports with a Report Wizard.
  • Create a simple report from a single table with Quick Report.
  • Modify existing reports or create your own report with the Report Designer.

With each of these methods, you create a report layout file you can modify using the Report Designer. The Report Wizard is the easiest way to start a report and automatically offers many of the Report Designer's customization features. The Quick Report is the fastest way to create a simple layout. If you create a report directly in the Report Designer, the Report Designer presents you with a blank layout.

Using a Report Wizard

Whenever you want to create a report, you can use a report wizard to help you set it up. The wizard asks you a series of questions and creates a report layout for you based on your answers.

Visual FoxPro provides these report and label layout wizards:

  • Report
  • One-to-Many
  • Label
  • Mail Merge

The wizard you choose depends on the general layout and complexity of your report.

To use a report wizard

  1. In the Project Manager, select Reports.
  2. Choose New.
  3. Choose Report Wizard.
  4. Select the type of report you want to create.
  5. Follow the instructions on the wizard screens.

You can also access the report wizards from the menu by choosing Wizards from the Tools menu, and selecting Report.

Once you use a wizard, you can use the Report Designer to add controls and customize your report.

Starting the Report Designer

If you do not want to use a report wizard, you can begin with a blank report layout and add controls yourself.

To create a blank report

  1. In the Project Manager, select Reports.
  2. Choose New.
  3. Choose New Report.

    The Report Designer appears.

You can use any of the Report Designer features to add controls and customize your report.

See Also

Report Designer | Creating Reports and Labels | Integrating Queries and Reports | Report Wizard | Report Layout Preparation | Selecting, Moving, and Resizing Report Controls


Report Layout Preparation

You can design your report to display your data in a variety of ways on the printed page. Using the Report Designer or report wizards, you can design comprehensive lists, summaries, or special subsets of data, like an invoice. Designing a report has four main steps:

  1. Determining what type of report to create.
  2. Creating the report layout file.
  3. Modifying and customizing the layout file.
  4. Previewing and printing the report.

Determining the General Layout

Before creating a report, decide the general format you want your report to have. Your report might be as simple as a telephone list based on a single table or as complex as an invoice based on multiple tables. You can also create special types of reports. For example, a mailing label is a special report with a layout designed to fit a special type of paper.

To help you choose a layout, here are some descriptions of general layouts, their common uses, and examples.

Layout Type | Description | Examples
Column | One record per row with fields placed horizontally across the page | Group/Total report1 Financial reports Inventory Sales summary
Row | One column of records with fields placed vertically down the side | Lists
One-to-many1 | One record or one-to-many relationship | Invoices Account statements
Multi-column | More than one column of records with fields placed vertically down the left margin | Telephone directory Business cards
Label | More than one column of records with fields placed vertically down the left margin; printed on special paper | Mailing labels1 Name tags

1 Layouts that have an associated report wizard

After you select the general report layout that meets your needs, you can create the report layout file with the Report Designer.

Understanding Report Layout Files

A report layout file, which has an .frx file extension, stores the specifications for the report. Each report file also has an associated file with an .frt file extension. The report file specifies the fields you want, the text to print, and the placement of the information on a page. To get the information from your database to the printed page, you process it by printing the report file. The file does not store the values for each of the data fields, only placement and format information for that particular report. The values can change each time you run the report, depending on the changes that have occurred in the fields of the data source used by the report file.

See Also

Report Designer | Creating Reports and Labels | Integrating Queries and Reports | Creating a Report Layout


Creating a Mailing Label Layout

A label is a multicolumn report layout that has special column settings that match a particular label paper. In Visual FoxPro, you can create labels quickly with the Label Wizard or the Label Designer.

Using the Label Wizard

The Label Wizard is an easy method for creating labels. Once you create the label file with the wizard, you can use the Report Designer to customize it.

To create labels with the Label Wizard

  1. In the Project Manager, select Labels.
  2. Choose New.
  3. Choose Label Wizard.
  4. Follow the instructions on the wizard screens.

You can use the label layout as it is or customize it using any of the features described for reports. You can also launch the Add Label wizard by clicking the New Label button of Step 2 of the Label Wizard.

Starting the Label Designer

If you do not want to use the wizard to create your labels, you can create a layout with the Label Designer. The Label Designer is like the Report Designer and uses the same menus and toolbars. The two designers are different in the default page and paper they use. The Report Designer uses a full page of standard paper. The Label Designer set its default page and paper to match standard label paper.

To create a label with the Label Designer

  1. In the Project Manager, select Labels.
  2. Choose New.
  3. Choose New Label to display the New Label dialog box.
  4. From the New Label dialog box, select a label layout and choose OK.

    The Label Designer displays a page definition for the label layout you selected.

You can specify a data source and insert controls just as you would for a report.

See Also

Creating a Report Layout | Protecting a Report's Data Session | Project Manager | Add Label wizard | Report Designer | Creating Reports and Labels | Adding Label Controls


Controlling Data Sources

You can control the data in your report through the data sources you choose, and you can manipulate and combine raw data with report variables. Report variables store values that are calculated and used in a report. To control the data sources for a report, you can define a data environment that is stored with the report or you can activate specific data sources in code each time you run a report. For more information about using the Data Environment Designer, see Creating Forms.

To | Add
Always use the same data sources. | Tables or views to the report's data environment.
 | DO query or SELECT - SQL to the Init event of the report's data environment.
Use separate sets of data sources. | USE table, USE view, DO query, or SELECT - SQL to the Click event or other code that precedes a REPORT or LABEL command.

If you use a table as the data source, use aliases on the fields in the report only if you don't plan to use the report with any other data source than the table itself. If you use a view or query as the data source and aliases are included in the report controls, the report might display the same record repeatedly on the report page.

Controlling Record Order

You can use the data sources used by the report to control the order the records print in your report. The records are processed and printed in the order they appear in the table, view, or query. To order the records in a table, you can set an index in code or as part of the report's data environment. For a query, view, or SELECT – SQL code, you can use the ORDER BY clause. If you don't order the records using the data sources, the only way to use just the report to order the records is through the ORDER property on a cursor in the data environment.

Controlling Record Selection

In addition to the order records appear in the report, you can select which records are printed by using the data source, the report printing options, or a combination of both.

To use | Add
View or query | Conditions in the Filter tab
SELECT - SQL | WHERE or HAVING clause
Report Designer | Setting in the Print Options dialog box
REPORT command | Scope, FOR, or WHILE expressions
Table | Filtered index

See Also

Displaying Results in a Window | Protecting a Report's Data Session | Refining Page Layout | Integrating Queries and Reports | Adding Label Controls | Selecting, Moving, and Resizing Report Controls | Adding, Copying, and Deleting Report Controls | Data Grouping in Layouts


Protecting a Report's Data Session

To prevent your report's data session from being affected by the global data session as a result of changes made in other designers, you can set the report's data session to Private.

To set a private data session

  • From the Report menu, choose Private Data Session.

If you want to display your query results in a graph, you can use the Graph Wizard, the Query Designer, or a SELECT - SQL command. To use the Query Designer or a SELECT - SQL command, follow the steps below. You need to include at least one numeric field in your result set to create a graph. After completing the query, you can select one of six types of graphs, each with two variations.

To modify the graph

  1. Browse the table containing the graph.
  2. Double-click the general field to display the graph.
  3. Double-click the graph to open Microsoft Graph and display the Microsoft Graph toolbar.
  4. Modify the graph in Microsoft Graph.

See Also

Creating Reports and Labels | Refining Page Layout | Using Expressions and Functions in Field Controls | Setting the Data Environment | Data Environment Designer | Programming for Shared Access | Graph Wizard | Query and View Designers | SELECT - SQL


Modifying Layouts

If you have a blank report or label, or the wizard or Quick Report generates a report that does not quite fit your needs, you can modify it in the Report Designer.

In the bands of the Report Designer, you can insert a variety of controls that hold the labels, fields, variables, and expressions that you want in the printed report. For example, in a phone list layout, you would place the field controls for the names and phone numbers as well as label controls and column headings at the top of the list. To enhance your report's visual appeal and readability, you can add line, rectangle, and rounded rectangle controls. You can also include picture controls.

You can open your report or label in the Report Designer to modify and customize the layout.

To modify a generated report or label

  1. In the Project Manager, select a report or label.
  2. Choose Modify.

You use the bands of the report to determine what each page, group, and the beginning and end of your report looks like. Report bands can be resized. In the report bands, you add report controls, then move, copy, resize, align, and adjust them to arrange the text and fields in your report.

See Also

Quick Report | Report Designer | Refining Page Layout | Project Manager Window | Creating Reports and Labels | Integrating Queries and Reports | Protecting a Report's Data Session | Adding Label Controls


Refining Page Layout

You can refine the layout of your report pages by defining multiple columns and changing the area of the page reserved for a band by changing the height of each band.

Defining Multiple Columns on a Page

To create phone directories, mailing labels, or other types of listings, you can define multiple columns per page.

To define a multi-column report

  1. From the File menu, choose Page Setup.

    Page Setup dialog box with columns defined

  2. In the Columns area, enter the number of columns for the page. This is the same as the number of records you want to print across the page.
  3. In the Width box, enter a value for column width.
  4. In the Spacing box, enter a value for the space you want to appear between each column.
    Tip If you're printing groups set to start on a new page, don't use the Print Order option.
  5. Choose OK.

    The Report Designer reflects your changes.

If your layout already contained report controls in the Detail band, you may need to move or resize them to fit within the boundaries of the new column.

Setting Report Band Height

While designing your report, you can change the height of a report band. The height of a report band determines the amount of space that each report band uses on the page within the page margins. For example, if the Title band is set at a half inch, the Title will appear in the first half inch of space after the top margin. The detail band shows the amount of space devoted to each printed record. The following information applies to all of the report bands. You can set additional parameters for Group Header and Footer bands.

To resize a band

  • Drag the band's bar to the appropriate height.

    Use the ruler to the left as a guide. The ruler's measurement is specific to the height of the band and does not include the page margins.

    Tip You cannot make a band shorter than the height of the controls in the layout. Move the controls within the band first, and then reduce the height.

To set a precise band height

  1. Double-click the bar for the appropriate band.

    A dialog box for the band appears.

  2. In the Height box, enter a value for the height.
  3. Choose OK.

See Also

Protecting a Report's Data Session | Using Expressions and Functions in Field Controls | Creating Reports and Labels | SELECT - SQL | Data Grouping in Layouts


Data Grouping in Layouts

After designing the basic layout, you may decide that grouping the records by certain fields or other criteria would make the report easier to read. Grouping allows you to separate groups of records visually and display introductory and summary data for each group. The group break is based on a grouping expression. This expression is usually based on one or more table fields but it can be as complex as you like.

When you have groups, your report layout has Group Header and Footer bands, to which you can then add controls. Typically, Group Header bands contain the Field control for the field used for the group. You may add lines, rectangles, rounded rectangles, or any label you want to appear before the first record in a group. Group Footers often contain group totals and other summary information for the group.

You can also specify other options for the groups:

  • Printing text in headers and footers to identify specific groups
  • Printing each group on a new page
  • Resetting page numbers when groups are printed on a new page

If the data source is a table, the records are probably not in the appropriate order for grouping. You can sort and order the data appropriately by setting an index on the table, using an ordered view in the data environment, or using a query as the data source to display the records in groups. The report layout does not actually sort and order your data but processes the records in the same order that they exist in the data source. Sorting and ordering must be done with a view, index, or other form of data manipulation outside the layout.

For example, if a group breaks at the Region field each time the report processes a different region value, it produces a group. It does not recognize that a country at the beginning of the table should be sorted to group with the same country at the end of the table.

See Also

Data Placement Preparation | Refining Page Layout | Modifying Your Layout | Creating Reports and Labels | Integrating Queries and Reports | Adding a Single Group Report


Defining the Report Page

When you plan a report, you usually have an idea of what the page will look like. For example, you know the margins, the type of paper, and the layout you want. This topic describes setting the margins, the page orientation, and the height for the bands of the report page.

Setting the Margin, Paper Size, and Orientation

You can set the left margin, paper size, and orientation for your report, as well as, the column widths and space between columns for a multicolumn report. In this context, the word "columns" refers to the number of records that print across the page, not the number of fields from a single record. The Report Designer does not display these settings. It shows only the area within the margins that contains one record in a column on the page. Also, if your report has columns and you change the left margin, the width for the column will automatically change to accommodate the new margin.

If you change the paper size and orientation settings, make sure that the orientation is correct for the paper size you select. For example, if you select an envelope, the orientation should be set to Landscape.

To set the left margin

  1. From the File menu, choose Page Setup.
  2. To set the margin, enter a number for the margin in the Left margin box.

    The page image changes to display the new margin.

  3. To select a paper size, choose Print Setup.
  4. In the Print Setup dialog box, select a paper size from the Size list.
  5. To select paper orientation, choose an orientation in the Orientation area, and then choose OK.
  6. In the Page Setup dialog box, choose OK.

Defining the Page Header and Footer

The controls placed in the Page Header or Page Footer bands appear once on each page of the report. A report that has many pages should include the report name, page number, date, and labels (if appropriate) in a header or footer.

Defining the Detail Band

Typically, the controls placed in the Detail band print once for each record.

Adding Title and Summary Bands

The Title band holds information that prints once at the beginning of the report and the Summary band holds information that prints once at the end of the report. Both the title and the summary can be on their own page. Fields with totaling expressions become grand totals when placed in the Summary band.

To add a title or summary band

  1. From the Report menu, choose Title/Summary.
  2. Select the bands you want.
  3. If you want the band to appear on its own page, select New Page.
  4. Choose OK. The Report Designer shows the new bands.

See Also

Creating Reports and Labels | Adding Lines, Rectangles, and Circles, | Adding a Picture to a Report | Formatting Field Controls | Report Designer


Data Placement Preparation

Once you have a report layout, you can modify the placement of the data on the report page. Using the bands in the Report Designer, you can control where data is printed on the page. Your report layout can have several bands.

A report can also have multiple group bands or bands for a column header and footer. You can add these bands using the procedures in Defining the Report Page and Data Grouping in Layouts. You can use the table below to determine which bands you want to use.

Use this band | To print | Use this command
Title | Once per report | Choose Title/Summary from the Report menu.
Page header | Once per page | Available by default.
Column header | Once per column | Choose Page Setup from the File menu and set Column Number greater than 1.
Group header | Once per group | Choose Data Grouping from the Report menu.
Detail band | Once per record | Available by default.
Group footer | Once per group | Choose Data Grouping from the Report menu.
Column footer | Once per column | Choose Page Setup from the File menu and set Column Number greater than 1.
Page footer | Once per page | Available by default.
Summary | Once per report | Choose Title/Summary from the Report menu.

You can place any of the report controls in any of the bands. You can also add user-defined functions that are processed when the report is run.

See Also

Using Expressions and Functions in Field Controls | Data Grouping in Layouts | Creating Reports and Labels | Defining the Report Page | Integrating Queries and Reports | Data Grouping in Layouts | Adding a Single Group Report


Adding a Single Group Report

A single group report has one level of data grouping based on an expression you enter. For example, you can base a group on the field Country to print all records for the same country together. The data source must be ordered by the field Country.

To add a group

  1. From the Report menu, choose Data Grouping.
  2. In the first Group box, type the group expression.

    -or-

    Choose the dialog button to create an expression in the Expression Builder.

  3. In the Group Properties area, select the properties you want.
  4. Choose OK.

After adding the expression, you can place any controls you want in the bands. Usually, the Field control used for grouping is moved from the Detail band to the Group Header band.

See Also

Data Grouping in Layouts | Adding Multiple Data Groupings | Creating Reports and Labels | Changing a Group Band | Deleting a Group Band | Changing the Grouping Order | Expression Builder Dialog Box | Data Grouping Dialog Box | Data Placement Preparation


Adding Multiple Data Groupings

You can define up to 20 levels of data grouping within a report. Nested groups are helpful for organizing data and totaling expressions for different levels.

To choose a level for a grouping, estimate how often the value might change, then define the group that will change most often first. For example, your report might need a grouping by region and a grouping by city. The value of a city field changes more than the value of a region field; therefore, the city should be the first of the two groups and the region should be the second. In this multiple group report, the table must be sorted or indexed on a key expression such as Region+City.

To add multiple groups

  1. From the Report menu, choose Data Grouping.
  2. In the first Group box, type the group expression.

    -or-

    Choose the dialog button to create an expression in the Expression Builder.

  3. In the Group properties area, choose the properties you want.
  4. Choose Insert and repeat steps 2 and 3 for each grouping expression.
  5. Choose OK.

Groups are numbered in the Data Grouping list in the order they are created. In the Report Designer, the names of the group bands contain the number of the group and a truncated group expression. The group headers and footers with the lowest number appear closest to the Detail band.

See Also

Adding a Single Group Report | Changing a Group Band | Data Grouping in Layouts | Deleting a Group Band | Changing the Grouping Order | Data Placement Preparation | Expression Builder | Report Designer


Changing the Grouping Order in a Report

You can change the order of groups in a report after they have been defined. When groups are reordered, all controls defined in a group band are moved to the new location. Reordering groups does not change any previously defined controls. If boxes or lines have been positioned relative to the top or bottom of a group band, they will remain anchored in that band.

To change the order of the groups

  1. From the Report menu, choose Data Grouping.
  2. Select the mover button to the left of the group you want to move and drag it to its new position.

See Also

Deleting a Group Band | Data Grouping in Layouts | Changing a Group Band | Adding Multiple Data Groupings | Creating Reports and Labels


Changing a Group Band in a Report

You can change the group's expression and group printing options.

To modify a group band

  1. From the Report menu, choose Data Grouping.
  2. In the Data Grouping dialog box, select a group expression to change.
  3. Enter the new expression.

    -or-

    Choose the dialog button to change the expression in the Expression Builder.

  4. Change the grouping options as necessary.
  5. Choose OK.
  6. In the Data Grouping dialog box, choose OK.

See Also

Adding Multiple Data Groupings | Deleting a Group Band | Data Grouping in Layouts | Changing the Grouping Order | Refining Page Layout | Creating Reports and Labels | Data Placement Preparation | Expression Builder


Deleting a Group Band in a Report

If you no longer need a particular group on your report layout, you can remove it.

To delete a group band

  1. From the Report menu, choose Data Grouping.
  2. Select the group you want to delete.
  3. Choose Delete.

    The group band is removed from the layout. If the group band contains controls, you are prompted to delete the controls as well.

See Also

Changing a Group Band | Changing the Grouping Order | Data Grouping in Layouts | Refining Page Layout | Controlling Report and Label Output | Creating Reports and Labels | Data Placement Preparation


Adding, Copying, and Deleting Report Controls

You can insert the following types of report controls in your report and label layouts.

To display | Choose this control
Table fields, variables, and other expressions | Field
Literal text | Label
Straight lines | Line
Boxes and borders | Rectangle
Circles, ovals, boxes with rounded corners, and borders | Rounded Rectangle
Bitmaps or general fields | Picture/OLE Bound

After placing the controls, you can change their format, size, color, position, and print options. You can also add a comment to each control for your reference only; it does not actually print in the report.

Adding Controls with Quick Report

Quick Report is a timesaving feature that automatically creates a simple report layout for you. You select basic report components, then Visual FoxPro creates the layout using your selections.

Tip You can use Quick Report in existing report files if the Detail band is empty. If the Page Header band contains controls already, Quick Report preserves them.

To create a Quick Report

  1. In the Project Manager, select Reports.
  2. Choose New.
  3. Choose New Report.
  4. From the Report menu, choose Quick Report.
  5. Select the table you want to use, and then choose OK.
  6. Select the field layout, title, and alias options you want.
  7. If you want to select fields for the report, choose Fields and complete the Field Picker dialog box.
  8. Choose OK.

The options you choose are reflected in the report layout.

You can save, preview, and run the report as it is.

Note Quick Reports do not add general fields to the report layout.

Adding a Comment to a Control

While creating or changing a control, you might want to include a description. The dialog box for each control offers a comment box. These comments are saved with the layout file but do not appear in the printed report or label.

To add a comment to a control

  1. Double-click the control.
  2. In the control's dialog box, enter your comment in the Comment box.

Choose OK.

Copying and Deleting Report Controls

You can copy and delete any of the controls on the layout individually or as a group.

To copy controls

  1. Select the controls.
  2. From the Edit menu, choose Copy then Paste.

    A copy of the controls appears below the original set.

  3. Drag the copy into position on the layout.

To delete controls

  1. Select the controls.
  2. From the Edit menu, choose Cut or press the DELETE key.

See Also

Data Placement Preparation | Using Expressions and Functions in Field Controls | Data Grouping in Layouts | Creating Reports and Labels | Defining the Report Page | Integrating Queries and Reports | Project Manager | Report Designer | Adding Label Controls | Adding a General Field | Selecting, Moving, and Resizing Report Controls


Adding Label Controls to a Report

Label controls are the literal text characters that you want to appear on the report. For example, the label "Grand Total" identifies the contents of a field control containing a total expression.

To add a label control

  1. From the Report Controls toolbar, choose the Label button.
  2. In the Report Designer, click to place the control.
  3. Type the characters for the label.

    You can edit as you would in a text editor: use the ENTER key to adds lines or the Edit menu to cut, copy, and paste text.

To edit a label control

  1. In the Report Designer, choose the Label button, and then click the label you want to edit.
  2. Type the changes.

After placing the text, you can change its font and colors.

See Also

Creating Reports and Labels | Adding, Copying, and Deleting Report Controls | Report Designer | Using Expressions and Functions in Field Controls | Integrating Queries and Reports | Adding a General Field


Adding Lines, Rectangles, and Circles to a Report

Lines, rectangles, and circles add visual interest to the layout of your report. You can use them to separate or emphasize parts of your report.

Drawing Lines

You can add vertical and horizontal lines to your report layout with the Line control. Often, you might want lines between the details contained in the body of the report and the information in the header and the footer.

To draw a line

  1. From the Report Controls toolbar, choose the Line button.
  2. In the Report Designer, drag to size the line.

After drawing the line, you can move or resize it, or change its thickness and color.

Drawing Rectangles

You can draw rectangles on your layout to visually organize the information that prints on the page. You can use them as borders around report controls, report bands, or the entire page.

To draw a rectangle

  1. From the Report Controls toolbar, choose the Rectangle button.
  2. In the Report Designer, drag to size the rectangle.

Drawing Rounded Rectangles and Circles

You can draw circles or rectangles with a variety of rounded corners.

To draw a rectangle or circle

  1. From the Report Controls toolbar, choose the Rounded Rectangle button.
  2. In the Report Designer, drag to size the control.
  3. Double-click the control.
  4. In the Style area, select the corner style you want.
  5. If appropriate, set position options.
  6. Choose OK.

Changing Line Thickness or Style

You can change the thickness of lines used for vertical and horizontal lines, rectangles, and rounded rectangles from a hairline to 6 points wide. You can also change the style of the line from dotted to a combination of dots and dashes.

To change line size or style

  1. Select the line, rectangle, or rounded rectangle controls you want to change.
  2. From the Format menu, choose Pen.
  3. From the submenu, select the appropriate size or style.

See Also

Formatting Field Controls | Adding, Copying, and Deleting Report Controls | Adding a Picture to a Report | Report Designer | Changing Line Thickness or Style | Line control | Creating Reports and Labels


Adding a Picture to a Report

You can insert a picture as part of the report. For example, a company logo can appear in the page header of an invoice. Pictures from a file are static; they do not change with each record or group of records. If you want to change the display depending on the record, insert a General field instead.

To add a picture

  1. From the Report Controls toolbar, choose the Picture/OLE Bound Control button.
  2. In the Report Designer, drag to size the picture.
  3. In the Picture from area, select File.
  4. In the File box, type a file location.

    -or-

    Choose the dialog button to select a graphic file.

  5. If appropriate, set the size, position, or print options.
  6. Choose OK.

See Also

Adding Lines, Rectangles, and Circles | Formatting Field Controls | Adding, Copying, and Deleting Report Controls | Defining the Report Page | Creating Reports and Labels | Adding a General Field | Report Designer


Adding a General Field to a Report

You can insert a General field containing OLE objects into your report.

To insert a General field

  1. In the Report Designer, add a Picture/OLE Bound control.
  2. In the Picture From area, select Field.
  3. In the Field box, type a field name.

    -or-

    Choose the dialog button to select a field or variable.

  4. Choose OK.

    The placeholder for the General field appears in the frame you defined. By default, the picture retains its original size.

See Also

Report Designer | Adding Label Controls | Creating Reports and Labels | Adding, Copying, and Deleting Report Controls | Report Designer | Using Expressions and Functions in Field Controls | Integrating Queries and Reports | OLE Bound Control


Using Expressions and Functions in Field Control in a Report

You can include field controls in your report or label to display values from a variety of expressions, including fields from tables and views, variables, and calculations. The following sections describe some commonly used expressions and functions such as multiple fields, dates, and page numbers.

Adding Field Controls

You can add field controls in several ways.

To add table fields from the data environment

  1. Open the report's data environment.
  2. Select a table or view.
  3. Drag fields onto the layout.

To add table fields from the toolbar

  1. From the Report Controls toolbar, insert a Field control.
  2. In the Report Expression dialog box, choose the dialog button after the Expression box.
  3. In the Fields box, double-click the name of the field you want.

    The table name and field name appear in the Expression for Field on Report box.

    Note If the Fields box is empty, add a table or view to the data environment. You don't have to keep the table name alias in the expression. You can delete it or you can clear the Expression Builder options.
  4. Choose OK.
  5. In the Report Expression dialog box, choose OK.

After entering the expression, you can change the format or set printing, position, or stretch options.

Inserting Concatenated Field Controls

After you add your table fields, you might notice that they don't print the way you would like on the page. For example, printing the field controls for City, Region, and Postal Code separately produces unwanted spaces between each value. You can trim or concatenate the table fields into one field expression. The space required by each value for this control will vary. You can set the control to adjust for each value.

To combine several table fields into an expression

  1. From the Report Controls toolbar, insert a Field control.
    Tip Size the field to the least amount of room the expression will require. If more space is needed, you can set the control to stretch for larger values, but you can't set it to shrink if less space is needed.
  2. In the Report Expression dialog box, select the dialog button after the Expression box.
  3. In the Expression Builder, select ALLTRIM(expC) from the String box.

    The string function appears in the Expression box with expC selected.

  4. Double-click the first field name you want to appear in the control.

    The field name replaces the expC.

  5. Type a plus sign after the field name or select + from the String functions box.
  6. Type , or select Text from the String functions list and then enter a comma.
  7. Repeat steps 3 and 4 for additional fields to complete the expression and then choose OK.
  8. In the Report Expression dialog box, select Stretch with Overflow.

    When the control is populated, the space allocated to the control adjusts downward to accommodate the value of the expression. For more information about Stretch with Overflow, see Printing Controls with Variable-Length Values.

To combine several fields in an expression, place an ALLTRIM( ) function before each field name, place punctuation inside quotation marks, and place a plus sign between each of the elements in the expression. If the field value lengths don't vary, such as with postal codes or abbreviations, you can insert just the field name, as in this example:

ALLTRIM(city)+", "+region+"  "+postal_code

Notice the spaces in quotes, rather than a comma, to separate the region and the postal code.

For more examples, see the report Invoice.frx in the Visual FoxPro ...\Samples\Solution\Reports directory.

Trimming and Concatenating Character Expressions

To quickly trim and concatenate character expressions in the Expression Builder, you can place commas between character expressions. The value of the expression preceding the comma is trimmed. You can also use semicolons to place the expression on a new line, provided that the trimmed value has a length greater than zero. The following example shows character expressions for fields in a mailing address:

contact_name; address; city, region, postal_code
Note Use these when you don't want to include punctuation in the value.

If you use these methods, make sure the field is set to Stretch with Overflow. For more information, see Printing Controls with Variable-Length Values.

Inserting the Current Date

You can insert a field control that prints the current date.

To insert the current date

  1. From the Report Controls toolbar, insert a Field control.
  2. In the Report Expression dialog box, select the dialog button after the Expression box.
  3. In the Expression Builder, select DATE( ) from the Date list.
  4. Choose OK.
  5. In the Report Expression dialog box, choose OK.

Inserting a Page Number

The Page Header or Footer bands usually contain a page number. If you use a wizard or Quick Report, a page number is inserted for you into the Page Footer band.

To insert a page number

  1. From the Report Controls toolbar, insert a Field control.
  2. In the Report Expression dialog box, select the dialog button after the Expression box.
  3. In the Expression Builder, select _pageno from the Variables list.
  4. Choose OK.
  5. In the Report Expression dialog box, choose OK.
    Tip You can use this procedure to insert any of the system variables from the Variables list into your report.

See Also

Refining Page Layout | Defining Report Variables | Creating Reports and Labels | SELECT - SQL | Adding a General Field | Selecting, Moving, and Resizing Report Controls | Setting a Control's Print Options


Selecting, Moving, and Resizing Report Controls

If you created a report layout that already has controls on it, you can change their placement and size on the report. You can change each control individually or you can select a group of them and treat them as one unit.

To move a control

  • Select the control and drag it to a new position in a report band.

    The control moves by increments into position within the layout. The increments are based on the grid settings. To override the grid, press the CTRL key while you drag the control.

To select multiple controls

  • Drag to draw a selection box around the controls.

    Selection handles appear around each control. While they are selected, you can move, copy, or delete them as a group.

You can associate a group of controls together for more than just the current task by identifying them as a group. For example, you might want to associate a label control and a field control with each other so you can move them without selecting them separately. This feature is also useful after you have formatted and aligned the controls because it preserves their positions with respect to one another.

To group controls together

  1. Select the controls you want to treat as a group.
  2. From the Format menu, choose Group.

    The selection handles move to the outside of the entire group. You can treat the group of controls as a single unit.

To ungroup a group of controls

  1. Select the group of controls.
  2. From the Format menu, choose Ungroup.

    The selection handles appear around each of the controls that were in the group.

Once a control is on your layout, you can change its size individually or you can resize a group of controls to match each other. You can resize any report control except labels; their size is determined by the text, font, and point size.

To resize a control

  • Select the control, then drag one of the selection handles to the desired size.

To match the size of multiple controls

  1. Select the controls you want to have the same size.
  2. From the Format menu, choose Size.
  3. Choose the appropriate option to match the width, height, or size.

    The controls resize to match the option you selected.

Aligning Controls

You can align controls in relationship to each other or you can place them according to the grid provided by the Report Designer. You can align the controls with a particular side or with the center.

To align controls with each other

  1. Select the controls you want to align.
  2. From the Format menu, choose Align.
  3. From the submenu, choose the appropriate alignment option. Visual FoxPro uses the control whose edge is the closest to the direction you selected to align as the anchor.

To align controls manually

  • From the Format menu, clear Snap to Grid.

You can also align controls using the Layout toolbar. Using the toolbar, you can align with the control farthest from the side you select by holding the CTRL key down while clicking the alignment button.

Align the controls with an edge that all of the selected controls have open and away from each other. Controls that are in a row and are selected to align with their right side, or left side, will pile on top of each other. Likewise, controls that are in a vertical line and selected to align with their top, bottom, will overlap.

To center controls within a band

  1. Select the controls you want to align.
  2. From the Format menu, choose Align.
  3. From the submenu, choose Center Vertically or Center Horizontally.

    The controls move to the vertical or horizontal center of their respective band.

Control Placement with the Status Bar or Grid

You can place a control in a specific position on the report page by using the status bar or the grid. By default, controls snap into position according to the grid. You can choose to turn off the snap feature and to show or hide the grid lines. Grid lines can help you in positioning controls on the layout.

To place a control at a specific position

  1. From the View menu, choose Show Position.
  2. Select the control, then move the control into place using the position information on the status bar.

To display grid lines

  • From the View menu, choose Grid Lines.

    A grid appears in the report bands.

To change the measurements of the grid

  1. From the Format menu, choose Set Grid Scale.
  2. In the Set Grid Scale dialog box, enter the number of pixels for the horizontal width and vertical height of each square in the grid.

See Also

Adding a General Field | Defining Report Variables | Using Expressions and Functions in Field Controls | Creating Reports and Labels | Integrating Queries and Reports


Defining Report Variables

To manipulate data- and display-calculated results in a report, you can use report variables. Using report variables, you can calculate values and then use those values to calculate subsequent values.

To define a report variable

  1. Open or create a report.
  2. From the Report menu, choose Variables.
  3. In the Report Variables dialog box, select the Variables box and type a name for the variable.
  4. In the Value to store box, type a field name or any other expression.
  5. If appropriate, select a calculation option.
  6. If appropriate, in the Initial value box, type an expression that sets the initial value.
  7. Choose OK.

    You can use the variable in any expression you enter in the report.

To count all the Canadian entries in the Company table, use this expression and select Count as the calculation option.

IIF(country="Canada",1,0)

The following example shows three variables for a simple time sheet:

To store this value Create this variable Using this expression
Time employee arrived
tArrive

hour_in + (min_in / 60)
Time employee left
tLeave

hour_out + (min_out / 60)
Total time employee was present
tDayTotal

tLeave - tArrive

You can use the tDayTotal variable in a variety of other calculations, such as the number of hours worked in a week, a month, or a year; the average number of hours worked each day; and so on.

For examples of report variables, see the reports Percent.frx and Invoice.frx in the Visual FoxPro ...\Samples\Solution\Reports directory.

Reordering Report Variables

Report variables are evaluated in the order that they appear in the list and can affect the value of expressions that use them. For example, if variable 1 is used to define the value of variable 2, variable 1 must appear before variable 2. In the previous time sheet example, tArrive and tLeave must precede tDayTotal.

To change the order of report variables

  1. From the Report menu, choose Variables.
  2. In the Variable box, drag the button to the left of the variable to rearrange the order.
  3. Choose OK.

Setting a Variable's Initial Value

If you use a variable in calculations, be sure that you initialize the variable with a non-zero value to avoid a division-by-zero error. If you don't specify a value, Visual FoxPro assigns a default value of 0.

To set a variable's initial value

  1. From the Report menu, choose Variables.
  2. In the Variable box, select the variable you want to set.
  3. In the Initial value box, enter the value.
  4. Choose OK.

If you reorder the groups in your report, your report variables might not be resetting on the correct field. For example, if your report has two groups, the first grouping by country and the second grouping by date, and you switch the order of the groups, the variables still reset according to the original positions of the groups.

You can change the value of a calculation by specifying when the variable is reset. By default, Visual FoxPro resets the report variables at the end of the report.

To reset a variable at the end of a report, a page, or a column

  1. From the Report menu, choose Variables.
  2. In the Reset at box, choose an option.
  3. Choose OK.

To reset a variable on entry or exit of any band

  1. In the Report Designer, open the report.
  2. Double-click the bar for the report band.
  3. In the Run expression area of the band's dialog box, choose the dialog button at the end of the On entry or On exit box.
  4. Enter an expression to reset the variable each time the band is entered or exited.

See Also

Using Expressions and Functions in Field Controls | Formatting Field Controls | Creating Reports and Labels | SELECT - SQL | Selecting, Moving, and Resizing Report Controls


Formatting Field Controls in a Report

After inserting a field control, you can change the control's data type and print format. Data types can be Character, Numeric, or Date. Each of these data types has its own format options, including the option to create your own format template. The format determines how the field is displayed when the report or label is printed.

You can enter format functions directly in the Expressions box of the Report Expression dialog box or you can select options from the Format dialog box.

Typically, you might convert all alphabetical output to uppercase, insert commas or decimal points in numeric output, display numeric output in currency format, or convert one date format to another.

Formatting Options for Report Controls

For field controls, you can set a variety of format options for each data type.

To format a field control

  1. Choose the Field control.
  2. In the Report Expression dialog box, choose the dialog button after the Format box.
  3. In the Format dialog box, select the data type for the field: Character, Numeric, or Date.

    The Editing options area displays the formatting options available for that data type.

    Note This data type applies only to the report control. It reflects the data type of the expression and doesn't change the data type of the field in the table.
  4. Select the justification and format options you want.

The Format dialog box displays different options depending on the data type you choose. You can also create a format template by entering characters in the Format box.

Justifying Text in a Field

You can justify field contents within the control in two ways. This setting does not change the position of the control on the report, only the contents within the space of the control.

To justify text in a field control

  1. Select the controls you want to change.
  2. From the Format menu, choose Text Alignment.
  3. From the submenu, choose the appropriate command.

To justify text in a field

  1. Choose the Field control.
  2. In the Report Expression dialog box, choose the dialog button after the Format box.
  3. In the Format dialog box, select the data type for the field: Character, Numeric, or Date.
  4. Select the justification and format options you want.

Defining Field Format Templates

A format template allows you to customize the format of the field. By entering a combination of characters and codes in the Format box of the Report Expression dialog box or the Format dialog box, you can create a wide variety of print formats. The characters you enter appear as literal text along with the field value. The codes you enter determine the appearance of the field output. For example, if you use the following format template for a 10 -digit numeric field, the characters (parentheses, spaces, and dashes) are printed along with the numeric data.

Format Template | Printed Output
(999) 999-9999 | (123) 456-7890

Changing Fonts

You can change the font and size of text for each field or label control or you can change the default font for the report.

To change fonts and size in a report

  1. Select the control.
  2. From the Format menu, select Font.

    The Font dialog box appears.

  3. Select the appropriate font and point size and then choose OK.

To change the default font

  1. From the Report menu, choose Default Font.
  2. In the Font dialog box, select the appropriate font and point size you want as the default and then choose OK.

    Only the controls inserted after you changed the default font will reflect the new font settings. To change existing objects, select them all, and then change the font using the Font option on the Format menu.

Cropping a Picture or OLE Object

The picture or OLE object you inserted might not fit the frame you drew when you created the control. By default, the picture or object retains its original size. You can clip or scale it to fit into your frame.

If the picture or OLE object is bigger than the frame you created in the Report Designer, only a portion of the picture or object appears in the frame. The picture or object is anchored at the top and at the left of the frame. You cannot see the lower right portion that extends beyond the frame.

To fit a picture in the frame

  1. In the Report Designer, create a Picture/OLE Bound Control.
  2. In the Report Picture dialog box, select Scale picture – Retain shape.

The whole picture appears, filling as much of the frame as possible while retaining its relative proportions. This protects your picture from vertical or horizontal distortion.

To fill the frame with the picture

  1. In the Report Designer, create a Picture/OLE Bound Control.
  2. In the Report Picture dialog box, select Scale picture – Fill the frame.

The whole picture changes to fill the frame that you sized. If necessary, the picture is stretched vertically or horizontally to fit the frame.

To see an example of a report with pictures, see the report Wrapping.frx in the Visual FoxPro ...\Samples\Solution directory.

Centering an OLE Object

The OLE objects included in a General field can vary in shape and size. If the object in a General field is smaller than the frame, it appears in the upper left corner of the frame. You can center it to ensure that all objects smaller than the frame are centered in the frame in the report or label. File pictures don't need to be centered because they don't vary.

To center General field OLE objects

  1. In the Report Designer, create a Picture/OLE Bound Control.
  2. In the Report Picture dialog box, select Center picture.

The printed OLE objects are centered within the area when the report is previewed or printed.

Changing Colors of Report Controls

You can change the color of a field, label, line, or rectangle.

To change colors

  1. Select the controls to change.
  2. In the Color Palette toolbar, choose Foreground Color or Background Color.
  3. Select the color you want.

See Also

Defining Report Variables | Setting Print Options for Controls | Creating Reports and Labels | SELECT - SQL


Setting Print Options for Controls

The general layout and band position of your controls determine the time and place they are printed. You can also set specific print options for each control. Each control has a default size based either on its value (fields and labels) or the size you created (lines, rectangles, and pictures). The length of the control on the layout defines the display width of the control. Because the value of some controls will vary from record to record, you can set the height of the control to stretch downward to display the entire value. If you don't set it to stretch, the value will be truncated within the display width. You cannot resize Label controls, but you can resize all other controls.

Printing Controls with Variable-Length Values

If you want a control to use only the space needed by its value, you can set it to stretch. For example, the values in an expression can vary from record to record. Rather than allot a fixed amount of space on the report that accommodates the longest value, you can set the control to stretch downward to display the entire value. You can set controls below the stretching control to float down the page relative to the stretching control.

Examples of controls set to stretch and float

The stretch option is available for fields, vertical lines, rectangles, and rounded rectangles.

For an example of controls that stretch and float, see the report Wrapping.frx in the Visual FoxPro ...\Samples\Solution\Reports directory.

To set a field to stretch with its value

  1. Double-click the field control to display its dialog box.
  2. Select Stretch with overflow.

Controls that are placed relative to controls that stretch must be set to float or they will be overwritten.

To set a control to float

  1. Double-click the control to display its dialog box.
  2. In the control's dialog box, select Float.
    Caution Some of your data could be overwritten during printing if: (1) you position a field relative to the bottom of the band and include below this field another field that is positioned relative to the top of the band and can stretch; or (2) you position a field relative to the top of the band and include above this field another field that is positioned relative to the top of the band and can stretch.

You can also set lines, rectangles, and rounded rectangles to stretch. They can stretch relative to the band or, if part of a group of controls, they can stretch relative to the largest control in the group.

To set a line or rectangle to stretch

  1. Double-click the control to display its dialog box.
  2. In the Stretch downwards area, select an option.

To print a border around a stretchable control

  1. Draw a rectangle around the stretchable controls.
  2. Double-click the rectangle to display the Rectangle/Line dialog box.
  3. In the Stretch downwards area, select Stretch relative to the tallest object in group.
  4. Choose OK.
  5. Drag a selection box around the rectangle.
  6. From the Format menu, choose Group.

    Selection handles appear at the corners of the rectangle. From now on you can treat all of the controls as one. The rectangle will stretch along with the stretchable field. Regardless of how far down the value in the field stretches, the rectangle will maintain its border around the field. You can place two of these groups side by side in the layout and one will not be affected by the stretching of the other.

To print one stretchable control below another

  1. Insert the two controls one below the other in the layout.
  2. Double-click the top control to display the control's dialog box.
  3. In the Field Position area, select Fix relative to top band, and then choose OK.
  4. Double-click the bottom control to display the control's dialog box.
  5. In the Field Position area, select Float, and then choose OK.

The two record values will print in their entirety and will not overwrite each other.

See Also

Formatting Field Controls | Setting Each Control's Print Options | Creating Reports and Labels | SELECT - SQL


Setting Each Control's Print Options

You can control when and how often each report control is printed in your report. For more information about a control's print options, see Print When Dialog Box.

Suppressing Repeated Values

For field controls, you can suppress values repeated for consecutive records so that the value is printed once for the first record but doesn't appear for subsequent records until the value changes. For example, if you're printing an invoice, and one of the fields contains the date of the transaction, the date would only be printed once for transactions that took place on the same date.

To suppress repeated values

  1. Double-click the control to display the control's dialog box.
  2. Choose Print When to display the Print When dialog box.
  3. In the Print Repeated Values area, select No, and then choose OK.

To repeat only on a new page or column

  1. Double-click the control.
  2. Choose Print When.
  3. In the Print repeated values area, select No.
  4. In the Also print area, select In first whole band of new page/column, and then choose OK.

To repeat when the detail band overflows to a new page or column

  1. Double-click the control.
  2. Choose Print When.
  3. In the Also Print area, select When detail overflows to new page/column, and then choose OK.

Building Print Expressions

You can add expressions to a control: they are evaluated before the field prints. If the expression evaluates to false (.F.), the field will not print. If you add an expression, all of the other options in the Print When dialog box are disabled except Remove Line If Blank.

For examples of Print When conditions, see the reports Colors.frx and Ledger.frx in the Visual FoxPro ...\Samples\Solution\Reports directory.

To add a print expression

  1. Double-click the control.
  2. Choose Print When.
  3. In the Print only when expression is true box, enter an expression.

    -or-

    Click the dialog button to create an expression with the Expression Builder.

Suppressing Blank Lines

Your report may include records that don't contain values for every field control. By default, Visual FoxPro leaves the area for that field blank. You can remove these blank areas to create a more pleasing and continuous display of the information.

To suppress blank lines

  1. Double-click the control that's likely to cause blank lines in the report.
  2. Choose Print When.
  3. Select Remove line if blank.

Visual FoxPro will remove the line from the report if it evaluates to blank. If the field doesn't print or if the table field is empty, Visual FoxPro checks for other controls in the line. If none are found, the line is removed. If you don't select this option and no other controls are on the same line, a blank line is printed.

See Also

Setting Print Options for Controls | Setting Print Options for Groups | Creating Reports and Labels | SELECT - SQL


Setting Print Options for Groups

You can control how groups are printed in your report. Sometimes you may want each group to start on a separate page or you may want to control when the group header prints.

Setting Group Page Breaks

In addition to selecting the field or expression to be grouped, the Data Grouping dialog box allows you to specify page break options for groups.

Choosing a Group Header Option

You might want your groups to appear in the next column for multi-column reports, on a new page for forms, or with a new page numbered at 1. The Data Grouping dialog box offers four options to accomplish these tasks. You can:

  • Start a group on a new column.
  • Start each group on a new page.
  • Reset the page number to 1 for each group.
  • Reprint the group header on each page.

After you enter an expression, you can select these options from the Group Properties area.

Preventing Orphaned Group Headers

Sometimes a group may print partially on one page and then finish on the next. To avoid a group header from printing near the bottom of the page with the majority of records on the next page, you can set the minimum distance from the bottom that a group header will print. If the header would be positioned closer to the bottom of the page than the number of inches or centimeters you enter, Visual FoxPro prints the header on a new page.

To prevent orphaned group headers

  1. From the Report menu, choose Data Grouping.
  2. In the Data Grouping dialog box, choose or enter a value in the Start group on new page box.
    Tip To determine a good value for orphan control, add the Group Header height to one to three times the Detail height.

Printing Suppressed Values When the Group Changes

If repeated values are suppressed, you may want them to print when a particular group changes.

To print repeated values when the group changes

  1. Double-click the control to display the control's dialog box.
  2. Choose the Print When button to display the Print When dialog box.
  3. Select When this group changes.

    The groups defined for the report appear in the box.

  4. Select a group from the box, and then choose OK.

Repeating Group Headers

When a group continues onto the next page, you might want the group header to repeat at the top of the group of continued information. If you have multiple data groups on your report, the header on the subsequent pages will be from the last group in the group list. Place all of the controls you want to print for the group header in the header band of the last group on the list.

To repeat the group header on the next page

  • In the Data Grouping dialog box, select the group you want to repeat and then choose Reprint group header on each page.

    If you don't want to repeat the group header, clear this check box.

See Also

Setting Each Control's Print Options | Controlling Report and Label Output | Creating Reports and Labels | SELECT - SQL


Controlling Report and Label Output

You can control where report and label output is sent by using one of these keywords with the REPORT or LABEL command:

  • PRINT
  • PREVIEW
  • FILE

If you don't use any keywords, the report is sent to the screen or active window.

Selecting Records to Print

When you print a report, you might want to limit the number of records that appear in the report by providing selection criteria. You can:

  • Choose a scope of records by specifying a quantity or range.
  • Build a FOR expression that selects records that match a condition.
  • Build a WHILE expression that selects records until one record is found that doesn't match a condition.

You can use any combination of these options. The WHILE expression overrides the other criteria.

Printing a Quantity or Range of Records

One way you can limit the number of records is to specify a quantity or range of records. Using the Scope option, you can select a single record or a group of records positioned sequentially in the file.

Note The active index and the current record pointer affect the results of the scope options Next and Rest. For example, the next record in a table indexed by last name is probably different than one in a table indexed by state. This doesn't affect the Record option because the number for a record doesn't change when the table is indexed.

To select a limited number of records

  1. From the File menu, choose Print.
  2. In the Print dialog box, choose Options.
  3. In the Print Options dialog box, choose Options.
  4. In the Print and Label Print Options dialog box, choose Scope.
  5. Select the appropriate scope option.
    To print | Choose this scope option
    Every record from the source file | ALL
    A range of records starting with 1 | NEXT
    A specific record by number | RECORD
    The current record plus all of those after it to the end of the file | REST

    Visual FoxPro prints the report using data from the records within the scope you selected.

Printing Records That Match a Condition

If the records you want to select are not sequential within the table, you can build a logical expression that specifies selection criteria a record must meet to be printed. For example, you can choose to print all records with a particular value in a field.

To enter criteria for selecting records

  1. From the File menu, choose Print.
  2. In the Print dialog box, choose Options.
  3. In the Print Options dialog box, choose Options.
  4. In the Print and Label Print Options dialog box, choose Scope.
  5. In the For box, enter a FOR expression.

    -or-

    Make sure the records sources used by the report are open, and then choose the For button to use the Expression Builder.

    Note You don't need to include the FOR command in the expression. For example, type country = "Canada" to see only Canadian data.

    Visual FoxPro evaluates all of the records and prints the report using those records that match the condition in the expression.

Controlling Selection of Records to Print

When printing, you can specify a condition that must be met to continue evaluating and selecting records. You enter this condition as a WHILE expression. As long as the WHILE expression remains true, Visual FoxPro processes the data source. After finding a record that doesn't meet the condition, Visual FoxPro ends the evaluation process and prints the selected records. This option allows you to select records based on information outside the values contained in the fields.

Tip If you use a WHILE expression on a file that hasn't been indexed, the selection process may end before evaluating all of the appropriate records. Before printing the report, be sure the source table has the appropriate index active for the WHILE expression you want to use.

To enter criteria for ending record selection

  1. From the File menu, choose Print.
  2. In the Print dialog box, choose Options.
  3. In the Print Options dialog box, choose Options.
  4. In the Print and Label Print Options dialog box, choose Scope.
  5. In the While box, enter a WHILE expression.

    -or-

    Choose the While button to use the Expression Builder.

    Note You don't need to include the WHILE command in the statement. For example, type sales > 1000 to see only sales above one-thousand dollars.

    Visual FoxPro prints the report using the records it evaluates while the expression is true.

Printing Reports and Labels

If you want to send the report to the printer, you can send it directly to the printer or display the Print Setup dialog box.

To send a report to the printer

  1. From the File menu, choose Print.
  2. Choose OK.
    Note If the data environment is not set, the Open dialog box appears with a list of tables from which you can select.

    Visual FoxPro sends the report to the printer.

    -or-

  • Use the TO PRINTER clause of the REPORT or LABEL command.

For example, the following code sends the report MyReport to the default printer and stops the report from printing on the screen:

REPORT FORM MYREPORT.FRX TO PRINTER NOCONSOLE

To display the Print Setup dialog box before sending the report to the printer

  • Use the TO PRINTER PROMPT clause of the REPORT or LABEL command.

For example, the following code displays the Print Setup dialog box, sends the report MyReport to the default printer, and stops the report from printing in the active window:

REPORT FORM MYREPORT.FRX TO PRINTER PROMPT NOCONSOLE

Previewing Reports and Labels

If you want to display a preview of the report, you can send it to the Preview window in the Report Designer. The Preview window has its own toolbar with buttons that move you from page to page in the report.

Caution If you get the prompt, "Do you want to save changes to your file?", you have selected to close not just the Preview window, but also the layout file. You can select Cancel to return to Preview mode or Save to save your changes and close the file. If you select No, any changes you made to the layout will not be saved.

To preview a report

  1. From the View menu, choose Preview.
  2. In the Print Preview toolbar, choose Previous Page or Next Page to switch pages.
  3. To change the size of the report's image, choose Zoom.
  4. To print the report, choose Print.
  5. To return to design mode, choose Close Preview.

    -or-

  • Use the PREVIEW clause of the REPORT command

For example, the following code displays the report in a modal window:

REPORT FORM MYREPORT.FRX PREVIEW

By default, the Preview window is modal but allows access to the Preview toolbar. If you want to make the preview modeless, you can add the keyword NOWAIT to the REPORT command.

For example, the following code displays the report in a modeless window:

REPORT FORM MYREPORT.FRX PREVIEW NOWAIT

If you want to preview the results in a specific window, you can include the WINDOW clause to specify a window created with DEFINE WINDOW.

REPORT FORM MYREPORT.FRX PREVIEW WINDOW MYWINDOW

Printing Reports to File

If you want to create an electronic version of the report, you can send it to a file formatted for your printer or to an ASCII file. Sending reports to a file allows you to print them in a batch on your printer at a later time.

If you want to create an ASCII file, you can create a file that includes only the text, dashes, and plus signs to represent lines and shapes. Font and color choices are not included. You can also specify the number of characters to place on each line and the number of lines to place on each page.

To print a report to an ASCII file

  • Use the FILE and ASCII keywords of the REPORT command.

The following example defines the variables for the ASCII page, then prints a report called Myreport.frx to an ASCII file name Myfile.txt.

Printing to an ASCII File
Code Comment
_asciirows = nLines
 Define the number of lines per page.
_asciicols = nChars
 Define the number of characters per line.
REPORT FORM MYREPORT.FRX
  TO FILE MYFILE.TXT ASCII
 Run the report.

See Also

Setting Print Options for Groups | Saving a Report as HTML | Creating Reports and Labels | SELECT - SQL


Saving a Report as HTML

You can use the Save As HTML option on the File menu when creating or modifying a report to save the contents of a form or report as an HTML (Hypertext Markup Language) file.

To save a report as HTML

  1. Open the report.
  2. Choose Save As HTML on the File menu. This option is only available when the report has been saved to disk. (You will be asked to save the report if it has been modified.)
  3. Enter the name of the HTML file to create and choose Save.

See Also

Controlling Report and Label Output | Integrating Queries and Reports | Creating Reports and Labels | SELECT - SQL


Integrating Queries and Reports

After you've created the components of your application, you can integrate them. The following illustration shows some ways you can add queries and reports to your application.

Some ways to integrate queries and reports

You can add code that executes a query or a report to the following objects in your application.

  • A button on a form. For more information about forms and buttons, see Creating Forms.
  • An item on a menu or a button on a toolbar. For more information, see Designing Menus and Toolbars.

To add a query, view, or program

  • Add a DO or USE command to the code behind a command button on a form, a button on a toolbar, or a menu item.

    For example, add code similar to one of the following lines:

    DO MYQUERY.QPR
DO MYPROGRAM.PRG
USE myview

You have several options for integrating reports into your application.

  • If you want the user to simply start the report and collect the printout, you can have the user initiate a report by adding the REPORT command to a control on a form, a command on a menu, or a button on a toolbar.
  • If you want to allow your user to enter some variables used in the report, you can gather values from the user just as you did for queries. For example, the user could enter a specified date range that the report will include.
  • If you want the user to create custom reports, you can offer the user the ability to create new reports or modify existing reports with the Report Designer.

To run reports and labels

  • Use the REPORT or LABEL commands.

    For example, you could use code similar to one of the following lines:

    REPORT FORM MYREPORT.FRX
LABEL FORM MYLABEL.LBX

To modify reports and labels

  • Use the MODIFY REPORT or MODIFY LABEL commands.

    For example, add code similar to one of the following lines:

    MODIFY REPORT MYREPORT.FRX
MODIFY LABEL MYLABEL.LBX

To create reports and labels

  • Use the CREATE REPORT or CREATE LABEL commands.

    For example, you could use code similar to one of the following lines:

    CREATE REPORT MYREPORT.FRX
CREATE LABEL MYLABEL.LBX

See Also

Saving a Report as HTML | DO | USE | Creating Reports and Labels | SELECT - SQL | Adding a General Field | Selecting, Moving, and Resizing Report Controls | Collecting User Input with Queries


Generating Forms and Reports

You can use the Application Builder to generate forms and reports without having to write code.

To generate forms or reports

  1. Use the Database Wizard button, the Table Wizard button, or the Select button to locate and choose a data source.

    If you select the Database Wizard or Table Wizard buttons, Visual FoxPro opens the selected wizard for you. After you have used the wizard you will be returned to the Data tab of the Application Wizard.

    When you specify the data source, the grid displays the table name and selected Form and Report controls. The wizard automatically selects standard forms and presentation style for all forms and reports. If you accept the default form style and report style choices, go to Step 4; otherwise, go to Step 2.

  2. If you want to only change the form style, clear the Report check box. If you want to only change the report style, clear the Form check box. If you want to change both, leave them both selected.
  3. Choose the styles you want from the Style controls.
  4. Click the Generate button to create the forms and or reports you have specified.
    Note Because the data grid is cleared after you generate forms or reports, you should choose reports and forms with differing styles in separate 'generate' sessions.

See Also

Data Tab, Application Builder | Creating Reports and Labels | Working with Data


Creating Help

You can add professional polish to your application by adding a Help file in the form of HTML Help or WinHelp.

In This Section

HTML Help
Explains that HTML Help is created with Microsoft HTML Help Workshop, which is included with Visual FoxPro and provides a complete authoring system for HTML Help including backwards compatibility that makes it possible for you to easily create HTML Help files from existing WinHelp projects.
WinHelp 4.0
Describes the WinHelp 4.0 Help Finder window, which is a single dialog box providing access to contents, index, and full-text searching.

Related Sections

Programming HTML Help Features
Describes how you can program your application so that users can access your HTML Help system by adding Help buttons and setting context sensitivity.


HTML Help

HTML Help provides many of the features of WinHelp, and adds the following features:

  • Support for HTML.
  • Support for Microsoft ActiveX and scripting.
  • Support for HTML image formats (.jpg, .gif, .png).
  • Capability to jump from a Help topic to a site on the Internet.
  • Capability to view the HTML code for a Help topic.

HTML Help is created with Microsoft HTML Help Workshop, which is included with Visual FoxPro. HTML Help Workshop provides a complete authoring system for HTML Help, and includes backwards compatibility that allows you to easily create HTML Help files from existing WinHelp projects. To create HTML Help files for your application, consult the online Help for the HTML Help Workshop.

A sample HTML Help project, part of the Solutions sample, is included in a .zip file, Solnhlp.zip, located in the Tools\XSource directory of HOME(0). It includes the following files:

File | Description
Solution.chm | Compiled Help file.
Solution.hhp | Project file - a text file that brings together all the elements of a help project and contains information about how a compiled help file will appear.
Solution.hhk | Index file - contains the index entries (keywords) for your index.
Solution.hhc | Table of Contents file.
Solution.ali | Alias file for context-sensitive Help support. Maps product Ids to Help topics.
Solution.hh | Header file for context-sensitive Help support. Includes product Ids.
Solution.chi | Index file used when you ship .chm files that are likely to remain on a CD-ROM, as in the case of the MSDN Library. The .chi file allows certain navigation information to be installed locally on a hard disk for quick access, while the main content lives on the CD-ROM. A .chi file should not be used in a non-CD-ROM scenario. When a .chi file is not used, all the information that would be in it remains in the .chm itself.
MSDN_ie3.css | Cascading style sheet.
MSDN_ie4.css | Cascading style sheet.
FileName.htm | Source content files.
FileName.gif | Source graphics files.

Planning Access to Online HTML Help

In addition to creating an HTML Help file that contains useful information, you need to provide a means for users of your application to access Help. There are three ways to deliver Help:

  • A Help menu — a menu that appears on the main menu bar of your application.
  • Context-sensitive Help — Help that appears when a user presses F1 (or another key that you specify) while a particular object, control, or menu option is selected.
  • "What's This?" Help — Help that appears when a user calls for help on a particular object or control.

Implementing HTML Help is similar to implementing WinHelp. The following sections describe how you can implement HTML Help for your application.

Planning a Help Menu

A Help menu typically contains commands that provide access to the topics in your Help system. It is strongly recommended to have a single command on your Help menu that opens your HTML Help system. Beyond that, you can place additional commands on the Help menu that provide system information, or copyright and version information about your application.

See Also

Creating Help | Adding Context Sensitivity to HTML Help | Implementing "What's This?" HTML Help | Programming HTML Help Features | WinHelp 4.0


Adding Context Sensitivity to HTML Help

Context-sensitive Help allows users to easily access Help topics relating to what they are doing or seeing in your application at any given time. For example, if a user is viewing a data entry form, context-sensitive Help could provide a topic relating specifically to that data entry form.

You decide the level of detail at which context-sensitive Help is implemented in your application. For example, you can associate a context-sensitive Help topic with a form, or you can associate more detailed Help topics with each control and field on your form.

Context-sensitive Help is typically accessed by pressing F1, but you can specify any key to activate context-sensitive Help with ON KEY LABEL.

Using Context-Sensitive Help on a Form

To implement context-sensitive Help, you must specify a Help file for your application, and then associate specific Help topics with different objects in your application.

To add context-sensitive Help

  1. Specify a Help file for your application.
  2. Assign a Help topic to each object for which you plan to provide context-sensitive Help.

Specifying a Help File

You determine the Help file that can be accessed in your application by including the command SET HELP TO file in your code, where file is the name of your Help file. For example, if your Help file is called Myhelp.chm, you can use the following command:

SET HELP TO MYHELP.CHM

This command is typically included in the setup code for the main program of your application.

Assigning Help Topics

You can assign a Help topic to specific objects in your Visual FoxPro application.

To assign a Help topic to an object

  1. In Design mode, open the object – a form, control, or toolbar, for example – that you want to assign context-sensitive Help to.
  2. View the object's properties.
  3. Set the HelpContextID property to the number representing a specific topic in your HTML Help file.

For more information about mapping HTML Help topics to context ID numbers, consult the online Help for the HTML Help Workshop.

Note To assign Help topics to menu titles or menu commands, you must include the SET TOPIC TO command in the procedure associated with the menu title or menu command.

See Also

HTML Help | Implementing "What's This?" HTML Help | Creating Help | Programming HTML Help Features


Implementing "What's This?" HTML Help

"What's This?" Help is similar to context-sensitive Help because it provides Help related to the specific object or control that currently has focus.

For WinHelp, instead of invoking the Help file and displaying the Help topic in the full default-sized Help window, "What's This?" Help displays the topic in a small pop-up window that disappears as soon as the user clicks anywhere on the screen. "What's This?" Help is useful for providing brief tip-style descriptions or definitions for specific controls.

Unlike WinHelp, HTML "What's This?" Help is displayed in the full default-sized Help window.

You associate "What's This?" Help with a particular form, form control, or toolbar by setting its WhatsThisHelpID property to a number representing a specific topic in your Help file.

Use the following properties and methods to implement "What's This?" Help:

Property | Description
WhatsThisHelp | Set this property to true (.T.) on a form to enable "What's This?" Help for the form and any controls on the form.
WhatsThisButton | Set this property to true (.T.) if you want a "What's This?" Help button to appear in the title bar of the form.
WhatsThisHelpID | For a form, control, or toolbar, set this property to an ID number corresponding to a topic in your HTML Help file.
WhatsThisMode | Use this method to display the "What's This?" Help question mark mouse pointer and enable "What's This?" Help mode. Clicking an object displays the "What's This?" Help topic specified by the WhatsThisHelpID property for the object.

To implement "What's This?" Help

  1. In design mode, open the form you want to enable "What's This?" Help for.
  2. Set the form's WhatsThisHelp property to true (.T.).
  3. To display a "What's This?" Help button in the form's title bar, set the form's WhatsThisButton property to true (.T.).
  4. To associate a "What's This?" Help topic with the form, set the form's WhatsThisHelpID property to an ID number corresponding to a topic in your HTML Help file.
  5. To associate a "What's This?" Help topic with a specific control on the form, select the control and set its WhatsThisHelpID property to an ID number corresponding to a topic in your HTML Help file.

See Also

Adding Context Sensitivity to HTML Help | Programming HTML Help Features | Creating Help | HTML Help


Programming HTML Help Features

You can program your application so that users can access your HTML Help system. Although an HTML Help system can consist of one or more separate files, Help appears to users as part of your application.

You can program your Visual FoxPro application to use graphical Help with the SET HELP TO and SET TOPIC TO commands. SET HELP TO specifies the name of a custom Help file for your application. SET TOPIC TO sets the identifying keyword for a topic in the custom Help file.

Reserving F1

When a user presses F1 in your application, Visual FoxPro can display a context-sensitive Help topic. To do this, assign a Help context ID to a topic in your Help table and assign the same value to the HelpContextID property of your form or control. When the form or control has the focus and the user presses F1, Visual FoxPro displays the matching topic.

Note F1 is enabled for context-sensitive Help by default. Because this is a recognized standard for Help, redefining this key is not recommended.

Including Help Buttons on Forms

If you add Help buttons to your forms, users can access Help more easily. You should especially consider adding a Help button if your user is a novice.

To set context sensitivity and add a Help button

  1. In the Init event for your form, set the HelpContextID property for all the form's objects to the same value you assigned to the Help topic. For example, if the value is 7, you can use the following command:
    THIS.SetAll("HelpContextID", 7)
  2. Add a command button to your form.
  3. Set the Caption property of the command button to Help.
  4. In the Click event of the command button, add the following command:
    HELP ID THIS.HelpContextID
    Tip Save the Help button as a class so that you can easily add it to any form. For more information about saving objects as classes, see Creating Forms.

Distributing a Compiled HTML System.

In addition to the .chm file you create for your HTML Help system, you can use a free-distributable setup program, Hhupd.exe, which will install and register the HTML Help runtime components listed below. Internet Explorer or the Internet Explorer runtime engine must be installed on your users' machines.

Component Name | Description
Hhctrl.ocx | HTML Help ActiveX control
Itss.dll | Dynamic link library that handles compiled HTML
Itircl.dll | Full-text search Dynamic link library
Hh.exe | HTML Help viewer

You will find this setup program in the Redist folder in the folder where HTML Help Workshop has been installed. This setup program can be called from other setup programs, and can be made to run in 'quiet' mode so that it does not interfere with the setup program you may have already created. For a complete list of command line options, run Hhupd.exe/?.

See Also

Implementing "What's This?" HTML Help | WinHelp 4.0 | Creating Help | HTML Help | SET HELP TO


WinHelp 4.0

Use the Microsoft Help Workshop to create Winhelp files. The Microsoft Help Workshop includes a Help Authoring Guide. The Help Authoring Guide (Hcw.hlp) is a graphical Help file that contains much of the information you must have to author a robust Help system.

Choosing Help Features

WinHelp systems can have some or all of the following features:

  • A contents page that provides a hierarchical view of the topics in your Help system.
  • An index, based on keywords you provide, that guides a user to specific information.
  • Full-text search capabilities that allow users to search for information in Help based on specific words and phrases.
  • Text with multiple fonts, font sizes, and colors.
  • Graphics, including bitmaps with multiple resolutions.
  • Macros that automate or extend the operation of the Help system.
  • Hot spots — mouse-sensitive areas you create to give users jumps that link topics; pop-up windows that display additional text; and macro commands that you add to the Help system.
  • Segmented hypergraphics: graphics with one or more hot spots.
  • Secondary windows.
  • Customizable menus.
  • Graphics in Windows metafile format.
  • .DLLs.

Planning Access to Online Help

In addition to creating a WinHelp file that contains useful information, you need to provide a means for users of your application to access Help. There are three ways to deliver Help:

  • A Help menu — a menu that appears on the main menu bar of your application.
  • Context-sensitive Help — Help that appears when a user presses F1 (or another key that you specify) while a particular object, control, or menu option is selected.
  • "What's This" Help — Help that appears as a brief pop-up tip when a user calls for help on a particular object or control.

Planning a Help Menu

A Help menu typically contains commands that provide access to the topics in your Help system. WinHelp 4.0 features the Help Finder window, which is a single dialog box providing access to contents, index, and full-text searching.

It is strongly recommended to have a single command on your Help menu that opens the Help Finder window. Beyond that, you can place additional commands on the Help menu that provide system information, or copyright and version information about your application.

You can call the Help Finder window programmatically using the WinHelp function with the HELP FINDER parameter.

See Also

Programming HTML Help Features | Adding Context Sensitivity to WinHelp | Implementing "What's This?" WinHelp | Programming WinHelp Features | HTML Help | Creating Help


Adding Context Sensitivity to WinHelp

Context-sensitive Help allows users to easily access Help topics relating to what they are doing or seeing in your application at any given time. For example, if a user is viewing a data entry form, context-sensitive Help could provide a topic relating specifically to that data entry form.

You decide the level of detail at which context-sensitive Help is implemented in you application. For example, you can associate a context-sensitive Help topic with a form, or you can associate more detailed Help topics with each control and field on your form.

Context-sensitive Help is typically accessed by pressing F1, but you can specify any key to activate context-sensitive Help with ON KEY LABEL.

Using Context-Sensitive WinHelp on a Form

To implement context-sensitive Help, you must specify a Help file for your application, and then associate specific Help topics with different objects in your application.

To add context-sensitive Help

  1. Specify a Help file for your application.
  2. Assign a Help topic to each object for which you plan to provide context-sensitive Help.

Specifying a Help File

You determine the Help file that can be accessed in your application by including the command SET HELP TO file in your code, where file is the name of your Help file. For example, if your Help file is called Myhelp.hlp, you can use the following command:

SET HELP TO MYHELP.HLP

This command is typically included in the setup code for the main program of your application.

Assigning Help Topics

You can assign a Help topic to specific objects in your Visual FoxPro application.

To assign a Help topic to an object

  1. In Design mode, open the object — a form, control, or toolbar, for example — that you want to assign context-sensitive Help to.
  2. View the object's properties.
  3. Set the HelpContextID property to the number representing a specific topic in your Help file.

For more information about mapping Help topics to context ID numbers, see the Help Authoring Guide.

Note To assign Help topics to menu titles or menu commands, you must include the SET TOPIC TO command in the procedure associated with the menu title or menu command.

See Also

WinHelp 4.0 | Implementing "What's This?" WinHelp | Programming WinHelp Features | ON KEY LABEL | Creating Help


Implementing "What's This?" WinHelp

"What's This?" Help is similar to context-sensitive Help because it provides Help related to the specific object or control that currently has focus. However, instead of invoking the Help file and displaying the Help topic in the full default-sized Help window, "What's This?" Help displays the topic in a small pop-up window that disappears as soon as the user clicks anywhere on the screen. "What's This?" Help is useful for providing brief tip-style descriptions or definitions for specific controls.

Tip Keep your "What's This?" Help topics brief and concise so that the window doesn't grow too large to obscure the feature you're describing.

"What's This?" Help

You associate "What's This?" Help with a particular form, form control, or toolbar by setting its WhatsThisHelpID property to a number representing a specific topic in your Help file.

Use the following properties and methods to implement "What's This?" Help:

Property | Description
WhatsThisHelp | Set this property to true (.T.) on a form to enable "What's This?" Help for the form and any controls on the form.
WhatsThisButton | Set this property to true (.T.) if you want a "What's This?" Help button to appear in the title bar of the form.
WhatsThisHelpID | For a form, control, or toolbar, set this property to an ID number corresponding to a topic in your Help file.
WhatsThisMode | Use this method to display the "What's This?" Help question mark mouse pointer and enable "What's This?" Help mode. Clicking an object displays the "What's This?" Help topic specified by the WhatsThisHelpID property for the object.

Using a "What's This?" button

To implement "What's This?" Help

  1. In design mode, open the form you want to enable "What's This?" Help for.
  2. Set the form's WhatsThisHelp property to true (.T.).
  3. To display a "What's This?" Help button in the form's title bar, set the form's WhatsThisButton property to true (.T.).
  4. To associate a "What's This?" Help topic with the form, set the form's WhatsThisHelpID property to an ID number corresponding to a topic in your Help file.
  5. To associate a "What's This?" Help topic with a specific control on the form, select the control and set its WhatsThisHelpID property to an ID number corresponding to a topic in your Help file.

See Also

Adding Context Sensitivity to WinHelp | Programming WinHelp Features | Creating Help | WhatsThisHelpID | WinHelp 4.0


Programming WinHelp Features

You can program your application so that users can access your Help system in Microsoft Help. Although a Help system can consist of one or more separate files, Help appears to users as part of your application.

You can program your Visual FoxPro application to use graphical Help with the SET HELP TO and SET TOPIC TO commands or with the WinHelp function described later in this topic. SET HELP TO specifies the name of a custom Help file for your application. SET TOPIC TO sets the identifying keyword for a topic in the custom Help file.

Using the WinHelp Function

Another way to program your application to use Help is to call the WinHelp function. The WinHelp function is part of the Windows application programming interface (API). The WinHelp function is only available on the Windows platform.

You can use the WinHelp function in addition to the HelpContextID property, especially to call a second Help file.

Tip If you use SET HELP TO, HELP ID, and SET TOPIC TO, you don't need to use the WinHelp function.

To use the WinHelp function

  1. Define the command parameters that you'll pass in your application.

    For a description of these parameters, see "The wCmd Parameter" later in this section.

  2. Set the library with SET LIBRARY TO and define the variables to be used, typically in the initialization code for your application's main file.
    SET LIBRARY TO SYS(2004) + "FOXTOOLS.FLL" ADDITIVE
Help = RegFn("Help", "LCIC", "I")

    The library must be set to Foxtools.fll. SYS(2004) returns the Visual FoxPro root directory, where Foxtools.fll is installed.

    If you want to open a Help topic by sending its K keyword, define a variable with RegFn( ), like the Help variable in the previous example. If you want to open a Help topic mapped with a number, define a variable with RegFn like the HelpI variable in the previous example and use a number instead of a string for dwData. If you pass numbers, you must map them in the [MAP] section of the .hpj file to unique context strings defined with the number sign (#) footnote.

  3. Use CallFn( ) to call the function.

    For example, if your Help file is called Myhelpfile.hlp, use CallFn( ) to open a topic in Myhelpfile.hlp by including the topic's K keyword:

    #define HELP_KEY 0x0101
wCmd = HELP_KEY
cFilename = Myhelpfile.hlp"
dwData = "Add Menu Items at Run Time"
CallFn(Help, MainHWND(), cFileName, wCmd, dwData)

For more information on FoxTools functions, see Foxtools.chm in the Vfp98\Tools directory.

Specifying WinHelp Parameters

The following parameters specify options for the WinHelp function.

The hWnd Parameter

The hWnd parameter identifies the window requesting Help. Help uses this identifier to track which applications have requested Help. In Visual FoxPro, use the MainHWND( ) function included in the Foxtools.fll library for the hWnd parameter.

The lpzFileName Argument

The lpzFileName argument represents a text string designating a valid path and file name for the Help file containing the desired topic. It is passed by value.

The wCmd Parameter

The wCmd parameter specifies either the type of search that Help uses to locate the specified topic or that the application no longer requires Help. It can be set to any of the following values.

Constant | Value | Meaning
HELP_FINDER | 0x000B | Displays the Help Finder window.
HELP_CONTEXT | 0x0001 | Displays Help for a particular topic identified by a context number.
HELP_HELPONHELP | 0x0004 | Loads Help.hlp and displays the Using Help index topic.
HELP_INDEX | 0x0003 | Displays the main Help index topic as defined in the [OPTIONS] section of the Help Project file (.hpj).
HELP_KEY | 0x0101 | Displays the first topic found in the keyword list that corresponds to the keyword in the dwData parameter.
HELP_QUIT | 0x0002 | Informs the Help application that Help is no longer needed. If no other applications have requested Help, Windows closes the Help application.
HELP_SETINDEX | 0x0005 | Sets a specific topic as the index topic.

The dwData Parameter

The dwData parameter represents the topic for which the application is requesting Help. Its content and format depend on the value of wCmd passed when your application calls the WinHelp function.

In most calls to Help you pass the dwData argument by value. This is the default in Visual FoxPro.

Depending on the circumstances, dwData in the preceding line can either represent a text string, indicating a keyword to look up, or a numeric value, indicating the context number that identifies a specific topic.

The following list describes the format of dwData for each value of wCmd.

wCmd Value | dwData Format
HELP_CONTEXT | A numeric value containing the context number for the topic. Instead of using HELP_INDEX, HELP_CONTEXT can use the value –1.
HELP_HELPONHELP | Ignored.
HELP_INDEX | Ignored.
HELP_KEY | A long pointer to a string that contains a keyword for the desired topic.
HELP_QUIT | Ignored.
HELP_SETINDEX | A numeric value containing the context number for the topic you want as the index.

Because the WinHelp function can specify either a context number or a keyword, it supports both context-sensitive Help and topical searches of the Help file.

Note If a Help file contains two or more indexes, the application must assign one as the default. To ensure that the correct index remains set, the application should call Help with wCmd set to HELP_SETINDEX (with dwData specifying the corresponding context identifier). Each call to Help should be followed with a command set to HELP_CONTEXT. You should never use HELP_INDEX with HELP_SETINDEX.

Reserving F1 for Help

When a user presses F1 in your application, Visual FoxPro can display a context-sensitive Help topic. To do this, assign a Help context ID to a topic in your Help table and assign the same value to the HelpContextID property of your form or control. When the form or control has the focus and the user presses F1, Visual FoxPro displays the matching topic.

Note F1 is enabled for context-sensitive Help by default. Because this is a recognized standard for Help, redefining this key is not recommended.

Including Help Buttons on Forms

If you add Help buttons to your forms, users can access Help more easily. You should especially consider adding a Help button if your user is a novice.

To set context sensitivity and add a Help button

  1. In the Init event for your form, set the HelpContextID property for all the form's objects to the same value you assigned to the Help topic. For example, if the value is 7, you can use the following command:
    THIS.SetAll("HelpContextID", 7)
  2. Add a command button to your form.
  3. Set the Caption property of the command button to Help.
  4. In the Click event of the command button, add the following command:
    HELP ID THIS.HelpContextID
    Tip Save the Help button as a class so that you can easily add it to any form. For more information about saving objects as classes, see Creating Forms.

Quitting Help

The Help application is a shared resource available to all Windows applications. Because it is also a stand-alone application, the user can execute it like any other application. As a result, your application has limited control over the Help application.

While your application cannot directly close the Help application window, it can inform the Help application that Help is no longer needed. Before closing its main window, your application should call Help with the wCmd parameter set to HELP_QUIT, which informs Help that your application will not need it again.

An application that has called Help at some point during its execution must call Help with the wCmd parameter set to HELP_QUIT before the application terminates.

If an application opens more than one Help file, it must call the WinHelp function to quit the Help application for each file.

If an application or dynamic-link library (DLL) has opened a Help file but no longer wants the associated instance of the Help application to remain active, then the application or DLL should call Help with the wCmd parameter set to HELP_QUIT to quit that instance of the Help application.

Note Before terminating, an application or DLL should always call Help for any of the opened Help files. A Help file is opened if any other Help call has been made using the Help file name.

The Help application does not exit until all windows that have called Help have subsequently called it with wCmd set to HELP_QUIT. If an application fails to do so, then the Help application will continue running, even after all applications that requested Help have terminated.

See Also

Implementing "What's This?" WinHelp | Adding Context Sensitivity to WinHelp | Creating Help | SET HELP TO | SET TOPIC TO | SET LIBRARY TO | WinHelp 4.0


Creating International Applications

To move into the world market, you must design your Visual FoxPro applications so they are as effective internationally as domestically. This section describes how to use the international features of Visual FoxPro to produce applications for selected locales.

In This Section

Code Pages in Visual FoxPro
Explains how data stored in Visual FoxPro often is tagged with a code page, which is a table of characters and corresponding numbers in memory that Microsoft Windows uses to display data properly.
Sorting Data in International Applications
Instructs that after creating a table of international data, you should check to see if your application sorts the data correctly. How the data sorts depends on the code page associated with the table because the code page specifies the available sort orders or collation sequences.
Modifying International Applications
Describes how you can prevent localization problems with code by observing certain guidelines.
Managing Files in an International Application
Explains how the Project Manager can help you organize an international application. In a project you can integrate the parts of an application, such as forms, menus, programs, and reports.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Creating the Application
Discusses how to create Visual FoxPro applications, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Setting the Starting Point
Describes how the main file is the starting point for your application, and can consist of a program or form. When your application is run, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed.
Initializing the Environment
Describes setting up the application environment as the first task that a main file or application object must accomplish.
Controlling the Event Loop
Discusses how to establish an event loop, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes, which occurs after the environment is set up and you've displayed the initial user interface.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application builder.
Client/Server Performance Optimization
Learn how you can fine-tune your application to gain maximum performance by increasing data throughput.
Creating the User Interface
Learn how creating forms, classes, controls, and toolbars can provide a rich set of tools for your user interface.
Upsizing Visual FoxPro Databases
Explains how to use the upsizing wizards to move databases, tables, and views from your system to a remote Microsoft SQL Server.


Code Pages in Visual FoxPro

Data stored in Visual FoxPro is often tagged with a code page, which is a table of characters and corresponding numbers in memory that Windows uses to display data properly. For example, if you enter the letter C in a .dbf file, the letter is stored on your hard disk as the number 67. When you open the file, Visual FoxPro determines its code page, inspects the code page to find the character corresponding to the number 67, and then displays the character (C) on your monitor.

Code pages correspond roughly to different alphabets. For example, Windows supplies code pages for English, German, Scandinavian languages, and so on. By using different code pages, applications can properly display characters from these different alphabets.

Understanding Code Pages in Visual FoxPro

Visual FoxPro displays data using one code page. By default, this is the current code page used by Windows. However, you can override the Windows code page by specifying an alternative code page in your configuration file (you must specify a valid code page).

Tables in Visual FoxPro are tagged with the code page that was in use when the table was created. When you use the table, Visual FoxPro checks the code page for the table against the current code page. If they match, Visual FoxPro displays the data as is. If there is no code page for the table (for example, the table was created in an earlier version of FoxPro), Visual FoxPro prompts you for a code page and then marks the file with it.

If the table code page does not match the system code page, Visual FoxPro attempts to translate characters from the table code page into the current one. For example, if you're using Visual FoxPro and the current system code page is the English code page, the character ü is represented by ANSI value 252. If the code page for the table represents the ü character as ANSI value 219, Visual FoxPro translates all instances of ANSI value 219 into ANSI 252 so that they display properly.

Code page translation doesn't work perfectly in all instances, because code pages usually contain characters that are not represented one-for-one in other code pages. For example, you cannot map data that contains the MS-DOS line-drawing characters into Windows because the Windows code pages don't contain line-drawing characters. Similarly, you cannot translate data created in the Russian code page into an English code page because there isn't a one-to-one correspondence between the alphabets for these languages. Finally, Visual FoxPro might not contain a character translation map for a particular code page. In that case the data is displayed with no code page translation. (Visual FoxPro does not display an error to indicate that no code page translation is occurring.) Any of these situations can cause some characters to display improperly.

If you want to create an application for a specific locale, you can avoid code page translation problems by creating the application's components using the code page designed for that locale and environment. For example, to create an application for use in Russia, you should use code page 1251. For a complete list, see Code Pages Supported By Visual FoxPro.

If you need to enter some characters not represented by keys on your keyboard, you can enter these characters using ALT in conjunction with keys on the numeric keypad. However, remember that the same key combination in different environments often displays different results. For example, if you enter ALT+0182 with code page 1252 in Visual FoxPro, you see a paragraph symbol. In contrast, if you enter ALT+0182 with code page 437 in FoxPro for MS-DOS, you see a graphic character with a double vertical line meeting a single horizontal line.

Although Visual FoxPro supports many code pages, only a few are used often. Typically, English-speaking users use code page 1252.

When working with code pages, be sure to test that the user interface and data display correctly by using the code page designed for a particular locale. If you see unexpected characters on the screen, check the underlying code page.

See Also

Entering International Data | Specifying the Code Page of a .dbf File | Developing International Applications | Specifying the Code Page of a Text File | Determining the Code Page of a Project File


Code Pages Supported by Visual FoxPro

A code page is a set of characters specific to a language or hardware platform. Accented characters are not represented by the same values across platforms and code pages. In addition, some characters available in one code page are not available in another.

Code page | Platform | Code page identifier
437 | U.S. MS-DOS | x01
620 * | Mazovia (Polish) MS-DOS | x69
737 * | Greek MS-DOS (437G) | x6A
850 | International MS-DOS | x02
852 | Eastern European MS-DOS | x64
857 | Turkish MS-DOS | x6B
861 | Icelandic MS-DOS | x67
865 | Nordic MS-DOS | x66
866 | Russian MS-DOS | x65
874 | Thai Windows | x7C
895 * | Kamenicky (Czech) MS-DOS | x68
932 | Japanese Windows | x7B
936 | Chinese (PRC, Singapore) Windows | x7A
949 | Korean Windows | x79
950 | Chinese (Hong Kong SAR, Taiwan) Windows | x78
1250 | Eastern European Windows | xC8
1251 | Russian Windows | xC9
1252 | Windows ANSI | x03
1253 | Greek Windows | xCB
1254 | Turkish Windows | xCA
1255 | Hebrew Windows | x7D
1256 | Arabic Windows | x7E
10000 | Standard Macintosh | x04
10006 | Greek Macintosh | x98
10007 * | Russian Macintosh | x96
10029 | Macintosh EE | x97

* Not detected when you include CODEPAGE=AUTO in your configuration file.

See Also

Preventing Translation of Data in Character or Memo Fields | Sorting Data in International Applications | Developing International Applications | Code Pages in Visual FoxPro | Specification of Code Pages for Variables | Special Terms for Configuration Files | SET COLLATE Command


Specifying the Code Page of a .dbf File

When you create .dbf files, Visual FoxPro automatically gives them code page marks so that you can tell which code pages they use. However, if you use .dbf files from previous versions of FoxPro, they might not have code page marks.

You can determine whether a .dbf file has a code page mark by using the CPDBF( ) function after opening the file or by having Visual FoxPro check when you open the file.

To check for code page marks automatically

  1. From the Tools menu, choose Options.
  2. Select the Data tab.
  3. Set the Prompt for code page check box, if it's not already set.

    To save this setting for future sessions of Visual FoxPro, choose Set as Default.

    Tip Instead of setting the Prompt for code page check box, you can use the SET CPDIALOG command to check for code pages.

If a file doesn't have a code page mark, you must add a mark, as described in the following section.

Adding Code Page Marks

If you use a .dbf file from a previous version of FoxPro, the file might not have a code page mark; without such a mark, the file might not display properly. If automatic code page checking is enabled, when you open the file you can tell if it has a code page mark. If it doesn't have one, you can add one.

To manually add a code page mark to a .dbf file

  1. Ensure automatic code page checking is in effect (see the previous procedure).
  2. Open the file.

    If the file doesn't have a code page mark, the Code Page dialog box appears.

  3. Choose the appropriate code page.
  4. View the file to see if you assigned the proper code page.

    If you can't see some of the data, or if you can't recognize some of it, the code page is not correct.

  5. If the code page is incorrect, remove the code page mark by using the CPZERO program in the Visual FoxPro Tools\Cpzero directory.
  6. Repeat this procedure until the code page is correct.
    Note Text files such as program (.prg) and query (.qpr) files don't have code page marks. This means that you can't tell which code pages the files use. However, if you include such files in a project, the project can keep a record of the code pages used. For more information, see Specifying the Code Page of a Text File.

Removing Code Page Marks

If a .dbf file doesn't display properly, it might have the wrong code page mark. You can remove the code page mark with the CPZERO program located in Tools\Cpzero. Running CPZERO sets the code page to 0, meaning none.

To remove a code page mark

  • Run CPZERO using the following syntax:

    DO CPZERO WITH "filename", 0

    Note When you remove the code page mark of a .dbf file, the data in the file doesn't change. To change the code page of the data, you must mark the file with the proper code page.

Changing Code Page Marks

You can change the code page of a .dbf file by removing its code page mark and then adding a new one, by copying the file to another file, or by using the CPZERO program.

To change the code page of a .dbf file by copying the file

  • Use the COPY TO command, specifying the target code page with the AS clause. (To set the code page to the current system code page, omit the AS clause.)

    For example, to copy Test.dbf to Test866.dbf, while changing the code page to 866, use the following commands:

    USE TEST.DBF
COPY TO TEST866.DBF AS 866

When the COPY TO completes, the data in the resulting file will have the new code page.

To change a code page mark using CPZERO

  • Run CPZERO using the following syntax:

    DO CPZERO WITH "filename", newCodePage

    Note Some characters cannot be translated between code pages successfully. In addition, some code page translations aren't supported by Visual FoxPro. Always check the results of a code page change to be sure that your data has been translated successfully.

See Also

Code Pages in Visual FoxPro | Specifying the Code Page of a Text File | Developing International Applications | Determining the Code Page of a Project File | Specification of Code Pages for Variables


Specifying the Code Page of a Text File

If you forget the code page of a text file that's not part of a project, you cannot determine the code page, because a text file doesn't have a code page mark as .dbf files have. The best way to remember the code page of a text file is to add the file to a project.

To specify the code page of a text file

  1. Open the Project Manager.
  2. Select the text file whose code page you want to specify.
  3. From the Project menu, choose Project Info.
  4. In the Project Information dialog box, click the Files tab.
  5. Right-click the selected file.
  6. From the submenu, choose Code Page.

    Visual FoxPro displays the Code Page dialog box.

  7. Choose the appropriate code page.

    Visual FoxPro displays the available code pages.

If you know the code page of a text file, you can specify it by using the AS clause of the appropriate Visual FoxPro command. For files you want to import or append, you can specify the code page in the IMPORT or APPEND commands. For query, program, and other text files already on your computer, you can change the code page using the MODIFY QUERY, MODIFY COMMAND, and MODIFY FILE commands.

If you're not sure which code page to apply, substitute the GETCP( ) function for the code page number in the command. GETCP( ) displays the Code Page dialog box, making it possible for you to select the appropriate code page.

Note Some characters cannot be translated between code pages successfully. In addition, some code page translations aren't supported by Visual FoxPro. Always check the results of a code page change to be sure that your data has been translated successfully.

See Also

Specifying the Code Page of a .dbf File | Determining the Code Page of a Project File | Developing International Applications | Specification of Code Pages for Variables | Preventing Translation of Data in Character or Memo Fields


Determining the Code Page of a Project File

After adding a file to a project, you can determine its code page. The method you use depends on whether the file is a table (.dbf file) or a text file.

To determine the code page of a text file

  1. Open the Project Manager.
  2. Under Other, select the text file whose code page you want to know.
  3. From the Project menu, choose Project Info.

To determine the code page of a table

  • Use the CPDBF( ) function.

When you build an application from a project, the Project Manager automatically integrates the files in the project no matter how many different code pages they have. The resulting application has the current code page.

Note When you add a .dbf file to a project, you don't have to specify a code page for the file because Visual FoxPro automatically determines the code page from the file's code page mark. However, when you add a text file to a project, you must specify a code page for the file because Visual FoxPro cannot determine the code page automatically.

To prepare a program for use with another code page, specify the original code page when you save or compile the program on the new platform. For example, to prepare a program created with Visual FoxPro for Macintosh for use with Visual FoxPro, specify the appropriate MS-DOS code page when you save or compile the program with Visual FoxPro. If you use the COMPILE command, specify the code page using the AS clause. Alternatively, specify the code page with SET CPCOMPILE before compiling the program.

See Also

Specifying the Code Page of a Text File | Specification of Code Pages for Variables | Developing International Applications | Preventing Translation of Data in Character or Memo Fields | Code Pages Supported by Visual FoxPro


Specification of Code Pages for Variables

You might want to manipulate international data in certain ways. For example, you might want to translate the data in a variable to another code page, or you might want to prevent translation of data in a character or memo field.

Translating Data in Variables

If the code in your application includes a variable containing data from another code page, you can translate the data to the proper code page using the CPCONVERT( ) function. For example, suppose the variable x contains data created with the Macintosh code page (10000). To translate the data to the Windows code page (1252), issue the following command:

cConvert=CPCONVERT(10000,1252,x)

In Windows, the converted data looks just as you see it on the Macintosh. For example, a character that looks like "ä" on the Macintosh looks identical in Windows.

See Also

Determining the Code Page of a Project File | Preventing Translation of Data in Character or Memo Fields | Developing International Applications | Code Pages Supported by Visual FoxPro | Code Pages in Visual FoxPro


Preventing Translation of Data in Character or Memo Fields

In some cases you don't want automatic code page translation. For instance, if a character field contains an encrypted password, you don't want Visual FoxPro to automatically translate the password because doing so would alter it.

To prevent translation of data in a character or memo field

  1. Open the project containing the table.
  2. Select the table.
  3. Choose the Modify button.

    The Table Designer appears.

  4. Select the field whose data you want to protect.
  5. From the Type list select Character (Binary) for a Character field, or Memo (Binary) for a memo field.
  6. Choose OK, and then choose Yes to make the changes permanent.
  7. Verify the changes by displaying the structure of the table with the DISPLAY STRUCTURE command.

    Alternatively, use the MODIFY STRUCTURE command to protect the appropriate fields.

You can also prevent translation of selected characters in text files by using the CHR( ) function.

See Also

Specification of Code Pages for Variables | Developing International Applications | Code Pages Supported by Visual FoxPro | Code Pages in Visual FoxPro | Determining the Code Page of a Project File


Sorting Data in International Applications

After creating a table of international data, check to see if your application sorts the data correctly. How the data sorts depends on the code page associated with the table, because the code page specifies the available sort orders or collation sequences.

Understanding Sort Orders

Sort orders incorporate the sorting rules of different locales, making it possible for you to sort data in those languages correctly. In Visual FoxPro, the current sort order determines the results of character expression comparisons and the order in which records appear in indexed or sorted tables.

Note Sorting works differently in double-byte character sets (DBCS) environments.

Use the appropriate sort order, because different sort orders produce different results, as shown in the following table.

Unsorted | Machine | General | Spanish
!@#$ | Space | space | Space
1234 | !@#$ | !@#$ | !@#$
space | 1234 | 1234 | 1234
Caesar | Caesar | äa | Äa
cæsar | Car | ab | Ab
Strasse | Char | äb | Äb
straße | Czech | Caesar | Caesar
Car | Strasse | cæsar | Cæsar
Char | Ab | Car | Car
Czech | Cæsar | Çar | Çar
ab | Straße | Char | Czech
Çar | Çar | Czech | Char
äa | Äa | Strasse | Strasse
äb | Äb | straße | Straße

Sort Order Guidelines

Consider the following guidelines when choosing a sort order:

  • Avoid the Machine sort order if you want to sort international characters properly, because Machine sorts international characters in ASCII order. For example, notice that Çar follows straße.
  • Characters with diacritical marks sort differently than characters without diacritical marks. For example, in the General and Spanish sort orders, notice that äa sorts before ab but ab sorts before äb.
  • Ligatures such as ß sort the same as their equivalent character expansions. For example, straße sorts the same as Strasse, and cæsar sorts the same as Caesar.
  • In some languages, two characters sort as a single character. For example, in Spanish the Ch in Char sorts as a character between C and D.

The following sections describe how to specify sort orders, check the current sort order, and recognize the effects of sort orders.

Specifying Sort Orders

You can specify a sort order for character fields used in subsequent indexing and sorting operations.

To specify a sort order

  1. From the Tools menu, choose Options.
  2. Select the Data tab.
  3. In the Collating sequence box, select the appropriate sort order.

    To save this setting for future sessions of Visual FoxPro, choose Set as Default.

    Tip You can also specify a sort order with the SET COLLATE TO command or the COLLATE statement in your Config.fpw file. For details about Config.fpw, see Configuring Visual FoxPro.

The current sort order doesn't affect previously created indexes; however, it does affect the results of comparisons and commands such as SEEK and SELECT - SQL.

You can change the sort order at any time. For instance, after opening a customer table you can create index tags representing different sort orders, as shown in the following code. Then you can change the sort order by simply using a different tag:

USE customer
SET COLLATE TO "GENERAL"
INDEX ON fname TAG mygeneral ADDITIVE
SET COLLATE TO "MACHINE"
INDEX ON custid TAG mymachine ADDITIVE
SET COLLATE TO "DUTCH"
INDEX ON lname TAG mydutch ADDITIVE
Note The sort order for an index overrides the current sort order.

The current code page determines which sort orders are available. If you use SET COLLATE to specify a sort order not supported by the current code page, Visual FoxPro generates an error. Also, if you specify a sort order in Config.fpw that isn't supported by the current code page, the sort order defaults to Machine.

Checking Sort Orders

You can determine the current sort order by using the SET ('COLLATE') function. For example, you can save the current sort order, set the current sort order to Machine, perform whatever work is necessary, and then restore the original sort order by using the following code:

cCurrentOrder=SET('COLLATE')
SET COLLATE TO 'MACHINE'
*
* code that requires the Machine sort order
*
SET COLLATE TO cCurrentOrder  && return to the previous sort order

You can also determine the sort order of an index or index tag by using the IDXCOLLATE( ) function.

Recognizing the Effects of Sort Orders

The sort order affects the results of string comparisons, SEEK, and SELECT - SQL, as described in the following sections.

Comparing Strings

All sort orders except for Machine and Unique Weight ignore case. This means that you don't have to use UPPER( ) in your index expressions.

The current sort order affects string comparisons. For example, when you set the sort order to General, the following statements return True (.T.):

?"A" = "a"
?"Straße"="Strasse"
?"æ" = "ae"

However, when you use the Machine sort order, all of these statements return False (.F.). because the strings are matched for an exact comparison, byte by byte.

The character string comparison operator (= =) gives you the same result as when you compare by value or when you compare using the Machine sort order; that is, it compares strings byte by byte. For example, the following statement returns False (.F.):

? "Straße" == "Strasse"
Note Visual FoxPro ignores SET EXACT when you use the character string comparison operator (= =).

Using SEEK

Visual FoxPro ignores diacritical marks when you perform a partial seek. A partial seek occurs when you make the length of the expression less than the length of the key. If diacritics are important, consider using SCAN FOR...ENDSCAN or LOCATE FOR...CONTINUE instead of SEEK.

The advantages of using SCAN and LOCATE instead of SEEK include the following:

  • SCAN and LOCATE are sensitive to diacritics.
  • Visual FoxPro fully optimizes the results of SCAN or LOCATE if the current sort order is Machine or Unique Weight, whereas Visual FoxPro only partly optimizes the results of SEEK.
  • SCAN and LOCATE remember the condition that invoked them, making it possible for you to use them for looping on a condition. In contrast, SEEK positions you somewhere in the index, and SKIP continues down the index from that point. Accordingly, SEEK might not produce the results you want with international data.

Using SELECT - SQL

The SELECT - SQL command uses the current sort order. For example, if you have an index tag based on the General sort order and the current sort order (returned by SET ('COLLATE')) is Machine, the result of SELECT SQL is based on Machine.

To employ the current sort order, use the ORDER BY clause of SELECT - SQL.

Using Indexes

Sort orders determine the order of records in indexed tables. Consider the following guidelines for using indexes with sort orders:

  • Rebuild indexes created in earlier versions of FoxPro if you want the indexes to use a sort order other than Machine.
  • Rebuild dBASE indexes to take advantage of Visual FoxPro sort orders.
  • Use the REINDEX command to rebuild an index, because REINDEX leaves the sort order unchanged.

See Also

Code Pages Supported by Visual FoxPro | Application Creation with Double-Byte Character Sets | Developing International Applications | Data | Creating or Modifying Programs


Application Creation with Double-Byte Character Sets

Visual FoxPro supports double-byte character sets (DBCS) — character sets that require more than one byte to represent a character. Some examples of languages that require a double-byte character set are Simplified Chinese, Traditional Chinese, and Korean.

Visual FoxPro DBCS support makes it possible for you to create international applications. For example, you can create a Korean application with a U.S. version of Visual FoxPro if you're running the Korean version of Windows. The Visual FoxPro DBCS functions operate properly on the Korean character set, and the Korean collation sequence is supported.

Note Visual FoxPro provides special programming functions for use with string in DBCS environments.

Using DBCS Characters When Naming Objects

Visual FoxPro makes it possible for you to use DBCS characters when naming elements of your applications. As with Visual FoxPro generally, elements can:

  • Be up to 254 bytes in length with the combination of double-byte characters and single characters. For example, if you use all double-byte characters, then the name you are creating can be only 127 characters long.
  • Begin with a letter, number, underscore or leading-trailing byte combination.
  • Contain only letters, numbers, underscores, or DBCS characters.

These rules apply to variables, objects (windows, menus, and so on), function and procedure names, class and subclass names, aliases, and constants. You can also use double-byte characters for file names. To avoid the possibility that characters in the file name are inadvertently treated as delimiters, it's safest to always enclose the file name in quotation marks.

Note Visual FoxPro length limits are expressed using single-byte characters. Using double-byte characters in field names, index expressions, variable names, window names, and so on, effectively shortens the length of the name. For example, a field name can be up to 10 bytes long in a free table, so a field name can consist of 10 single-byte characters, but only 5 double-byte characters. For more information about Visual FoxPro system capacities, see System Capacities.

Sorting DBCS Data

To help you order information in DBCS environments, Visual FoxPro supports collation sequences for Simplified Chinese, Traditional Chinese, Japanese, and Korean. Collation sequences make it possible for you to properly order character fields in tables for each language.

The following table lists the Visual FoxPro collation sequence options and the corresponding language.

Options | Language
JAPANESE | Japanese
KOREAN | Korean
PINYIN | Simplified Chinese
STROKE | Simplified and Traditional Chinese

For more information, see Specifying Sort Orders.

See Also

Sorting Data in International Applications | Creating or Modifying Programs | Developing International Applications | Code Pages Supported by Visual FoxPro | Code Pages in Visual FoxPro |


Modifying International Applications

You can prevent localization problems with code by observing the following guidelines.

Testing for International Versions

If it's important for your application to be able to determine what language Visual FoxPro is running in, you can call VERSION( ). Knowing the language environment can help you determine what text to display, how to format data, and so on. For example, the following code determines what language environment Visual FoxPro is running in and then runs a language-specific form:

IF VERSION(3) = 34 THEN
   * Running in Spanish--display Spanish form
   DO FORM CST_SPN.SCX
ELSE
   * Display English form
   DO FORM CST_ENU.SCX
ENDIF
Note Support for double-byte characters strings has been available in Visual FoxPro only since version 3.0b. If your application is relying on the availability of double-byte character set (DBCS) functions, you should also call the VERSION(1) function to test the Visual FoxPro version number.

Using Strings

Avoid including strings directly in code because they make localization difficult. For instance, don't include dates and currencies as strings in code. If possible, write your code so that it retrieves strings from files or tables separate from the program.

Note The performance of your program might suffer if you remove all strings from it. For example, performance might suffer if the program searches for strings while inside a loop.

One way to work with strings in an application that will be translated is to use string constants throughout the application. You can then define the text for these constants in a separate text file that is referenced from your programs using the #INCLUDE preprocessor directive. For example, instead of embedding the error message "file not found," you can use the constant ERR_FILE_NOT_FOUND. The text for this constant could be in a file called ERR_TEXT.H. A program that uses this technique might look like this:

#INCLUDE ERR_TEXT.H

* processing here

IF ERR THEN
   MESSAGEBOX( ERR_FILE_NOT_FOUND )
ENDIF

When your application is localized, the translator can create a locale-specific version of the error text file and then recompile the application.

Working With Strings in DBCS Environments

Visual FoxPro includes functions for manipulating character expressions containing any combination of single-byte or double-byte characters. By using DBCS string functions you can develop applications without having to write extra code that tests for double-byte characters when counting, locating, inserting, or removing characters in a string.

Most DBCS functions are equivalent to their single-byte counterparts except that they're named with a C suffix to distinguish them. You can use these functions with both single-byte and double-byte data; the DBCS functions return exactly the same value as their single-byte counterparts when single-byte data is passed to them. A few other functions help you work with strings specifically in double-byte environments.

DBCS string functions | Description
AT_C( ) | Returns the position of one string within another (case-sensitive), starting at the left.
ATCC( ) | Returns the position of one string within another (case-insensitive).
CHRTRANC( ) | Replaces characters in a string.
IMESTATUS( ) | Toggles double-byte editing in the Browse window.
ISLEADBYTE( ) | Tests whether a character is a DBCS character.
LEFTC( ) | Returns leftmost characters from a string.
LENC( ) | Returns the number of characters in a string.
LIKEC( ) | Determines whether two strings match.
RATC( ) | Returns the position of one string within another (case-sensitive), starting at the right.
RIGHTC( ) | Returns rightmost characters from a string.
STRCONV( ) | Converts characters between single-byte and double-byte representations.
STUFFC( ) | Replaces characters in a string with another string.
SUBSTRC( ) | Returns a substring.

When working with double-byte string functions, remember that the maximum-length limit for variables, names, and so on is effectively cut in half. For more information, see System Capacities.

Note The Visual FoxPro DBCS functions are not supported in earlier versions of Visual FoxPro, and calling them might cause unpredictable results. If you use any DBCS functions in your application, use VERSION(1) to verify that the Visual FoxPro version is later than version 3.0.

Working with Date, Time, and Currency Formats

To help you format dates, times, and currency to match what your users are accustomed to, you can use a variety of formatting techniques. You can:

  • Allow Visual FoxPro to use the settings established in the Control Panel.
  • Specify a language or a specific format in the Visual FoxPro Options dialog box that you want to use.
  • Format dates, times, and currency information in code.

To set a format for date, times, and currency

  1. From the Tools menu, choose Options, and then click the Regional tab.
  2. To use the settings made with the Windows Control Panel, choose Use system settings.

    -or-

    Choose a language or format for dates and times and then choose options for formatting currency and numbers. If you choose the format Short or Long for the date format, you cannot specify any further options for the date format, and the settings are read from the Windows Control Panel.

  3. Choose OK to use the options for this session, or Set As Default to make the changes the default settings for this copy of Visual FoxPro.

You can also make these settings using the SET SYSFORMATS and SET DATE commands. As a rule, you would issue this command during the initialization of your application (for example, in the configuration file). The default for SET SYSFORMATS is OFF, so you must explicitly set it to ON when starting your application.

You can establish data validation in individual text boxes by setting the Format property of the text box. However, because text box formatting takes precedence over system-wide formatting, this can make it more difficult to localize your application to an environment that uses a different format for dates, currency, and so on.

Using Preprocessor Directives

You can create application variants for different locales by using preprocessor directives. These control compilation of code in the application and include the #INCLUDE, #DEFINE, #UNDEF, and #IF...#ENDIF constructs.

Using preprocessor directives can produce variants quickly; however, such directives have the following drawbacks:

  • To use preprocessor directives, you bracket code, and extensive bracketing can increase the code's complexity.
  • Compile-time constants are available only in the program that creates them.

See Also

Application Creation with Double-Byte Character Sets | Managing Files in an International Application | Developing International Applications | VERSION( ) | VERSION(1) | #INCLUDE


Managing Files in an International Application

The Project Manager can help you organize an international application. In a project you can integrate the parts of an application, such as forms, menus, programs, and reports. The project ensures that the parts are current when you build the application for its target market.

Unlike .dbf files, text files such as query and program files don't have code page marks. This means that you must keep track of the code pages used by text files so that you can use the files properly. With the Project Manager, you can track the code pages used by text files.

Distributing Locale-Specific Run-Time Files

If you're distributing your application along with the run-time version of Visual FoxPro, you might need to include a locale-specific resource file. This file contains the dialog boxes and other user-interface elements that Visual FoxPro uses to interact with the user. There is a different run-time resource file for each language in which Visual FoxPro is available.

You would normally need to concern yourself about a locale-specific run-time resource only if all of the following are true:

  • You are including the run-time version of Visual FoxPro with your application.
  • You are distributing your application to users who use a language different from the one in which you developed it. For example, if you develop in English for an English-speaking user base, you don't need to worry about including a locale-specific resource file. However, if you use the English version of Visual FoxPro to develop but are distributing your run-time application in a French-speaking country, you should consider including the run-time resource file.
  • Your application displays Visual FoxPro dialog boxes, menus, or error messages. Typically, if you've designed and localized your own versions of these interface elements, you don't need to include the locate-specific resource file.

Run-time resource files are named using the format Vfp8aaa.dll, where "8" is the version number and "aaa" is a three-letter code representing the language. For example, the code ENU stands for United States English, the code DEU stands for German, and the code FRA for French. The run-time resource files for these languages are therefore Vfp8renu.dll, Vfp8rdeu.dll, and Vfp8rfra.dll, respectively.

You must always include at least one run-time resource file, even if you don't intend to use any of the user interface elements in Visual FoxPro as part of your application. By default, Visual FoxPro includes the resource file that's provided with your copy of the program. For example, if you're developing an application using the United States version of Visual FoxPro, Visual FoxPro automatically includes Vfp8renu.dll if you include run-time files with your application. If you have no reason to use a locale-specific resource file, you can simply distribute the default resource file as part of your application.

When the application is installed, users can specify the run-time resource file to use by making an entry in the Windows system registry or by using a command-line switch.

To specify a run-time resource file

  • In the command line that starts your application, include the L switch and the name of the resource file that you want to use (including a path if necessary). Do not put a space between the switch and the file name.

    For example, the following command specifies the file Vfp8rdeu.dll as the resource file:

    C:\Program Files\Microsoft Visual ;
FoxPro\MYAPP.EXE -LC:\Myapp\Vfp8rdeu.dll

    -or-

  • Set the Windows registry on the user's machine (using code or an application such as Regedit.exe) to point to the resource file to use. The registry entry containing the name of the run-time resource file is:

    HKEY_CLASSES_ROOT\VisualFoxProRuntime.<current version number>\Resources

    For example, the following registry entry points to the run-time resource file vfprdeu.dll:

    HKEY_CLASSES_ROOT\VisualFoxproRuntime.8\Resources
    C:\Program Files\Common Files\Microsoft Shared\VFP\vfprdeu.dll

    If you want to control the resource file used by the full development version of Visual FoxPro, use a similar registry key without the run-time reference:

    HKEY_CLASSES_ROOT\VisualFoxpro.<current version number>\Resources

    For example, the following registry entry points to the resource file on a computer with the full version of Visual FoxPro installed:

    HKEY_CLASSES_ROOT\VisualFoxpro.8\Resources
    C:\Program Files\Visual FoxPro 8\vfpdeu.dll

When the run-time application starts, Visual FoxPro searches for a resource file, first according to the L switch and then according to the Registry setting. If neither of these settings specifies a locale-specific resource file, Visual FoxPro uses the current system (Windows) locale to dynamically construct a DLL file name. Therefore, if the locale-specific resource file for your application matches the system locale on the user's version of Windows, you don't need to explicitly specify the resource file name. However, it's always safest not to rely on the system default if you want to be sure that the proper file is loaded.

See Also

Creating or Modifying Programs | Specifying the Code Page of a Text File | Application Distribution Process | Developing International Applications | Application Creation with Double-Byte Character Sets | Sorting Data in International Applications


Web Services and Components

To extend a basic Microsoft Visual FoxPro application, you can enable it to work for multiple users, access and distribute XML Web services, use Microsoft ActiveX controls and automation-enabled applications, and add international capabilities.

In This Section

XML Web Services in Visual FoxPro
Describes how to access and distribute XML Web services with your Visual FoxPro applications. XML Web services are classes or objects available on the Web that you can use in your applications programmatically as normal object-oriented calls.
Automation and COM Servers
Describes how to you can extend the functionality of your Visual FoxPro applications without a lot of extra coding time by using Automation and COM Servers.
Interoperability and the Internet
Explains how to use OLE drag-and-drop to develop applications that make it possible for you to move data between Microsoft Windows-based applications and within a Visual FoxPro application. Create documents for use on the Internet, or use one of two different Visual FoxPro run times to create COM components (Automation servers) as normal or multithreaded applications.

Related Sections

Using Visual FoxPro
Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Explains that careful planning saves time, effort, and money and that many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating the Application
Discusses how to create a Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Data
Describes how to create effective applications with indexes, tables, and databases based on your data requirements.
Working with Projects
Defines a project configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Explains how to use the modular approach to verify the functionality of each component you create so that you can compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Describes Visual FoxPro debugging tools that help you find and correct any errors you discover in your applications.
Distributing Applications
Prepares you to distribute your application by including all required files and creating distribution disks after you have completed developing and testing your application.


XML Web Services in Visual FoxPro

XML Web services are classes or objects available on the Web that you can use in your applications programmatically as normal object-oriented calls. You can also publish Visual FoxPro COM Servers (OLEPUBLIC) as XML Web services to make information available to other clients on the Internet.

For example, you can use an XML Web service in your application that returns the weather for a given city when you call a method that returns the temperature when passed the name of the city.

Visual FoxPro support for XML Web services is handled through SOAP using an implementation of the Web Services Description Language (WSDL) compliant with WSDL version 1.1. Visual FoxPro includes Microsoft SOAP Toolkit version 3.0, which provides support for XML Web services through a set of extensions, and is also available from the Microsoft Web site. Visual FoxPro extends the functionality of the Toolkit; therefore, any future changes to the WSDL specification by the W3C propagate directly to Visual FoxPro when you upgrade to a newer version of the Toolkit.

Note You must have the Microsoft SOAP Toolkit installed to use XML Web services. If you plan to publish XML Web services from Visual FoxPro COM Servers, you must have Microsoft Internet Information Services (IIS) installed.

The SOAP Toolkit also provides objects that you can use to call XML Web services at low levels that interact directly with the actual SOAP messages. However, these objects are not directly supported by the Visual FoxPro extensions.

For more information on supported platforms, SOAP, WSDL, or the Toolkit, see the Toolkit online documentation or the SOAP Developer Resources Web site at http://msdn.microsoft.com/soap/.

In This Section

Accessing XML Web Services
Describes how to locate, register, and use XML Web services in Visual FoxPro applications.
Distributing XML Web Services
Describes how to specify a default location for publishing XML Web services, publish Visual FoxPro COM Servers as XML Web services, include components for deploying XML Web services, and generate XML Web service support files automatically when your COM Server is rebuilt.

Related Sections

Web Services and Components
Discusses how you can enable a Visual FoxPro application to work for multiple users by taking advantage of ActiveX controls and automation-enabled applications and adding international capabilities.
Automation and COM Servers
Describes how to you can extend the functionality of your Visual FoxPro applications without a lot of extra coding time by using automation and COM Servers.
Walkthrough: Creating XML Web Services with Visual FoxPro
Explains how to create and publish a Visual FoxPro COM Server as an XML Web service.
Interoperability and the Internet
Explains how to use OLE drag-and-drop to develop applications so you can move data between Microsoft Windows-based applications and within a Visual FoxPro application. Create documents for use on the Internet, or use one of two different Visual FoxPro run-times to create COM components (Automation servers) as normal or multithreaded applications.


Accessing XML Web Services

Support for XML Web services in Visual FoxPro provided by the Microsoft SOAP Toolkit make it possible for you to access XML Web services from the Web. The extensions provided by the SOAP Toolkit 3.0 provide access to XML Web services using the Toolkit's SoapClient object. This high-level late-binding access architecture makes it possible for you to call an XML Web service method directly using only a few lines of simple object code.

The WSHandler foundation class, which is included with the _WS3Client.vcx class library in the ...\Ffc folder, is the XML Web service class used for all Visual FoxPro XML Web service calls.

Registering XML Web Services

Before using an XML Web service in your application, register it in Visual FoxPro. You can then select the XML Web service in the Visual FoxPro Toolbox and use operation or method calls from that XML Web service to return results. When calling the XML Web service, you can set the results to a property of a specified control, such as the TextBox Value property.

Note You do not have to register an XML Web service to access it; however, registering an XML Web service makes it possible for Visual FoxPro to provide IntelliSense for the XML Web service methods and their parameters.

To register an XML Web service

  1. On the Tools menu, click Task Pane.
  2. On the Task Pane Manager toolbar, click More Panes, and then click XML Web Services.
  3. In the XML Web Services pane, click Register an XML Web Service.
  4. In the Visual FoxPro XML Web Services Registration dialog box, type the Web Services Description Language (WSDL) URL for the XML Web service, and then click Register.

You also can open the Visual FoxPro XML Web Services Registration dialog box programmatically as shown in the following code:

DO (_wizard) WITH "project",,"Web","IntelliSense"

For more information about the settings you need to configure, see Visual FoxPro XML Web Services Registration Dialog Box.

Calling XML Web Services

After you register an XML Web service in Visual FoxPro, you can call and bind the XML Web service to a control or object on a form You can then process results from the XML Web service in your application. You can call and bind XML Web services using the XML Web Service Builder or in code. The builder provides extensive binding capabilities without your having to write code. For more information, see XML Web Service Builder.

The following steps illustrate how to call the XML Web service in your program using code.

To call an XML Web service using code

  1. On the Tools menu, click Toolbox.
  2. In the Toolbox, click My XML Web Services.
  3. Open an editing window to the location in your program or code where you want to call the XML Web service.
  4. Drag and drop the XML Web service in the editing window.

    The code for the XML Web service appears in the editing window.

You can also type the characters, ws, in the editing window. The Select dialog box appears so that you can select an XML Web service and any additional options and insert code for the XML Web service in the editing window. For more information, see Select Dialog Box.

You can use IntelliSense to see the available methods and parameters for the XML Web service. For example, IntelliSense displays a list of methods available for the XML Web service when you type the following line of code in the editing window:

? YourXMLWebService.
Note Make sure to replace MyXMLWebService with the XML Web service object provided in the code.

You can select a method and continue typing as follows to specify parameters for the method:

? MyXMLWebService.WSMethod(
Note Replace WSMethod with the XML Web service method you select.

IntelliSense displays the possible parameters and the return type for that method.

You can also port the code for the XML Web service to another computer that does not have the XML Web service registered. Visual FoxPro can detect that the XML Web service is not registered and prompts you to register it. If you do not want to register the XML Web service, you can remove the line that contains the WSDL reference, for example:

* __VFPWSDef__: lofoxtypes=http://mywebserver/foxws/foxtypes.wsdl

For more details about accessing XML Web services using high and low-level calls, see the SOAP Toolkit 3.0 documentation.

Binding XML Web Services to Controls

You can bind an XML Web service to a control or object on a Visual FoxPro form and assign the results of the XML Web service to properties of the control or object.

To bind an XML Web service to a control

  1. Create a new or open an existing form or class.
  2. On the Tools menu, click Toolbox.
  3. Under My XML Web Services in the Toolbox, drag and drop the Generic Handler control or the registered XML Web to a form or class.

    The XML Web Service Builder appears so that you can bind the XML Web service to controls or objects on the form. If the builder does not appear, right-click the XML Web service control and select Builder.

For more information, see XML Web Service Builder.

Note It is recommended that you save a newly created form before dropping an XML Web service because the builder needs to access controls on the form using the container path.

See Also

XML Web Services in Visual FoxPro | Distributing XML Web Services


Distributing XML Web Services

Support for XML Web services in Visual FoxPro provided by the Microsoft SOAP Toolkit make it possible for you to publish Visual COM Servers (OLEPUBLIC) as XML Web services that can be accessed from the Web. The extensions and objects available in the SOAP Toolkit provide publishing capabilities for XML Web services. For information about publishing Visual FoxPro COM Servers as XML Web services, see Walkthrough: Creating XML Web Services with Visual FoxPro.

Specifying a Default Location for XML Web Services

Before you publish an XML Web service, you can specify a default location for publication. This location is a local Web server Uniform Resource Locator (URL) or a virtual directory that you use to store XML Web service support files, such as ASP listeners and WSDL files. Although this location is optional, it can simplify the process of publishing XML Web services.

Note The Visual FoxPro XML Web Service Location dialog box appears the first time you select Web Services on the Wizards menu. If you do not provide a default location, Visual FoxPro prompts you for the default location each time you publish a new XML Web service. You can change the location later by clicking Advanced in the Visual FoxPro XML Web Services Publisher dialog box.

For more information, see Visual FoxPro XML Web Service Location Dialog Box and Visual FoxPro XML Web Services Publisher Dialog Box.

To specify a default location for an XML Web service

  1. On the Tools menu, point to Wizards, and click Web Services.
  2. In the dialog box that appears, click OK.
  3. In the Visual FoxPro XML Web Service Location dialog box, to select an existing location to publish your XML Web service, click Existing and select a location in the Select Location (Virtual Directory) box.

    -or-

    To select a new location, click New, select a location in the Select Location (Virtual Directory) box, click the Ellipsis (...) button to specify a file output path if desired, and type a name for the directory in the New Virtual Directory Name box.

Settings for each XML Web service are preserved so that you can easily update the XML Web service, for example, if the content of the WSDL changes. These settings are stored in the FoxWS3.dbf table in the same directory as the FoxCode.dbf table (_FOXCODE).

Publishing XML Web Services

You can publish a Visual FoxPro COM Server as an XML Web service to make it available on the Web.

Note Publishing XML Web services through the Visual FoxPro Web Services Publisher dialog box is supported only for generating WSDL files containing a single service and port or class. If you want to select multiple classes, you should use the wizard available in the SOAP Toolkit.

To publish an XML Web service

  1. On the Tools menu, click Task Pane.
  2. On the Task Pane Manager toolbar, click More Panes.
  3. In the XML Web Services pane, click Publish Your XML Web Service.
  4. In the Visual FoxPro XML Web Services Publisher dialog box, click the Ellipsis (...) button to browse for and select the Visual FoxPro COM Server you want.

You can also publish your COM Server by clicking Web Services on the Wizards menu, right-clicking an open COM Server project, clicking Builder on the shortcut menu, and selecting Web Services Publisher in the Wizard Selection dialog box. You can also open the Visual FoxPro XML Web Services Publisher dialog box using the following code:

DO (_wizard) WITH "project",,"Web"

For more information, see Visual FoxPro XML Web Services Publisher.

Test and Rebuild Process for COM Servers

When rebuilding your COM Server, you can generate XML Web service support files automatically by creating a project hook for the COM Server project that calls the XML Web service engine to rebuild the XML Web service support files. You can select this option in the Advanced dialog box of the Visual FoxPro XML Web Services Publisher dialog box. The project hook (WSHOOK) is stored in the XML Web services foundation class library, _WS3Utils.vcx, located in the ...\Ffc folder. For more information, see XML Web Services Foundation Classes.

When you are working with and testing your XML Web service, it is likely that IIS caches your COM Server for performance reasons. To rebuild your COM Server, you might need to first end the process that has the COM Server in use, for example, the IIS Out-Of-Process Pooled Applications COM+ application; otherwise, a denial of access message is generated during the project build process. This process can be a cumbersome if you must test and rebuild the COM Server frequently. The project hook in the XML Web service foundation class library, _WS3Utils.vcx, can close this process for you.

Note You might need to change the default setting in the project hook so that the application ends, depending on which OS platform and version of IIS you are running.

For more information, see XML Web Services Foundation Classes.

Deployment of XML Web Services

When deploying Visual FoxPro applications that use XML Web services, you must include the redistributable components from the SOAP Toolkit. If your application accesses only existing XML Web services, you must include only the SOAP Client merge module.

For applications that publish XML Web services, you must include the client-side and server merge modules from the SOAP Toolkit. In addition, you must include the specific server support files, for example, ASP listener and WSDL files. You should also consider using the XML Web services foundation class files, _WS3Utils.vcx and _WS3Client.vcx, to automate this process when running the deployed application for the first time.

If you automate the XML Web service publishing process, you can create a virtual directory created and generate support files on the fly. However, it is recommended that you perform extensive Setup testing if you choose this approach for deployment.

See Also

XML Web Services in Visual FoxPro | Accessing XML Web Services


Automation and COM Servers

You can extend the functionality of your Visual FoxPro applications without a lot of extra coding time by using Automation and COM Servers. With Automation, you can control other applications, such as Microsoft Excel, from within your own application. COM servers allow you to package complex routines into reusable components.

In This Section

Control of Visual FoxPro from Other Applications
Discusses how you can control Visual FoxPro from other applications by using the Visual FoxPro Application object. Applications that support Automation can create instances of Visual FoxPro, run Visual FoxPro commands, and access Visual FoxPro objects.
Visual FoxPro and Advanced COM
Shows how to take advantage of the COM features in Visual FoxPro by implementing interfaces and event binding. Discusses the inner workings of early versus late binding for both client and server, COM performance, and making COM objects more discoverable.
Creating Automation Servers
Describes the steps and issues involved in creating, compiling, and registering an Automation server using Visual FoxPro. An Automation server is a COM component application that exposes functionality that can be used and reused by other applications through Automation.
Visual FoxPro Run-Time Libraries
Describes the two separate run-time libraries that ship with Visual FoxPro: one for most normal application types and the other for highly scalable in-process server applications.
Server Design Considerations and Limitations
Describes certain behaviors, processes, and limitations that can determine the effectiveness of your server application.

Related Sections

Web Services and Components
Describes how you can enable a Visual FoxPro application to work for multiple users, taking advantage of ActiveX controls and automation-enabled applications, and adding international capabilities.
XML Web Services in Visual FoxPro
Explains how to use Web Services with your applications. A Web Service is a class (object), deployed somewhere on the Internet that you can access programmatically through normal object-oriented calls.
Interoperability and the Internet
Explains how to use OLE drag-and-drop to develop applications that make it possible for you to move data between Microsoft Windows-based applications and within a Visual FoxPro application. Create documents for use on the Internet, or use one of two different Visual FoxPro run times to create COM components (Automation servers) as normal or multithreaded applications.


Control of Visual FoxPro from Other Applications

Because Visual FoxPro acts as a server (with level 2 compliance) as well as a client, applications that support Automation can create instances of Visual FoxPro, run Visual FoxPro commands, and access Visual FoxPro objects.

You control Visual FoxPro from other applications by using the Visual FoxPro Application object. An Application object is automatically created whenever Visual FoxPro is launched, either directly, through DDE or through Automation.

For example, the following lines of code in Visual Basic®, or a Microsoft Excel module create a reference to a Visual FoxPro application object:

Dim oFox as Object
Set oFox = CreateObject("VisualFoxPro.Application")

Once you have a reference to the Visual FoxPro Application object, you can call methods associated with the application object and access other objects through the collection properties of the Application object.

Methods of the Application Object

DataToClip | Help
DoCmd | Quit
Eval | RequestData

The following example uses Visual Basic for Applications code in an Excel module to create a Visual FoxPro Application object, open a Visual FoxPro table, and add the results of a query to the active spreadsheet:

Sub FoxTest()
Dim oFox as Object
Set oFox = CreateObject("VisualFoxPro.Application")

oFox.DoCmd "USE customer"
oFox.DoCmd "SELECT contact, phone FROM customer
   WHERE country = " + Chr$(39) + USA+ Chr$(39) + " INTO CURSOR cust"
oFox.DataToClip "cust",,3
Range("A1:B1").Select
ActiveSheet.Paste
End Sub

The Visual FoxPro Application Object Model

An application object is automatically created whenever Visual FoxPro is launched, either directly, through Automation or DDE. This application object provides access to all other objects created in a Visual FoxPro session through Collection properties.

Visual FoxPro application object model

Accessing Objects Through Collection Properties

The Visual FoxPro application object and all container objects in Visual FoxPro have a count property and a collection property associated with them. The collection property is an array referencing each contained object. The count property is a numeric property indicating the number of contained objects.

The following table lists objects and the corresponding collection and count properties.

Object | Collection Property | Count Property
Application | Objects Forms | Count FormCount
FormSet | Forms | FormCount
Form | Objects Controls | Count ControlCount
PageFrame | Pages | PageCount
Page | Controls | ControlCount
Grid | Columns | ColumnCount
CommandGroup | Buttons | ButtonCount
OptionGroup | Buttons | ButtonCount
Column | Controls | ControlCount
ToolBar | Controls | ControlCount
Container | Controls | ControlCount
Control | Controls | ControlCount

These properties allow you to use a program loop to manage all or specific contained objects. For example, the following lines of code set the Visible property of all forms to True (.T.):

FOR EACH Form IN Application.Forms
   Form.Visible = .T.
ENDFOR

See Also

The Subclassing of Objects | Creating Automation Servers | Adding OLE


Visual FoxPro and Advanced COM

You can take advantage of the COM features in Visual FoxPro by implementing interfaces and event binding. Earlier versions of Visual FoxPro provided early binding support for COM servers, but only late binding support as a client. Visual FoxPro now contains support for early binding clients. This topic discusses the inner workings of early versus late binding for both client and server, as well as COM performance and making COM objects more discoverable.

Contents

Introduction

Creating a Simple Visual FoxPro COM Server

Type Libraries

Performance

Using Visual Basic as a Client

Error Handling

Interfaces

Event Binding

Using Office XP Smart Tags

Visual FoxPro Callback Design

Introduction

COM was developed to make it possible for applications to be treated as objects, which can call each other. Object relationships can take on many forms. The simplest form is a client object, which calls a server object. Examples of object interactions that are more complex than this client-server scenario include peer-to-peer objects, which call each other.

If the objects have no a prior knowledge of each other, there must be some way for the objects to describe how another can call into itself. Event interfaces are examples of objects that describe these callback interfaces. These are interfaces that are not implemented by the software object developer but are implemented by a client of that object. Microsoft ActiveX controls are an example of COM objects with very sophisticated interfaces. These interfaces (on both the control and the host) make it possible for the control to act as a native control on a host site. The host site can implement the control's events interface. This combination can be very powerful in the hands of the developer.

This topic starts with a very simple Microsoft Visual FoxPro COM server and shows how useful it is. Then, it covers Type Libraries, how you can read them to discover how a COM object exposes itself to the world, and performance and error handling. Finally, it talks about what an interface is and about implementing interfaces.

Another dimension of objects calling each other is how they call each other. Visual FoxPro 6.0 made it possible for both early and late binding clients to call Visual FoxPro 6.0 servers, but Visual FoxPro 6.0 only could call servers using late binding. The current version of Visual FoxPro includes the capability of early binding client calls.

Creating a Simple Visual FoxPro COM Server

You create a PRG file, which will be called MYCLASS.PRG, with the following code:

*This entirely self-contained program will build a COM server
* called "myserver.myclass"
* It will unregister a prior instance, if any
IF PROGRAM() != "MYCLASS"
   ?"this file MUST BE NAMED 'myclass.prg'"
   return
ENDIF
IF FILE("myclass.dll")
   DECLARE integer DllUnregisterServer IN myclass.dll
   DllUnregisterServer()
   CLEAR DLLS
ENDIF
BUILD PROJECT myserver FROM myclass
BUILD DLL myserver from myserver recomp
*now test this COM server:
ox = CreateObject("myserver.myclass")    && create the server object
ox.mydocmd("USE home(1)+'samples\data\customer'")    && use a table
?ox.myeval("RECCOUNT()")    && get the record count

DEFINE CLASS myclass AS session OLEPUBLIC
   PROCEDURE MyDoCmd(cCmd as String) as Variant ;
         helpstring "Execute a VFP cmd"
      &cCmd    && just execute parm as if it were a fox command
   FUNCTION MyEval(cExpr as String) ;
         helpstring "Evaluate a VFP expression"
      RETURN &cExpr    && evaluate parm as if it were a fox expr
   FUNCTION Error(nError, cMethod, nLine)
      COMreturnerror(cMethod+'  err#='+str(nError,5)+;
         '  line='+str(nline,6)+' '+message(),_VFP.ServerName)
      && this line is never executed
ENDDEFINE

A program of this structure builds COM servers and does not pollute the registry. Note that the code before the class definition is executed at build time only. Building a COM server automatically registers it in the registry. Rebuilding the server automatically unregisters it first. However, the information to unregister is stored in the PJX file. If the PJX is deleted and rebuilt, the registry entries are not removed when a new PJX is built.

Now, you have built your first server. Building a server in Visual FoxPro also builds a Type Library and registers information in the system registry including the ProgId, Type Library, and file location. The build process creates a file called myserver.vbr, which shows what registry keys get changed for registering the server correctly.

Notice that you are using the SESSION base class that was new to Visual FoxPro 6.0 SP3. It is a very lightweight base class that is non-visual and only has the DataSession property to make it possible for separate data sessions. When building COM servers, the FORM base class also has a DataSession property, but it has many other properties that are irrelevant to a COM server. In addition, these properties are, by default, written out to the Type Library unless you mark them all as protected or hidden.

Type Libraries

A Type Library is a file that can be either freestanding or embedded as a resource inside an EXE or DLL. It is a language-independent method of publishing the interfaces, properties, and methods of a COM object. It can contain help strings, Help context IDs, parameter names, and member names (of properties and methods). If it is not embedded inside an EXE or DLL, typical file extensions are TLB or OLB.

The Visual FoxPro 6.0 generated Type Libraries contain the method and parameter names of OLE Public methods. If there is a description in the Description of the class in the VCX, then that description is put in the Type Library as a help string.

You can view a Type Library using a variety of tools. For example, use the Object Browser in Microsoft Excel or Microsoft Word, the Class Browser in Visual FoxPro, or the OLE Viewer in Visual C++ to view a Type Library. You can see that Type Libraries can contain entire object models of the server application and can be rather extensive.

When a tool is viewing a Type Library, the server cannot be rebuilt, because the Type Library cannot be rewritten. Also, if a client has the server instantiated, it cannot be rebuilt. Using a copy of the built DLL or EXE is one way to avoid this problem.

Reading a Type Library

A Type Library reading tool (TLBINF32.DLL) ships with Microsoft Visual Studio. It is a tool intended for use by multiple products, so it was written as a COM server. Here is some sample code to read the Type Library from the sample server created earlier.

clear
PUBLIC otlb
otli=NEWOBJECT('tli.tliapplication')
otlb=otli.TypeLibInfoFromFile("myserver.dll")
*otlb=otli.TypeLibInfoFromFile("tlbinf32.dll")
*otlb=otli.TypeLibInfoFromFile("c:\program files\microsoft office\office\excel9.olb")
?"CoClasses:"
FOR each oCoClass in otlb.CoClasses
   ?"  ",oCoClass.name
   *now each interface associated with this CoClass
   for each oInterface in oCoClass.Interfaces
      ?"     ",oInterface.name
   endfor
endfor

?
?"Interfaces"

FOR each oInterface in otlb.Interfaces
   ?"  ",oInterface.name
ENDFOR
?
?"Interface Members for 1st interface"
FOR each oMember IN otlb.Interfaces(1).Members
   ?"  ", oMember.name
   FOR each oParm in oMember.Parameters
      ?"             ",oParm.name
   ENDFOR
ENDFOR

This code first creates an instance of the TLB reading tool and then invokes the TypeLibInfoFromFile method to load a Type Library. Items within the library are represented as various collections, which can be manipulated quite easily in Visual FoxPro using the FOR EACH construct.

The Interface collection is a collection of interfaces described in the Type Library. These interfaces can be those implemented by the server or they could be interfaces that should be implemented by a client, for example, in the case of Events.

The CoClass collection describes the COM objects that can be created by a client. The default interface implemented by the CoClass is shown, along with an optional Event Source interface.

Other interfaces besides the default of the CoClass and the Event interface could be described. The way a client obtains these other interfaces could be through a method call. For example, an ICell interface could be returned from a method called GetCell.

Constants also can be defined in the Type Library. For example, to obtain the constants, such as xlMaximized, from the Excel Type Library, explore the otlb.Constants collection.

One way to learn how to use the TLBINF32.DLL tool is to use it on itself. This will show you the properties, methods, parameters, and so on that are useful.

Performance

Performance means many things to many people. In the context of software and COM objects, performance means getting results faster. COM is about making software modules communicate with one another. So improving COM communications will achieve higher performance.

For example, consider the following code:

ox=CreateObject("excel.application")
start = seconds()
ox.workbooks.add
SET EXCLUSIVE OFF
USE HOME()+'samples\data\customer'
ox.visible=1
FOR i= 1 TO RECCOUNT()
   FOR J = 1 TO FCOUNT()
      ox.Activesheet.cells(i,j).value = EVAL(FIELD(j))
   NEXT
   SKIP
NEXT
ox.Workbooks(1).Close(0)   && close workbook, discarding changes
ox=0   && release Excel
?seconds() - start

It fills an Excel spreadsheet with the values from a table. This code takes about 30 seconds to run for 92 records on the author's machine.

When trying to improve performance, you must keep in mind exactly what is happening and try to figure out where the bottlenecks are.

Making the spreadsheet visible only after it has been filled in, rather than before, shaves off some time. Making Excel not maximized makes it a little faster.

Note that most of the time is spent executing the single line of code that assigns the cell a value. You can remove all COM calls by changing this line to

      oa= EVAL(FIELD(j))

This obviously changes the intent of the code but makes the double loop take only one second. This indicates that 29 seconds was being spent in evaluating the ox.Activesheet.cells part of the line.

Analyzing this line further, Visual FoxPro evaluates ox.Activesheet, and the result is put in a temporary value. Then, this temp value is dereferenced to get the cells collection. Each "." in the expression results in a temporary value being obtained and then being dereferenced to get a new value.

Each of these "." dot operator dereferences is actually a round-trip COM method call to Excel, invoking an Excel method which returns a value. First, the IApplication.ActiveSheet method is invoked, which returns to Visual FoxPro a temporary reference to the active sheet. Then, that object's interface is used to get the cells collection. Then, the collection is dereferenced using the cell's indices as parameters to get an object reference to a single cell. Then, that cell's value property is assigned a new value (another COM round-trip). This totals four round-trips.

Obtaining an object reference to ox.Activesheet before the double nested loop and using that cached reference instead resulted in about 50 percent improvement.

oa = ox.Activesheet    && get an object reference
FOR i= 1 TO RECCOUNT()
   FOR J = 1 TO FCOUNT()
      oa.cells(i,j).value = EVAL(FIELD(j))
   NEXT
   SKIP
NEXT

Because the Activesheet is loop invariant with respect to the double loop, you can obtain an object reference to it before the loop and cache it in a variable. This removes one round trip, thus making the total three.

The number of round-trips decreased by 25 percent, but the time decrease was 50 percent. The removal of the number of round-trips will not result in a proportional decrease in overall time. The overhead of creating and releasing several temporary variables, the fraction of the time spent actually in the server executing the code, and other factors are not linear.

Note The previous code does not have to use Activesheet at all. The cells collection also is found from the Iapplication interface. It was used here only for illustration purposes.

Using Visual Basic as a Client

You can use Visual Basic as a client to accomplish the same task.

To use Visual Basic as a client

  1. Start Excel.
  2. On the Tools menu, point to Macro.
  3. Click Macros, and name it t.
  4. Click Create.
  5. On the Tools menu, click References, and add the myserver Type Library to the references.

    This makes it possible for the myserver Type Library information to be used in the macro.

  6. Paste the following code:
    Sub t()
Dim ox As New myserver.myclass
ox.mydocmd ("set exclusive off")
ox.mydocmd ("use d:\fox70\test\customer")
n = ox.MyEval("reccount()")
nflds = ox.MyEval("fcount()")
nsecs = ox.MyEval("seconds()")
For i = 1 To n
    For j = 1 To nflds
        cc = "evaluate(field(" & j & "))"
        Application.Sheets(1).Cells(i, j).Value = ox.MyEval(cc)
    Next
    ox.mydocmd ("skip")
Next
MsgBox (ox.MyEval("seconds()") - nsecs)
End Sub

Error Handling

Error handling is very important in COM servers, and particularly so in DLL servers. If the client were to invoke a method on the server that caused some sort of error, such as File Not Found or Access Denied, it would not be good to have the server show a message box indicating the error. The developer should use the Error Method of the OLE Public class to handle such errors gracefully. A new function in Visual FoxPro 6.0, called COMReturnError, will cause a COM Error object to be created and returned to the COM client. It takes two parameters: the Source and the Description. You can put any strings you want into these parameters. This example method can be pasted right into the previous myserver sample.

FUNCTION Error(nError, cMethod, nLine)
   COMreturnerror(cMethod+'  err#='+str(nError,5)+'  line='+str(nline,6)+'
      '+message(),_VFP.ServerName)
   && this line is never executed

You can invoke this error method by calling the MyDocmd method with an invalid command:

ox = CreateObject("myserver.myclass")    && create the server object
?ox.mydocmd("illegal command")    && causes an Error to occur

The error that occurs in the server is trapped by the MyClass::Error method, which then causes the server to abort processing and return the COM Error object with the Source and the Description filled out.

?aerror(myarray)
list memo like myarray
MYARRAY     Pub    A
   (   1,   1)     N  1429        (      1429.00000000)
   (   1,   2)     C  "OLE IDispatch exception code 0 from mydocmd
                      err#=   16  line=     2 Unrecognized command v
                      erb.: c:\fox\test\myserver.exe.."
   (   1,   3)     C  "c:\fox\test\myserver.exe"
   (   1,   4)     C  "mydocmd  err#=   16  line=     2 Unrecognized
                       command verb."
   (   1,   5)     C  ""
   (   1,   6)     N  0           (         0.00000000)
   (   1,   7)     N  0           (         0.00000000)

Interfaces

Operationally, a COM interface can be thought of as a pointer to a table of function addresses. This table is sometimes called the vtable, or virtual function table. The interface definition includes the number of entries in the table, the association between the method name and the table index, and the function signatures of each method call. The signature consists of the number of parameters, the types of the parameters, and the return value.

All COM interfaces inherit from IUnknown. This means that the first three entries in every COM interface vtable are defined to be the addresses of the server's implementation of IUnkown::QueryInterface, IUnkown::AddRef, and IUnkown::Release.

When an interface inherits from another interface, all that means is that the interfaces vtable consists of the vtables of the inherited interfaces first.

Dual interfaces are COM Interfaces that inherit from the IDispatch interface. The IDispatch interface has only four methods: GetTypeInfoCount, GetTypeInfo, GetIDsOfNames, and Invoke. Thus, the first seven interfaces are well defined in an IDispatch interface and any other interface that inherits from IDispatch.

For Myserver.dll created earlier, the dual interface IMyClass would look like this:

   IMyClass
      QueryInterface(QI params)  (from IUnknown)
      Addref                     (from IUnknown)
      Release                    (from IUnknown)
      GetTypeInfoCount()         (from IDispatch)
      GetTypeInfo()              (from IDispatch)
      GetIDsOfNames()            (from IDispatch)
      Invoke()                   (from IDispatch)
      MyDoCmd(cCmd)              (from IMyClass)
      MyEval(cExpr)              (from IMyClass)

Suppose that the client wants to make a call to the Activesheet method of the dual interface IApplication on the server. The actual call can be made in two ways: early and late binding. Early binding is sometimes called VTtable binding, because it just means the client calls the server directly by finding the address of Activesheet in the vtable directly. This function address is an entry in the vtable and will be larger than seven. This function address index is hard coded into the client call at client compile time and is known as early binding. If subsequent versions of the server were to change the vtable order, then early binding client calls would be erroneous.

Late binding calls go through the IDispatch interface. The client calls IDispatch::GetIDsOfNames with the string Activesheet to get the function ID of that function. (This function ID then can be cached by the client for subsequent calls.) The client then packages all the Activesheet parameters into a single DISPPARAMS structure, and the IDispatch::Invoke function is called with the function ID and the DISPPARAMS as parameters. The implementation of IDispatch::Invoke on the server side unpacks the DISPPARAMS structure, makes the actual call to Activesheet, gets the return value, and passes that back to the client.

Because late binding does not hard code the function index of method calls, clients do not have to know at compile time what the function index is for methods and still will work, even if a new version of the server rearranges the vtable order or changes the method signatures. However, the parameter packaging on the client side and the unpackaging on the server side adds execution time to the method calls that does not exist with early binding calls.

Implementing Interfaces

Implementing an interface means that you examine an object's properties, events, and methods and create a new object that has exactly the same properties, events, and methods. This includes any parameters, parameter types, and return values. In other words, if an object knows how to call another object using a specific interface, then it also knows how to call any object that implements that specific interface.

Implementing an interface promises to the client that every method on that interface can be called. That means if there is a method called Sample(parm1 as int, parm2 as string, parm3 as variant @) as int, then that identical method signature must be found in the object.

In the following ADO sample, for example, if a parameter is removed from the method signature, running the code yields this message:

Class can not be instantiated because Member 'RECORDSETEVENTS_WillChangeField' has wrong # of parameters

Similarly, removing a method yields another error message.

As mentioned earlier, interfaces are described in Type Libraries for all to see. The Visual FoxPro 7.0 Object Browser (on the Tools Menu) makes it possible for you to inspect type libraries. If you drag an interface from it onto a PRG that is open in the Visual FoxPro editor, then the object browser will generate the method signatures required for implementing that interface.

Event Binding

The ability to implement interfaces makes it possible for some interesting capabilities with Microsoft Office. This sample implements the events for Microsoft Outlook, Excel, and Word. As you can see from the method names, each Office application provides different interfaces. The new EventBinding command in the current version of Visual FoxPro makes it possible for the developer to bind a Visual FoxPro class that implements an interface to the COM object that is the event source and publisher.

This event model is called tightly coupled events. The client and the server must have intimate knowledge about each other, and there's a one-to-one correspondence between the objects. A new model of object event interaction is called loosely coupled events, in which an object can publish events, and another object can subscribe to those events.

CLEAR
CLEAR all
PUBLIC ox as Excel.Application, ;
   ow as word.application, ;
   oOutlook as Outlook.Application

oOutlookEvents= NEWOBJECT('OutlookEvents')

oOutlook = NEWOBJECT("Outlook.Application")
oOutlookEvents.oo = oOutlook
? "Outlook",EVENTHANDLER( oOutlook, oOutlookEvents)

oWordEvents = NEWOBJECT("WordEvents")
ow = NEWOBJECT("word.application")
oWordEvents.ow = ow
?"Word",EVENTHANDLER(ow,oWordEvents)
ow.visible = .t.
ow.Activate
ow.Documents.Add

oExcelEvents = NEWOBJECT("ExcelEvents")
oex = NEWOBJECT("excel.application")
oex.Workbooks.Add
?"Excel",EVENTHANDLER(oex, oExcelEvents)
oex.visible = .t.

_screen.WindowState= 1

DEFINE CLASS OutlookEvents AS SESSION OLEPUBLIC
   IMPLEMENTS ApplicationEvents IN Outlook.Application
   oo = .null.
   PROCEDURE ApplicationEvents_ItemSend(ITEM AS VARIANT, ;
         CANCEL AS LOGICAL) AS VOID
      ?PROGRAM()
      m.item.Body=STRTRAN(m.item.Body,"good","bad") + ;
         CHR(13)+CHR(10)+TRANSFORM(DATETIME())+" Fox was here!"
*      if Recipients fails, it could be outlook security
*      m.item.Recipients.Add("anyone@anywhere.com")
   PROCEDURE ApplicationEvents_NewMail() AS VOID
      ?PROGRAM()
   PROCEDURE ApplicationEvents_Reminder(ITEM AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE ApplicationEvents_OptionsPagesAdd(PAGES AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE ApplicationEvents_Startup() AS VOID
      ?PROGRAM()
   PROCEDURE ApplicationEvents_Quit() AS VOID
      ?PROGRAM()
   PROCEDURE destroy
      ?PROGRAM()
      IF !ISNULL(this.oo)
         ?EVENTHANDLER(this.oo,this,.t.)
      ENDIF
ENDDEFINE

DEFINE CLASS WordEvents as Custom
   implements applicationevents2 in "word.application"
   ow = .null.
   PROCEDURE applicationevents2_startup()
      ?PROGRAM()
   PROCEDURE applicationevents2_quit
      ?PROGRAM()
   procedure applicationevents2_DocumentBeforeClose(Cancel,Doc)
      ?PROGRAM()
   procedure DocumentBeforeClose(Cancel,Doc)
      ?PROGRAM()
   procedure applicationevents2_DocumentBeforePrint(Cancel,Doc)
      ?PROGRAM()
   procedure applicationevents2_DocumentBeforeSave(Doc,SaveAsUI,Cancel)
      ?PROGRAM()
   procedure applicationevents2_DocumentChange
      ?PROGRAM()
   procedure applicationevents2_DocumentOpen(Doc)
      ?PROGRAM()
   procedure applicationevents2_NewDocument(Doc)
      ?PROGRAM()
   procedure applicationevents2_WindowActivate(Doc,Wn)
      ?PROGRAM()
   procedure applicationevents2_WindowBeforeDoubleClick(Sel,Cancel)
      ?PROGRAM()
   procedure applicationevents2_WindowBeforeRightClick(Sel,Cancel)
      ?PROGRAM()
   procedure applicationevents2_WindowDeactivate(Doc,Wn)
      ?PROGRAM()
   procedure applicationevents2_WindowSelectionChange(Sel)
      ?PROGRAM(),sel.text
      IF sel.start < sel.end
          sel.InsertAfter("Fox!")
*!*         mtmp = sel.text
*!*         sel.text=STRTRAN(mtmp,"good","Great!")
      endif
   PROCEDURE destroy
       ?PROGRAM()
       IF !ISNULL(this.ow)
         ?EVENTHANDLER(this.ow,this,.t.)
      ENDIF
ENDDEFINE

DEFINE CLASS ExcelEvents AS session OLEPUBLIC
   IMPLEMENTS AppEvents IN "excel.application"
   PROCEDURE AppEvents_NewWorkbook(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetSelectionChange(Sh AS VARIANT, ;
         Target AS VARIANT) AS VOID
      LOCAL mtmp,mcell
      mcell = m.target.Cells(1,1)
      IF !ISNULL(mcell)
         mtmp = m.target.Cells(1,1).Value
         ?PROGRAM(),VARTYPE(mtmp)
         DO case
         case ISNULL(mtmp)
   *         m.target.Cells(1,1).Value  = "Fox is great"
         CASE VARTYPE(mtmp)='C'
            m.target.Cells(1,1).Value = ;
               STRTRAN(mtmp,"good","great!")
         CASE VARTYPE(mtmp)='N'
            m.target.Cells(1,1).Value = mtmp + 1
         ENDCASE
      ENDIF
   PROCEDURE AppEvents_SheetBeforeDoubleClick(Sh AS VARIANT, ;
         Target AS VARIANT, Cancel AS LOGICAL) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetBeforeRightClick(Sh AS VARIANT, ;
         Target AS VARIANT, Cancel AS LOGICAL) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetActivate(Sh AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetDeactivate(Sh AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetCalculate(Sh AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetChange(Sh AS VARIANT, Target AS VARIANT) AS
         VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookOpen(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookActivate(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookDeactivate(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookBeforeClose(Wb AS VARIANT, ;
         Cancel AS LOGICAL) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookBeforeSave(Wb AS VARIANT, ;
         SaveAsUI AS LOGICAL, Cancel AS LOGICAL) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookBeforePrint(Wb AS VARIANT, ;
         Cancel AS LOGICAL) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookNewSheet(Wb AS VARIANT, ;
         Sh AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookAddinInstall(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookAddinUninstall(Wb AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WindowResize(Wb AS VARIANT, Wn AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WindowActivate(Wb AS VARIANT, Wn AS VARIANT) AS
         VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WindowDeactivate(Wb AS VARIANT, Wn AS VARIANT) AS
         VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetFollowHyperlink(Sh AS VARIANT, ;
         Target AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_SheetPivotTableUpdate(Sh AS VARIANT, ;
         Target AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookPivotTableCloseConnection(Sh AS VARIANT, ;
         Target AS VARIANT) AS VOID
      ?PROGRAM()
   PROCEDURE AppEvents_WorkbookPivotTableOpenConnection(Sh AS VARIANT, ;
         Target AS VARIANT) AS VOID
      ?PROGRAM()
ENDDEFINE

Here is a sample of implementing ADO event interfaces. In this case, the user is not interacting with an application, causing events to occur, as in the Office examples earlier. Here, the user is calling ADO directly using method calls, and ADO is calling back to the client using its event interface.

clear
CLEAR all
local ox as adodb.recordset
local oc as ADODB.Connection
oe = NEWOBJECT("myclass")
oe2 = NEWOBJECT("myclass")

oc=NEWOBJECT("adodb.connection")
connstr = "Driver={Microsoft Visual FoxPro Driver};UID=;PWD=;SourceDB=" + ;
   HOME(1)+"samples\data\testdata.dbc" + ;
    ";SourceType=DBC;Exclusive=No;BackgroundFetch=No;Collate=Machine;"
*
oc.ConnectionString= connstr
oc.Open
ox = oc.Execute("select * from customer")
* Now enable event handling
?EVENTHANDLER(ox,oe)
?EVENTHANDLER(ox,oe2)

?
?PADR(ox.Fields(0).Value,20)

?EVENTHANDLER(ox,oe2,.f.) && Turn off 2nd obj event handling
ox.MoveNext
?PADR(ox.Fields(0).Value,20)
ox.MoveNext
CLEAR all
retu
for i = 0 to ox.Fields.Count-1
*   ?PADR(ox.Fields(i).Name,20)
*   ?ox.Fields[i].value
endfor

DEFINE CLASS myclass AS session
   implements RecordsetEvents IN "adodb.recordset"
*  implements RecordsetEvents IN ;
*"C:\PROGRAM FILES\COMMON FILES\SYSTEM\ADO\MSADO15.DLL"
   PROCEDURE Recordsetevents_WillChangeField(cFields AS Number @, ;
         Fields AS VARIANT @, adStatus AS VARIANT @, ;
         pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_FieldChangeComplete(;
         cFields AS Number @, ;
         Fields AS VARIANT @, pError AS VARIANT @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_WillChangeRecord(adReason AS VARIANT @, ;
         cRecords AS Number @, adStatus AS VARIANT @, ;
         pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_RecordChangeComplete(adReason AS VARIANT @, ;
         cRecords AS Number @, pError AS VARIANT @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_WillChangeRecordset(adReason AS VARIANT @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
      ?adreason,adstatus,precordset.recordcount
   PROCEDURE Recordsetevents_RecordsetChangeComplete(;
         adReason AS VARIANT @, ;
         pError AS VARIANT @, adStatus AS VARIANT @, ;
         pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_WillMove(adReason AS VARIANT @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_MoveComplete(adReason AS VARIANT @, ;
         pError AS VARIANT @, adStatus AS VARIANT @, ;
         pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_EndOfRecordset(fMoreData AS LOGICAL @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_FetchProgress(Progress AS Number @, ;
         MaxProgress AS Number @, adStatus AS VARIANT @, ;
         pRecordset AS VARIANT @) AS Void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
   PROCEDURE Recordsetevents_FetchComplete(pError AS VARIANT @, ;
         adStatus AS VARIANT @, pRecordset AS VARIANT @) AS void
      ? " "+program() + ' ' + TRANSFORM(DATETIME())
ENDDEFINE

Using Office XP Smart Tags

Office XP includes a new capability called Smart Tags. As a typical knowledge worker at a company works, she might use several computer applications and use similar subjects in each one. For example, the company might have a customer list, and she might need to e-mail, create documents or spreadsheets, or even view Web pages about customers. Suppose that at this instant, she is writing an e-mail message about customer ALFKI, and she must know the customer phone number or credit limit. Typically, this means starting or switching to another application, which maintains this information, doing a lookup for ALFKI, and transferring the data to the e-mail.

Smart Tags technology is a way that multiple applications can recognize strings (tags) within text and optionally provide the user a way to invoke a menu right on top of that tag which can give useful information or perform useful tasks. A smart tag on ALFKI might not only offer the credit limit and address but also might offer the option to go to the customer's Web site, add to a transaction log, launch another application, or even dial the phone. The user could even type in ALFKI temporarily to any application that is being used currently, look up information, then delete that string in the app.

The following is a sample of Smart Tags technology that recognizes the customer IDs in the sample customer table. The Smart Tag action verbs make up the fields of the table, plus one to visit the customer Web site. If the application is Word, the verb for the field inserts that field into the Word document. For Excel, the field value is inserted in the adjacent column, and the width of that column is adjusted. For Internet Explorer, a message box is displayed (note that even though this is a Visual FoxPro DLL, MessageBox can be called using Declare DLL).

A Smart Tag only must register its ProgID in the registry at the appropriate places. The Smart Tag SDK (available on the Microsoft Web site) gives more details on Smart Tags.

A Smart Tag must implement two interfaces: ISmartTagRecognizer and ISmartTagAction. The first scans a string and calls back on a parsed object if a tag is recognized. The second interface describes the actions possible and actually performs the actions.

Note If you have any Office applications open, they will have an instance of your DLL open. You will not be able to modify the DLL until you close the Office application.

The Logit method writes to a log file, which is a useful technique to learn about how the interfaces work and to debug any code. Using an editor that automatically refreshes an externally modified file to display the log is useful.

CLEAR ALL
clear
SET excl off
?PROGRAM()

*Smart tags in Office XP. Just change the DATAPATH,STAGPATH if necessary
IF PROGRAM() != "STAG"
   ?"this file MUST BE NAMED 'stag.prg'"
ENDIF
#define STNAME  "MynameSpaceURI#MyLocalName"
#define DATAPATH HOME(1)+"samples\data\"
#define STAGPATH "C:\Program Files\Common Files\Microsoft Shared\Smart Tag\mstag.tlb"
IF .t.
   IF FILE("stag.dll")
      DECLARE integer DllUnregisterServer IN stag.dll
      DllUnregisterServer()
      CLEAR DLLS
   ENDIF
   BUILD PROJECT stag FROM stag
   BUILD mtDLL stag from stag recomp
   STRTOFILE("","d:\t.txt")    && null log file
endif

#DEFINE HKEY_CURRENT_USER  -2147483647  && BITSET(0,31)+1
oFoxReg=NEWOBJECT("foxreg", HOME(1)+"FFC\registry")
oFoxReg.OpenKey("Software\Microsoft\Office\Common\Smart Tag\Actions\stag.MyStag", ;
   HKEY_CURRENT_USER, .T.)
oFoxReg.OpenKey(;
   "Software\Microsoft\Office\Common\Smart Tag\Recognizers\stag.MyStag", ;
   HKEY_CURRENT_USER, .T.)

DEFINE CLASS MyStag AS Session OLEPUBLIC
   IMPLEMENTS ISmartTagRecognizer IN STAGPATH
   IMPLEMENTS ISmartTagAction IN STAGPATH
   PROCEDURE ISmartTagRecognizer_get_ProgId() AS STRING
      logit()
      RETURN   "stag.MyStag"
   PROCEDURE ISmartTagRecognizer_get_Name(LocaleID AS Integer) AS STRING
      logit()
      RETURN "VFP NorthWind Customer Recognizer"
   PROCEDURE ISmartTagRecognizer_get_Desc(LocaleID AS Integer) AS STRING
      logit()
      RETURN "VFP NorthWind Customer ID Recognizer"
   PROCEDURE ISmartTagRecognizer_get_SmartTagCount() AS Integer
      logit()
      RETURN 1
   PROCEDURE ISmartTagRecognizer_get_SmartTagName(;
         SmartTagID AS Integer) AS STRING
      logit()
      If SmartTagID = 1
         RETURN STNAME
         EndIf
      RETURN ""
   PROCEDURE ISmartTagRecognizer_get_SmartTagDownloadURL(;
         SmartTagID AS Integer) AS STRING
      logit()
      RETURN ""
   PROCEDURE ISmartTagRecognizer_Recognize(cText AS STRING, ;
         DataType AS Integer, ;
         LocaleID AS Integer, RecognizerSite AS VARIANT) AS VOID
      logit(ctext+' '+TRANSFORM(LEN(CTEXT)))
      LOCAL i,  mat,cWord,propbag
      i = 1
      DO WHILE i <= LEN(cText)
         IF ISALPHA(SUBSTR(cText,i))
            mst = i
            DO WHILE i <= LEN(cText) AND ;
                  (ISALPHA(SUBSTR(cText,i)) or ;
                  ISDIGIT(SUBSTR(cText,i)))
               i=i+1
            ENDDO
            IF mst # i
               cWord = SUBSTR(cText,mst,i-mst)
               IF SEEK(cWord,"Customer")
                  * Ask for a property bag
                  propbag = ;
                     RecognizerSite.GetNewPropertyBag()
                  * Commit the smart tag
                  propbag.write("test","value")
                  propbag.write("test2","value2")
                     RecognizerSite.CommitSmartTag(STNAME, ;
                       mst, LEN(cWord), propbag)
                    propbag=.null.
               ENDIF
            ENDIF
         ENDIF
         i=i+1
      ENDDO
***********************
   PROCEDURE ISmartTagAction_get_ProgId() AS STRING
      logit()
      RETURN "stag.MyStag"
   PROCEDURE ISmartTagAction_get_Name(LocaleID AS Integer) AS STRING
      logit()
      RETURN "Customer Actions"
   PROCEDURE ISmartTagAction_get_Desc(LocaleID AS Integer) AS STRING
      logit()
      RETURN  "Provides actions for VFP Customer data"
   PROCEDURE ISmartTagAction_get_SmartTagCount() AS Integer
      logit()
      RETURN 1
   PROCEDURE ISmartTagAction_get_SmartTagName(SmartTagID AS Integer) AS
         STRING
      logit()
      IF SmartTagID = 1
         RETURN STNAME
      EndIf
      RETURN ""
   PROCEDURE ISmartTagAction_get_SmartTagCaption(SmartTagID AS Integer, ;
         LocaleID AS Integer) AS STRING
      logit(TRANSFORM(SmartTagID ))
      RETURN  "Customer Lookup"
   PROCEDURE ISmartTagAction_get_VerbCount(SmartTagName AS STRING) AS
         Integer
      logit(SmartTagName )
      If SmartTagName = STNAME
            RETURN FCOUNT()+1
         ENDIF
         RETURN 0
   PROCEDURE ISmartTagAction_get_VerbID(SmartTagName AS STRING, ;
         VerbIndex AS Integer) AS Integer
      logit(SmartTagName +', '+ TRANSFORM(VerbIndex ))
      RETURN VerbIndex
   PROCEDURE ISmartTagAction_get_VerbCaptionFromID(VerbID AS Integer, ;
         _ApplicationName AS STRING, LocaleID AS Integer) AS STRING
      logit(TRANSFORM(VerbID )+' '+_ApplicationName +;
         ' '+TRANSFORM(LocaleID))
      IF VerbId <= FCOUNT()
         RETURN "View "+FIELD(VerbID)
      ENDIF
      RETURN "Visit customer Web site"
   PROCEDURE ISmartTagAction_get_VerbNameFromID(VerbID AS Integer) AS
         STRING
      logit(TRANSFORM(VerbID))
      IF VerbId <= FCOUNT()
         RETURN FIELD(VerbID)
      ENDIF
      RETURN "Visit Web site"
   PROCEDURE ISmartTagAction_InvokeVerb(VerbID AS Integer, ;
         cApplicationName AS STRING, ;
         Target AS VARIANT, oProperties AS VARIANT, ;
         cText AS STRING, Xml AS STRING) AS VOID
      logit(TRANSFORM(VerbID )+' '+cApplicationName +' '+cText+' ';
          +Xml+' '+TRANSFORM(oProperties.count))
      LOCAL i,cProp
      oProperties.write("iitest","iivalue")
      oProperties.write("iitest2","iivalue2")
      FOR i = 1 to oProperties.count
         cProp = oProperties.keyfromindex(i-1)
         logit(cProp)
         logit(oProperties.read(cprop))
      endfor
      LOCAL fExcel,fWord
      DO case
      CASE capplicationname = "Excel.Application.10"
         fExcel = .t.
         logit(m.target.cells[1,1].value)
      CASE capplicationname = "Word.Application.10"
         fWord = .t.
*         logit(m.target.range
      ENDCASE
      IF verbId > FCOUNT()
         LOCAL oie as internetexplorer.application
         oie = NEWOBJECT("internetexplorer.application")
         oie.navigate2("localhost/"+ctext+".html")
         oie.visible=1
      else
         IF SEEK(cText,"customer")
            DO case
            case fExcel
               target.cells[1,2].value = ;

   ALLTRIM(TRANSFORM(EVALUATE(FIELD(VerbID))))
               target.Columns(2).columnWidth = 25
            case fWord
               target.insertAfter(' '+;

   ALLTRIM(TRANSFORM(EVALUATE(FIELD(VerbID)))))
            otherwise
               DECLARE Integer MessageBox IN WIN32API ;
                  as msgbox ;
                  Integer,string,string, integer
               msgbox(0,;

   ALLTRIM(TRANSFORM(EVALUATE(FIELD(VerbID)))), ;
                  ctext+"="+company,0)
            endcase
         ELSE
            logit("not found")
         ENDIF
      ENDIF
   PROCEDURE Init
      logit()
      SET EXACT ON
      SET EXCLUSIVE off
      SET PATH TO DATAPATH
      USE customer order cust_id shared
   PROCEDURE Destroy
      logit()
   PROCEDURE MyDoCmd(cCmd as String)
      &cCmd
   PROCEDURE MyEval(cExp as String)
      RETURN &cExp
   PROCEDURE Error(nError, cMethod, nLine)
      logit(TRANSFORM(nError)+' '+TRANSFORM(nLine)+' '+MESSAGE())
ENDDEFINE
#if .f.
DEFINE CLASS STagAction AS StagRecognizer OLEPUBLIC
   PROCEDURE Error(nError, cMethod, nLine)
      logit(PROGRAM()+" "+TRANSFORM(nError)+' '+TRANSFORM(nLine)+' '+MESSAGE())

ENDDEFINE
#endif
   FUNCTION Logit(cStr)
TEXT TO mystr TEXTMERGE NOSHOW
<<DATETIME()>> <<PROGRAM(PROGRAM(-1)-1)>> <<cStr>>

ENDTEXT
      STRTOFILE(myStr,"D:\t.TXT",.T.)

Visual FoxPro Callback Design

Visual FoxPro makes it possible for the developer to create COM objects, which publish interfaces that clients can implement. This callback scenario is almost identical to Visual FoxPro objects raising events to clients. This sample consists of a main COM server class called IDEMO, which also publishes an event interface, called DemoEvents.

The client code has a single class called cCallBack, which implements DemoEvents.

IDEMO has a method called BuyStock, which clients can call to buy some stock. The BuyStock method just has a comment where code can be put to buy the stock. However, before and after that code, the method calls methods in the DemoEvents class. If the client does not have a callback procedure set using the SetCallBack method, then the calls to the DemoEvents methods do nothing. However, if there is a callback object, then those methods will be called on the client.

CLEAR ALL
IF PROGRAM() != "IDEMO"
   ?"this file MUST BE NAMED 'idemo.prg'"
   RETURN
ENDIF
IF .t.
   IF FILE("idemo.dll")
      DECLARE integer DllUnregisterServer IN idemo.dll
      DllUnregisterServer()
      CLEAR DLLS
   ENDIF
   BUILD PROJECT idemo FROM idemo
   BUILD DLL idemo from idemo recomp
endif
clear

oCallback = NEWOBJECT("cCallback")    && the event callback
ostock=newOBJECT("idemo.idemo")       && the business COM obj
ostock.setcallback(oCallBack)         && like BindEvents
?ostock.BuyStock("MSFT",10000 )       && invoke a method
ostock.setcallback(.null.)            && like UnBindEvents
?ostock.BuyStock("MSFT",20000 )       && this one doesn't fire events

*This is the actual implementation of the event interface
DEFINE CLASS cCallback as session
   implements iDemoEvents in idemo.dll
   procedure iDemoEvents_BeforeBuyStock(cStock as String, qty AS Number)
      ?program(),cstock,qty
   procedure iDemoEvents_AfterBuyStock(cStock as String, qty AS Number)
      ?program(),cstock,qty

enddefine
*the rest of this file is used in the COM server
DEFINE CLASS idemo as session olepublic
   oc = .null.
   PROCEDURE init
      this.SetCallBack(.null.)    && set callback to default
   PROCEDURE setcallback(oC as Variant)
      IF ISNULL(oc)
         && dummy instance that does nothing: virtual function
         this.oc = NEWOBJECT("DemoEvents")
      else
         IF VARTYPE(oc) != 'O'
            COMRETURNERROR(PROGRAM(),"callback must be obj")
         ENDIF
         this.oc = GETINTERFACE(oC,"iDemoEvents","idemo.idemo")
      endif
   procedure MyDoCmd(cCmd as String) as Variant
      &cCmd
   procedure MyEval(cExpr as String) as Variant
      return &cExpr
   procedure BuyStock(cStock as String, qty AS Number) as Boolean
      this.oc.BeforeBuyStock(cStock, qty)
      *here we buy the stock
      this.oc.AfterBuyStock(cStock, qty)
   FUNCTION Error(nError, cMethod, nLine)
      COMreturnerror(cMethod+'  err#='+str(nError,5)+'  line='+;
         str(nline,6)+' '+message(),_VFP.ServerName)
      && this line is never executed

enddefine

*Just an interface definition that should be implemented by outside callers
DEFINE CLASS DemoEvents as session olepublic
   procedure BeforeBuyStock(cStock as String, qty AS Number)
   procedure AfterBuyStock(cStock as String, qty AS Number)
enddefine

COM enables objects to interact with each other in various ways. Each addition of new COM capabilities to Visual FoxPro, including a simple COM client functionality, interface implementation, and early binding server and client support, has provided many new capabilities.

See Also

Creating Automation Servers | Automation Server Programming Notes | Event Binding for COM Objects | Automation and COM Servers


Creating Automation Servers

An Automation server is a COM component application that exposes functionality that can be used and reused by other applications through Automation. For example, using Visual FoxPro you can create an Automation server that displays reusable forms (in an out-of-process .exe file), or packages a complex routine into a simple component that other programmers can use. In addition, you can create one or more classes to handle enterprise-wide business rules. A client application that uses the business rule object would pass input parameters in a method call, and the Automation server might then do a great deal of work, retrieving or storing data from various sources and performing complex calculations, before returning the answer.

Examples of Automation servers are installed in the Visual FoxPro...\Samples\Servers directory.

Creating the Automation Server

All you need to create an Automation server in Visual FoxPro is a project that contains classes defined as OLEPUBLIC. You can have as many OLEPUBLIC classes as you want in the project and they can be defined in program files (.prg) or class libraries (.vcx).

For example, the following class definition in a program file creates a custom OLE public class:

DEFINE CLASS person AS CUSTOM OLEPUBLIC
   FirstName = SPACE(30)
   LastName = SPACE(45)

   PROCEDURE GetName
      RETURN THIS.FirstName + " " + THIS.LastName
   ENDPROC
ENDDEFINE

When you're designing a class in the Class Designer, select OLE Public in the Class Info dialog box to designate the class as OLEPUBLIC.

Compiling the Automation Server

In Visual FoxPro, you can create either an out-of-process or an in-process Automation server. An out-of-process component is an executable (.exe file) that runs in its own process. Communication between a client application and an out-of-process server is therefore called cross-process communication. An in-process component is a dynamic-link library (DLL) that runs in the same process address space as the client that calls it.

There are benefits to each. An in-process server is faster because there is no inter-process communication overhead. On the other hand, an out-of-process server can be deployed remotely and an in-process server cannot. Additionally, because the in-process server and the client share a process address space, any serious error in the .dll will terminate the client whereas an error in an out-of-process .exe would only terminate the server.

Note Because in-process .dll and out-of-process .exe Automation servers are invoked through class instantiation, your project need not specify a main file. In Visual FoxPro you can now build an in-process .dll or an out-of-process .exe Automation server without first specifying a main file in the Project Manager.

When you create an executable with OLE Public classes, you don't lose any of your normal .exe capabilities. You can still run the executable, provide a user interface, and all the normal functionality you would include in an application. You increase the extensibility of your application, though, by allowing other applications to tap into the specific functionality you want to expose.

To compile an Automation server

  1. From the Project Manager, choose Build.
  2. In the Build Options dialog box, choose Build Win32 executable / COM server (exe), Build Single-threaded COM server (dll), or Build Multi-threaded COM server (dll).
  3. Choose OK.

    -or-

    When you type BUILD<space> in the command window and there is an active project, an Intellisense script will help to complete the BUILD command by showing the full paths to the target and the project

Once you build the project, you can see the server classes displayed in the Project Information dialog box. Here you can also specify a help file and a Help context ID for each class. This help file can be opened from most generic object browsers.

You can choose class-specific instancing values in the Project Information dialog box. The instancing options are:

  • Not Creatable Even though the class is marked OLE public, it will not be available to other applications. For example, you could have a standard library of OLE public classes used in multiple applications and disable automation of one or more classes for a single application.
  • Single Use Each client application that uses your server creates a separate instance of the server class. Each instance has a single thread of execution. Although separate instances require more memory, choosing Single Use allows the operating system to apply preemptive multitasking.
  • Multi Use Once the server has been created, other applications can use the same instance.
    Note If you make changes in the Servers tab of the Project Information dialog box, you need to rebuild the .dll or .exe for the new settings to take effect.

When you build a project with OLE public classes, three files are created:

  • The .dll or .exe file
  • A type library (.tlb) file
  • A registry (.vbr) file

The type library file is a binary file that lists all the published classes in your Automation server, along with their properties, methods, and events. OLE object browsers read this information and present it in a readable interface. For more information, see Binding Type Libraries.

The registry file lists the global unique IDs (GUID) for the classes in your server.

Note A .vbr registry file is the same as a .reg registry file except that the .vbr file doesn't include hard-coded paths.

Registering an Automation Server

Your Automation servers are available to other applications once the servers have been added to the Windows Registry. When you build an Automation server, it's automatically registered on the build machine. You can also register your servers on other machines.

When you use the Visual FoxPro Setup to create setup disks, the setup program registers your servers on your customers' machines. You can also manually register servers.

To register an .exe component

  • Run the .exe file with the /regserver switch.

    For example, to register Myserver.exe, run the following command:

    myserver /regserver

To remove an .exe component registry entry

  • Run the .exe file with the /unregserver switch.

    For example, to unregister Myserver.exe, run the following command:

    myserver /unregserver

To register a .dll component

  • Run REGSVR32 with the name of the server.

    For example, to register Myserver.dll run the following command:

    REGSVR32 myserver.dll

To remove a .dll component registry entry

  • Run REGSVR32 with the name of the server and the /u switch.

    For example, to register Myserver.dll run the following command:

    REGSVR32 /u myserver.dll
    Note The registry contains the full path name to the file, so if you move the file, you'll need to register it again.

Using the Automation Server

Any application that can create Automation objects can create objects based on your Automation server, set properties that are not HIDDEN or PROTECTED, and call methods. For example, assuming that your server is named foxole and contains a class named person with a GetName method, the following code could be run in Visual FoxPro:

oTest = CREATEOBJECT("foxole.person")
cName = oTest.GetName()

Similar code could be run in Microsoft Excel or Visual Basic:

Set oTest = CreateObject("foxole.person")
cName$ = oTest.GetName()

Handling Exceptions

When a Visual FoxPro Automation server generates an exception, the Automation server sets the COM ErrorInfo object (via IErrorInfo) and cancels out of the current method. The Automation client can either release the Visual FoxPro Automation server or, if the client has access to the COM ErrorInfo object, handle the exception based on that information.

For an example using ErrorInfo, see _ErrorInfo( ) API Library Routine.

The new Visual FoxPro function, COMRETURNERROR( ), handles errors that occur on an Automation server. You can use COMRETURNERROR( ) in the Error method, to populate the COM exception structure with information that Automation clients can use to determine the source of Automation server errors. For more information, see COMRETURNERROR( ) Function.

Raising or Returning Errors from Automation Servers

The only interaction with the objects provided by an Automation server (COM component) is through the methods and properties of the exposed classes. When a client application calls a method of an object, and an error occurs in the Automation server, the method either returns an error value or raises an error in the client application.

The client application decides whether to alert the user or proceed with another execution path. The Automation server itself never interacts with the user. This allows the location of the Automation server to be transparent to the client application. The Automation server can be local, running on the user's computer, or you can use the Remote Automation feature of Visual FoxPro to run it on a network server.

See Also

The Control of Visual FoxPro from Other Applications | Adding OLE | Class Info | Build Options


Binding Type Libraries

Visual FoxPro supports intrinsic (Visual FoxPro) properties, events, and methods in an Automation server type library. Only properties whose visibility is set as PUBLIC are included in the type library.

Both custom user-defined properties, and user-defined methods appear in Visual FoxPro type libraries as long as they are marked PUBLIC. For methods, Visual FoxPro also includes a return value type (variant) and a list of parameters (variants) parsed from the original method definition. Property descriptions from .vcx class files will also appear in the type library.

Type libraries generated by the Build process are stored in .tlb files created along with the .dll or .exe server. The type libraries are also included in the .dll or .exe file as a bound resource. This eliminates the need to ship the extra .tlb file, although it is still built, along with the .vbr file, for use with remote deployment.

Note The Visual FoxPro Release method isn't included in the type library because it already exists as a COM method.

See Also

Interoperability and the Internet | Passing Arrays


Passing Arrays

A Visual FoxPro function, COMARRAY( ), makes it possible for you to specify how an array is passed to an automation server, and makes it possible for you to specify whether the array is zero or one-based.

Earlier versions of Visual FoxPro passed arrays to COM objects (such as Automation servers created in Visual FoxPro, Visual Basic, or Visual C++) by value; the array elements were the same after a method call, and the COM object changes weren't propagated to the elements on the client. This restriction prevented passing large amounts of data back and forth between Visual FoxPro and COM objects.

The array passed to the COM object is assumed to be a one-based array, meaning that the first element, row, or column in the array is referenced with 1 (for example, Myarray[1]). However, some COM objects require that the array passed is zero-based (the first element, row, or column in the array is referenced with 0; for example, Myarray[0]).

Note COMARRAY( ) is used only when arrays are passed to COM objects using the following syntax:
oComObject.Method(@MyArray)

If you omit the @ token, only the first element of the array is passed to the COM object and COMARRAY( ) has no effect. This behavior is the same behavior as in earlier versions of Visual FoxPro.

See Also

Interoperability and the Internet | Compiling Source Code | COMARRAY( )


Compiling Source Code

In Visual FoxPro, you can compile Visual FoxPro source into run-time files created with either vfp8r.dll or vfp8t.dll. In prior versions of Visual FoxPro, you had to use macro substitution or expression evaluation for each line in order to execute code generated at run time. This process was not always optimal because of the complexities of executing large blocks of code and the performance penalty incurred using the macro operator &, or the EVALUATE( ) function.

The COMPILE command is now enabled in the run time so that your applications can generate and compile a program (.prg) file. You can use the STRTOFILE( ) function to output your code to a program file. Run time compilation works with all files supported by the COMPILE command including programs, forms, classes, labels, reports and databases.

There are a few differences between the compiler in the development product and in the run time:

  • The "?" switch of the COMPILE command has been disabled for run time since unattended automation servers (.dlls) do not allow modes involving user input.
  • The SET DEVELOPMENT command has no effect in the run time.

    With the full product, SET DEVELOPMENT causes Visual FoxPro to compare the creation date and time of a program with those of its compiled object file when the program is run. If SET DEVELOPMENT is set ON, the latest version is always executed – out-of-date programs are automatically recompiled. In the run time, you must explicitly call the COMPILE command to recompile source. This means that calling the DO command in your run time will never cause the PRG file to be recompiled. Also, with the run time, the DO command ignores the file extension and looks for a file with an .fxp extension, even if you specify a .prg.

See Also

Early (vtable) and Late (IDispatch) Binding | Interoperability and the Internet | Scalability and Multithreading | Visual FoxPro Run-Time Libraries


Early (vtable) and Late (IDispatch) Binding

Visual FoxPro COM servers support both early (vtable) binding and the existing late binding (IDispatch) interface (together known as dual-interface support). Binding describes how clients access properties and methods of a server. Early binding provides performance benefits for Automation controllers that support early binding such as Visual Basic and the Microsoft Transaction Server. While Visual FoxPro servers support both interfaces, the one used is determined by the client.

Early Binding

If your client can detect at compile time what object a property or method belongs to, it can resolve the reference to the object at compile time. The compiled executable contains only the code to invoke the object's properties, methods, and events. This is called early binding.

Example: Visual FoxPro client

LOCAL xlApp1 As Excel.Application
xlApp1 = CreateObjectEx("Excel.Application","","")

Example: Visual Basic client

Dim xlApp1 As Excel.Application
Set xlApp1 = New Excel.Application

Early binding dramatically reduces the time required to set or retrieve a property value, because the call overhead can be a significant part of the total time. For method calls, the improvement depends on the amount of work the method performs. Short methods, where the call overhead is comparable to the time required to complete the task, benefit the most.

Late Binding

Although late binding is the slowest way to invoke the properties and methods of an object, there are times when it is necessary. For example, in Visual Basic you can write a function that uses an object variable to act on any of several different classes of objects. Because you do not know in advance what class of object will be assigned to the variable, you must declare it as a late-bound variable using the Visual Basic DIM As Object command. In Visual FoxPro, you would use the CREATEOBJECT() function rather than the CREATEOBJECTEX() function.

Example: Visual FoxPro client

LOCAL xlApp2 As Excel.Application
xlApp2 = CreateObject("Excel.Application")

Example: Visual Basic client

Dim xlApp2 As Object
Set xlApp2 = CreateObject("Excel.Application")

Method calls to objects created this way may run slower than calls to early-bound object methods because the client must include code in the compiled executable that will determine at run time whether or not the server has a particular method.

See Also

Compiling Source Code | Scalability and Multithreading | Interoperability and the Internet | Visual FoxPro Run-Time Libraries


Scalability and Multithreading

When a component has one thread of execution, code for only one object can execute at any given time. The Automation feature of the Component Object Model (COM) deals with this situation by serializing requests. That is, the requests are queued and processed one at a time until all have been completed.

In a multithreading operating environment, serialization protects single-threaded objects from overlapping client requests — that is, from code in a property or method being executed while one or more previous client requests are still being run. Overlapping requests can cause internal data errors if objects aren't designed for reentrancy.

Serialization is thus an extremely important feature of Automation. However, serialization of single-threaded components means that requests are sometimes blocked. For example, suppose you're using a Widget object that has two methods, spin and flip.

  • The Spin method takes anywhere from several seconds to half an hour to complete.
  • The Flip method is almost instantaneous.

Because 32-bit applications are preemptively multitasked, a second application could call the Flip method while the Spin method is already running. The short Flip method is blocked until the long Spin method is complete.

When short operations are blocked by long ones, productivity suffers and user frustration rises. Components that behave in this fashion are said to scale poorly. That is, they work poorly if many requests of mixed length are made.

Visual FoxPro provides two component features to address scalability and avoid blocked calls — SingleUse instancing and multithreaded objects. For details, see Controlling Call Blocking.

See Also

Early (vtable) and Late (IDispatch) Binding | Visual FoxPro Run-Time Libraries | Interoperability and the Internet | Compiling Source Code


Automation Server Programming Notes

You can find additional information on writing automation servers in the following locations:

The Application Object

The Application object is not exposed in an Automation server type library, therefore you cannot access the Application object DoCmd and Eval methods. You can expose the Application object by creating a custom property and setting its value to the Application object, or you can provide a method that accesses the Application object.

Read/write properties of the Application object such as AutoYield are global to the project, so ensure that your multithreaded servers do not assume that the values of these settings are protected across threads.

Automation Server Samples

This version of Visual FoxPro includes two sample ISAPI Automation servers, FoxWeb and FoxIS. These samples manage the return of selected Visual FoxPro records to an Internet browser as HTML. For more information about these samples, see FoxISAPI: An OLE Server Sample.

Note FoxISAPI included in Visual FoxPro includes improvements designed specifically for use with new multithreaded DLL Servers. DLL Servers run through FoxISAPI should not use the built-in Pool Manager.

Configuration Files

In Visual FoxPro, only CONFIG.FPW files bound inside of either EXE and DLL servers will be used during run-time initialization. The Configuration file stores critical settings that are set at the time Visual FoxPro starts up (both product and run time). Prior to Visual FoxPro 6.0, the CONFIG.FPW file could exist as a separate file or bound into the application (.app, .exe or .dll). If a CONFIG.FPW file is found bound into an application, then it is used, otherwise Visual FoxPro searches along normal paths for a separate CONFIG.FPW file.

You will still get full functionality with normal distributed .app and .exe applications.

Codepage Handling

Codepages are supported in all servers and are specific to a particular project (.dll). The default codepage can be set in the CONFIG.FPW file and is set only at run-time initialization. The codepage is global across all projects. All objects using a particular instance of the run time will share the same codepage. Because there is a potential for multiple .dll servers to change the default codepage for a run time (that is, each server has its own CONFIG.FPW with a different codepage setting), Visual FoxPro prevents changing this setting once the run time has been launched. So, once a codepage is set, it is permanent until the run time is released.

Users who need to have servers, each with a unique codepage, can place these servers, along with a copy of the vfp8t.dll run-time library in a unique folder. A server will always default to using a run-time library stored in its folder.

Special Language Considerations

There are several commands that you need to be aware of when working with automation servers since their behavior differs slightly from normal product operations.

SET PROCEDURE

Since this command is stored in thread local storage it is unique to each individual thread. However, by default, when you instantiate either an .exe or .dll COM server, Visual FoxPro implicitly performs a SET PROCEDURE to the entire server. For example:

? SET("PROCEDURE")
C:\VFP\MYSERVER.DLL

This makes it possible for you to access any procedure stored in the server. If an existing object on the thread calls SET PROCEDURE TO, then the procedure path is reset to nothing; however, a new object created on the same thread will automatically reset the procedure path to the entire server once again.

SET CLASS

This command works similarly to SET PROCEDURE. Its value is held in thread local storage, however, it is initialized to the entire set of class libraries in your .exe or .dll server. For example:

? SET("CLASS")
C:\VFP\myClass.VCX ALIA

CD, CHDIR, SET DEFAULT Commands

These commands change the default directory of the entire process, so all threads which are part of the process are affected. Use the SET PATH command instead of CD, CHDIR, and SET DEFAULT.

See Also

Language Supported in Run-Times | Selection of a Run-Time Library | FoxISAPI: An OLE Server Sample | Interoperability and the Internet | Application object | DoCmd | Eval


Visual FoxPro Run-Time Libraries

Visual FoxPro ships with two separate run-time libraries:

Runtime Library Description
VFP8R.DLL
Normal run time for most application types.
VFP8T.DLL
Special multithreaded run time for highly scalable in-process server applications such as those created for use with Microsoft Transaction Server.

When you use the Project Manager Build Options dialog box, the build action you choose determines which run time is used by the generated application or server. Only .dll servers can use the vfp8t.dll run time. The Project.Build method also makes it possible for you to choose which run time is used.

The compiled source (such as an .exe, or .dll file) is marked internally to identify which run time to use when invoked. The only way to change which run time a server uses is by rebuilding it. Your server can determine at run time which run-time library it is using through the read-only Application.StartMode property. You need to know which run-time library is associated with your .dll server so that you can choose the right run time to include in the setup .

Note As with all Visual FoxPro run-time files, these files are installed in the <program files>\Common Files\Microsoft Shared\VFP folder. Both run times share the same resource file (such as vfp8renu.dll).

See Also

Scalability and Multithreading | VFP8R.DLL Run-Time Library | Interoperability and the Internet | VFP8T.DLL Run-Time Library | Server Design Considerations and Limitations


VFP8R.DLL Run-Time Library

Vfp8r.dll provides services for the following types of Visual FoxPro-generated applications:

  • Distributed applications (.exe files)
  • Out-of-process servers (.exe files)
  • In-process servers (.dll files)

This is the primary run time used by Visual FoxPro for most types of applications.

The Visual FoxPro run time, vfp8r.dll, does not service multiple in-process .dll Automation servers. Each in-process .dll now uses a separate instance of the vfp8r.dll run time. The following rules determine how in-process .dlls use the vfp8r.dll run time:

  • The in-process .dll first called has exclusive use of the vfp8r.dll run-time library (typically installed in the System folder or the System32 folder, depending on your operating system).

    If an in-process .dll already has exclusive use of the vfp8r.dll run time, a renamed copy of the vfp8r.dll run time is created on disk and loaded into memory for each in-process .dll called. The vfp8r.dll run time is assigned a name based on the name of the in-process .dll. For example, if an in-process .dll named Myserver.dll is called, a copy of the vfp8r.dll run time is renamed to myserverr.dll (note the "r" appended to the name) and is loaded into memory to service the in-process .dll. This can also occur with a Visual FoxPro .exe server creating an instance of a .dll server – a situation where both would be sharing the same run time from the same process.

  • Visual FoxPro run times are renamed only for in-process .dlls that run within the same process. This means that two separate clients, each running in their own process, can load two different Visual FoxPro in-process .dll files without the run time being renamed. In this case, both Visual FoxPro in-process .dll files use vfp8r.dll because the clients load in separate processes.
  • Multiple Automation servers, created with OLEPUBLIC clause in the DEFINE CLASS command, in a single in-process .dll share the same vfp8r.dll run time. In this case, it's possible that the Automation servers can affect each other by sharing PUBLIC memory variables, setting the same SET commands, and so on if they reside on a common thread. Be careful that multiple Automation servers in a single in-process .dll don't interfere with each other. The new Session class can help eliminate some of these conflicts. Using the multithreaded run time, vfp8t.dll, avoids these conflicts because objects created on separate threads will use their own separate memory space (thread-local storage).

You can use the vfp8r.dll library with in-process .dll servers. Because there are limitations in using vfp8r.dll, you should consider using the vfp8t.dll run time instead. The vfp8r.dll run time does not fully protect instance data and globals, therefore the library blocks multiple objects from executing code concurrently. If one of the objects is executing code, all other instances must queue up to execute code. As soon as the object executing code finishes, another object can enter the run time to begin its execution (whether it is a property assignment or method invocation). While this may not be ideal in many application scenarios, there are certain types of server applications where this may be the optimal approach.

If in-process (.dll) servers are deployed in a Component Services (or Microsoft Transaction Server) package, creating an instance of the server will load the .dll into the memory space of a Component Services process rather than the calling process. Moreover, multiple processes (.exe's) can instantiate Visual FoxPro .dll servers that will be loaded into a single Component Services process. Component Services generates (or reuses) a thread for each client requesting an instance (OLEPUBLIC) from a Visual FoxPro server. Since such applications often require enterprise scalability, there is the potential for many concurrent instances to access your Visual FoxPro server simultaneously. If only one client (instance) is allowed to execute code at a time, all others must wait. With a single processor machine, this may be fine, depending on the nature and execution times of methods in your server. Remember, a single processor can only run one line of code at a time.

You should always consider using the vfp8t.dll run time for multiple processor machines since each processor can simultaneously execute code for different objects. Since vfp8r.dll blocking behavior prevents simultaneous code execution, you should use vfp8t.dll for most situations.

See Also

Visual FoxPro Run-Time Libraries | VFP8T.DLL Run-Time Library | Interoperability and the Internet | Server Design Considerations and Limitations | Scalability and Multithreading


VFP8T.DLL Run-Time Library

This multithreaded run-time helps eliminate the blocking issues associated with the vfp8r.dll run time. With vfp8t.dll run time library, you can deploy in-process servers without blocking of code execution.

Because the Vfp8t.dll is a lightweight run-time library designed only for in-process servers, many commands and functions related to visual and user input features have been disabled.

Because no blocking occurs in vfp8t.dll, an object executing an unusually long procedure (such as printing out a report) won't prevent other objects from executing quick rapid routines. For example, with vfp8r.dll, an object that executes a 1 second database query routine may have to wait 15 minutes for an object printing a long, complex report. If you build with vfp8t.dll you won't have the same bottleneck.

In addition to addressing blocking issues, implementing Apartment-model threading in the vfp8t.dll run time also eliminates conflicts in accessing global data from multiple threads by giving each apartment its own copy of global data. The vfp8t.dll uses thread local storage to give each class instance its own set of data. This means that a variable you declare PUBLIC is global only to the thread; each thread has an instance of the variable.

Note Read/write properties of the Application object such as AutoYield are global to the project.

Visual FoxPro makes it possible for the same vfp8t.dll run time to be deployed with multiple, concurrently called in-process .dll automation servers whether they are in same process/thread or not. The original vfp8r.dll run time creates a renamed copy of the library for each in-process .dll server running in the same process.

Visual FoxPro offers a Session Class, which you should use for OLEPUBLIC server classes. As with forms, the DataSession property makes it possible for you to create a private data session for your object upon instantiation. The advantage of the Session class is that it uses much less memory than a form. The vfp8t.dll run time automatically protects globals and user data through thread local storage, but this only applies between apartments (threads). Objects on the same thread instantiated from the same .dll are able to access each other's data. The Session class aids in data protection within the thread.

Since the vfp8t.dll run time is designed for use only with in-process servers, it has been scaled down in size. Many user interface commands and functions have been eliminated including older FoxPro 2.x READ and @...Get/Say support. In addition, some of the designers such as Table Designer and Report Designer, which exist in the vfp8r.dll run time, have also been removed. The vfp8t.dll run time still supports visual classes such as forms.

See Also

VFP8R.DLL Run-Time Library | Server Design Considerations and Limitations | Interoperability and the Internet | Visual FoxPro Run-Time Libraries | Selection of Process Types


Server Design Considerations and Limitations

There are many critical issues to consider in server design. Certain behaviors, processes, and limitations can determine the effectiveness of your server application.

In This Section

Selection of Process Types
Discusses the different services provided by in-process and out-of-process servers, and what effect they have on the user interface of your application.
Control of Call Blocking
Describes how SingleUse Objects and Apartment-model threading can be used to control issues of call blocking and enhance the scalability of your applications.
Selection of a Run-time Library
Provides information on using Visual FoxPro API calls, scalability issues, reentrancy, and resource contention.
Language Supported in Run Times
Discusses Visual FoxPro commands, functions, and system variables that are not supported in vfp8t.dll.

Related Sections

VFP8T.DLL Run-Time Library
Discusses this multithreaded run time that helps eliminate the blocking issues associated with the vfp8r.dll run time.
Automation Server Programming Notes
Describes where you can find additional information on writing automation servers.
Interoperability and the Internet
Provides links to information on how you can move data between Visual FoxPro and other applications as well as within Visual FoxPro applications.


Selection of Process Types

In-Process and out-of-process servers provide differing services, especially regarding the user interface of your application.

User Interfaces

Although earlier versions of Visual FoxPro make it possible for you to use forms as output-only elements in an Automation server application, the two run-time libraries in Visual FoxPro handle this situation differently for out-of-process and for in-process servers.

In-Process Servers

Apartment-model threading support requires that in-process .dll Automation servers not have user interfaces. In Visual FoxPro 5.0, it was possible (though not recommended) to create an in-process .dll Automation server that had a user interface such as a form. You could use the form only for display because the form events were not supported. Since Visual FoxPro 6, if you attempt to create a user interface in an in-process .dll, Automation generates an error. This is referred to as unattended mode.

Out-of-Process Servers

An out-of-process (.exe) Automation server can have a user interface. The Visual FoxPro function SYS(2335) enables you to disable UI and modal events for an out-of-process .exe Automation server so they can be handled remotely without user intervention. Modal events are created by user-defined modal forms, system dialogs, the MESSAGEBOX( ) function and the WAIT command, and so on and normally require user input.

See Also

Server Design Considerations and Limitations | Control of Call Blocking | Selection of a Run-Time Library | Language Supported in Run-Times | Automation Server Programming Notes


Control of Call Blocking

To enhance the scalability of your applications, Visual FoxPro provides SingleUse Objects and Apartment-model threading as ways of controlling issues of call blocking.

SingleUse Objects

By setting the Instancing property of an OLEPUBLIC class to SingleUse in the Project Info dialog box, you cause each instance of the class to run in a separate instance of your component. This means that even though your component is single-threaded, each instance of the SingleUse class has its own thread of execution. The behavior of SingleUse objects differs between .exe and .dll servers:

SingleUse Objects in EXE Servers

With the Instancing property set to SingleUse, each instance causes a new EXE process to begin (under Windows NT 4.0 or later you will see each running process in the Task Manager). With the MultiUse setting, the first instance will cause a new process to start, but each new object instance shares the same process as the first.

SingleUse Objects in DLL Servers

The Instancing property is ignored for multithreaded .dlls and is only read for the Vfp8r.dll run time. Servers built for use with the vfp8t.dll library are always MultiUse regardless of their setting. In general, you should always set the Instancing property to MultiUse for vfp8r.dll in-process servers. If you set it to SingleUse, only one instance of an object from that server can be created. You will get an error if you try to instantiate more objects. Only under rare circumstances would you want to use the SingleUse setting. In fact, Microsoft Transaction Server components require the MultiUse setting. SingleUse objects often require more memory overhead than multiple objects in a multithreaded component.

There are reasons, however, for which you might want to use SingleUse objects. For example, you can isolate high-risk activities in separate processes with SingleUse objects. If the object suffers a fatal error, other processes are not affected. By contrast, a fatal error in a multithreaded component terminates all threads.

Apartment-Model Threading

Visual FoxPro Automation servers now support Apartment-model threading. The Microsoft Transaction Server utilizes servers marked as apartment-threaded and offers better thread protection and scalability through serialization and marshaling.

In Visual FoxPro, apartment-model threading provides thread safety. In apartment-model threading, each thread is like an apartment — all objects created on the thread live in this apartment, and are unaware of objects in other apartments. Each Apartment-model object (such as a Visual FoxPro Automation server) may only be entered by one thread, the thread that created the object. However, an object server (such as Microsoft Transaction Server) can support multiple objects, each being entered simultaneously by different threads. Common data held by the object server must be protected against thread collisions.

Apartment-model threading provides the following benefits:

  • All of the objects a client creates on a given thread are created in the same apartment (thread) in the DLL. Calls on the same thread to these objects do not require cross-thread marshaling, making them more efficient.
  • Because an object is only accessed on the thread on which it was created, calls are serialized so that a call is never interrupted by a call from another thread.
  • Arguments for cross-thread calls are marshaled, and the calling thread is blocked. This synchronization of data protects the calling thread's state.

Apartment-threaded DLLs cannot create their own threads; the first time a client thread requests an object provided by your DLL, a new apartment is created, and the object Init event runs for that apartment. All single threaded client objects requested by that client will reside in the same apartment, and will share global data. Any PRIVATE objects (including forms) that are created by the public objects will also reside in the apartment.

Though Visual FoxPro does not provide a way for apartments to access each other, a multithreaded client could obtain a reference to an object on Thread A, and pass that reference to an object on Thread B.

For more information about Apartment-model threading, search on "Apartment-Model Threading" in the MSDN library.

The Visual FoxPro implementation of Apartment-model threading eliminates conflicts in accessing global data from multiple threads by giving each apartment its own copy of global data. This means that all objects created on the thread exist in this apartment, and are unaware of objects in other apartments.

Visual FoxPro uses thread local storage to store a unique set of application and environment global data for each thread (apartment). This means that two instances of the same class created on different threads cannot access each other's data. However, if these same two instances reside on the same thread, each object can access the other's data. This could cause timing issues for your applications. In fact, as long as two objects on the same thread are created from OLEPUBLIC classes in the same .dll server, data from those objects is common between them (Note: You can use the Session class to give each object a unique private datasession.)

In addition to thread local storage, Visual FoxPro also provides each project (.dll) a unique set of globals data. Objects created from different projects (.dll servers) cannot access each other's globals, even if the two objects reside on the same thread.

See Also

Selection of Process Types | Selection of a Run-Time Library | Interoperability and the Internet | Language Supported in Run Times | Automation Server Programming Notes


Selection of a Run-Time Library

You may have an application need such as an Internet Server Application like FoxIsapi where you want to instantiate a form to use in mapping to equivalent HTML. The impact of eliminating a number of non-critical features by using the new vfp8t.dll run time will improve overall performance of your multithreaded server applications.

A common misconception about server choice is that an application will automatically scale well just by building the .dll to use the new run time. You can often do this, but you should also consider issues involving use of Visual FoxPro API calls, scalability, reentrancy, and resource contention.

Using Visual FoxPro API Calls

When using Visual FoxPro FLL or standard Windows DLL libraries that make Visual FoxPro API calls, there are some issues you need to be aware of when designing your servers. The Visual FoxPro API does not readily determine to which project (.dll) a particular call belongs. So, there is a potential, although rare, for an API call to be made against the wrong project (.dll - thread local storage). This may occur if your FLL/DLL library creates an instance from a different Visual FoxPro .dll server before making its API call. There are several possible solutions if your server should experience this problem:

  • Create a separate copy of the vfp8t.dll run-time library file, and place the copy in the same folder as your .dll server. The server will always search first in your server folder before attempting to locate files in the Windows System folder or folder of your client process. By having its own run-time library servicing it, a server will not experience potential conflicts from other .dlls (assuming these other .dlls are not in the same folder). Since this behavior (automatic copying/renaming of run time) occurs by default with the Vfp8r.dll run time, the above API issues only manifest themselves in the Vfp8t.dll run time.
  • Limit your application to a single .dll server. If you are using several .dll servers (projects), there may be potential for API conflicts. Remember that a project can contain many OLEPUBLICs, so you don't need to have a separate project for each OLEPUBLIC. Be aware that on shared computer servers, its possible that people may install other Visual FoxPro COM servers, which could potentially conflict with yours if running concurrently.

Scalability Issues

The multithreaded run time in Visual FoxPro allows for very scalable Visual FoxPro in-process servers. Though scalability of your servers will be handled automatically by the run time, certain tight code loops may not allow thread switching to occur as frequently. For example, a very tight DO WHILE loop may cause this. If you experience scalability problems, you can include code such as the following example which forces the processor to switch threads:

DECLARE Sleep IN Win32API INTEGER
SLEEP(0)

Though you can use multithreading on a single-processor machine, consider that this may not provide quite the results you expect. For example, on a single-processor machine, multithreading results in a perceived performance improvement only with a mix of long and short tasks. Multithreaded method calls, as described in this example, may appear to be slower.

In the example, method A and method B are called at the same time. In a single-threaded component, the requests are serialized, so that B doesn't begin until A has finished. With multithreading, the two active threads duel for the processor's attention.

Not only does the perceived average completion time increase, but more processor time is spent switching between threads.

The problem is that method A and method B take about the same amount of time.

For example, if method B required only three time slices to complete, the user of the system would perceive a huge improvement in the responsiveness of method B — and only a slight degradation in the time required to execute method A.

The scenarios in which multithreading shows to best advantage are those in which most threads spend a substantial percentage of the time blocked — for example, waiting for file I/O — so that other threads can be executing code at any given time.

If you are considering an application on a single-processor machine with characteristics that provide minimal thread blocking, you may want to consider using the vfp8r.dll run time. On multiprocessor machines and in most other applications, you should consider using the vfp8t.dll for .dll servers.

Reentrancy

In the apartment model, reentrancy refers to the following sequence of events:

  1. An apartment's thread of execution enters an object's code, because a property or method has been invoked.
  2. While the thread is in the property or method, another thread invokes a property or method of the object, and Automation serializes this request — that is, it queues the request until the thread that owns the object's apartment finishes the member it's currently executing.
  3. Before the thread reaches the end of the member, it executes code that yields control of the processor.
  4. Automation tells the thread to begin executing the serialized request, so that the thread reenters the object's code.

The new request may be for the member the thread was already executing — in which case the thread enters the member a second time — or it may be for another member. If the second member doesn't yield, it will finish processing before the first member. If it changes module-level data the first member was using, the result may be unfortunate.

By serializing property and method calls for each apartment, Automation protects you from reentrancy — unless your code yields control of the processor. Ways in which your code can yield control of the processor include:

  • Calling DoEvents.
  • Invoking the properties or methods of an object on another thread, or in another process. Setting the Application.AutoYield property to false (.F.) will suspend processing of intermittent events between lines of code executing.
  • Invoking a cross-thread or cross-process method from within a method.

Unless you've carefully written all of an object's code so that it doesn't matter whether two members are executing at the same time, you should not include code that yields control of the processor.

Resource Contention

The new vfp8t.dll run-time library will protect objects from accessing each other's application data. This includes both declared and intrinsic environment globals. Some resources present potential problems of contention, including:

  • Files
  • Registry
  • Data

File I/O presents resource contentions that can be easily handled through code since file management is handled through the operating system. When using a file, your server can open (and lock) a file so that other objects see that the file is in use. A properly written server can handle this scenario by waiting for the file to become available, or otherwise gracefully handle the error. Files can also be opened shared in which case your server should be aware that other objects can potentially change values.

A common scenario is presented with INI files in which different objects can read or write values. The process of reading and then writing a value to an INI file requires two steps. So, there is a potential that the value read by one client is not necessarily the same one it overwrites later if another client alters it first, producing a need for conflict resolution.

As do INI files, the Registry stores settings, which can be accessed by multiple clients. Your applications should use common Windows API routines to access the Registry. Again, your server design should reflect that a potential exists for Registry key values to change between the time the key is read and the time it's written. The Windows API routines work to avoid the necessity for conflict resolution.

Data is a tricky resource to handle. Fortunately, the rich Visual FoxPro language available in the run-times provides all the information and functionality necessary to handle resource contention issues. For more information on handling shared data, see Programming for Shared Access.

See Also

Control of Call Blocking | Language Supported in Run-Times | Interoperability and the Internet | Automation Server Programming Notes | FoxIsapi


Language Supported in Run Times

The vfp8r.dll run-time library supports the entire language set of objects, commands, and functions, excluding design-time specific language.

To design the vfp8t.dll as a lightweight run-time library for in-process servers, many user-input commands and functions have been removed. All Object syntax is still available, though events from visual classes such as forms are disabled. The following language categories have been removed from vfp8t.dll:

  • READ, @...Get/Says
  • Menu, Popup, and Bar commands and functions
  • MESSAGEBOX() and WAIT WINDOW
  • User-defined Window commands and functions

Disabled Commands that Generate Run-Time Errors

The following table is a list of unsupported commands, which will generate one of these errors at run time in the vfp8t.dll library:

  • Commands: Feature is not available
  • Functions: Function is not implemented
  • System variables: Variable is not found

The unsupported commands are:

@...BOX | @...CLASS | @...CLEAR
@...EDIT | @...FILL | @...GET
@...MENU | @...PROMPT | @...SAY
@...SCROLL | @...TO | _ALIGNMENT
_ASSIST | _BEAUTIFY | _BOX
_CALCMEM | _CALCVALUE | _CONVERTER
_COVERAGE | _CUROBJ | _DBLCLICK
_DIARYDATE | _FOXDOC | _GALLERY
_GENMENU | _GENPD | _GENSCRN
_GETEXPR | _INCSEEK | _INDENT
_LMARGIN | _PADVANCE | _PBPAGE
_PCOLNO | _PCOPIES | _PDRIVER
_PDSETUP | _PECODE | _PEJECT
_PEPAGE | _PLENGTH | _PLINENO
_PLOFFSET | _PPITCH | _PQUALITY
_PSCODE | _PSPACING | _PWAIT
_RMARGIN | _SCCTEXT | _SPELLCHK
_STARTUP | _TABS | _THROTTLE
_TRANSPORT | _WRAP |
ACCEPT | ACTIVATE MENU | ACTIVATE POPUP
ACTIVATE SCREEN | ACTIVATE WINDOW | AGETCLASS()
AMOUSEOBJ() | ANSITOOEM() | APROCINFO()
ASELOBJ() | ASSERT | ASSIST
BAR() | BARCOUNT() | BARPROMPT()
BROWSE | CALL | CHANGE
CLEAR DEBUG | CLEAR GETS | CLEAR MACROS
CLEAR MENUS | CLEAR POPUPS | CLEAR PROMPT
CLEAR READ | CLOSE DEBUGGER | CLOSE FORMAT
CLOSE MEMO | CNTBAR() | CNTPAD()
COL() | CREATE | CREATE CLASS
CREATE CLASSLIB | CREATE COLOR SET | CREATE FORM
CREATE LABEL | CREATE MENU | CREATE PROJECT
CREATE QUERY | CREATE REPORT | CREATE SCREEN
DEACTIVATE MENU | DEACTIVATE POPUP | DEACTIVATE WINDOW
DEBUG | DEBUGOUT | DEFINE BAR
DEFINE BOX | DEFINE MENU | DEFINE PAD
DEFINE POPUP | DEFINE WINDOW | EDIT
FKLABEL() | FKMAX() | GETBAR()
GETCOLOR() | GETCP() | GETDIR()
GETEXPR() | GETFILE() | GETFONT()
GETPAD() | GETPICT() | GETPRINTER()
HELP | HIDE MENU | HIDE POPUP
HIDE WINDOW | IMESTATUS() | INPUT
KEYBOARD | LOAD | LOCFILE()
MCOL() | MDOWN() | MENU
MENU TO | MENU() | MESSAGEBOX()
MODIFY Commands | MOUSE | MOVE POPUP
MOVE WINDOW | MRKBAR() | MRKPAD()
MROW() | MWINDOW() | OBJNUM()
OBJVAR() | OEMTOANSI() | ON BAR()
ON ESCAPE | ON EXIT Commands | ON KEY
ON KEY LABEL | ON PAD | ON PAGE
ON READERROR | ON SELECTION BAR | ON SELECTION MENU
ON SELECTION PAD | ON SELECTION POPUP | PAD()
PLAY MACRO | POP KEY | POP MENU
POP POPUP | POPUP() | PRMBAR()
PRMPAD() | PROMPT() | PUSH KEY
PUSH MENU | PUSH POPUP | PUTFILE()
RDLEVEL() | READ | READ MENU
READKEY() | RELEASE BAR | RELEASE MENUS
RELEASE PAD | RELEASE POPUPS | RELEASE WINDOWS
RESTORE MACROS | RESTORE SCREEN | RESTORE WINDOW
ROW() | SAVE MACROS | SAVE SCREEN
SAVE WINDOWS | SCROLL | SHOW GET(S)
SHOW MENU | SHOW OBJECT | SHOW POPUP
SHOW WINDOW | SIZE POPUP | SIZE WINDOW
SKPBAR() | SKPPAD() | SUSPEND
VARREAD() | WAIT | WBORDER()
WCHILD() | WCOLS() | WEXIST()
WFONT() | WLAST() | WLCOL()
WLROW() | WMAXIMUM() | WONTOP()
WOUTPUT() | WMINIMUM() | WPARENT()
WREAD() | WROWS() | WTITLE()
WVISIBLE() | ZOOM WINDOW |

Disabled Commands that Generate No Run-Time Errors

The following table is a list of unsupported commands, which will not generate an error when executed at run time in vfp8t.dll library. These functions are still disabled for use in the run time; however, because of the frequency of usage in commonly used code and class libraries between different types of applications, they do not cause an error. When one of these commands or functions is encountered in code, Visual FoxPro ignores that line of code and continues executing. This includes certain SET commands and SYS functions.

CD | CHDIR | DOEVENTS
SET ASSERTS | SET BELL | SET BORDER
SET BROWSEME | SET BRSTATUS | SET CONSOLE
SET COLOR | SET CLEAR | SET CLOCK
SET COVERAGE | SET CONFIRM | SET CURSOR
SET CPDIALOG | SET DEBUGOUT | SET DEBUG
SET DEFAULT | SET DEVELOPMENT | SET DELIMITERS
SET DISPLAY | SET DOHISTORY | SET ESCAPE
SET ECHO | SET EVENTLIST | SET EVENTTRACKING
SET FORMAT | SET FUNCTION | SET HELP
SET INTENSITY | SET MARK OF | SET MACDESKTOP
SET MACKEY | SET MARGIN | SET MESSAGE
SET NOTIFY | SET ODOMETER | SET PALETTE
SET PDSETUP | SET READBORDER | SET REFRESH
SET RESOURCE | SET SAFETY | SET SKIP OF
SET STICKY | SET STATUS | SET SYSMENU
SET TALK | SET TRBETWEEN | SET TYPEAHEAD
SET VIEW | SET WINDOW | SYS(1037)
SYS(18) | SYS(103) | SYS(2002)
SYS(1270) | SYS(2017) | SYS(4204)
SYS(2016) |  |

The following table lists the properties and functions added to Visual FoxPro to make it easier to manage Automation clients and servers. See each topic for further information.

New Server language elements | Description
COMARRAY( ) Function | Specifies how arrays are passed to COM objects.
COMCLASSINFO( ) Function | Returns registry information about a COM object such as a Visual FoxPro Automation server.
COMRETURNERROR( ) Function | Populates the COM exception structure with information that Automation clients can use to determine the source of Automation server errors.
CREATEOBJECTEX( ) Function | Creates an instance of a registered COM object (such as a Visual FoxPro Automation server) on a remote computer. For a Visual FoxPro in-process .dll, you can use Microsoft Transaction Server to create an instance of the .dll on a remote computer.
EVENTHANDLER( ) Function | Binds a COM server event to implemented interface methods in an instantiated Visual FoxPro object.
ProcessID Property | Returns the ID of the Process that created the object.
ServerName Property | Contains the full path and file name for an Automation server. The ServerName property is a property of the Application object.
StartMode Property | Contains a numeric value that indicates how the instance of Visual FoxPro was started.
SYS(2334) – Automation Server Invocation Mode | Returns a value that indicates how a Visual FoxPro automation server method was invoked.
SYS(2335) – Unattended Server Mode | Enables or disables support for modal states in distributable Visual FoxPro .exe Automation servers.
SYS(2336) - Critical Section Support Function | Controls access of critical section in Multithreaded servers.
SYS(2339) - Internal Global Variable Function | Returns current value of internal global variable called g_fCallCoFreeOnRelease.
ThreadID Property | Returns the ID of the thread on which the object was created.

See Also

Selection of a Run-Time Library | Automation Server Programming Notes | Interoperability and the Internet | Control of Call Blocking | Selection of Process Types


Interoperability and the Internet

Visual FoxPro supports OLE drag-and-drop, which makes it possible for you to move data between Visual FoxPro and other applications, as well as within Visual FoxPro applications.

Visual FoxPro also makes it easy to create applications for use with the Internet and other Microsoft Windows-based applications, such as Excel and Visual Basic.

In addition, Visual FoxPro makes it easy to create Automation servers that work better with the Internet, Microsoft Transaction Server, and the Active Desktop.

In This Section

OLE Drag-and-Drop
Describes how Visual FoxPro supports OLE drag-and-drop, a powerful and useful tool, which makes it possible for you to move data between other applications that support OLE drag-and-drop (such as Visual FoxPro, Visual Basic, the Microsoft Windows Explorer, Word and Excel, and so on).
Sharing Information and Adding OLE
Explains how you can use Visual FoxPro to share information with other applications.

Related Sections

Web Services and Components
Explains how you can enable a Visual FoxPro application to work for multiple users, include XML Web services, ActiveX controls, and automation-enabled applications, and add international capabilities.
XML Web Services in Visual FoxPro
Describes how to use XML Web services with your Visual FoxPro applications. XML Web services are classes or objects available on the Web that you can use in your applications programmatically as normal object-oriented calls.
Automation and COM Servers
Describes how to you can extend the functionality of your Visual FoxPro applications without a lot of extra coding time by using Automation and COM Servers.


OLE Drag-and-Drop

Visual FoxPro supports OLE drag-and-drop, a powerful and useful tool that makes it possible for you to move data between other applications that support OLE drag-and-drop (such as Visual FoxPro, Visual Basic, the Windows Explorer, Microsoft Word and Excel, and so on). In a distributed Visual FoxPro application, you can move data between controls in the application or between controls and other Window applications that support OLE drag-and-drop.

Note that previous versions of Visual FoxPro supported a programmatic drag-and-drop feature for controls, making it possible for you to move controls on a form. This form of drag and drop is still supported in Visual FoxPro. However, if you choose to implement drag and drop support in your applications, you should exclusively use either programmatic drag and drop for controls or OLE drag-and-drop – don't mix the two types of drag and drop support.

Understanding some of the basics of OLE drag-and-drop applications makes it easier to take full advantage of their features.

Dragging and Dropping Data

The mouse is used to drag and drop data between applications and controls. For example, you can select a set of files in the Windows Explorer. You can then press and hold the mouse button down while dragging the files, then release the mouse button to drop them onto the Visual FoxPro Project Manager, or you can select text in a Word document and drop the text into a text box on a Visual FoxPro form. During the OLE drag-and-drop operation, the mouse cursor changes to indicate that an OLE drag-and-drop operation is in effect.

Drag Source

The application or control from which data is moved is called the drag source.

Drag Source Properties, Events, and Methods

The following table lists the properties, events, and methods available for an OLE drag source.

Property, Event, or Method | Description
OLECompleteDrag Event | Occurs when data is dropped on the drop target or the OLE drag-and-drop operation is canceled.
OLEDrag Method | Starts an OLE drag-and-drop operation.
OLEDragPicture Property | Specifies the picture displayed under the mouse pointer during an OLE drag-and-drop operation. You can specify a picture file of type .bmp, .dib, .jpg, .gif, .ani, .cur, and .ico.
OLEDragMode Property | Specifies how a drag source manages OLE drag operations.
OLEGiveFeedBack Event | Occurs after every OLEDragOver event. Allows the drag source to specify the type of OLE drag-and-drop operation and the visual feedback.
OLESetData Event | Occurs when a drop target calls the GetData method and there is no data in a specified format on the OLE drag-and-drop DataObject.
OLEStartDrag Event | Occurs when the OLEDrag method is called.

Drop Target

The application or control to which the data is moved is called the drop target.

Drop Target Properties and Events

The following table lists the properties, events, and methods available for an OLE drop target.

Property or Event | Description
OLEDragDrop Event | Occurs when data is dropped on a drop target and the drop target's OLEDropMode property is set to 1 – Enabled.
OLEDragOver Event | Occurs when data is dragged over a drop target and the drop target's OLEDropMode property is set to 1 – Enabled.
OLEDropEffects Property | Specifies the type of drop operations an OLE drop target supports.
OLEDropHasData Property | Specifies how a drop operation is managed.
OLEDropMode Property | Specifies how a drop target manages OLE drop operations.

Moving Data

To perform a drag-and-drop operation to move data using the default (left) mouse button, select the data you want to move in the drag source. After selecting the data, press and hold down the mouse button as you move the mouse pointer over the drop target. Release the mouse button to drop the data onto the drop target. During the OLE drag-and-drop operation, the mouse cursor changes to indicate that an OLE drag-and-drop operation is in effect.

You can also click the non-default (right) mouse button on the data in a drag source and drag it to a drop target. Depending on the drop target, a context menu may be displayed when you drop the data on the drop target. The context menu contains a set of options that make it possible for you to choose how the data is processed by the drop target.

Copying Data

You can also copy data from a drag source and paste it in a drop target. Press the Ctrl key as you click the mouse on the data selected in the drag source. The mouse cursor displays a plus sign (+) while the mouse is dragged to indicate a Copy operation is in effect.

Targets and Sources Not Supporting OLE drag-and-drop

You can only move or copy data from a drag source that supports OLE drag-and-drop, and the drop target must also support OLE drag-and-drop. Note that while a drop target may support OLE drag-and-drop, the drop target doesn't have to accept the data you attempt to drop on it. For example, the data you're moving or copying may be in a format the drop target doesn't support. During a drag-and-drop operation, the mouse cursor changes to a No Drop symbol (a slashed circle) to indicate the mouse is positioned over an area of an application or control where the data cannot be dropped.

Canceling an Operation

To cancel the OLE drag-and-drop operation, press ESC during the operation.

See Also

Interoperability and the Internet | Design-Time OLE Drag-and-Drop Support | Run-Time OLE Drag-and-Drop Support | Implementing Intrinsic and Manual OLE Drag-and-Drop Modes


Design-Time OLE Drag-and-Drop Support

Design-time support for OLE drag-and-drop in Visual FoxPro makes developing applications even faster than previous versions. OLE drag-and-drop makes it easy to drop files into the Project Manager and the Visual FoxPro designers from the Windows Explorer. Text can be easily moved or copied from other applications to the Command Window, the Visual FoxPro text editors, and the Properties Window.

The following table lists the Visual FoxPro design time features that support OLE drag-and-drop with a description of the support.

Interface item Description
Command Window Drop target for files, drag source and drop target for text.

If a file created in Visual FoxPro is dropped on the Command window, the file is opened with the appropriate Visual FoxPro command. For example, if a database is dropped on the Command window, Visual FoxPro issues the OPEN DATABASE and MODIFY DATABASE commands to open the file for modification. If a table is dropped on the Command window, the table is opened with the USE ... AGAIN and BROWSE commands. If SET EXCLUSIVE is ON, the table is opened for exclusive use. If SET EXCLUSIVE is OFF, the table is opened for shared use.

Other Visual FoxPro files are opened with the appropriate MODIFY command — forms are opened with MODIFY FORM, queries are opened with MODIFY QUERY, text and header (.H) files are opened with MODIFY FILE, and so on.

If a file that has been created in another application is dropped on the Command window, the file is opened in the application with which it is associated. For example, dropping a Microsoft Excel spreadsheet on the Command window starts Excel and opens the spreadsheet.
Project Manager Drop target for files.

Files are added to the appropriate Project Manager categories, based on their file extensions. If a file with an extension Visual FoxPro does not recognize is dropped on the Project Manager, the file is added to the Other category.

If a table contained in a database is dropped on the Project Manager, the database is added to the Databases category of the Data item and is marked as Excluded. If a free table is dropped on the Project Manager, the table is added to the Free Tables category of the Data item and is marked as Excluded. If a database is dropped on the Project Manager, the database is added to the Databases category of the Data item and is marked as Excluded.

While OLE drag-and-drop makes it easy to add files to the Project Manager, remember that the Project Manager automatically adds any referenced files to the project when you build the project. For example, if a program you add to the project executes a second program, the second program is automatically added to the project when the project is built. It isn't necessary to manually add the second program to the project.
Text Editors Drag source and drop target for text.

Text editors include editing windows opened with MODIFY COMMAND, MODIFY FILE, and MODIFY MEMO, the Command window, snippet editing windows in the Form, Class, Menu, and Data Environment Designers, and the Stored Procedure editor in the Database Designer.
Debugger Drag source and drop target for text.

The Watch window text box and Name list are drag sources and drop targets for text. The Trace window and the Debug Output window are drag sources for text.
Database Designer Drop target for files.

Dropping a table onto the Database Designer adds the table to the current database.
Class Designer Drop target for text and files.

By default, dropping text on a container object in the Class Designer creates a label with the text as the value of its Caption property. You can change the default control created when text is dropped on the Form Designer in the Field Mapping Tab of the Options Dialog Box.

If you drop text onto a non-container control (a CheckBox, CommandButton, Header, Label, or OptionButton control), the Caption property is set to the text.

Dropping a graphics file (.ani, .bmp, .cur, .gif, .ico, or .jpg) onto the Class Designer creates an Image control with the Picture property set to the name of the graphics file.
Data Environment Designer Drop target for files.

Dropping a table onto the Data Environment Designer adds the table to the data environment. Dropping a database onto the Data Environment Designer displays the Add Table or View dialog, making it possible for you to add a table or view to the data environment.
Query Designer Drop target for files.

Dropping a table onto the Query Designer adds the table to the query. Dropping a database onto the Query Designer displays the Add Table or View dialog, making it possible for you to add a table or view to the query.
View Designer Drop target for files.

Dropping a table onto the View Designer adds the table to the view. Dropping a database onto the View Designer displays the Add Table or View dialog, making it possible for you to add a table or view to the view.
Properties window Drop target for text.

You can drop text onto the text box that appears at the top of the Properties window when a design time property is selected.
Component Gallery Drag source and drop target for files.

You can drag objects out of the Component Gallery and drop them onto the Form Designer. You can also drag files out of the Component Gallery and drop them onto the Project Manager.

Files can be dropped on the Component Gallery.

See Also

OLE Drag-and-Drop | Run-Time OLE Drag-and-Drop Support | Implementing Intrinsic and Manual OLE Drag-and-Drop Modes | Interoperability and the Internet


Run-Time OLE Drag-and-Drop Support

OLE drag-and-drop support is available at run time for Visual FoxPro controls and the text editor. The controls and the text editor support OLE drag-and-drop interactively at run time, and the controls provide programmatic support at run time. The DataObject object provides programmatic OLE drag-and-drop support for the controls.

Two modes of OLE drag-and-drop are available for Visual FoxPro controls: intrinsic mode and manual mode. In intrinsic mode, Visual FoxPro intrinsically handles an OLE drag-and-drop operation. In manual mode, OLE drag-and-drop operations are handled programmatically. The events that occur are determined by the OLE drag-and-drop mode. For more information, see the section, "Intrinsic and Manual OLE drag-and-drop Modes."

Drag and Drop in Previous Versions of Visual FoxPro

Previous versions of Visual FoxPro supported programmatic drag-and-drop for controls, making it possible for you to move controls on a form. This form of drag and drop is still supported. If you use the default settings for the OLEDragMode and OLEDropMode properties, your existing applications will run as before without any changes.

The DataObject Object

The DataObject object is a container for data being transferred from an OLE drag source to an OLE drop target, and exists only for the duration of an OLE drag-and-drop operation. The DataObject object cannot be created programmatically and references to it become invalid once the OLE drag-and-drop operation is completed. The DataObject is passed as the oDataObject parameter in the OLEStartDrag, OLEDragOver, OLEDragDrop, and OLESetData events.

The DataObject can store multiple sets of data, each in a different format. The existence of a specific format in the DataObject can be determined with the GetFormat method. See the GetFormat Method for a listing of the formats supported by the DataObject.

DataObject Object Methods

The DataObject object has methods that make it possible for you to programmatically manipulate the data being dragged and dropped. The following table lists the methods available at run time for the DataObject.

Method | Description
ClearData | Clears all data and data formats from the OLE drag-and-drop DataObject object.
GetData | Retrieves data from the OLE drag-and-drop DataObject object.
GetFormat | Determines whether data in a specified format is available on the OLE drag-and-drop DataObject.
SetData | Places data and its format on the OLE drag-and-drop DataObject.
SetFormat | Places a data format without data on the OLE drag-and-drop DataObject.

See Also

Design-Time OLE Drag-and-Drop Support | Implementing Intrinsic and Manual OLE Drag-and-Drop Modes | Interoperability and the Internet


Implementing Intrinsic and Manual OLE Drag-and-Drop Modes

Visual FoxPro supports two OLE drag-and-drop modes for controls: intrinsic and manual. In intrinsic mode, OLE drag-and-drop operations are handled by Visual FoxPro. In manual mode OLE drag-and-drop operations, you programmatically specify function and control.

Intrinsic OLE drag-and-drop Mode

Intrinsic OLE drag-and-drop mode can be implemented in an application to provide standard OLE drag-and-drop support without any additional programming.

To implement intrinsic OLE drag-and-drop support for a control

  1. Set its OLEDragMode property to 1 – Automatic, allowing the control to act as an OLE drag source.
  2. Set the control's OLEDropMode property to 1 – Enabled, to allow the control to act as an OLE drop target.

For intrinsic OLE drag-and-drop operations, Visual FoxPro determines if the drop target supports the format of the data being dropped on it; if the drop target supports the format, the drop occurs, otherwise the drop is not allowed.

The following table lists the Visual FoxPro controls and the data formats they support as drag sources in intrinsic mode. Note that CF_TEXT is text, such as text you would enter in a text box, and CFSTR_VFPSOURCEOBJECT is an object type reference to a Visual FoxPro control or object. For the controls below that support the CF_TEXT data format, you can drag text from the text portion of the control.

Drag Source Data Formats

Control | Data Format (defined in Foxpro.h)
Container, Image, Line, PageFrame, and Shape | CFSTR_VFPSOURCEOBJECT
CommandButton and Label | CFSTR_VFPSOURCEOBJECT and CF_TEXT
CheckBox, ComboBox, EditBox, ListBox, Spinner, and TextBox | CFSTR_VFPSOURCEOBJECT, CF_TEXT, and CFSTR_OLEVARIANT

The Visual FoxPro controls and data formats they support as drop targets in intrinsic mode are listed in the following table. For the controls listed in this table, you can drop text onto the text portion of the control. The text is inserted at the insertion point.

Drop Target Data Formats

Control | Data Format
EditBox and ComboBox (When the ComboBox Style property is set to 0 - Dropdown Combo) | CF_TEXT
Spinner and TextBox | CFSTR_OLEVARIANT

Manual OLE drag-and-drop Mode

There may be cases where you'd like to control the type of data that can be dropped on a drop target, or provide additional functionality for a drag-and-drop operation. For example, you can convert data to a format supported by the drop target, or you can display a dialog that asks the user to verify that they want to drop the data on the drop target. To override the intrinsic OLE drag-and-drop support and provide greater control over drag-and-drop operations use manual OLE drag-and-drop.

To implement manual OLE drag-and-drop support for a control write your own event or method code for the event or method you want to override. Include the NODEFAULT keyword in the event or method code to override the intrinsic Visual FoxPro drag-and-drop behavior.

Visual FoxPro provides backward compatibility (no OLE drag support) for existing applications when OLEDragMode is set to 0 (the default) and you do not include additional OLE drag-and-drop coding.

See Also

Run-Time OLE Drag-and-Drop Support | Interoperability and the Internet | Design-Time OLE Drag-and-Drop Support | OLE Drag-and-Drop


Sharing Information and Adding OLE

With Visual FoxPro, you can employ the strengths of other applications by sharing information with them. You can copy and paste data between applications, create mail merges using data from Visual FoxPro tables, link or embed data from other applications, and import or export data between applications. By sharing information, you can save time and avoid errors. For example, instead of entering results from Excel in a table, you can copy the results from Excel or link to Excel to get the results automatically.

In addition, you can extend the power of your Visual FoxPro applications by employing the strengths of other Automation-enabled applications or ActiveX controls. In the forms or General fields of your applications, you can include specific functionality or data such as text, sound, pictures, and video from other applications. You can view or manipulate this data visibly by using the application that created it or you can manipulate the data invisibly and automatically by controlling the application with Automation.

Other applications also can tap into the power of Visual FoxPro through Automation. You can even create Automation servers (COM components) in Visual FoxPro that your applications or other applications can access locally and remotely.

In This Section

Dynamic Information Sharing
Explains how, using Visual FoxPro, you can include data from other applications dynamically and still have those applications maintain the data by linking or embedding it in your application.
Adding OLE Objects to Applications
Describes how you can add OLE objects to tables and forms interactively or programmatically.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
OLE Drag-and-Drop
Describes OLE drag-and-drop, a powerful and useful tool supported by Visual FoxPro, which makes it possible for you to move data between other applications that support OLE drag-and-drop (such as Visual FoxPro, Visual Basic, the Microsoft Windows Explorer, Word and Excel, and so on).
Programming in Visual FoxPro
Describes how to access the full power of Visual FoxPro by creating applications that incorporate object-oriented programming techniques and the event-driven model to maximize your programming productivity.


Dynamic Information Sharing

In Visual FoxPro, you can dynamically include data from other applications and still have those applications maintain the data by linking or embedding it in your application. For example, you can link or embed a Word document in a General field or you can link or embed a Microsoft Excel worksheet on a form.

When you dynamically link data, it is stored in its source file, not in your Visual FoxPro table or form. The table or form stores only the location of the source and displays a representation of the linked data. Linked data is updated when the source file changes and retains a connection to its source file, unless you break the connection (see Changing or Breaking Links to Data in Tables).

Note Files with an .avi extension are always linked.

When you dynamically embed data, it is stored only in your table or form. This data does not retain a connection to its source file. If changes are made to the source file, they do not appear in your Visual FoxPro application.

Embedding and linking data

Create links when:

  • Data or graphics are likely to change.
  • Your application necessarily includes the latest version available.
  • The source files are available for updating on your computer or across a network.
  • The source files must be shared with other applications.

Embed data or graphics when:

  • You don't need to have the most current versions in your application.
  • The embedded data need not be included in more than one application.
  • The source files would not be available for updating if they were linked.

Use the following guidelines to decide on linking or embedding:

To | Use this method | Details
Create applications you can use on other computers or edit, even if the source files are not present. | Embed the data. | To edit the data, all applications from which the data come must be installed on the computer.
Include data that might not always be available, such as data stored on a server. | Embed the data. | All the necessary information is included with the embedded data.
Include a very large file, such as a video or sound clip. | Create a link to the source file. | Your application stores only the link, keeping the size of the application manageable.
Include data that is maintained separately in its source application. | Create a link to the source application. | Your application reflects any changes made to the source application.

Related topics describe how to add data to tables, add data to forms, change or break links to data, display linked or embedded data from tables, and edit linked or embedded data.

Copying and Pasting Data

If you want to share small amounts of data quickly and easily, but don't want to share entire files, select the data manually, cut or copy it, and then paste it wherever you want it. For example, copy selected data from a form and then paste it into a Microsoft Word document, or copy selected cells from a Microsoft Excel worksheet and then paste them into a General field in a table. You can even copy and paste data into mail messages and send the messages from within Visual FoxPro.

Tip To share entire files, link or embed them. For details about linking and embedding, see Dynamic Information Sharing.

To paste data from another application into a General field

  1. Copy the data to the Clipboard.
  2. Open and browse the table containing the General field in which you want to paste the data.
  3. Double-click the General field.
  4. Embed the data by choosing Paste or Paste Special from the Edit menu.

    -or-

    Link to the data by choosing Paste Special from the Edit menu and then selecting Paste Link in the Paste Special dialog box.

    Tip You can save disk space when linking or embedding by selecting the Display As Icon check box. When this is selected, Visual FoxPro displays the icon instead of the data.

Embedding Hyperlinks

Visual FoxPro Editor supports embedding and enabling hyperlinks. When you include any valid hyperlink protocol trigger, Visual FoxPro applies hyperlink attributes to the entered text.

If hyperlinks are enabled (Options Dialog Box or EditorOptions Property), a hyperlink will be displayed in your editor with the typical underline visual cue of a hyperlink in HTML. The hyperlink termination character is a space, so if you have spaces in your path you must replace them with %20. For example, http://servername/program files/my folder must be written http://servername/program%20files/my%20folder.

By default, you need to CTRL + click to follow a link. The EditorOptions property lets you change the default so that simple clicking will follow the link. The following table describes the valid protocols.

Protocol | Trigger(s) | Syntax
File | File:/ | file:///cDrive/cPath | cFile | file:////cUNCPath
FTP | FTP:/ | ftp://[cUserName[:cPassword@]]cDomain
Gopher | Gopher:/ | gopher://cDomain
HTTP | HTTP:/, www.<char> | http://cDomain
HTTPS | HTTP:/ | https://cDomain
MailTo | MailTo: | mailto:cAddress[;cMoreAddresses][&cSubject] [&cBody] [&cCC][&cBCC]
News | News: | news:cNewsGroup
Telnet | Telnet:/ | telnet://cDomain[:iPort]

Creating Mail Merges

A common way of sharing data is to mail letters created from addresses stored in Visual FoxPro and templates stored in Microsoft Word. With Visual FoxPro, you can create a Word document containing data from a Visual FoxPro table by using the Mail Merge Wizard.

To use the Mail Merge Wizard

  1. From the Tools menu, choose Wizards.
  2. From the submenu, choose Mail Merge.
  3. Follow the directions in the wizard.

Sending Mail from Visual FoxPro

If you have a mail program installed, you can send mail from Visual FoxPro.

To send mail

  • From the File menu, choose Send.

    Your electronic mail program displays a dialog box in which you can compose and send a mail message.

You can also send mail from an application by using the MAPI Session Control and MAPI Messages Control For more information on these controls, see the ActiveX Controls Overview.

See Also

Inserting Data in Tables | Changing or Breaking Links to Data in Tables | Displaying Embedded or Linked Data on Forms | Displaying Embedded or Linked Data from Tables | Importing and Exporting Data | Adding OLE


Inserting Data in Tables

You can include data from other applications in a Visual FoxPro table by inserting the data into General fields. For example, if you have pictures of products, you can include them in a table containing other product information by inserting them into a General field.

To insert data into a General field

  1. Open and browse the appropriate table.
  2. Double-click the General field in which you want to insert the data.
  3. From the Edit menu, choose Insert Object.

    The Insert Object dialog box appears listing the types of data you can insert into the field.

  4. To create data of your own, select Create New and then choose the appropriate type of data.

    -or-

    To use existing data, select Create from File. Then, type the name of the file containing the data, or choose Browse and select the appropriate file. If you want to link to the file, select Link.

See Also

Dynamic Information Sharing | Changing or Breaking Links to Data in Tables | Displaying Embedded or Linked Data on Forms | Displaying Embedded or Linked Data from Tables | Editing OLE Objects in Forms and Tables | Importing and Exporting Data | Adding OLE


Changing or Breaking Links to Data in Tables

After linking to some data, you might want to use a different data source, or you might want to embed rather than link. To change the data source, you must change the link; and to embed, you must break the link.

To change the link to data in a General field

  1. Open and browse the appropriate table.
  2. Double-click the General field containing the data whose link you want to change.
  3. From the Edit menu, choose Links. The Links dialog box appears.
    Note Choose Automatic to automatically update data any time it changes in the source application, or Manual if you want to manually update data.
  4. In the Links dialog box, choose Change Source.

    The Change Source dialog box appears.

  5. Specify the new data source and choose OK.
  6. In the Links dialog box, choose Close to complete the change.

To break a link to data in a General field

  1. Open and browse the appropriate table.
  2. Double-click the General field containing the data whose link you want to break.
  3. From the Edit menu, choose Links.
  4. In the Links dialog box, choose Break Link.
  5. Choose Close.

When the link is broken, the data becomes static.

See Also

Inserting Data in Tables | Displaying Embedded or Linked Data on Forms | Displaying Embedded or Linked Data from Tables | Editing OLE Objects in Forms and Tables | Replacing Linked or Embedded Data with Static Data | Dynamic Information Sharing | Importing and Exporting Data | Adding OLE


Displaying Embedded or Linked Data on Forms

You can enhance the design of forms by linking or embedding data such as Word documents or Microsoft Excel worksheets. Similarly, you can enhance reports by displaying linked or embedded data from General fields.

To link or embed data on a form

  1. Create or open a form.
  2. On the Form Controls toolbar, select the OLE Container Control button and drag to size on the form.

    The Insert Object dialog box appears, listing the types of files you can link or embed.

  3. Create a new file by selecting Create New.

    -or-

    Use an existing file by selecting Create from File. Type the name of the file containing the data or choose Browse and select the appropriate file. Additionally, if you want to link to the file, select Link.

Changing or Breaking Links to Data on Forms

You change or break a link to data displayed on a form by using the Links command on the Edit menu.

To change a link to data on a form

  1. Open the appropriate form.
  2. Select the object whose link you want to change.
  3. From the Edit menu, choose Links.
  4. In the Links dialog box, choose Change Source.
  5. In the Change Source dialog box, specify the new data source and choose OK.
  6. In the Links dialog box, choose Close to complete the change.

To break a link to data on a form

  1. Open the appropriate form.
  2. Select the object whose link you want to break.
  3. From the Edit menu, choose Links.
  4. In the Links dialog box, choose Break Link.
  5. Choose Close.

When the link is broken, the data becomes static.

See Also

Adding a General Field | Creating Reports and Labels | Changing or Breaking Links to Data in Tables | Displaying Embedded or Linked Data from Tables | Editing OLE Objects in Forms and Tables | Replacing Linked or Embedded Data with Static Data | Dynamic Information Sharing | Importing and Exporting Data | Adding OLE


Displaying Embedded or Linked Data from Tables

On a form or report, you can display linked or embedded data from General fields in a table. For example, suppose you have a product table in which each record includes a General field containing a brochure (a Word document) about a product. On a form, you could display selected information from the records — including the brochure describing the product.

To display data from a General field on a form

  1. In the Form Designer, add an OLE Bound control to your form.

    On the form, Visual FoxPro creates an object through which you can view the data at run time.

  2. Specify the General field that contains the data by setting the object's ControlSource property.

    For example, if the table name is Inventory and the General field name is Current, then set the ControlSource property to Inventory.Current.

  3. On the form, add buttons or menu commands for browsing the General field specified in the ControlSource property.

To display data from a General field on a report

  • Add a General field to the report.

    For details, see Adding a General Field.

Including Data in a Report

When creating a report, you can link or embed pictures or icons directly into the report from an outside source using the image container. Other forms of data, such as Word documents or Microsoft Excel spreadsheets, can be included only if they were previously linked or embedded into a General field in a Visual FoxPro table.

See Also

Adding a General Field | Creating Reports and Labels | Displaying Embedded or Linked Data on Forms | Editing OLE Objects in Forms and Tables | Replacing Linked or Embedded Data with Static Data | Dynamic Information Sharing | Importing and Exporting Data | Adding OLE


Editing OLE Objects in Forms and Tables

You can edit linked or embedded data in a table or form while designing the table or form. In addition, you can edit the data in a form while running the form. The following procedures describe the ways you can edit data.

To edit data in a General field in a table

  1. Open and browse the appropriate table.
  2. Go to the record containing the General field you want to edit.
  3. Double-click the General field to display the editing window.
  4. In the editing window, double-click to edit the data.

To edit embedded or linked objects on a form while designing the form

  1. Select the object representing the data.
  2. With the mouse pointer over the object, click the right mouse button.
  3. From the shortcut menu, choose the object type, and then choose Edit or Open.

To edit objects or data from General fields on a form while running the form

  1. From the Edit menu, select the object.

    For example, if the object is a Microsoft Excel worksheet, select Spreadsheet Object from the Edit menu.

    Tip You can also right-click on the object if its AutoVerbMenu property is set to True. Choose the object type, and then choose Edit or Open.
  2. To edit the object visually, choose Edit from the submenu.

    -or-

    To edit the object in a separate window, choose Open from the submenu.

    Caution If you change the data in an object while running a form, Visual FoxPro saves the changes only if the data is linked or is associated with an OLE Bound control. Changes associated with an OLE Container control are not saved.

If you edit in the Visual FoxPro window, menus from the application you're using replace or merge with Visual FoxPro menus. For example, if you're using Microsoft Excel, the Excel Edit menu replaces the Visual FoxPro Edit menu. However, the Visual FoxPro File, Program, and Window menus are not replaced.

See Also

Displaying Embedded or Linked Data from Tables | Replacing Linked or Embedded Data with Static Data | Dynamic Information Sharing | Importing and Exporting Data | Adding OLE


Replacing Linked or Embedded Data with Static Data

You can replace linked or embedded data with stand-alone bitmaps by using the application that created the data.

To replace linked or embedded data with a bitmap

  1. Start the application that created the data by choosing the object containing the data.
  2. In the application, copy the object's presentation to the Clipboard.

    For example, if the application has a Copy Picture command, use it to copy the object's presentation.

  3. From the Edit menu in Visual FoxPro, choose Paste Special.
  4. In the Paste Special dialog box, choose Paste Option.
  5. Choose the Picture (Metafile) option.

See Also

Editing OLE Objects in Forms and Tables | Displaying Embedded or Linked Data from Tables | Displaying Embedded or Linked Data on Forms | Dynamic Information Sharing | Importing and Exporting Data | Adding OLE


Adding OLE Objects to Applications

You can add OLE objects to tables and forms interactively or programmatically.

Adding OLE Objects to Tables

While you're designing tables for your application, consider whether you need OLE objects in the tables. For instance, suppose you have a product table and want to include Word documents containing formatted descriptions of the products to be sent to potential customers. To include the Word documents, you must define a General field in the table. Then, you add the documents to the table by linking or embedding them in the General field.

To add an OLE object to a table

  1. Use the Table Designer to create a table with General field.
  2. Open the window for the General field by browsing the table and double-clicking the General field or by using the MODIFY GENERAL command.
  3. From the Edit menu, choose Insert Object.

    -or-

    Use the APPEND GENERAL command.

Appending OLE Objects to Tables

You can add OLE objects to tables with the APPEND GENERAL command. With this command, you can import an OLE object from a file and place it in a General field. If the field already contains an object, the new object replaces it.

Note Unlike APPEND and APPEND BLANK, APPEND GENERAL does not add a new record to the table.

You can use APPEND GENERAL to embed OLE objects or link to OLE objects created by applications such as Microsoft Excel and Word. These applications support both linking and embedding. However, some applications such as Microsoft Graph only support embedding.

Suppose you have Microsoft Word files that you want to store in a Visual FoxPro table. If the table has a General field named WordDoc, you can embed the documents by using the following code:

CREATE TABLE oletable (name c(24), worddoc g)
CD GETDIR()

nFiles = ADIR(aWordFiles, "*.doc")
IF nFiles > 0
   FOR i = 1 to nFiles
      APPEND BLANK
      REPLACE Oletable.Name WITH aWordFiles(i,1)
      APPEND GENERAL WordDoc FROM aWordFiles(i,1)
   ENDFOR
ELSE
   MESSAGEBOX("No Word files found.")
ENDIF
Note The preceding example looks only for files ending in .doc, the standard extension used by Word files. Because Microsoft Word and OLE are aware of this, the files are automatically associated with the Word server when you use APPEND GENERAL.

If you use a different extension than the one expected by the server, you must declare the class of the server, using the CLASS clause. For example, if you add the class for Word to the previous example, the code becomes:

APPEND GENERAL WordDoc FROM wordfiles(i,1) CLASS "Word.Document.6"

If you have files with common extensions (for example, .bmp) that other servers might use, you can use the CLASS clause to specify the particular server you want to use for those files. Alternatively, if you'd rather link than embed objects, use the LINK keyword, as in the following example:

APPEND GENERAL WordDoc FROM wordfiles(i,1) LINK CLASS "Word.Document.6"

In addition, you can replace data in an object by using the DATA keyword of APPEND GENERAL, as the following Microsoft Graph example illustrates.

Refreshing Microsoft Graph

Microsoft Graph is an embeddable application. The values in a Microsoft Graph chart are based on the values in the Microsoft Graph data sheet.

In order to programmatically change the data in a Microsoft Graph chart, you need to construct a string that contains the new data, including tabs, carriage returns, and line feeds, and pass this string to a Microsoft Graph object with the DATA clause of the APPEND GENERAL command.

The following example assumes you have a table, named stock, with, among other fields, date and close for the date and the closing price of the stock. The Microsoft Graph object is stored in the msgraph general field of a table named graph. The example refreshes a graph with stock closing prices from the previous 30 days.

Code Comments
#DEFINE CRLF CHR(13)+CHR(10)

#DEFINE TAB CHR(9)
LOCAL lcData
Define carriage return and tab characters.
SELECT date, close;

  FROM Stock WHERE BETWEEN(date, ;
  DATE(),DATE() - 30) ;
  ORDER BY date INTO CURSOR wtemp
Select the values that you want to update the graph with, in this case, the date and closing values for stocks for the last 30 days.
SELECT wtemp

lcData = " " + ;
  TAB + "Closing Price" + CRLF
SCAN
  lcData = lcData + DTOC(date)
  lcData = lcData + TAB
  lcData = lcData + ;
  ALLTRIM(STR(close)) + CRLF
ENDSCAN
Build a character string (lcData) of data from the cursor to refresh the graph.

"Closing Price," as the column header, is the text that will be displayed by default in the graph's legend.

SELECT graph
APPEND GENERAL msgraph DATA lcData
Send the new values to the graph in the DATA clause of the APPEND GENERAL command.
USE IN wtemp
 Close the cursor.
Note You can also display OLE objects from General fields in your reports.

Adding OLE Objects to Forms

Using the Form Designer, you can add insertable OLE objects to forms with the OLE Container control. In addition, you can display OLE objects from General fields by using the OLE Bound control.

To add an OLE object to a form

  1. In the Form Designer, add an OLE Container control to your form. The Insert Object dialog box opens.
  2. In the Insert Object dialog box, select Create New or Create from File.
  3. Choose the appropriate OLE object from the Object Type list.

You can also customize the Form Controls toolbar so that you can directly add specific OLE objects.

To add OLE objects to the Form Controls toolbar

  1. From the Tools menu, choose Options.
  2. In the Controls tab of the Options dialog box, choose ActiveX controls.
  3. In the Selected list, select the OLE objects and ActiveX controls you want to be available from the Form Controls toolbar.
  4. Choose Set as Default, and then choose OK.
  5. In the Form Controls toolbar, choose View Classes, and then choose ActiveX Controls.

To display an OLE object from a General field

  1. In the Form Designer, add an OLE Bound control to your form.
  2. Specify the General field that contains the data by setting the object's ControlSource property.

    For example, if the table name is Inventory and the General field name is Current, then set the ControlSource property to Inventory.Current.

You can also display an OLE object from a General field programmatically:

Code Comments
frm1 = CREATEOBJECT("form")
 Create form.
frm1.ADDOBJECT("olb1",
"oleboundcontrol")
 Add control.
frm1.olb1.ControlSource =
"Inventory.Current"
 Bind the data to the control.
frm1.olb1.Visible = .T.

frm1.Visible = .T.
Make the control and form visible.

Interacting with OLE Objects

If you add an OLE object to a form or General field, you can edit the data and display characteristics of the object at run time or design time.

Note You cannot edit the data of an OLE object in an OLE Bound control at design time.

Some OLE objects support in-place editing so that you can edit the object in the window used by your application. For example, if you double-click a Microsoft Excel worksheet object in a General field, rather than starting a copy of Microsoft Excel in another window, the menu titles change to reflect the Microsoft Excel menu structure and the default Microsoft Excel toolbars are displayed. You or your application user can then edit the Microsoft Excel object without leaving your application.

Note You can edit only embedded objects in place, not linked objects.

You can also open the Automation server in another window, edit the data or display characteristics there, and have the new values reflected in your application when you return to it.

To edit an OLE object in place in a General field window

  • From the Edit menu, select the specific object type, and from the submenu, choose Edit.

    For example, if the object is a Word document, select the Document Object menu item; if the object is a Microsoft Graph chart, select the Chart Object menu item.

    -or-

    Double-click the object.

To open the application for an OLE object in a General field window

  • From the Edit menu, select the specific object type, and from the submenu, choose Open.

When you add an OLE object to a form in either the OLE Container control or the OLE Bound control, you have more control over the opening and editing of the object.

You can determine whether the OLE object is opened or edited when the control gets the focus or when the user double-clicks the control by setting the AutoActivate property of an OLE bound or container control. The AutoVerbMenu property specifies whether the shortcut menu of the ActiveX control allows a user to open or edit the OLE object.

To control access so that the OLE object can only be opened or edited programmatically with the DoVerb method, set AutoActivate to 0 - Manual and AutoVerbMenu to false (.F.).

Controlling Menus

When a user is in-place editing an OLE object, the menu bar displays the menus for the OLE object, not the menus for your application. If you create a menu title and want it to be displayed even while the user edits an OLE object, select Negotiate in the Prompt Options dialog box of the Menu Designer. For more information, see Designing Menus and Toolbars, or the NEGOTIATE clause in the DEFINE PAD Command topic.

See Also

Adding a General Field | Design of an OLE Application | Using ActiveX Controls | Adding OLE | Table Designer | MODIFY GENERAL | APPEND GENERAL


Design of an OLE Application

Automation-enabled applications and COM components can act as Automation servers, clients, or both. Components that act as servers can provide objects to another application; components that act as clients can create objects.

You can easily incorporate the power and flexibility of applications, such as Microsoft Excel and Word, in your Visual FoxPro applications. Because Visual FoxPro also acts as a server, you can also provide functionality that can be integrated into solution packages based around Microsoft Office or other COM components.

Insertable OLE objects come from OLE-capable applications such as Microsoft Excel and Word. Such objects include Word documents and Excel worksheets. On forms, you can link or embed these objects using the OLE Container control, and you can store such objects in General fields of a table, displaying them in your forms with the OLE Bound control.

In a Visual FoxPro application, you can use OLE and ActiveX technology in many ways. Before you create an application, consider the ways you can use these technologies.

Linking or Embedding OLE Objects

You can embed or link files from other Windows applications in your tables and forms. For example, you can embed or link a Word document in a General field of a table, and you can embed or link an Excel worksheet on a form.

The difference between embedding and linking lies in where the data is stored. Embedding stores the data in the table or form, whereas linking does not. For example, when you embed an Excel worksheet on a form, the form contains a copy of the worksheet. When you link, however, the form contains only a reference to the worksheet — not the worksheet itself.

Both embedded and linked data start off with the original contents of the server file.

But when the original file is changed, linked data is automatically updated to reflect the change, whereas embedded data is not:

Linked data updated in a form

Embedded data is not necessarily static, though. Both embedded and linked data can be displayed, changed, and manipulated interactively and programmatically in Visual FoxPro.

Adding Bound or Unbound OLE Objects

On a form or in a report, you can create objects that are bound to General fields in tables. Such objects are called bound OLE objects and you use them to display the contents of OLE objects in General fields. You create bound OLE objects by using the OLE Bound control on the Form Controls toolbar. Alternatively, you create unbound OLE objects by using the OLE Container control. An unbound OLE object is not connected to a General field in a table.

See Also

Adding OLE Objects to Your Applications | Adding OLE | Using ActiveX Controls | Manipulation of Objects with Automation | The Subclassing of Objects


Using ActiveX Controls

ActiveX controls are objects with encapsulated functionality and exposed properties, events, and methods. ActiveX controls provide a wide range of functionality that you can easily tap into. ActiveX controls that ship with Visual FoxPro include:

  • Windows controls, like the RichText and the TreeView controls.
  • System controls, like the Communications and MAPI controls.

ActiveX controls are versatile because you can subclass them to create other controls and you can control them by using the events, methods, and properties associated with the controls. You cannot create ActiveX controls with Visual FoxPro; however, you can create them using the Microsoft OLE Custom Control Developer's Kit provided with Microsoft Visual C++® 4.0, and with the Microsoft Visual Basic® Control Creation Edition version 5.0.

For more information about accessing ActiveX controls, see Extending Visual FoxPro with External Libraries. For more information on creating ActiveX controls specific to Visual FoxPro, see Accessing the Visual FoxPro API.

Adding ActiveX Controls to a Form

ActiveX controls in Visual FoxPro must be contained in an OLE Container control (the base class is OLEControl). When you add an OLE Container control to a form, you can choose the ActiveX control you want to add to the form.

To add an ActiveX control to a form

  1. From the Form Controls toolbar, choose OLE Container Control and drag it to size in the form.
  2. In the Insert Object dialog box, choose Insert Control.
  3. In the Control Type list, select the desired ActiveX control.
  4. Choose OK.

Managing Bound ActiveX Controls

If an ActiveX control supports simple data binding, Visual FoxPro will expose a ControlSource property for the control. All you have to do is set the ControlSource property to a table field and the value displayed in the ActiveX control reflects that value in the underlying field. Changes to the value in the control are saved to the field.

For examples of using ActiveX controls, run Solution.app in the Visual FoxPro ...\Samples\Solution directory.

Note To ensure all ActiveX control events are processed, set the AutoYield property of the Visual FoxPro Application object to false (.F.).

See Also

Adding OLE Objects to Your Applications | Manipulation of Objects with Automation | Adding OLE | OLE Container Control | Insert Object


Manipulation of Objects with Automation

OLE objects in your forms or programs, or ActiveX controls inside OLE Container controls, can be manipulated through code in the same way that you can program native Visual FoxPro objects.

Manipulating Extrinsic Object Properties

In code, you can manipulate an object using its properties. The way you reference a property depends on whether the object stands alone or is part of a container, such as the OLE Container control or OLE Bound control.

Note ActiveX controls are always part of an OLE Container control.

An object in a container has two parts: the object itself and a container around the object. Both the object and the container have properties, and sometimes they have the same property names. To ensure you reference the object's properties, always append the container's Object property to the object's name. For example, the following code refers to the object's Left property:

frm1.olecontrol1.Object.Left = 25  && Object's Left

If you omit the Object property, you reference the container's Left property instead:

frm1.olecontrol1.Left= 25  && Container's Left property

For example, suppose you have an application that sends mail when the user clicks on a compose command button. If you've added a Microsoft MAPI message control to a form as olecontrol1, the code associated with the Click event of the command button might be:

THISFORM.olecontrol1.Object.Compose
THISFORM.olecontrol1.Object.Send(.T.)

In addition to using the Object property to reference properties of the contained object, you can use other properties of the container control. For example, you can reference the read-only OLEClass property to identify the type of object in the container and the Sizable property to prevent users from changing the size of an object. For details about container control properties, see OLE Container Control.

In the Form and Class Designers, the properties of ActiveX controls are displayed in the Visual FoxPro Properties window, but most ActiveX controls also have their own interface for setting common properties. You can see this properties interface by selecting the object-specific Properties option from the ActiveX control's shortcut menu. For example, to open the Properties dialog box for a rich text control, choose Microsoft RichText Control Properties from the shortcut menu.

Using Extrinsic Object Methods

In addition to setting and retrieving properties of objects, you can manipulate an object using methods it supports. For example, you can use the Add method of a Microsoft Excel collection object to create a new Microsoft Excel workbook.

The following Automation example uses the Add method to create an Excel workbook, the Save method to save the workbook, and the Quit method to end Excel:

Code Comments
oleApp = CREATEOBJECT("Excel.Application")
 Start Excel.
OleApp.Visible=.T.
 Display Excel.
OleApp.Workbooks.Add
 Create a workbook.
OleApp.Cells(1,1).Value=7
 Set a cell's value.
OleApp.ActiveWorkbook.SaveAs("C:\TEMP.XLS")
 Save the workbook.
OleApp.Quit
 Quit Excel.

If you create an object using the OLE Container control or OLE Bound control, you can use the DoVerb method of the control to execute a verb on the object. For example, use DoVerb(0) to execute the default verb, DoVerb(– 1) to activate the object for visual editing, and DoVerb(– 2) to open the object in a separate window.

Note See an application's documentation to determine what Automation commands it supports. For example, Microsoft Excel add-in components are not available for Automation.

Setting Time Outs

When you pass a request to an OLE object, the Automation server processes it. You don't have much control over the server processing, but you can specify how long you'll wait for a process to finish by setting the OLERequestPendingTimeout and OLEServerBusyTimeout properties. You can determine what happens when that time has expired by setting the OLEServerBusyRaiseError property.

Accessing Collections of Objects

An object type can represent a single object or a collection of related objects. For example, a Microsoft Excel Workbook object represents a single workbook, whereas the Workbooks object represents all the workbooks currently loaded. Because the Workbooks object represents a collection of objects, it's called a collection object.

In code, a collection is an unordered list in which the position of an object can change whenever objects are added to or removed from the collection. You access an object in a collection by iterating through the collection, using the Count property of the collection. The Count property returns the number of items in the collection. You can also use the Item method to return an item in a collection.

For example, to display the names of worksheets in a Microsoft Excel workbook, use the following code:

oleApp = CREATEOBJECT("Excel.Application")
oleApp.Workbooks.Add
FOR EACH x IN oleApp.Workbooks
 ? x.Name
ENDFOR

You can also access a collection within a collection. For example, you can access a cells collection within a range using the following code:

oleApp = CREATEOBJECT("Excel.sheet")
oleApp.Workbooks.Add
oleApp.Range(oleApp.Cells(1,1),oleApp.Cells(10,10)).Value=100
oleApp.Visible=.T.

Using Arrays of Objects

You can pass arrays to methods, and you can receive arrays back. However, you must pass arrays by reference by prefixing the array name with the @ sign.

For example, to send a Visual FoxPro array to Microsoft Excel, consider the following code. It creates an array in Visual FoxPro, assigns the array some values, starts Microsoft Excel, creates a workbook, sets a value to the first cell of a worksheet, and then copies that value to the other sheets in the array:

DIMENSION aV(3)
aV(1) = "Sheet1"
aV(2) = "Sheet2"
aV(3) = "Sheet3"
oleApp=CREATEOBJECT("Excel.Application")
oleApp.Workbooks.Add
oleI=oleApp.Workbooks.Item(1)
oleI.Sheets.Item(1).Cells(1,1).Value = 83
oleI.Sheets(@aV).;
 FillAcrossSheets(oleI.Worksheets("Sheet1").Cells(1,1))

oleApp.Visible = .T.

Alternatively, the following example returns an array to Visual FoxPro and then displays the contents of the array:

oleApp = CREATEOBJECT("Excel.Application")
aOleArray = oleApp.GetCustomListContents(3)
FOR nIndex = 1 to ALEN(aOleArray)
   ? aOleArray(nIndex)
ENDFOR
Note With Visual FoxPro, you cannot pass arrays larger than two dimensions to OLE objects. For more information about working with arrays in Visual FoxPro, see Arrays and Arrays of Members and Objects.

Releasing Extrinsic Objects

An Automation server is automatically released if it is not visible and no variables in scope reference the object. You can use the RELEASE command to release the variable associated with an object. If the server is visible, use the Quit method to release it.

See Also

Using ActiveX Controls | The Subclassing of Objects | Adding OLE | OLE Container | OLE Bound | Object


Subclassing of Objects

You can create custom objects by subclassing the base classes provided with Visual FoxPro. For example, the following code subclasses the Outline control provided with Visual FoxPro:

Subclassing the Outline Control

Code Comments
PUBLIC frmMyForm, cFilename
SET SAFETY OFF
 Declare variables and initialize.
frmMyForm = CREATEOBJECT("form")
frmMyForm.Width = 100
frmMyForm.ADDOBJECT("oleOutl","myoutline")
DIMENSION aSection(3)
aSection(1) = "Table"
aSection(2) = "Field"
aSection(3) = "Index"
 Create a form, add the custom outline control to the form, and then create an array for the items that the control lists.
cFilename = GETFILE("dbc","Select a DBC")
USE (cFilename)
INDEX ON objecttype FOR (objecttype = "Table" ;
   OR objecttype = "Field" ;
   OR objecttype = "Index" ) ;
   TAG fname
 Prompt for a database that contains the information you want the control to list.
FOR nIndex = 1 TO 3 STEP 1
   frmMyForm.oleOutl.AddItem(aSection(nIndex))
   frmMyForm.oleOutl.Indent;
    ((frmMyForm.oleOutl.ListCount-1)) = 1
   SCAN
      IF objecttype = aSection(nIndex)
         frmMyForm.oleOutl.Additem(objectname)
         frmMyForm.oleOutl.Indent;
         ((frmMyForm.oleOutl.ListCount-1)) = 2
      ENDIF
   ENDSCAN
   GO TOP
ENDFOR
 Gather information from the database, and then add it to the control.
frmMyForm.oleOutl.Visible = .T.
frmMyForm.Show
 Make the control visible, and then display the form.
DEFINE CLASS myoutline AS olecontrol
   OleClass = "msoutl.outline"
   Top = 5
   Left = 5
   Height = 10
   Width = 60
ENDDEFINE
 Define a subclass of the OLE Container control and add the outline control by setting the OleClass property of the container, and then defining other custom settings.

If you want to distribute your applications, there are some additional considerations.

See Also

Manipulation of Objects with Automation | The Control of Visual FoxPro from Other Applications | Adding OLE | Using ActiveX Controls


Working with Data

To create effective applications, you must analyze your data requirements and then design your databases, tables, and indexes to meet these needs.

In This Section

Developing Databases
Describes how to use databases in Visual FoxPro to establish relationships between tables, enforce referential integrity, and manage local and remote data.
Working with Tables
Discusses how to make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.
Working with Records
Explains how to store data in the table by adding new records and that you can change and delete existing records through the interface or by using commands.
Working with Queries
Describes how to use queries to select and display data from tables or views.
Working with Views
Explains how to use views to create a customized updateable data set for your application.
Creating Reports and Labels
Discusses how to add reports or labels to your application to present data to users.
Importing and Exporting Data
Explains how information is copied between Visual FoxPro and other applications by importing to and exporting from Visual FoxPro.
Database Container Events
Discusses how you can enable DBC events and add code to specific events on data contained in a database.
Programming for Shared Access
Explains how programming for shared access makes it possible for you to create an application that will run on several machines in a network environment.
Visual FoxPro Data Access Using the OLE DB Provider
Describes the Visual FoxPro OLE DB Provider and how to access Visual FoxPro data from other languages and applications.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Stresses that careful planning saves time, effort, and money and that many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating the Application
Discusses how to create a Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Creating Web Services and Components
Explains how you can extend your Visual FoxPro application by making it possible for it to work for multiple users, take advantage of Microsoft ActiveX controls and automation-enabled applications.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Projects
Defines a project configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Explains how to use the modular approach to verify the functionality of each component you create and then compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Describes the debugging tools provided by Visual FoxPro to help you find and correct any errors you discover in your applications.
Distributing Applications
Discusses how to prepare to distribute your application by including all required files and creating distribution disks after you have completed developing and testing your application.


Developing Databases

After you have designed your database, you can build the database through the interface or with the language. You might want to add existing tables to your database and then modify them to take advantage of the data dictionary features in Microsoft Visual FoxPro. If you are working within a project in the Project Manager, you can add the tables as you create them.

In This Section

Designing Databases
Explains how to take advantage of relational database technology in Visual FoxPro with well-planned databases.
Creating a Database
Details the functionality of the Microsoft Visual FoxPro data dictionary and explains how to create a new database and create a database with the Database Wizard.
Managing a Database
Gives instructions on how to add or remove a database from a project, or delete a database altogether, as well as explains how to handle database errors and reference multiple databases.

Related Sections

Developing Visual FoxPro Applications
This section includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Working with Data
Find out how to create effective applications with indexes, tables, and databases based on your data requirements.
Working with Tables
Make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.
Working with Records
Store data in the table by adding new records. Through the interface or by using commands you can change and delete existing records.
Importing and Exporting Data
Information is copied between Microsoft Visual FoxPro and other applications by importing to and exporting from Visual FoxPro.
Viewing and Modifying Database Architecture
Provides descriptions of how to view a database file, a schema, and database objects, as well as explains how to validate a database and extend a .dbc file.


Designing Databases

In Microsoft® Visual FoxPro®, you use databases to organize and relate tables and views. Databases provide the architecture for storing your data and have additional benefits as well. When you use a database, you can create table-level extensions such as field- and record-level rules, default field values, and triggers. In addition, you can create stored procedures and persistent table relationships. You can use your database to access connections to remote data sources and to create views of local and remote tables.

In This Section

Database Design Process
Provides an introduction on how to create a well-designed database and lists the important steps in the design process.
Analysis of Data Requirements
Focuses on the first step in designing a Microsoft Visual FoxPro database, which involves finding out the reason for the database and how it will be used.
Organization of Requirements into Tables
Describes how to select the tables in your database, which can be the most difficult step in the database design process.
Determination of the Fields You Need
Explains the importance of determining what you must know about the people, things, or events recorded in the table.
Identification of Relationships
Contains information and examples on how the Microsoft Visual FoxPro relational database management system can be used to link information in meaningful ways.
Refinement of the Design
After the tables, fields, and relationships have been established, details the important step of reviewing your database design to locate remaining flaws.
Sample Database Diagrams
Offers database diagrams as a way to spark ideas for creating your own database.

Related Sections

Working with Data
Discusses how to create effective applications with indexes, tables, and databases based on your data requirements.
Developing Databases
Shows how to use databases in Microsoft Visual FoxPro to establish relationships between tables, enforce referential integrity, and manage local and remote data.
Working with Tables
Describes how to make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.
Working with Records
Shows how to store data in the table by adding new records. Through the interface or by using commands you can change and delete existing records.
Importing and Exporting Data
Describes how information is copied between Microsoft Visual FoxPro and other applications by importing to and exporting from Visual FoxPro.


Database Design Process

If you use an established database design process, you can quickly and effectively create a well-designed database that provides you with convenient access to the information you want. With a solid design, you'll spend less time constructing the database and you'll end up with faster, more accurate results.

Note The terms "database" and "table" are not synonymous in Visual FoxPro. The term database (.dbc file) refers to a relational database that is a container of information about one or more tables (.dbf files) or views.

The key to effective database design lies in understanding exactly what information you want to store and the way a relational database management system, such as Visual FoxPro, stores data. To efficiently and accurately provide you with information, Visual FoxPro needs to have the facts about different subjects organized into separate tables. For example, you might have one table that stores facts only about employees and another that stores facts only about sales.

When you organize your data appropriately, you design flexibility into your database and gain the capability to combine and present facts in many different ways.

When you design a database, you first break down the information you want to keep as separate subjects, and then you tell Visual FoxPro how the subjects are related to each other so that Visual FoxPro can bring the right information together when you need it. By maintaining information in separate tables, you make it easier to organize and maintain your data, as well as to build a high-performance application.

Here are the steps in the database design process. Each step is discussed in greater detail in related topics.

  1. Determine the purpose of your database Knowing the purpose will help you decide which facts you want Visual FoxPro to store. For more information, see Analysis of Data Requirements.
  2. Determine the tables you need When you have a clear purpose for your database, you can divide your information into separate subjects, such as "Employees" or "Orders." Each subject will be a table in your database. For more information, see Organization of Requirements into Tables
  3. Determine the fields you need Decide what information you want to keep in each table. Each category of information in a table is called a field and is displayed as a column when you browse the table. For example, one field in an Employee table could be Last_name; another could be Hire_date. For more information, see Determination of the Fields You Need
  4. Determine the relationships Look at each table and decide how the data in one table is related to the data in other tables. Add fields to tables or create new tables to clarify the relationships, as necessary. For more information, see Identification of Relationships
  5. Refine your design Analyze your design for errors. Create the tables and add a few records of sample data. See if you can get the results you want from your tables. Make adjustments to the design as needed. For more information, see Refinement of the Design

Don't worry if you make mistakes or leave things out of your initial design. Think of it as a rough draft that you can refine later. Experiment with sample data and prototypes of your forms and reports. With Visual FoxPro, it's easy to change the design of your database as you're creating it. However, it becomes much more difficult to make changes to tables after they're filled with data and after you've built forms and reports. For this reason, make sure that you have a solid design before you proceed too far into building your application.

You can use the Database Designer to define a set of tables and link them with relationships that persist whenever you use the tables.

Take a look at the sample database. To open the database in the Database Designer, choose Open from the File menu, and locate Testdata.dbc in the Visual FoxPro ...\Samples\Data directory.

The Database Designer shows the relationships between tables

See Also

Designing Databases | Analysis of Data Requirements | Developing Databases | Working with Tables | Organization of Requirements into Tables


Analysis of Data Requirements

Your first step in designing a Visual FoxPro database is to analyze your data requirements by determining the purpose of the database and how it is to be used. This tells you what information you want from the database. From that, you can determine what subjects you need to store facts about (the tables) and what facts you need to store about each subject (the fields in the tables).

Talk to the people who will use the database. Brainstorm about the questions you'd like the database to answer. Sketch out the reports you'd like it to produce. Gather the forms you currently use to record your data. You'll use all this information in the remaining steps of the design process.

Example

Suppose that Tasmanian Traders, an import/export company that sells specialty foods from around the world, wants a database that can track information about the company's sales and inventory.

Start by writing down a list of questions the database should be able to answer. How many sales of our featured product did we make last month? Where do our best customers live? Who's the supplier for our best-selling product?

Next, gather all the forms and reports that contain information the database should be able to produce. The company currently uses a printed report to keep track of products being ordered and an order form to take new orders. The following illustration shows these two documents.

Forms and reports show some data requirements for your database.

Tasmanian Traders also needs to print mailing labels for customers, employees, and suppliers.

After gathering this information, you're ready for the next step.

See Also

The Database Design Process | Organization of Requirements into Tables | Designing Databases | Developing Databases | Working with Tables


Organization of Requirements into Tables

Determining the tables in your database can be the trickiest step in the database design process. That's because the results you want from your database — the reports you want to print, the forms you want to use, and the questions you want answered — don't necessarily provide clues about the structure of the tables that produce them. They tell you what you want to know but not how to categorize the information into tables.

See the order form in Analysis of Data Requirements as an example. It includes facts about the customer — the customer's address and phone number — along with facts about the order. This form provides you with a number of facts that you know you want to store in your database. Although the facts are all on the same form, you can easily prevent common data integrity problems by storing them in separate tables.

Storing information once reduces the chance of error

For example, if you only use one table to store the information for an order form, suppose that one customer places three different orders. You could add the customer's address and phone number to your database three times, once for each order. But this multiplies the chance of data entry errors.

The Customer table stores address information once

Also, if the customer moves, you'd have to either accept contradictory information or find and change each of that customer's sales records in the table. It's much better to create a Customer table that stores the customer's address in your database once. Then, if you need to change the data, you change it only once.

Preventing the deletion of valuable information

Suppose a new customer places an order and then cancels it. When you delete the order from the table containing information on both customers and their orders, you would delete the customer's name and address as well. But you want to keep this new customer in your database so you can send the customer your next catalog. Again, it's better to put the information about the customer in a separate Customer table. That way you can delete the order without deleting customer information.

Look at the information you want to get out of your database and divide it into fundamental subjects you want to track, such as customers, employees, products you sell, services you provide, and so on. Each of these subjects is a candidate for a separate table.

Tip One strategy for dividing information into tables is to look at individual facts and determine what each fact is actually about. For example, on the Tasmanian Traders order form, the customer address isn't about the sale; it's about the customer. This suggests that you need a separate table for customers. In the Products On Order report, the supplier's phone number isn't about the product in stock; it's about the supplier. This suggests that you need a separate table for suppliers.

See Also

Analysis of Data Requirements | Determination of the Fields You Need | Designing Databases | Developing Databases | Working with Tables


Determination of the Fields You Need

To determine the fields in a table, decide what you need to know about the people, things, or events recorded in the table. You can think of fields as attributes of the table. Each record (or row) in the table contains the same set of fields or attributes. For example, an address field in a customer table contains customers' addresses. Each record in the table contains data about one customer, and the address field contains the address for that customer.

In This Section

Identifying Fields
Provides tips for determining the fields you might need in your database.
Using Primary Key Fields
Explains how each table in your database should include a field or set of fields that uniquely identifies each individual record stored in the table, for Visual FoxPro to work most efficiently.

Related Sections

Designing Databases
Take advantage of relational database technology in Visual FoxPro with well-planned databases.
Database Design Process
Provides an introduction on how to create a well-designed database and lists the important steps in the design process.
Analysis of Data Requirements
Focuses on the first step in designing a Microsoft® Visual FoxPro® database, which involves finding out the reason for the database and how it will be used.
Organization of Requirements into Tables
Describes how to select the tables in your database, which can be the most difficult step in the database design process.
Determination of the Fields You Need
Explains the importance of determining what you must know about the people, things, or events recorded in the table.
Identification of Relationships
Contains information and examples on how the Microsoft® Visual FoxPro® relational database management system can be used to link information in meaningful ways.
Refinement of the Design
Details the important step of reviewing your database design to locate remaining flaws after the tables, fields, and relationships have been established.
Sample Database Diagrams
Offers database diagrams as a way to spark ideas for creating your own database.


Identifying Fields

Here are a few tips for determining your fields:

Relate each field directly to the subject of the table

A field that describes the subject of a different table belongs in that other table. Later, when you define relationships between your tables, you'll see how you can combine the data from fields in multiple tables. For now, make sure that each field in a table directly describes the subject of the table. If you find yourself repeating the same information in several tables, it's a clue that you have unnecessary fields in some of the tables.

Don't include derived or calculated data

In most cases, you don't want to store the result of calculations in tables. Instead, you can have Visual FoxPro perform the calculations when you want to see the result. For example, the Tasmanian Traders order form displays the extended price for each line of the order in the Tasmanian Traders database. However, there's no Extended Price subtotal field in any Tasmanian Traders table. Instead, the Order_Line_Items table includes a quantity field that stores the units on order for each individual product, as well as the unit price for each item ordered. Using that data, Visual FoxPro calculates the subtotal each time you print an order form. The subtotal itself doesn't need to be stored in a table. For more information, see Analysis of Data Requirements.

Include all the information you need

It's easy to overlook important information. Return to the information you gathered in the first step of the design process. Look at your paper forms and reports to make sure all the information you have required in the past is included in your Visual FoxPro tables or can be derived from them. Think of the questions you will ask Visual FoxPro. Can Visual FoxPro find all the answers using the information in your tables? Have you identified fields that will store unique data, such as the customer ID? Which tables include information that you'll combine into one report or form? For more information, see Using Primary Key Fields and Identification of Relationships.

Store information in its smallest logical parts

You might be tempted to have a single field for full names, or for product names, along with product descriptions. If you combine more than one kind of information in a field, it's difficult to retrieve individual facts later. Try to break down information into logical parts; for example, create separate fields for first and last name, or for product name, category, and description.

Example

Tasmanian Traders sells imported specialty foods from around the world. The employees use a Products On Order report to keep track of products being ordered.

Report for tracking the inventory of products

The report indicates that the Products table, which contains facts about products sold, needs to include fields for the product name, units in stock, and units on order, among others. But what about fields for the supplier name and phone number? To produce the report, Visual FoxPro needs to know which supplier goes with each product.

Draft of the Supplier table containing fields for supplier name and phone number

You can solve this without storing redundant data in your tables by creating a Supplier table with separate fields for the supplier's name and phone number. For more information, see Using Primary Key Fields.

See Also

Determination of the Fields You Need | Using Primary Key Fields


Using Primary Key Fields

The power in a relational database management system such as Visual FoxPro comes from its ability to quickly find and bring together information stored in separate tables. In order for Visual FoxPro to work most efficiently, each table in your database should include a field or set of fields that uniquely identifies each individual record stored in the table. This is often a unique identification number, such as an employee ID number or a serial number. In database terminology, this information is called the primary key of the table. Visual FoxPro uses primary key fields to quickly associate data from multiple tables and bring the data together for you.

If you already have a unique identifier for a table, such as a set of product numbers you've developed to identify the items in your stock, you can use that identifier as the table's primary key. But make sure the values in this field will always be different for each record — Visual FoxPro doesn't allow duplicate values in a primary key field. For example, don't use someone's name as a primary key, because names aren't unique. You could easily have two people with the same name in the same table.

When choosing primary key fields, keep these points in mind:

  • Visual FoxPro doesn't allow duplicate or null values in a primary key field. For this reason, you shouldn't choose a primary key that could contain such values.
  • You can use the value in the primary key field to look up records, so it shouldn't be too long to remember or type. You might want it to have a certain number of letters or digits, or be within a certain range of values.
  • The size of the primary key affects the speed of operations in your database. When you create primary key fields, use the smallest size that will accommodate the values you need to store in the field.

Example

The primary key of the Tasmanian Traders Products table contains product ID numbers. Because each product number identifies a different product, you don't want two products with the same number.

The Primary key for the Products table is the Product_id field.

In some cases, you might want to use two or more fields that together provide the primary key of a table. For example, the Order_Line_Items table in the Tasmanian Traders database uses two fields as its primary key: Order_id and Product_id. For more information, see Identification of Relationships.

See Also

Determination of the Fields You Need | Identifying Fields


Identification of Relationships

Once you've divided your information into tables, you need a way to tell Visual FoxPro how to bring it back together again in meaningful ways. For example, the following form includes information from several tables.

The Order Entry form uses information from several tables.

Visual FoxPro is a relational database management system. That means you store related data in separate tables. Then you define relationships between the tables and Visual FoxPro uses the relationships to find associated information stored in your database.

For example, suppose that you want to phone an employee with questions about a sale the employee made. Employee phone numbers are recorded in the Employee table; sales are recorded in the Orders table. When you tell Visual FoxPro which sale you're interested in, Visual FoxPro can look up the phone number based on the relationship between the two tables. It works because Employee_id, the primary key for the Employee table, is also a field in the Orders table. In database terminology, the Employee_id field in the Orders table is called a foreign key, because it refers to a primary key from a different, or foreign, table.

Employee_id field as primary key for Employee table and foreign key for Orders table

So, to set up a relationship between two tables — Table A and Table B — you add one table's primary key to the other table, so that it appears in both tables. But how do you decide which table's primary key to use? To set up the relationship correctly, you must first determine the nature of the relationship. There are three types of relationships between tables:

  • One-to-many relationships
  • Many-to-many relationships
  • One-to-one relationships

The following examples present each type of relationship and explain how to design your tables so that Visual FoxPro can associate the data correctly. The purpose of each example is to explain how you determine the relationships between your tables and how you decide which fields belong in the tables to support those relationships — it doesn't describe how to use the Visual FoxPro interface to relate tables.

Example

A one-to-many relationship is the most common type of relationship in a relational database. In a one-to-many relationship, a record in Table A can have more than one matching record in Table B, but a record in Table B has, at most, one matching record in Table A.

For example, the Category and Products tables in the Tasmanian Traders database have a one-to-many relationship.

A one-to-many relationship

To set up the relationship, you add the field or fields that make up the primary key on the "one" side of the relationship to the table on the "many" side of the relationship. You use a primary or candidate index key for the "one" side of the relationship, and a regular index key for the "many" side. In this case, you would add the Category_id field from the Category table to the Products table, because one category includes many products. Visual FoxPro uses the category ID number to locate the correct category for each product.

For more information, see Working with Tables.

Example

In a many-to-many relationship, a record in Table A can have more than one matching record in Table B, and a record in Table B can have more than one matching record in Table A. This type of relationship requires changes in your database design before you can correctly specify the relationship to Visual FoxPro.

To detect many-to-many relationships between your tables, it's important that you look at both directions of the relationship. For example, consider the relationship between orders and products in the Tasmanian Traders business. One order can include more than one product. So for each record in the Orders table, there can be many records in the Products table. But that's not the whole story. Each product can appear on many orders. So for each record in the Products table, there can be many records in the Orders table.

A many-to-many relationship

The subjects of the two tables — orders and products — have a many-to-many relationship. This presents a challenge in database design. To understand the problem, imagine what would happen if you tried to set up the relationship between the two tables by adding the Product_id field to the Orders table. To have more than one product per order, you need more than one record in the Orders table per order. You'd be repeating order information over and over for each record that relates to a single order — an inefficient design that could lead to inaccurate data. You run into the same problem if you put the Order_id field in the Products table — you'd have more than one record in the Products table for each product. To solve this problem, create a third table that breaks down the many-to-many relationship into two one-to-many relationships. This third table is called a junction table, because it acts as the junction between two tables. You put the primary key from each of the two tables into the junction table.

The Order_Line_Items table creates a one-to-many link between Orders and Products

A junction table might hold only the two primary keys from the tables it links together or, as in the Order_Line_Items table, the junction table might hold additional information.

Each record in the Order_Line_Items table represents one line item on an order. The Order_Line_Items table's primary key consists of two fields — the foreign keys from the Orders and Products tables. The Order_id field alone doesn't work as the primary key for this table, because one order can have many line items. The order ID is repeated for each line item on an order, so the field doesn't contain unique values. The Product_id field alone doesn't work either, because one product can appear on many different orders. But together the two fields in the junction table always produce a unique value for each record. The junction table does not require its own primary key.

In the Tasmanian Traders database, the Orders table and the Products table aren't related to each other directly. Instead, they are related indirectly through the Order_Line_Items table. The many-to-many relationship between orders and products is represented in the database using two one-to-many relationships:

  • The Orders and Order_Line_Items tables have a one-to-many relationship. Each order can have more than one line item, but each line item is connected to only one order.
  • The Products and Order_Line_Items tables have a one-to-many relationship. Each product can have many line items associated with it, but each line item refers to only one product.

Example

In a one-to-one relationship, a record in Table A can have no more than one matching record in Table B, and a record in Table B can have no more than one matching record in Table A. This type of relationship is unusual and might call for some changes in your database design.

One-to-one relationships between tables are unusual because in many cases, the information in the two tables can simply be combined into one table. For example, suppose you created a table, called Ping-Pong Players, to track information about a Tasmanian Traders Ping-Pong fundraising event. Because the ping-pong players are all employees of Tasmanian Traders, this table has a one-to-one relationship with the Employee table in the Tasmanian Traders database.

A one-to-one relationship

You could add all the fields from the Ping-Pong Players table to the Employee table. But the Ping-Pong Players table tracks a one-time event, and you won't need the information after the event is over. Additionally, not all employees play Ping-Pong, so if these fields were in the Employee table, they would be empty for many records. For these reasons, it makes sense to create a separate table.

When you detect the need for a one-to-one relationship in your database, consider whether you can put the information together in one table. For example, in the Employee table, one employee can have one manager, who is also an employee. You can add a field for the manager's id number. To pull the information together later, you can use a self-join in your query or view. You don't need a separate table to resolve the one-to-one relationship. If you don't want to do that for some reason, here's how to set up the one-to-one relationship between two tables:

  • If the two tables have the same subject, you can probably set up the relationship by using the same primary key field in both tables.
  • If the two tables have different subjects with different primary keys, choose one of the tables (either one) and put its primary key field in the other table as a foreign key.

See Also

Determination of the Fields You Need | Refinement of the Design | Organization of Requirements into Tables | Analysis of Data Requirements | Designing Databases | Developing Databases | Working with Tables


Refinement of the Design

When you have the tables, fields, and relationships you need, it's time to study the design and detect any flaws that might remain.

You might encounter several pitfalls while you are designing your database. These common problems can cause your data to be harder to use and maintain:

  • Do you have one table with a large number of fields that don't all relate to the same subject? For example, one table might contain fields pertaining to your customers as well as fields that contain sales information. Try to make sure each table contains data about only one subject.
  • Do you have fields that are intentionally left blank in many records because they aren't applicable to those records? This usually means that the fields belong in another table.
  • Do you have a large number of tables, many of which contain the same fields? For example, you have separate tables for January sales and February sales, or for local customers and remote customers, in which you store the same type of information. Try consolidating all the information pertaining to a single subject in one table. You might also need to add an extra field, for example, to identify the sales date.

Create your tables, specify relationships between the tables, and enter a few records of data in each table. See if you can use the database to get the answers you want. Create rough drafts of your forms and reports and see if they show the data you expect. Look for unnecessary duplications of data and eliminate them.

As you try out your initial database, you will probably discover room for improvement. Here are a few things to check for:

  • Did you forget any fields? Is there information that you need that isn't included? If so, does it belong in the existing tables? If it's information about something else, you might need to create another table.
  • Did you choose a good primary key for each table? If you use it to search for specific records, is it easy to remember and type? Make sure that you won't need to enter a value in a primary key field that duplicates another value in the field.
  • Are you repeatedly entering duplicate information in one of your tables? If so, you probably need to divide the table into two tables with a one-to-many relationship.
  • Do you have tables with many fields, a limited number of records, and many empty fields in individual records? If so, think about redesigning the table so it has fewer fields and more records.

As you identify the changes you want to make, you can alter your tables and fields to reflect the improved design. For information about modifying tables, see Working with Tables.

Example

Each product in the Tasmanian Traders stock falls under a general category, such as Beverages, Condiments, or Seafood. The Products table could include a field that shows the category of each product.

Products table with a Category_name field

Suppose that in examining and refining the database, Tasmanian Traders decides to store a description of the category along with its name. If you add a Category Description field to the Products table, you have to repeat each category description for each product that falls under the category — not a good solution.

A better solution is to make Category a new subject for the database to track, with its own table and its own primary key. Then you can add the primary key from the Category table to the Products table as a foreign key.

The Category table stores category information efficiently

The Category and Products tables have a one-to-many relationship: one category can have more than one product in it, but any individual product can belong to only one category.

See Also

Identification of Relationships | Sample Database Diagrams | Determination of the Fields You Need | Organization of Requirements into Tables | Analysis of Data Requirements | Designing Databases | Developing Databases | Working with Tables


Sample Database Diagrams

The following database diagrams might give you ideas for designing your own database. These databases aren't included with Visual FoxPro; they're included here as examples of the types of databases and tables you can create.

Appointments Database

This database structure stores appointments for a professional office, and could easily be modified for use in an office of doctors, dentists, lawyers, or accountants. The Appointments table has a multiple-field primary key to uniquely identify each appointment. This primary key, the "client_sta" index, is created by indexing on an expression that combines the client_id and date_start time fields.

Example of an appointments database

Personnel Database

This database structure stores human resources information. The Job History table stores information on each hire or promotion, so it can contain many records for each employee.

Example of a personnel database

Library Database

This database stores information about library books and loans to patrons. Notice the many-to-many relationships between the Books and Authors tables and between the Books and Subjects tables.

Example of a library database

See Also

Refinement of the Design | Identification of Relationships | Determination of the Fields You Need | Organization of Requirements into Tables | Analysis of Data Requirements | Designing Databases


Creating a Database

After you have designed your database and determined what fields you might need, you are ready to create your database.

In This Section

Database Creation Process
Learn how to create a database, a database container, gather tables together into one collection, and use data dictionary features.
Working with a Database
Explains how a database provides a working environment that can be used to store a collection of tables, establish relationships between the tables, and set properties and data validation rules that control how the related tables work together.
Adding Tables to a Database
Describes how adding a table creates links between the table file and the database container. When you create a new database, it is empty, containing no associated tables or other objects.
Updating Table and Database Links
Moving a database file or a table associated with a database will change the relative paths and might break links that Visual FoxPro uses to associate database and table files. You will need to reestablish links and update the relative path information to reflect the new file location.
Removing a Table from a Database
Learn how to remove a table from a database, which also removes the table and associated data dictionary information from the database file, but does not delete the table.
Creating Persistent Relationships
Explains how persistent relationships are relationships between database tables that are stored in the database file.
Building Referential Integrity
Describes how to open and use the Referential Integrity Builder and gives background on how to create a set of rules to maintain the defined relationships between tables when adding or deleting records.
Creating Stored Procedures
Explains how to create, modify, or remove a stored procedure.
Viewing and Setting Database Properties
Explains how to view and set Version and Comment properties within a Microsoft Visual FoxPro database.

Related Sections

Designing Databases
Explains how to take advantage of relational database technology in Visual FoxPro with well-planned databases.
Viewing and Modifying Database Architecture
Provides descriptions of how to view a database file, a schema, and database objects, as well as explains how to validate a database and extend a .dbc file.
Managing a Database
Gives instructions on how to add or remove a database from a project, or delete a database altogether, as well as explains how to handle database errors and reference multiple databases.


Database Creation Process

When you create a database, you gather tables together into one collection and gain the benefit of data dictionary features.

A data dictionary gives you greater flexibility in designing and modifying the database, and frees you from having to write code to create field-level and row-level validation or to ensure the uniqueness of values within primary key fields. The Visual FoxPro data dictionary enables you to create or specify:

  • Primary and candidate keys.
  • Persistent relationships between database tables.
  • Long names for tables and fields.
  • Captions on fields that display in Browse windows and Grid columns as headers.
  • Default values on fields.
  • The default control class used in forms.
  • Input masks and display formats for fields.
  • Field-level rules and record-level rules.
  • Triggers.
  • Stored procedures.
  • Connections to remote data sources.
  • Local and remote views.
  • Comments for each field, table, and database.

Some data dictionary features, such as long field names, primary and candidate keys, default values, field-level and record-level rules, and triggers, are stored in the .dbc file but are created as part of the process of building a table or view. For more information, see Working with Tables, and Creating Views.

Collecting Tables into a Database

To collect tables into a database, you need to create a database container to hold all of the objects such as views, connections, and stored procedures associated with the tables that make up your database.

To create a new database

  • In the Project Manager, select the Data tab, then select Databases from the list and choose New.

    -or-

  • Use the CREATE DATABASE command.

For example, the following code creates and exclusively opens a new database called Sample:

CREATE DATABASE Sample

When you create a new database, it is empty, containing no associated tables or other objects. Adding a table creates links between the table file and the database container. The link information stored in the database about a table is a forward link. The link information stored in the table about the database container is the backlink.

Links specify the associations between a database container and tables.

Using the Database Wizard

You can use the Database Wizard to help you create a new database. The wizard provides templates and poses a series of questions to help you set up your database based on your answers.

To create a database using the Database Wizard

  1. In the Project Manager, select the Data tab and select Databases.
  2. Choose New.
  3. Choose the Database Wizard button.
  4. Follow the instructions on the wizard screens.

You can also access the Database Wizard from the menu by choosing New from the File menu, selecting Database, and selecting the Database Wizard option.

The wizard provides templates for tables and views, indexes, primary keys, and relationships you can choose or edit.

You can use the following commands and functions to work with a database and its objects programmatically.

Commands and functions that manipulate databases and database objects

ADATABASES( ) | CREATE VIEW | MODIFY CONNECTION
ADBOBJECTS( ) | DBC( ) | MODIFY DATABASE
ADD TABLE | DBGETPROP( ) | MODIFY PROCEDURE
ALTER TABLE | DBSETPROP( ) | MODIFY STRUCTURE
APPEND PROCEDURES | DELETE CONNECTION | MODIFY VIEW
CLOSE DATABASE | DELETE DATABASE | OPEN DATABASE
COPY PROCEDURES | DELETE VIEW | PACK DATABASE
CREATE CONNECTION | DISPLAY DATABASE | RENAME TABLE
CREATE DATABASE | DROP TABLE | REMOVE TABLE
CREATE SQL VIEW | INDBC( ) | SET DATABASE
CREATE TABLE | LIST DATABASE | VALIDATE DATABASE

See Also

Developing Databases | Adding Tables to a Database | Browse | Removing a Table from a Database | Updating Table and Database Links | Project Manager | CREATE DATABASE | Database Wizard | Database Designer | Designing Databases


Working with a Database

A database provides a working environment where you can store a collection of tables, establish relationships between the tables, and set properties and data validation rules that control how the related tables work together. A database is stored as a file with a .dbc extension.

Contents of a Database

You can use databases independently or incorporate them into a project by adding them to the Project Manager. To access the tables within a database, the database must be open.

To open a database

  1. In the Project Manager, select the name of the database you want to use.
  2. Choose Modify.

You can also choose Open from the File menu and choose the name of a database.

To look at the structure of a sample database, open the Testdata.dbc file located in the Visual FoxPro ...\Samples\Data directory.

Tables in the Database Designer

When you open a database, the Database Designer appears and displays the tables in the database and the relationships between them. The Database Designer toolbar makes it possible for you to access database-related options quickly. Database commands are available on the Database menu and shortcut menus are available when you right-click the Database Designer.

Finding a Table or View in a Database

If your database contains many tables and views, you might want to quickly locate a specific table in the Database Designer. When the Database Designer is open, you can quickly locate the table or view you want to work using the Find Object command from the Database menu.

To locate a table in a database

  1. From the Database menu, choose Find Object.
  2. In the Find Table or View dialog box, select the table you want to locate.

The located table appears active in the Database Designer.

Displaying Tables or Views

You can choose to display only tables or specific views.

To display only tables or views

  1. From the Database menu, choose Properties.
  2. In the Database Properties dialog box, select the desired display options.

You can expand tables in the Database Designer to see the fields and the indexes they contain or collapses tables to show only the table names, which is helpful if the database contains many tables.

To expand or collapse a table

  • In the Database Designer, right-click a table and select Expand or Collapse.

To expand or collapse all tables

  • Right-click the Database Designer and select Expand All or Collapse All.

Arranging Tables in a Database

You can change the layout of your tables displayed in the Database Designer. For example, after working in the database, you might want to return the tables to the default height and width or you might want to improve the layout by aligning the tables.

To arrange the tables in a database

  • From the Database menu, choose Arrange, and then select the appropriate options in the Find Table or View dialog box.

    In the Database Designer, the title bar of the table you selected is highlighted.

    To | Select
    Arrange the tables alphabetically by name | By name
    Arrange the tables by type | By type
    Align the tables in a row | Horizontally
    Align the tables in a column | Vertically
    Return the tables to their original size | Resize objects to default height and width

See Also

Developing Databases | Adding Tables to a Database | Browse | Removing a Table from a Database | Updating Table and Database Links | Creating a Database | Database Designer | Project Manager


Adding Tables to a Database

Begin building your database by adding the tables you want to use. You can select any table that is not currently part of another database. Since tables can only belong to one database at a time, you need to remove a table from a database before you can use it in a new database.

To add a table to a database

  1. From the Database menu, choose Add Table.
  2. In the Open dialog box, select a table and choose OK.

Free Tables and Database Tables

Each Visual FoxPro table can exist in one of two states: either as a free table, which is a .dbf file that is not associated with any database, or as a database table, which is a .dbf file that is associated with a database. Tables associated with a database can have properties that tables outside a database do not have, such as field-level and record-level rules, triggers, and persistent relationships.

You associate tables with a database by creating them within an open database, or by adding existing tables to a database. For more information, see Working with Tables.

To add a free table to a database

  • In the Project Manager, select Tables from the All tab or the Data tab, then choose Add.

    -or-

  • Use the ADD TABLE Command.

For example, the following code opens the testdata database and adds the orditems table:

OPEN DATABASE testdata
ADD TABLE orditems

You must explicitly add an existing free table to a database to make it a part of a database. Modifying the structure of a free table does not cause Visual FoxPro to add the free table to a database, even if a database is open when you issue the MODIFY STRUCTURE command.

Using Free Tables

You can associate a given table with only one database. However, you can use the data in an existing .dbf file without incorporating it into your database.

To access a table in another database

  • Create a view in your database that references the table.

    -or-

  • Access the table with the USE command and the "!" symbol.

Use the "!" symbol to refer to a table in a database other than the current database. For example, if you want to browse the orditems table in the testdata database, you can type:

USE testdata!orditems
BROWSE

In the previous example, the testdata database is opened automatically for you when you issue the USE command, but Visual FoxPro does not set testdata as the current database. A database opened automatically, as in the previous example, is automatically closed when the table is closed, unless you open the database explicitly before closing the table.

For more information, see Creating Views.

See Also

Creating a Database | Removing a Table from a Database | Updating Table and Database Links | Creating Persistent Relationships | ADD TABLE | Designing Databases | Developing Databases | Working with a Database


Updating Table and Database Links

If you move database files (.dbc, .dct, and .dcx), or a table associated with a database, the relative paths change and might break the backlinks and forward links that Visual FoxPro uses to associate database and table files:

  • The backlink links the table back to the table's owning database. It consists of the relative path and file name for the .dbc file associated with the table, and is stored in the header of the Visual FoxPro table file (.dbf).
  • The forward link tells the database which tables belong to it. Forward links are stored in the database file (.dbc), and consist of the relative path and file name for each associated table file.

You can reestablish links and update the relative path information to reflect the new file location.

To update links after moving a table or a database

  • Use the RECOVER clause of the VALIDATE DATABASE command.

For example, the following code opens the testdata database and displays dialog boxes that allow you to locate tables that are not in the locations contained in the database:

OPEN DATABASE testdata
VALIDATE DATABASE RECOVER
Tip If you want to use a table without taking time to reestablish the links for all tables in the database, you can open the table with the USE command. Visual FoxPro displays the Open dialog box to allow you to locate the owning database or delete the links.

For more information, see FREE TABLE.

See Also

Removing a Table from a Database | Creating Persistent Relationships | Adding Tables to a Database | Developing Databases | Creating a Database | Working with a Database


Removing a Table from a Database

When you add a table to a database, Visual FoxPro modifies the table file's header record to document the path and file name for the database that now owns the table. This path and file name information is called a backlink, because it links the table back to the owning database. The process of removing a table from a database not only removes the table and associated data dictionary information from the database file, but also updates the backlink information to reflect the table's new status as a free table.

You can remove a table from a database through the interface or with the REMOVE TABLE command. As you remove the table from the database, you can also choose to physically delete the table file from the disk.

To remove a table from a database

  • In the Project Manager, select the table name, and then choose Remove.

    -or-

  • From the Database Designer, select the table. From the Database menu choose Remove, and then in the dialog box, choose Remove.

    -or-

  • Use the REMOVE TABLE command.

For example, the following code opens the testdata database and removes the orditems table:

OPEN DATABASE testdata
REMOVE TABLE orditems

Removing a table from a database does not automatically delete the table file. If you want to both remove the table from the database and delete the table's .dbf file from the disk, use the DELETE clause of the REMOVE TABLE command or the DROP TABLE command. For example, the following code opens the testdata database and deletes the orditems table from disk:

OPEN DATABASE testdata
REMOVE TABLE orditems DELETE

The following code also opens the testdata database, then deletes the orditems table without moving a copy to the Windows Recycle bin:

OPEN DATABASE testdata
DROP TABLE orditems NORECYCLE

See Also

Adding Tables to a Database | Updating Table and Database Links | Creating a Database | Developing Databases | REMOVE TABLE | Designing Databases | Working with a Database


Creating Persistent Relationships

You can create persistent relationships between tables in a database. Persistent relationships are relationships between database tables that are stored in the database file and are:

  • Automatically used as default join conditions in the Query and View Designers.
  • Displayed in the Database Designer as lines relating table indexes.
  • Displayed in the Data Environment Designer as default relationships for forms and reports.
  • Used to store referential integrity information.

Unlike temporary relationships created with the SET RELATION command, persistent relationships do not need to be re-created each time you use tables. However, because persistent relationships do not control the relationship between record pointers in tables, you will use both temporary SET RELATION relationships and persistent relationships when developing Visual FoxPro applications.

In Visual FoxPro, you use indexes to establish persistent relationships between tables in a database. You create a persistent relationship between indexes rather than between fields, which enables you to relate tables based on a simple or a complex index expression.

To prepare for relationships

  1. Determine which table has the primary records and which table has the related records.
  2. To the table with the primary record, add an integer field, and then add a primary index on the new field.
  3. To the table with the related records, add a field that matches the primary key in the other table, then add a regular index on that new field.
    Note Use the same expression for both indexes. For example, if you use a function in the expression on the primary key field, you need to use the same function in the expression on the foreign key field.

To create a persistent relationship between tables

  • In the Database Designer, choose the index name you want to relate, then drag it to the index name of the related table.

    -or-

  • Use the FOREIGN KEY clause with the CREATE TABLE or ALTER TABLE commands.

For example, the following command adds a one-to-many persistent relationship between the customer and orders table, based on the primary cust_id key in the customer table, and a new foreign key, cust_id, in the orders table:

ALTER TABLE orders;
   ADD FOREIGN KEY cust_id TAG ;
      cust_id REFERENCES customer

If you were to then examine the database schema in the Database Designer, you would see a line joining orders and customer, representing the new persistent relationship.

Indexes provide the basis for persistent relationships

The type of index tag or key determines the type of persistent relationship you can create. You must use a primary or candidate index tag or key for the "one" side of a one-to-many relationship; for the "many" side, you must use a regular index tag or key.

You can also edit the relationship.

To edit a relationship between tables

  • Double-click the relationship line between the tables, and then select the appropriate settings in the Edit Relationship dialog box.

To delete a persistent relationship between tables

  1. In the Database Designer, click the relationship line between the two tables.

    The width of the relationship line increases to indicate that you have selected the relationship.

  2. Press the DELETE key

    -or-

    Use the DROP FOREIGN KEY clause with the ALTER TABLE command.

For example, the following command deletes a persistent relationship between the customer and orders table, based on the primary cust_id key in the customer table, and a foreign key, cust_id, in the orders table:

ALTER TABLE orders DROP FOREIGN KEY TAG cust_id SAVE

See Also

Updating Table and Database Links | Building Referential Integrity | Developing Databases | Creating a Database | Database Designer | CREATE TABLE | ALTER TABLE | Working with a Database | Working with Tables


Building Referential Integrity

Establishing referential integrity involves building a set of rules to preserve the defined relationships between tables when you enter or delete records.

If you enforce referential integrity, Visual FoxPro prevents you from:

  • Adding records to a related table when there is no associated record in the primary table.
  • Changing values in a primary table that would result in orphan records in a related table.
  • Deleting records from a primary table when there are matching related records.

You can choose to write your own triggers and stored procedure code to enforce referential integrity. However, the Visual FoxPro Referential Integrity Builder enables you to determine the types of rules you want to enforce, the tables on which you want the rules enforced, and the system events that will cause Visual FoxPro to check referential integrity rules.

The RI Builder handles multiple levels of cascading for cascade deletes and updates and is recommended as a tool for building referential integrity.

To open the RI Builder

  1. Open the Database Designer.
  2. From the Database menu, choose Referential Integrity.

To use the RI Builder

  1. In the Database Designer, create a relationship between two tables, or double-click the relationship line to edit the relationship.
  2. In the Edit Relationship dialog box, choose the Referential Integrity button.
  3. In the Referential Integrity Builder, select the rules you want to enforce for updating, deleting, or inserting records.
  4. Choose OK, and then choose Yes to save your changes, generate RI code, and exit the builder.

When you use the RI Builder to build rules for your database, Visual FoxPro generates code to enforce relational integrity rules, then saves it as triggers that reference stored procedures. You can view this code by opening the stored procedure text editor for your database.

Caution When you make changes to the design of a database, such as modifying database tables or altering indexes used in a persistent relationship, you should rerun the RI Builder before you use the database. Rerunning the RI Builder revises the stored procedure code and table triggers used to enforce referential integrity so that they reflect the new design. If you don't rerun the RI Builder, you might have unexpected results, because the stored procedures and triggers are not rewritten to reflect your changes.

See Also

Creating Persistent Relationships | Creating Stored Procedures | Viewing and Setting Database Properties | Referential Integrity Builder | Developing Databases | Creating a Database | Working with a Database | Trigger Usage


Creating Stored Procedures

You can create stored procedures for the tables in your database. A stored procedure is Visual FoxPro code that is stored in the .dbc file. Stored procedures are code procedures that operate specifically on the data in the database. Stored procedures can improve performance because they are loaded into memory when a database is opened.

To create, modify, or remove a stored procedure

  • In the Project Manager, select a database and select Stored Procedures, then choose New, Modify, or Remove.

    -or-

  • In the Database Designer, choose Edit Stored Procedures from the Database menu.

    -or-

  • In the Command window, use the MODIFY PROCEDURE command.

Each of these options opens the Visual FoxPro text editor, allowing you to create, modify, or remove stored procedures in the current database.

You can use stored procedures for creating user-defined functions that you reference in field- and record-level validation rules. When you save a user-defined function as a stored procedure in your database, the code for the function is saved in the .dbc file and automatically moves with the database if you relocate the database. Using stored procedures also makes your application more portable because you don't have to manage user-defined function files separately from your database file.

See Also

Building Referential Integrity | Viewing and Setting Database Properties | Viewing and Modifying Database Architecture | Creating Persistent Relationships | Developing Databases | Working with a Database


Viewing and Setting Database Properties

Each Visual FoxPro database has Version and Comment properties. You can view and set these properties with the DBGETPROP( ) and DBSETPROP( ) functions.

For example, the following code displays the version number of the testdata database:

? DBGETPROP('testdata', 'database', 'version')

The value returned represents the Visual FoxPro .dbc version number, and is read-only. Using the same function, you can view the comment, if one exists for the database:

? DBGETPROP('testdata', 'database', 'comment')

Unlike the Version property, the Comment property can be set. Use the DBSETPROP( ) function to enter a description or other text that you want to store with the database.

To set the comment property on the current database

  • In the Database Designer, choose Properties from the Database menu and type a comment in the Comment box.

    -or-

  • Use the comment option of the DBSETPROP( ) function.

For example, the following code changes the comment for the testdata database:

? DBSETPROP('testdata', 'database', 'comment', ;
  'TestData is included with Visual FoxPro')

You can also use the DBGETPROP( ) and DBSETPROP( ) functions to view and set properties on other database objects such as connections and views.

See Also

Creating Stored Procedures | Viewing and Modifying Database Architecture | Extending Database Files | Building Referential Integrity | Developing Databases | Working with a Database


Managing a Database

After creating a database, you might want to add it to a project if it isn't already part of one. If your database is already part of a project, you can remove it from a project. Also, if you no longer need the database, you can delete it from the disk.

When you create a database with the CREATE DATABASE command, the database is not automatically a part of a project, even if the Project Manager is open. You can add the database to a project to make it easier to organize, view and manipulate database objects through the interface, as well as to simplify the process of building an application. You can add a database to a project only through the Project Manager.

To add a database to a project

  • In the Project Manager, select Databases and choose Add.

You can remove a database from a project only through the Project Manager.

To remove a database from a project

  • In the Project Manager, select the database and choose Remove, and then choose Remove again.

You can delete a database from disk using the Project Manager or the DELETE DATABASE command.

To delete a database

  • In the Project Manager, select the database and choose Remove, and then choose Delete.

    -or-

  • Use the DELETE DATABASE command.

For example, the following code deletes the sample database:

DELETE DATABASE sample

Always use one of the methods above to delete a database from disk. Using the Project Manager or the DELETE DATABASE command enables Visual FoxPro to remove backlinks to the database from the tables in a database. If you use another file manipulation utility to delete a database file, such as the Windows Explorer, these backlinks are not removed.

Note The DELETE DATABASE command does not delete the tables associated with a database from the disk; rather, the tables that were associated with the database become free tables. If you want to delete both a database and all its associated tables from disk, use the DELETETABLES clause with the DELETE DATABASE command.

See Also

Validating a Database | Referencing Multiple Databases | CREATE DATABASE | Project Manager | Viewing and Modifying Database Architecture | Developing Databases | Working with a Database


Referencing Multiple Databases

You can have many Visual FoxPro databases on your system to meet organizational needs in a multiuser environment. Multiple databases offer the following advantages:

  • Controlling user access to a subset of tables in the overall system.
  • Organizing the data to efficiently meet the information needs of various groups using the system.
  • Allowing exclusive use of a subset of tables for creating local and remote views at run time.

For example, you might have a sales database that maintains sales information used primarily by the sales force working with customers and another database that maintains inventory information used primarily by the buyers working with suppliers. At times the information needs of these groups will overlap. These databases can be opened at the same time and accessed at will but they contain completely different types of information.

Multiple databases can add flexibility to your system.

You can use multiple databases either by opening more than one database simultaneously or by referencing tables in a closed database. Once multiple databases are open, you can set the current database and select tables in it.

Opening More Than One Database

When a database is open, the tables and relationships between tables are controlled by the information stored in the open database. You can have more than one database open at a time. For example, you might use multiple open databases when you run multiple applications, each based on a different database. You might also want to open multiple databases to use information, such as custom controls, stored in a database that is separate from your application's database.

To open more than one database

  • In the Project Manager, select a database and choose Modify or Open.

    -or-

  • Use the OPEN DATABASE command.

Opening a new database does not close any databases you've opened previously. Other open databases remain open, and the newly opened database becomes the current database.

Setting the Current Database

When you open multiple databases, Visual FoxPro sets the most recently opened database as the current database. Any tables or other objects you create or add to the database become a part of the current database by default. Commands and functions that manipulate open databases, such as ADD TABLE and DBC( ), operate on the current database.

You can choose a different database as the current database through the interface or with the SET DATABASE command.

To set the current database

  • On the standard toolbar, select a database from the Databases box.

    -or-

  • Use the SET DATABASE command.

For example, the following code opens three databases, sets the first database as the current database, then uses the DBC( ) function to display the name of the current database:

OPEN DATABASE testdata
OPEN DATABASE tastrade
OPEN DATABASE sample
SET DATABASE TO testdata
? DBC( )
Tip Visual FoxPro might open one or more databases automatically when you execute a query or a form that requires the databases to be open. To be sure you are operating on the correct database, set the current database explicitly before issuing any commands that operate on the current database.

Selecting Tables in the Current Database

You can choose from a list of tables in the current database with the USE command.

To choose a table from the current database

  • Issue the USE command with a "?" symbol.

    The Use dialog box displays so that you can select a table to open.

For example, the following code opens the sales database and prompts you to select a table from the list of tables in the database.

OPEN DATABASE SALES
USE ?

If you want to select a table that is not associated with the open database, you can choose Other in the Use dialog box.

Closing a Database

You can close an open database from the Project Manager or with the CLOSE DATABASE command.

To close a database

  • From the Project Manager, select the database and choose Close.

    -or-

  • Use the CLOSE DATABASE command.

For example, the following code closes the testdata database:

SET DATABASE TO testdata
CLOSE DATABASE

Both options close the database automatically. You can also close databases and all other open objects with the ALL clause of the CLOSE command.

Issuing the CLOSE DATABASE command from the Command window does not close a database if the database was opened by:

  • The Project Manager when you expanded the outline to view the contents of a database.
  • A form that is running in its own data session.

In these circumstances, the database remains open until the Project Manager closes the database, or until the form using the database is closed.

Scope Resolution

Visual FoxPro uses the current database as the primary scope for named objects, such as tables. When a database is open, Visual FoxPro first searches within the open database for any objects you request, such as tables, views, connections, and so on. If the object is not in the database, Visual FoxPro looks in the default search path.

For example, if the customer table is associated with the sales database, Visual FoxPro would always find the customer table in the database when you issue the following commands:

OPEN DATABASE SALES
ADD TABLE F:\SOURCE\CUSTOMER.DBF
USE CUSTOMER

If you issue the following command, Visual FoxPro will first look in the current database for the products table.

USE PRODUCTS

If products is not in the current database, Visual FoxPro will look outside the database, using the default search path.

Note You can specify the full path for a table if you want to be able to access it inside or outside a database — for example, if you anticipate a change in the location of a table. However, you increase performance when you reference only the table name, because Visual FoxPro accesses database table names more quickly than names specified with a full path.

See Also

Managing a Database | Handling Database Errors | Validating a Database | Project Manager | OPEN DATABASE | SET DATABASE | USE | CLOSE | Developing Databases | Working with a Database


Handling Database Errors

Database errors, also called "engine errors," occur when run-time errors occur in record-level event code. For example, a database error occurs when a user attempts to store a null value to a field that doesn't allow null values.

When a database error occurs, the underlying database engine that detects the error typically posts an error message. However, the exact nature of the error message depends on what database is being accessed — for example, the error messages produced by a remote database server (such as Microsoft SQL Server) will probably be different from those produced if a database error occurs in a local Visual FoxPro table.

In addition, engine-level errors are sometimes very generic, because the database engine has no information about the context in which a record is being updated. As a consequence, error messages produced by a database engine are often less useful to the end user of a Visual FoxPro application.

To handle database errors in a more application-specific way, you can create triggers using the CREATE TRIGGER command. The trigger is called when a record update is attempted (delete, insert, or update). Your custom trigger code can then look for application-specific error conditions and report these.

If you handle database errors using triggers, you should turn buffering on. That way, when a record is updated your trigger is called, but the record is not immediately sent to the underlying database. You therefore avoid the possibility of producing two error messages: one from your trigger, and another from the underlying database engine.

To create custom error messages using triggers

  1. Inside a user-defined function or stored procedure, write your own message text.
  2. Enable buffering with the CURSORSETPROP( ) function to display your custom text. If buffering is off, the user will see both your custom text and the engine error message.

See Also

Referencing Multiple Databases | Managing a Database | Validating a Database | Developing Databases | Validating a Database | Working with a Database


Viewing and Modifying Database Architecture

When you create a database, Visual FoxPro creates and exclusively opens a .dbc (DataBase Container) file. The .dbc file stores all the information about the database, including the names of files and objects associated with it. The .dbc file does not physically contain any top-level objects such as tables or fields. Rather, Visual FoxPro stores file path pointers to the tables in the .dbc file.

To examine the architecture of your database, you can browse the database file, view the schema, browse the database objects, validate the database, and even extend the .dbc file.

Viewing the Database Schema

The database schema is a visual representation of the table structures and persistent relationships established in your database. The Database Designer window displays the schema of the open database.

To view the database schema

  • Use the MODIFY DATABASE command.

For example, the following code opens the testdata database and displays the schema in the Database Designer:

MODIFY DATABASE testdata

From the Database Designer, you can use the Database toolbar to create a new table, add an existing table to the database, remove a table from the database, or modify the structure of a table. You can also create connections and edit stored procedures.

Browsing the Database File

The database file contains a record for each table, view, index, index tag, persistent relationship, and connection associated with the database, as well as for each table field or view field having extended properties. It also includes a single record that contains all the stored procedures for the database.

For more information, see Table File Structure.

While the Database Designer provides a conceptual representation of the database schema, sometimes you might need to browse the contents of the database file itself. You can browse a closed database by issuing the USE command on the .dbc file. The following example opens a Browse window displaying the contents of the sales database in table form.

CLOSE DATABASE sales
USE sales.dbc EXCLUSIVE
BROWSE
Caution Don't use the BROWSE command to alter the database file unless you are knowledgeable about the structure of the .dbc file. If you make an error while attempting to change the .dbc file you can invalidate the database and potentially lose data.

See Also

Viewing and Setting Database Properties | Extending Database Files | Database Designer | MODIFY DATABASE | Validating a Database | Developing Databases | Working with a Database


Extending Database Files

Each .dbc file contains a Memo field named User that you can use to store your own information about each record in the database. You can also extend a .dbc file to add fields to accommodate your own needs as a developer. Fields must be added to the end of the structure. You must have exclusive access to a .dbc file to modify its structure.

To add a field to a .dbc file

  1. Open the .dbc file for exclusive use with the USE command.
  2. Use the MODIFY STRUCTURE command.

For example, the following code opens the Table Designer so you can add a field to the structure of Testdata.dbc:

USE TESTDATA.DBC EXCLUSIVE
MODIFY STRUCTURE

When you add a new field to a database file, begin the field name with "U" to designate it as a user-defined field. This designation prevents your field from conflicting with any future extensions to the .dbc file.

Caution Don't change any existing Visual FoxPro- defined fields in a .dbc file. Any changes you make to a .dbc file could affect the integrity of your database.

See Also

Viewing and Modifying Database Architecture | Validating a Database | Managing a Database | Developing Databases | Referencing Multiple Databases | Working with a Database


Validating a Database

Validating a database ensures that the rows of the database are storing accurate representations of the metadata in the database. You can check the integrity of the current database with the VALIDATE DATABASE command.

To validate a database

  • Use the VALIDATE DATABASE command.

For example, the following code uses and validates the .dbc file for the testdata database:

OPEN DATABASE testdata EXCLUSIVE
VALIDATE DATABASE

See Also

Extending Database Files | Managing a Database | Developing Databases | Referencing Multiple Databases | Viewing and Modifying Database Architecture | Working with a Database


Working with Tables

Building your database includes creating tables. When you designed your database, you specified the table fields and relationships required for your application. Now, as you create those tables, you make more detailed choices about the data types, captions, and potential default values for each field, the triggers for each table, and the table indexes you build to establish relationships between tables.

In This Section

Table Creation
Provides an overview on how to create tables and includes descriptions of interactive and programmatic table creation.
Field Creation
Describes the process of creating table fields and introduces explanations of how to name fields and restrict access to fields.
Enforcing Business Rules
Details how to enforce business rules by creating field-level and record-level rules, called validation rules.
Trigger Usage
Gives a description of triggers and how they are used and points to topics on creating, modifying, removing, and deleting triggers.
Modifying the Table Structure
Describes how to add, change, or delete field names, widths, data types, change default values, or rules, as well as add comments or captions.
Working with Multiple Tables
Explains how to open a data session window, and how to open and close a table in a work area.
Data Access Management Using CursorAdapters
Describes support for working with different data source types as native Visual FoxPro cursors using CursorAdapter objects.

Related Sections

Working with Data
Find out how to create effective applications with indexes, tables, and databases based on your data requirements.
Developing Databases
Use databases in Visual FoxPro to establish relationships between tables, enforce referential integrity, and manage local and remote data.
Working with Records
Store data in the table by adding new records. Through the interface or by using commands you can change and delete existing records.
Importing and Exporting Data
Information is copied between Visual FoxPro and other applications by importing to and exporting from Visual FoxPro.
Choosing Data Types
Lists the decision made when choosing a field's data type and provides explanations of how to choose a data type for a field, how to control entering null values per field, how to permit null values in all table fields, and how to add a comment to a field in a database table


Table Creation

Tables store your data in a row and column format, similar to a spreadsheet. Each row represents a record, and each column represents the fields in the records. You can create a table in a database, or just create a free table not associated with a database. If you put the table in a database, you can create long table and field names for database tables. You can also take advantage of data dictionary capabilities for database tables, default field values, and field- and record-level rules, as well as triggers.

Designing Database vs. Free Tables

A Visual FoxPro table, or .dbf file, can exist in one of two states: either as a database table (a table associated with a database) or as a free table that is not associated with any database. Tables associated with a database have several benefits over free tables. When a table is a part of a database you can create:

  • Long names for the table and for each field in the table.
  • Captions and comments for each table field.
  • Default values, input masks, and format for table fields.
  • Default control class for table fields.
  • Field-level and record-level rules.
  • Primary key indexes and table relationships to support referential integrity rules.
  • One trigger for each INSERT, UPDATE, or DELETE event.

Some features apply only to database tables. For information about associating tables with a database, see Developing Databases.

Database tables have properties that free tables do not have.

You can design and create a table interactively with the Table Designer, accessible through the Project Manager or the File menu, or you can create a table programmatically with the language.

Interactive Table Creation

When you need to build a new table, you can get assistance from the Table Wizard, or use the Table Designer and interactively set up a table with the fields you need.

Remember these main points when you set up a table:

  • Make the data type for a field match the kind of information you are going to store in it.
  • Make the field wide enough to accommodate the information it will display.
  • Set an appropriate number of decimal places for Numeric or Float fields.
  • Check NULL if you want the field to accept .NULL. as a value.

Programmatic Table Creation

You use the following commands to create and edit a table programmatically:

Commands for Creating and Editing Tables

ALTER TABLE | CLOSE TABLES
CREATE TABLE | DELETE FILE
REMOVE TABLE | RENAME TABLE
DROP TABLE |

See Also

Working with Tables | Creating a Database Table | Creating a Free Table | Naming a Table | Renaming a Table | Viewing Data in Tables | Choosing Data Types | Moving Around in a Table | Customizing a Browse Window | Customizing Tables


Creating a Database Table

You can create a new table in a database through the menu system, the Project Manager, or through the language. As you create the table, you can create long table and field names, default field values, field- and record-level rules, as well as triggers.

To create a new database table

  1. In the Project Manager, choose Tables under Databases.
  2. Choose New, and then choose New Table.
  3. In the Create dialog box, enter a name for the table and choose Save.
  4. On the Fields tab of the Table Designer, type the name for the first field in the Name field.
  5. In the Type field, select a field type from the list.
  6. In the Width column, set the width of the column in characters.
  7. If Type is Numeric or Float, set the number of decimal places to display in the Decimal box.
  8. If you want to add an index to the field, select a sort order in the Index column.
  9. If you want the field to accept the input of null values, select NULL. You can choose to begin entering records immediately, or open the table later when ready to enter records.

    -or-

  • Use the CREATE TABLE command with a database open.

For example, the following code creates the table smalltbl with one column, called name:

OPEN DATABASE Sales
CREATE TABLE smalltbl (name c(50))

The new table is automatically associated with the database that is open at the time you create it. This association is defined by a backlink stored in the table's header record.

To add records to a table

  1. In the Project Manager, select the name of the table.
  2. Choose Browse.
  3. From the View menu, choose Append Mode.
  4. Enter new record changes in the Browse window.

    If you prefer to view each field on a separate line, switch to Edit mode by choosing Edit from the View menu.

See Also

Table Creation | Creating a Free Table | Working with Tables | Naming a Table | Renaming a Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Creating a Free Table

A free table is a table that is not associated with a database. You might want to create a free table, for example, to store lookup information that many databases share.

To create a new free table

  1. In the Project Manager, choose Free Tables under Databases.
  2. Choose New, and then choose New Table.
  3. In the Create dialog box, enter a name for the table and choose Save.
  4. On the Fields tab of the Table Designer, type the name for the first field in the Name field.
  5. In the Type field, select a field type from the list.
  6. In the Width column, set the width of the column in characters.
  7. If Type is Numeric or Float, set the number of decimal places to display in the Decimal box.
  8. If you want to add an index to the field, select a sort order in the Index column.
  9. If you want the field to accept the input of null values, select NULL. You can choose to begin entering records immediately, or open the table later when ready to enter records.

    -or-

  • Use the FREE keyword with the CREATE TABLE command.

For example, the following code creates the free table smalltbl with one column, called name:

CLOSE DATABASES
CREATE TABLE smalltbl FREE (name c(50))

If no database is open at the time you create the table, you do not need to use the keyword FREE.

See Also

Table Creation | Creating a Database Table | Naming a Table | Working with Tables | Renaming a Table | Deleting a Database Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Naming a Table

When you issue the CREATE TABLE command, you specify the file name for the .dbf file Visual FoxPro creates to store your new table. The file name is the default table name for both database and free tables. Table names can consist of letters, digits, or underscores and must begin with a letter or underscore.

If your table is in a database, you can also specify a long table name. Long table names can contain up to 128 characters and can be used in place of short file names to identify the table in the database. Visual FoxPro displays long table names, if you have defined them, whenever the table appears in the interface, such as in the Project Manager, the Database Designer, the Query Designer, and the View Designer, as well as in the title bar of a Browse window.

To give a database table a long name

  • In the Table Designer, enter a long name in the Table Name box.

    -or-

  • Use the NAME clause of the CREATE TABLE command.

For example, the following code creates the table vendintl and gives the table a more understandable long name of vendors_international:

CREATE TABLE vendintl NAME vendors_international (company C(40))

You can also use the Table Designer to rename tables or add long names to tables that were created without long names. For example, when you add a free table to a database, you can use the Table Designer to add a long table name. Long names can contain letters, digits, or underscores, and must begin with a letter or underscore. You cannot use spaces in long table names.

See Also

Table Creation | Creating a Free Table | Renaming a Table | Working with Tables | Deleting a Database Table | Deleting a Free Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Renaming a Table

You can rename database tables through the interface because you are changing the long name. If you remove the table from the database, the file name for the table retains the original name. Free tables do not have a long name and can only be renamed using the language.

To rename a table in a database

  1. In the Database Designer, select the table to rename.
  2. From the Database menu, choose Modify.
  3. In the Table Designer, type a new name for the table in the Table Name box on the Table tab.

To rename a free table

  • Use the RENAME command.
    Caution If you use the RENAME command on tables associated with a database, the command does not update the backlink to the database and can cause table access errors.

See Also

Table Creation | Naming a Table | Deleting a Database Table | Working with Tables | Deleting a Free Table | Duplicating a Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Customizing Tables

You can customize your tables so that only certain records are displayed by setting a filter on the table. You can also restrict access to certain fields in a table by setting a field filter, which allows you to select which fields to display.

Filtering a Table

If you want to see only records of a certain type, you can set a filter to limit the records shown in the Browse window. Filtering is useful when, for example, you want to restrict the browse to show only sales above a certain amount, or employees in a range of hire dates.

To set a filter, use the Work Area Properties dialog box, available through the Properties command on the Table menu.

To set a filter on a table

  1. Browse the table you want to filter.
  2. From the Table menu, choose Properties.
  3. In the Work Area Properties dialog box, enter your filter expression directly in the Data filter box.

    -or-

  • Choose the dialog button under Data Filter, and in the Expression Builder, create an expression to select the records you want to see and choose OK.

When you browse the table, you see only records that are selected by the filter expression.

For example, using the Customers table from the Visual FoxPro ...\Samples\Data directory, you could focus on customers residing in the United States by entering the following expression in the Data Filter box:

Customer.Country = "USA"

See Also

Table Creation | Naming a Table | Deleting a Database Table | Working with Tables | Deleting a Free Table | Duplicating a Table | Viewing Data in Tables | Customizing a Browse Window | Moving Around in a Table | Renaming a Table


Moving Around in a Table

Use the scroll bars to move through the table and display different fields and records. You can also use the arrow keys and the TAB key to move around.

To see different records

  1. From the Table menu, choose Go to Record.
  2. In the submenu, choose Top, Bottom, Next, Previous, or Record #.
  3. If you choose Record #, enter the record number you want to see in the Go to Record dialog box, and choose Go To.

See Also

Table Creation | Working with Tables | Naming a Table | Deleting a Database Table | Deleting a Free Table | Duplicating a Table | Viewing Data in Tables | Renaming a Table | Customizing a Browse Window | Customizing Tables


Viewing Data in Tables

The quickest way to see the contents of a table is to look at it in a Browse window. The Browse window displays the contents of the table as a series of rows and columns you can scroll through. To familiarize yourself with some typical tables, you can browse the sample tables in the Visual FoxPro ...\Samples\Data directory.

To browse a table

  1. From the File menu, choose Open and select the name of the table you want to view.
  2. From the View menu, choose Browse.

You can also select the name of a table in the Project Manager, and choose the Browse button.

For example, open the Customer table in the Visual FoxPro ...\Samples\Data directory.

Table in a Browse window

For easier data entry, you can place a Browse window into Edit mode. In Edit mode, the column names are displayed on the left side of the window.

To change the Browse window to Edit mode

  • From the View menu, choose Edit.

    Table in Edit mode

In either mode, you can scroll through records, search for specific records, and make changes directly to the contents of the table.

Also, from the Project Manager, you can browse the contents of the tables in your project.

To browse a table from the Project Manager

  1. Select the Data tab.
  2. Select a table and choose Browse.

You can reuse your work from one project by sharing files with another project. The files are not duplicated, because the project stores only a reference to the file. Files can be associated with different projects simultaneously.

To share files between projects

  1. In Visual FoxPro, open the two projects that will share the file.
  2. In the Project Manager containing the file, select the file.
  3. Drag the file to the container for the other project.

See Also

Table Creation | Naming a Table | Deleting a Database Table | Working with Tables | Deleting a Free Table | Duplicating a Table | Renaming a Table | Customizing a Browse Window | Customizing Tables


Customizing a Browse Window

You can customize the Browse window to fit your needs by using the following procedures:

  • Rearranging columns
  • Changing column widths
  • Fitting columns to data automatically
  • Turning grid lines on and off
  • Splitting a Browse window
  • Locking columns

Rearranging Columns

You can rearrange the columns of the Browse window into the order you want. This does not affect the actual structure of the table.

To rearrange the columns in a Browse window

  • Drag a column heading to a new location.

    -or-

  • From the Table menu, choose Move Field, and use the LEFT ARROW or RIGHT ARROW keys to move the column. Press ENTER when you are done.

Changing Column Widths

You can change the width of a column in a Browse window. This resizing does not affect the field length or the structure of the table.

If you want to change the actual length of the fields, modify the structure of the table using the Table Designer.

To change the width of a column

  • Position the pointer in the column heading between two field names, and drag the pointer to resize the column.

    -or-

  • Select a field, and from the Table menu, choose Size Field, and use the LEFT ARROW or RIGHT ARROW keys to resize the column. Press ENTER when done.

Fitting Columns to Data Automatically

You can resize columns to automatically fit the data that they contain.

To resize one column to data

  • Double-click the area, between the column headers, to the immediate right of the column you want to resize.

To resize all columns to data

  • Double-click the square immediately preceding the first column header in the upper and leftmost corner of the grid.

Turning Grid Lines On and Off

You can turn off the grid lines in a Browse window.

To turn grid lines on or off

  • From the View menu, choose Gridlines.

Splitting a Browse Window

You might find it useful to split the Browse window so that you can look at two different areas in the table, or look at the same records in Browse and Edit modes simultaneously.

To split a Browse window

  1. Place the pointer on the split bar at the bottom left corner of the view.
  2. Drag the split bar to the right to divide the Browse window into two panes.

    -or-

  3. From the Table menu, choose Resize Partitions.
  4. Press the RIGHT ARROW key to move the split bar.
  5. Press ENTER.

To resize the panes of a split Browse window

  1. Place the pointer on the split bar.
  2. Drag the split bar to the right or left to change the relative size of the panes.

    -or-

  3. From the Table menu, choose Resize Partitions.
  4. Press the LEFT ARROW or RIGHT ARROW key to move the split bar.
  5. Press ENTER.

By default, the two panes of the Browse window are linked; that is, as you select different records in one pane, the change is reflected in the other. If you want to detach the two panes so that they function independently (that is, so that scrolling one pane does not affect the other), clear the Link Partitions command on the Table menu.

Locking Columns

You can lock columns in a Browse window to keep certain columns visible while you scroll back and forth across the grid. Tabbing to the right does not cause locked columns to scroll out of the Grid/Browse window.

To lock all columns to the left of a specific column

  1. Select the rightmost column you want to lock.
  2. Right-click the area, between the column headers, immediately following the rightmost column you want to lock.

A column separator line, which appears 1 pixel wider than the line separating the other columns, indicates the area where the locked columns end and the normal columns begin.

To unlock all columns

  • Right-click any area between the headers in a grid where one or more columns are locked.

Right-clicking any area between the headers unlocks all columns.

When any of the locked columns scroll out of the Grid window to the left, they remain out of view and do not become visible again until locking is removed.

For example, suppose a grid contains five columns, and the data source has ten columns. When you scroll two columns to the right, the first and second columns scroll out of the grid to the left. When you right-click the area between the first and second visible columns, which are the third and fourth columns in reality, the first visible, or third absolute, column becomes locked. The first and second, currently invisible, absolute columns are also locked. However, you cannot scroll back to the left to view all of the locked columns. This functionality is useful if you want to lock the columns in the middle of the grid and do not want to display the preceding or following columns.

The Column.SetFocus method does not work if a column is locked and not visible in the grid window, for example, scrolled off to the left side.

See Also

Table Creation | Working with Tables | Naming a Table | Deleting a Database Table | Deleting a Free Table | Duplicating a Table | Renaming a Table | Table Designer | Browse Window | Customizing Tables


Deleting a Database Table

If a table is associated with a database, you can delete the table as a by-product of removing the table from its database. Deleting a table is different from removing a table from a database, however. If you just want to remove a table from a database but do not want to physically delete the table from disk, see Removing a Table from a Database in Developing Databases.

To delete a database table from disk

  • In the Project Manager, select the table name, choose Remove, and then choose Delete.

    -or-

  • From the Database Designer, select the table, choose Remove from the Database menu, and then choose Delete.

    -or-

  • To delete the table plus all primary indexes, default values, and validation rules associated with the table, use the DROP TABLE command.

    -or-

  • To delete just the table file (.dbf), use the ERASE command.
    Caution If you use the ERASE command on tables associated with a database, the command does not update the backlink to the database and can cause table access errors.

The following code opens the database testdata and deletes the table orditems and its indexes, default values, and validation rules:

OPEN DATABASE testdata
DROP TABLE orditems

If you delete a table using the DELETE clause of the REMOVE TABLE command, you also remove the associated .fpt memo file and .cdx structural index file.

See Also

Table Creation | Renaming a Table | Deleting a Free Table | Working with Tables | Duplicating a Table | Naming a Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Deleting a Free Table

If a table is not associated with a database, you can delete the table file through the Project Manager or with the DELETE FILE command.

To delete a free table

  • In the Project Manager, select the free table, choose Remove, and then choose Delete.

    -or-

  • Use the DELETE FILE command.

For example, if sample is the current table, the following code closes the table and deletes the file from disk:

USE
DELETE FILE sample.dbf

The file you want to delete cannot be open when DELETE FILE is issued. If you delete a table that has other associated files, such as a memo file (.fpt) or index files (.cdx or .idx), be sure to delete those files as well. For example, if the file sample.dbf also has an associated memo file, you could delete both files with the following commands:

USE
DELETE FILE sample.dbf
DELETE FILE sample.fpt

See Also

Table Creation | Deleting a Database Table | Duplicating a Table | Working with Tables | Renaming a Table | Copying and Editing Table Structure | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Duplicating a Table

You can make a copy of a table's structure, its stored procedures, trigger expressions, and default field values by using the language. There is no menu option to perform the same function. This procedure does not copy the contents of the table.

To duplicate a table

  1. Open the original table.
  2. Use the COPY STRUCTURE command to make a copy of the original table.
  3. Open the empty table created with the COPY STRUCTURE command.
  4. Use the APPEND FROM command to copy the data from the original table.

See Also

Table Creation | Deleting a Free Table | Copying and Editing Table Structure | Working with Tables | Deleting a Database Table | Saving a Table as HTML | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Copying and Editing Table Structure

To modify the structure of an existing table, you can use the Table Designer or ALTER TABLE. Alternatively, you can create a new table based on the structure of an existing table, then modify the structure of the new table.

To copy and edit a table structure

  1. Open the original table.
  2. Use the COPY STRUCTURE EXTENDED command to produce a new table containing the structural information of the old table.
  3. Edit the new table containing the structural information to alter the structure of any new table created from that information.
  4. Create a new table using the CREATE FROM command.

    The new table is empty.

  5. Use APPEND FROM or one of the data copying commands to fill the table if necessary.

See Also

Table Creation | Duplicating a Table | Saving a Table as HTML | Working with Tables | Field Creation | Deleting a Free Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Saving a Table as HTML

You can use the Save As HTML option on the File menu when you are browsing a table to save the contents of a table as an HTML (Hypertext Markup Language) file.

To save a table as HTML

  1. Open the table.
  2. Browse the table by issuing the BROWSE command in the Command window or by choosing Browse from the View menu.
  3. Choose Save As HTML on the File menu.
  4. Enter the name of the HTML file to create and choose Save.

See Also

Table Creation | Copying and Editing Table Structure | Field Creation | Working with Tables | Duplicating a Table | Deleting a Free Table | Viewing Data in Tables | Customizing a Browse Window | Customizing Tables


Field Creation

When you create table fields, you determine how data is identified and stored in the table by specifying a field name, a data type, and a field width. You also can control what data is allowed into the field by specifying whether the field allows null values, has a default value, or must meet validation rules. Setting the display properties, you can specify the type of form control created when the field is added onto a form, the format for the contents of the fields, or the caption that labels the content of field.

Note Tables in Visual FoxPro can contain up to 255 fields. If one or more fields can contain null values, the maximum number of fields the table can contain is reduced by one, from 255 to 254.

See Also

Table Creation | Naming Fields | Working with Tables | Creating a Database Table | Choosing Data Types | Restricting Access to Fields


Naming Fields

You specify field names as you build a new table. These field names can be 10 characters long for free tables or 128 characters long for database tables. If you remove a table from a database, the table's long field names are truncated to 10 characters.

To name a table field

  • In the Table Designer, enter a field name in the Name box.

    -or-

  • Use the CREATE TABLE command or ALTER TABLE command.

For example, to create and open the table customer with three fields, cust_id, company, and contact, you could issue the following command:

CREATE TABLE customer (cust_id C(6), company C(40), contact C(30))

In the previous example, the C(6) signifies a field with Character data and a field width of 6. Choosing data types for your table fields is discussed later in this section.

Using the ALTER TABLE command, you add fields, company, and contact to an existing table customer:

ALTER TABLE customer ;
   ADD COLUMN (company C(40), contact C(30))

Using Short Field Names

When you create a table in a database, Visual FoxPro stores the long name for the table's fields in a record of the .dbc file. The first 10 characters of the long name are also stored in the .dbf file as the field name.

If the first 10 characters of the long field name are not unique to the table, Visual FoxPro generates a name that is the first n characters of the long name with the sequential number value appended to the end so that the field name is 10 characters. For example, these long field names are converted to the following 10-character names:

Long Name | Short Name
customer_contact_name | customer_c
customer_contact_address | customer_2
customer_contact_city | customer_3
... | ...
customer_contact_fax | customer11

While a table is associated with a database, you must use the long field names to refer to table fields. It is not possible to use the 10-character field names to refer to fields of a table in a database. If you remove a table from its database, the long names for the fields are lost and you must use the 10-character field names (stored in the .dbf) as the field names.

You can use long field names composed of characters, not numbers, in your index files. However, if you create an index using long field names and then remove the referenced table from the database, your index will not work. In this case, you can either shorten the names in the index and then rebuild the index; or delete the index and re-create it, using short field names. For information on deleting an index, see Deleting an Index.

The rules for creating long field names are the same as those for creating any Visual FoxPro identifier, except that the names can contain up to 128 characters.

For more information about naming Visual FoxPro identifiers, see Creating Visual FoxPro Names.

See Also

Field Creation | Choosing Data Types | Working with Tables | Table Designer | Creating Default Field Values | Restricting Access to Fields


Restricting Access to Fields

If you want to keep certain fields from displaying when tables are browsed or used in a form, you can set a field filter to restrict access to those fields. You select the fields you want to display, which leaves the remaining fields inaccessible.

To set a field filter

  1. From the Table menu, choose Properties.
  2. In the Work Area Properties dialog box, under Allow access to, select Only fields specified by 'field filter' and choose Field Filter.
  3. In the Field Picker dialog box, add the fields you want to the Selected fields column and choose OK.

When you browse the table, only fields you selected in the field filter are displayed.

See Also

Field Creation | Choosing Data Types | Working with Tables | Table Designer | Creating Default Field Values | Naming Fields


Choosing Data Types

When you create a field in a table, you can choose the type of data that the field stores. When you choose the data type for a field, you need to consider the following:

  • What kind of values the field allows. For example, you cannot store text in a Numeric field.
  • How much storage space Visual FoxPro needs to set aside for the values stored in that field. For example, any value with the Currency data type uses 8 bytes of storage.
  • What types of operations can be performed on the values in that field. For example, Visual FoxPro can calculate the sum of Numeric or Currency values but not the sum of Character or General values.
  • Whether Visual FoxPro can index or sort values in the field. You cannot sort or create an index for Memo or General fields.
    Tip For phone numbers, part numbers, and other numbers you do not intend to use for mathematical calculations, you should select the Character data type, not the Numeric data type.

Choosing a Data Type

Each field in your table holds a particular type of data. You can set the following data types for a field in a table.

Visual FoxPro Field Data Types

Character | Character (Binary) | Currency
Date | DateTime | Double
Float | General | Integer
Integer (Autoinc) | Logical | Memo
Memo (Binary) | Numeric |

For more information about these data types, see Data and Field Types Overview.

To specify a data type for a field

  1. In the Table Designer, create or choose a field in the Fields tab.
  2. From the Type list, select a data type for the field.

For more information about the Table Designer, see Fields Tab, Table Designer.

You can also programmatically specify a data type for a field by using the CREATE TABLE command. For example, to create and open the table products with three fields, prod_id, prod_name, and unit_price, you could issue the following command:

CREATE TABLE products (prod_id C(6), prod_name C(40), unit_price Y)

In the previous example, the 'Y' after the unit_price field name specifies a Currency data type.

Adding a Regular Index Quickly

When you add a field, you can quickly define a regular index on the field by specifying ascending or descending in the Index column of the Table Designer. The index you create is automatically added to the Index tab and uses the field as the expression. To modify the index, you can switch to the Index tab to change the index name, type, or to add a filter.

Specifying Null Values

When you build a new table, you can specify whether one or more table fields accept null (.NULL.) values. When you use a null value, you are indicating the fact that information usually stored in the field or record is not currently available.

For example, an employee's health benefits or tax status might be unknown at the time a record is populated. Instead of storing a zero or a blank, which could be interpreted to have meaning, you could store a null value in the field until more information becomes available.

To specify whether null values can be entered in a field

  • In the Fields tab of the Table Designer, select or clear the check box in the NULL column for the field.

When the check box in the NULL column is selected, you can enter null values in the field.

You can also programmatically indicate that the field accepts null values by specifying the NULL and NOT NULL clauses when using the CREATE TABLE command. For example, the following command creates and opens a table that does not permit null values for the cust_id and company fields but does permit null values in the contact field:

CREATE TABLE customer (cust_id C(6) NOT NULL, ;
   company C(40) NOT NULL, contact C(30) NULL)

You can also programmatically control whether null values are permitted in table fields by using the SET NULL command.

To permit null values in all fields of the table

  • In the Fields tab of the Table Designer, select the check box in the NULL column for every field.

You can also programmatically allow null values in all fields by using the SET NULL command before using the CREATE TABLE command.

When you issue SET NULL ON, Visual FoxPro automatically selects the check box in the NULL column for each table field when you add fields in the Table Designer. If you call SET NULL before CREATE TABLE, you do not have to specify the NULL or NOT NULL clauses. For example, the following code creates a table that allows null values in every table field:

SET NULL ON
CREATE TABLE test (field1 C(6), field2 C(40), field3 Y)
Note The presence of null values affects the behavior of tables and indexes. For example, if you use APPEND FROM or INSERT INTO to copy records from a table containing null values to a table that does not permit null values, appended fields containing null values are treated as blank, empty, or zero in the current table.

Adding Comments to Fields

After you create a table in an open database, you can add a description of each table field to make your tables easier to understand and update. Visual FoxPro displays a field's comment text in the Project Manager when you select the field in the list of fields for the table.

To add a comment to a field in a database table

  1. In the Table Designer, select the field.
  2. In the Field Comment box, enter the text for your comment.
  3. Choose OK.

    -or-

  • Use the DBSETPROP( ) function.

For example, you might want to clarify what is stored in the unit_price field in your orditems table by entering "Current retail price per unit" as comment text for the field:

?DBSETPROP('orditems.price', 'field', 'comment', ;
          'Current retail price per unit')

See Also

Naming Fields | Creating Default Field Values | Working with Tables | Table Designer | CREATE TABLE | Data and Field Types | Handling Null Values | Developing Databases | Restricting Access to Fields


Creating Default Field Values

If you want Visual FoxPro to fill the contents of a field automatically as you add a new record, you can create a default value for the field. The default value is applied whether you enter data through a form, in a Browse window, a view, or programmatically, and remains in the field until you enter a new value.

You create default values either through the Table Designer or through the language. You can specify default values for any data type except General.

To assign a default value to a database table field

  1. In the Database Designer, select the table.
  2. From the Database menu, choose Modify.
  3. In the Table Designer, select the field you want to assign the default value to.
  4. In the Default value box, type the field value you want displayed in all new records (enclose character fields in quotes).
  5. Choose OK.

    -or-

  • Use the DEFAULT clause of the CREATE TABLE command.

For example, you might want your application to limit the amount of merchandise a new customer can order until you have had time to complete a credit check and determine the amount of credit you are willing to extend to that customer. The following example creates a maxordamt field with a default value of 1000:

CREATE TABLE customer (cust_id C(6), company C(40), contact C(30), ;
                maxordamt Y(4) DEFAULT 1000)

If your customer table already included the maxordamt column, you could add a default value for the column with this command:

ALTER TABLE customer ALTER COLUMN maxordamt SET DEFAULT 1000

Using Default Values to Speed Data Entry

You can use default values to speed data entry for your application's users, enabling them to skip a field unless they want to enter a different value. For example, if your business primarily deals with domestic customers, you may want the country/region field in the customer table in a database to be filled with the name of your country/region automatically. If you are entering a customer record for an international customer, you can overwrite the name of your country/region with theirs.

Tip If one of your application's business rules requires that a field contain an entry, providing a default value helps to ensure that a particular field-level or record-level rule will not be violated.

If you remove or delete a table from a database, all default values bound to that table are deleted from the database. Stored procedures referenced by the removed or deleted default value remain even after the default value has been removed.

When you do not specify a default value, a blank value (as defined for each data type) is inserted unless SET NULL is on. This preserves backward compatibility with any existing FoxPro code you might have.

You can use .NULL. as a default value if you want the field to use null values. Whether SET NULL is on or off, if you use .NULL. as a default value, Visual FoxPro inserts .NULL. for all commands except APPEND BLANK.

Allowable Default Values

You can specify default values that are either scalar values (such as "a number") or expressions that evaluate to a scalar quantity. You can also specify any valid FoxPro expression that returns a value consistent with the data type for the field.

Visual FoxPro evaluates expressions for data type when the table structure is closed. If the data type does not match the associated field type, Visual FoxPro generates an error. If the expression is a user-defined function (UDF) or contains a UDF, it is not evaluated.

When you create the default value through the language, the CREATE TABLE or ALTER TABLE commands will generate an error if the data types do not match. If the expression is a UDF or contains a UDF, it is not evaluated at CREATE time and no error is returned.

When Default Values Are Applied

Default values are evaluated (if necessary) and placed in the appropriate fields when the APPEND, APPEND BLANK, or INSERT commands are issued.

When you assign values with the APPEND FROM or INSERT - SQL commands, Visual FoxPro assigns default values to any fields not explicitly assigned. The APPEND FROM and INSERT - SQL commands also respect default values. However, when either of these commands is issued, defaults will not overwrite existing values in fields. If appended or inserted fields contain values, the existing value is retained as the record is appended or inserted and the default value is not applied.

Using Default Values to Auto-Populate NOT NULL Fields

Default values are particularly useful to automatically populate fields that do not allow null values. When you add a new record, default values are applied first, then each field is checked in definition order for missing information. This ensures fields designated as NOT NULL have the opportunity to be populated with default values before the NOT NULL constraint is applied.

Specifying an Input Mask

By specifying an input mask, you define the punctuation, spacing, and other format attributes of values as they are entered into the field. The values are then stored in a uniform manner that can reduce data entry errors and make processing more efficient. For example, adding a mask to a numeric field storing telephone numbers helps the user to quickly fill out the field because the punctuation and spaces are already provided by the mask.

To provide an input mask

  • In the Table Designer, enter the mask in the Input mask box in the Display area.

    -or-

  • Use the DBSETPROP( ) function to set the InputMask property.

    For example, the following code specifies an input mask for a date:

    DBSetProp("orders.postalcode","field","InputMask", "99999-9999")

See Also

Choosing Data Types | Controlling Display of a Field | Working with Tables | Enforcing Business Rules | Table Designer | CREATE TABLE | Restricting Access to Fields


Controlling Display of a Field

Additional properties for fields allow you to control how a field and its values appear on forms, Browse windows, and reports. You can specify a display format, a default field caption, and a default class and class library.

Defining a Format

A format provides an output mask that determines the manner in which the value of a field is displayed in a form, Browse window, or report. For example:

To provide a format

  • In the Table Designer, enter the mask in the Format box in the Display area.

    -or-

  • Use the DBSETPROP( ) function to set the Format property.

For example, the following code specifies a display format for a postal code:

DBSetProp("orders.postalcode","field","Format","@R 99999-9999")

Creating Captions for Fields

You can create a caption for each field in a database table. Visual FoxPro displays a field's caption text as the column header in a Browse window and as the default header name in a form grid. To specify an expression for a field caption, include an equal sign (=) preceding the caption string. Expressions cannot exceed 254 characters. If the expression exceeds 254 characters, the caption defaults to the field name.

To add a caption to a field in a database table

  • In the Table Designer, enter the text for your caption in the Caption box in the Display area.

    -or-

  1. Select the table in the Database Designer and choose Modify.
  2. Select the field you want to assign the caption to.
  3. In the Caption box, type the caption you want displayed for the field.
  4. Choose OK.

    -or-

  • Use the DBSETPROP( ) function.

For example, you might want to create a caption for the fax field in your supplier table by entering "Supplier_Fax" as the caption for the field:

?DBSETPROP('supplier.fax', 'field', 'caption', 'Supplier_Fax')

For more information on using DBSETPROP( ) to set properties on database table fields, see Developing Databases.

Setting a Default Class

To save time later when you are creating forms, you can set a default class for a field. Once set, each time you add the field to a form, the control on the form uses the class you specify as the default. For example, character fields automatically appear as text box controls when you add them to a form. If you want to automatically create a combo box control instead when you use the field in a form, you can set that class as the default for this field. You can also use class libraries that you have created.

To set a default class

  • In the Table Designer, choose a class and library in the Default Class box and the Default Library box.

If you find you are often changing the library and class for your fields, you can map the fields' data types to a library and class in the Options dialog box. For more information about mapping your field data types to classes, see Customizing the Visual FoxPro Environment. For more information about creating classes, see Object-Oriented Programming.

See Also

Creating Default Field Values | Enforcing Business Rules | Working with Tables | Naming Fields | Creating Default Field Values | Table Designer, | DBSETPROP( ) | Restricting Access to Fields


Adding Fields

You can add a new field to a table with the Table Designer or with the language.

To add a field to a table

  1. In the Table Designer, choose Insert.
  2. In the Name column, type the name of the new field.
  3. In the Type column, select a data type for the field.
  4. In the Width column, set or enter a width for the field.
  5. If the field has a type of Numeric or Float, set the number of decimal places in the Decimal column.
  6. If you want the table to accept null values, select the NULL column.
  7. Choose OK.
  8. Choose Yes to make the table structure changes.

    -or-

  • Use the ADD COLUMN clause of the ALTER TABLE command.

For example, the following command adds a field called fax to the customer table and allows the field to have null values:

ALTER TABLE customer ADD COLUMN fax c(20) NULL

See Also

Modifying the Table Structure | Deleting Fields | Working with Tables | Renaming Fields | Setting or Changing Field-Level or Table Rules


Editing Fields

You can edit information in fields in various ways, depending on the type of field.

To change the current information in a Character, Numeric, Logical, Date, or DateTime field

  • Place the cursor in the field and edit the information.

    -or-

  • Select the entire field and begin typing the new information.

To edit the information in a Memo field

  • Double-click the field in the Browse window.

    -or-

  • Press CTRL+PGDN. An editing window opens with the contents of the memo field.

A General field contains an embedded or linked OLE object.

To edit the information in a General field

  • Double-click the field in the Browse window, and edit the document directly (as with a Microsoft Word document or a Microsoft Excel worksheet).

    or-

  • Double-click the object to open the parent application (as with a Microsoft Paint object).

See Also

Working with Tables | General | Memo Field Type | Renaming Fields | Deleting Fields | Adding Fields


Deleting Fields

You can delete an existing field from a table with the Table Designer or with the language.

To delete a field from a table

  • In the Table Designer, select the field and choose Delete.

    -or-

  • Use the DROP COLUMN clause of the ALTER TABLE command.

For example, the following command drops the field called fax from the customer table:

ALTER TABLE customer DROP COLUMN fax

Removing a field from a table also removes the field's default value setting, rule definitions, and caption. If index key or trigger expressions reference the field, the expressions become invalid when the field is removed. The invalid index key or trigger expression will not generate an error until run time.

See Also

Adding Fields | Renaming Fields | Working with Tables | Setting or Changing Field-Level or Table Rules | Setting or Changing Default Values | Modifying the Table Structure


Renaming Fields

You can rename existing table fields in two ways.

To rename a table field

  • In the Table Designer, enter a new field name in the Name box for the existing field.

    -or-

  • Use the RENAME COLUMN clause of the ALTER TABLE command.

For example, to rename the column company in the customer table, you could issue the following command:

ALTER TABLE customer RENAME COLUMN company TO company_long_new_name

In the previous example, the new field name takes advantage of the ability to create long field names in database tables.

See Also

Deleting Fields | Setting or Changing Field-Level or Table Rules | Working with Tables | Setting or Changing Default Values | Modifying the Table Structure


Setting or Changing Default Values

You can set or change default values for table fields after you have built your table.

To change an existing default value

  • In the Table Designer, enter the new value in the Default value box of the Fields tab.

    -or-

  • Use the ALTER TABLE command.

To view the current default value for a field, use the DBGETPROP( ) function; these values are read-only for tables and can only be changed using the ALTER TABLE command.

See Also

Setting or Changing Field-Level or Table Rules | Renaming Fields | Working with Tables | Deleting Fields | Modifying the Table Structure


Setting Autoincrementing Field Values

You can turn on autoincrementing for fields of Integer type in a database container (DBC) or free table by using the Table Designer or the AUTOINC clause in the CREATE TABLE - SQL and ALTER TABLE - SQL commands. For more information about using the AUTOINC option, see CREATE TABLE - SQL Command and ALTER TABLE - SQL Command.

To enable autoincrementing for a new field using the Table Designer

  1. Create a new table, or open an existing table.
  2. In the Table Designer, click the Fields tab.
  3. Create the field for which you want to enable autoincrementing.
  4. In the Type drop-down list for the field, select Integer (AutoInc).
  5. In the AutoIncrement group box, choose a start value for Next Value and an increment value for Step.
  6. Create another field, if desired, or click OK to finish.

To enable autoincrementing for an existing field using the Table Designer

  1. Open an existing table.
  2. In the Table Designer, click the Fields tab.
  3. Select the field for which you want to enable autoincrementing.
  4. In the Type drop-down list for the field, select Integer (AutoInc).
  5. In the AutoIncrement group box, choose a start value for Next Value and an increment value for Step.
  6. Select another field for setting autoincrementing, if desired, or click OK to finish.

See Also

Field Creation | Autoincrementing Field Values in Tables | Fields Tab, Table Designer | Adding Fields | Editing Fields


Enforcing Business Rules

You can enforce business rules for data entry by creating field-level and record-level rules, called validation rules, to control the data entered into database table fields and records. Field- and record-level rules compare the values entered against the rule expressions that you define. If the entered value does not meet the requirements of the rule, the value is rejected. Validation rules exist only in database tables.

Field- and record-level rules enable you to control the types of information entered into a table, whether the data is accessed through a Browse window, a form, or programmatically through the language. They allow you to consistently enforce the rule for a field with less coding than if you wrote the rule expression as code in a VALID clause on a form, or in a portion of program code. In addition, the rules you establish in a database are enforced for all users of the table, regardless of the requirements of the application.

You can also create candidate or primary indexes that prevent duplicate entries in a field, and triggers to enforce referential integrity or perform other actions when the data in your database is changed.

Knowing When Constraints Are Enforced

You choose database constraints based on the level at which you want to enforce a business or referential integrity rule, as well as the action that causes the constraint to be activated. The following table lists the data validation constraints in the order in which they are enforced by the Visual FoxPro engine, the level at which they are applied, and when the engine activates the validation.

Enforcement Mechanism | Level | Activated
NULL validation | Field or column | When you move out of the field/column in a browse, or when the field value changes during an INSERT or REPLACE.
Field-level rules | Field or column | When you move out of the field/column in a browse, or when the field value changes during an INSERT or REPLACE.
Record-level rules | Record | When the record update occurs.
Candidate/primary index | Record | When the record update occurs.
VALID clause | Form | When you move off the record.
Triggers | Table | When table values change during an INSERT, UPDATE, or DELETE event.

Constraints are activated in the order in which they appear in the table. The first violation of any validation test stops the command.

Candidate and primary indexes are explained in the section Controlling Duplicate Values.

Limiting Values in a Field

When you want to control the type of information a user can enter into a field, and you can validate the data in a field independently of any other entry in the record, you use a field-level validation rule. For example, you might use a field-level validation rule to ensure that the user does not enter a negative number in a field that should contain only positive values. You can also use a field-level rule to compare the values entered in a field against the values in another table.

You should not create field- or record-level rules that are application-specific. Use field- and record-level validation rules to enforce data integrity and business rules that always apply to the data in your database, regardless of who may access the data. For example, you might create a rule that compares the entry in the postal_code field of a table against a lookup table that contains the postal abbreviation codes for your country/region, and rejects any value that is not already present as a valid postal code abbreviation.

To create a field-level rule

  1. Open a table in the Table Designer.
  2. In the Table Designer, select the name of the field you want to set a rule for.
  3. Choose the dialog button next to the Rule box.
  4. In the Expression Builder, set up the validation expression and choose OK.
  5. In the Message box, type the error message in quotes.
  6. Choose OK.

    -or-

  • In the Table Designer, enter the rule expression in the Rule box in the Field validation area.

    -or-

  • Use the CHECK clause of the CREATE TABLE command.

    -or-

  • Use the SET CHECK clause of the ALTER TABLE command.

For example, the following code adds a field-level validation rule to the orditems table requiring that numbers entered into the quantity field be 1 or greater:

ALTER TABLE orditems
    ALTER COLUMN quantity SET CHECK quantity >= 1

When the user attempts to enter a value less than 1, Visual FoxPro displays an error and the value is rejected.

You can customize the message displayed when the rule is violated by adding validation text to the field. The text you enter is displayed instead of the default error message.

To add a custom error message to a field-level rule

  • In the Table Designer, enter the error message you want in the Message box in the Field validation area.

    -or-

  • Use the optional ERROR clause with the CHECK clause of the CREATE TABLE or ALTER TABLE commands.

For example, the following code adds both a field-level validation rule for the orditems table requiring that numbers entered into the quantity column must be 1 or greater, as well as a custom error message:

ALTER TABLE orditems ;
   ALTER COLUMN quantity SET CHECK quantity >= 1 ;
   ERROR "Quantities must be greater than or equal to 1"

When the user attempts to enter a value less than 1, Visual FoxPro displays an error with the custom error message you defined, and rejects the failed value. You can also use the SET CHECK clause of the ALTER TABLE command with the optional ERROR clause to create a custom error message.

See Also

Controlling Display of a Field | Knowing When Field-Level Rules Are Checked | Working with Tables | Creating Default Field Values | Record-Level Rule Checking


Knowing When Field-Level Rules Are Checked

Field-level rules are checked when the field's value changes. Unlike triggers, field-level rules fire even if data is buffered. When you work with data in a Browse window, form, or other window, Visual FoxPro checks field-level rules as you move away from the field. If a field value has not been changed, the rule is not checked. This means that you are free to tab through fields without the system validating any of the data.

Field-level Rule Checking

Data entry method | Window or command | Field-level rule checked
User interface | Browse window Form Other window | As you move away from the field, if the field value has changed. (If the field value has not been changed, the rule is not checked.)
Commands that do not specify fields | APPEND APPEND GENERAL APPEND MEMO BROWSE CHANGE DELETE EDIT GATHER | As field value changes, in field definition order.
 | APPEND BLANK INSERT INSERT - SQL | As the record is appended or inserted.
Commands that specify fields | UPDATE UPDATE - SQL REPLACE | In the order in which fields are specified in the command.

Validating Record-Level Values

You use record-level validation rules to control the type of information a user can enter into a record. Record-level validation rules typically compare the values of two or more fields in the same record to make sure they follow the business rules established for the database. For example, you can use a record-level validation rule to ensure that one field's value is always greater than that of another in the same record.

To create a record-level validation rule and custom error message

  • In the Table tab of the Table Designer, enter the rule and error message you want in the Rule and Message boxes.

    -or-

  • Use the CHECK clause of the CREATE TABLE or ALTER TABLE commands.

For example, you might want to ensure employees are 18 years or older when hired. The following code adds a record-level validation rule and error text for the employee table requiring that the date of hire entered into the hire_date column is greater than or equal to their birth date plus 18 years:

ALTER TABLE employee SET CHECK ;
   hire_date >= birth_date + (18 * 365.25) ;
   ERROR "Employees must be 18 years or older by date of hire"

If the user enters an employee record with an invalid date, Visual FoxPro displays an error with the custom error message you defined, and does not update the record.

You can also use the SET CHECK clause of the ALTER TABLE command to create a record-level validation rule. You should ensure that any rules specified for fields do not conflict semantically with the rules you define for the table. Visual FoxPro makes no attempt to compare the field-level and record-level expressions for consistency.

See Also

Enforcing Business Rules | Record-Level Rule Checking | Working with Tables | Trigger Usage | Creating Triggers | Restricting Access to Fields


Setting or Changing Field-Level or Table Rules

You can set new field-level or table rule expressions and rule text, as well as alter rules and text you established with CREATE TABLE or ALTER TABLE commands.

To change an existing rule

  • In the Table Designer, select the Table tab and enter the new rule expression or rule text in the Rule and Message boxes in the Record validation section.

    -or-

  • Use the ALTER TABLE command.

To view the current rule expression and associated text, you can use the DBGETPROP( ) function; these values are read-only for tables and can only be changed using the ALTER TABLE command.

See Also

Renaming Fields | Setting or Changing Default Values | Working with Tables | Deleting Fields | Modifying the Table Structure


Record-Level Rule Checking

Record-level rules, like field-level rules, activate when the record value changes. No matter how you work with data, whether in a Browse window, form, or other user interface window, or through commands that alter data, Visual FoxPro checks record-level rules as you move the record pointer off the record. If no values within the record have changed, the record-level rule is not checked when you move the record pointer. You are free to move through records without the system validating any of the data.

If you modify a record, but do not move the record pointer, and then close the Browse window, the rule is still checked. You are warned of any errors that occur, and the Browse window is closed.

Caution Do not include any commands or functions in your validation rules that attempt to move the record pointer in the current work area (that is, in the work area whose rules are being checked). Including commands or functions such as SEEK, LOCATE, SKIP, APPEND, APPEND BLANK, INSERT, or AVERAGE, COUNT, BROWSE, and REPLACE FOR in validation rules may cause them to trigger recursively, creating an error condition.

Unlike triggers, record-level rules fire even if data is buffered. When a record-level rule fires during a running application, you need to include error-handling code. Typically, this will mean not allowing the application to leave the form (or change the active environment, to be more generic) until the user either corrects the reported error or cancels the update.

Removing a Table with Associated Rules from a Database

If you remove or delete a table from a database, all field-level and record-level rules bound to that table are deleted from the database. This is because the rules are stored in the .dbc file, and removing a table from the database breaks the link between the .dbf file and its .dbc file. However, stored procedures referenced by the removed or deleted rule are not deleted. They are not automatically removed, because they may be used by rules in other tables that remain in the database.

See Also

Knowing When Field-Level Rules Are Checked | Trigger Usage | Working with Tables | Enforcing Business Rules | Creating Triggers | Controlling Display of a Field


Trigger Usage

A trigger is an expression that is bound to a table and is invoked when any of the table's records are modified by one of the specified data-modification commands. Triggers can be used to perform any side-effect operations that a database application requires when data is modified. For example, you can use triggers to:

  • Log database modifications.
  • Enforce referential integrity.
  • Create an automatic reorder for a product that is low on stock.

Triggers are created and stored as properties on a specific table. If you remove a table from a database, the triggers associated with that table are deleted. Triggers fire after all other checks, such as validation rules, primary key enforcement, and null value enforcement, are performed. And unlike field- and record-level validation rules, triggers do not fire on buffered data.

See Also

Record-Level Rule Checking | Creating Triggers | Working with Tables | Removing or Deleting Triggers | Modifying Triggers


Creating Triggers

You create triggers using the Table Designer or the CREATE TRIGGER command. For each table, you can create one trigger for each of the three events: INSERT, UPDATE, and DELETE. A table can have a maximum of three triggers at any one time. A trigger must return a true (.T.) or false (.F.) value.

To create a trigger

  • In the Table tab of the Table Designer, enter the trigger expression or the name of a stored procedure containing the trigger expression in the Insert trigger, Update trigger, or Delete trigger box.

    -or-

  • Use the CREATE TRIGGER command.

For example, perhaps each time Tasmanian Traders sells an item, they want to compare the remaining Units_in_stock against the Reorder_level and be notified if they need to reorder that item. You can create an Update trigger on the products table to accomplish this. Every time a product is sold, the Update trigger will fire and the Units_in_stock field will be updated to reflect the remaining items in stock.

To create the trigger, you can specify updProductsTrigger( ) as your Update trigger for the products table. You can add a field to products, named reorder_amount, which stores the amount you want to order each time you reorder the item, and create a reorder table with the fields: product_id and reorder_amount. You can then add this code to your stored procedure:

PROCEDURE updProductsTrigger
   IF (units_in_stock+units_on_order) <= reorder_level
   INSERT INTO Reorder VALUES(Products.product_id, ;
    Products.reorder_amount)
   ENDIF
ENDPROC

You can create similar triggers for an insert or delete event by using the FOR INSERT or FOR DELETE clause, respectively, instead of the FOR UPDATE clause. If you attempt to create a trigger that already exists for a particular event and table while SET SAFETY is on, Visual FoxPro asks you if you want to overwrite the existing trigger.

See Also

Trigger Usage | Removing or Deleting Triggers | Working with Tables | Modifying Triggers | Modifying the Table Structure


Removing or Deleting Triggers

You can remove a trigger from a database table through the interface or with the DELETE TRIGGER command.

To delete a trigger

  • In the Table tab of the Table Designer, select the trigger expression in the Insert trigger, Update trigger, or Delete trigger box and delete it.

    -or-

  • Use the DELETE TRIGGER command.

The following example removes the update trigger for the customer table:

DELETE TRIGGER ON customer FOR UPDATE

If you remove or delete a table from a database, all triggers bound to that table are deleted from the database. However, stored procedures referenced by the removed or deleted trigger are not deleted.

See Also

Creating Triggers | Modifying Triggers | Working with Tables | Trigger Usage | Modifying the Table Structure | Adding Fields


Modifying Triggers

You can modify triggers through the Table Designer or through the language.

To modify a trigger

  • In the Table tab of the Table Designer, enter the new trigger expression in the Insert trigger, Update trigger, or Delete trigger box.

    -or-

  • Issue the SET SAFETY OFF command, and then use the CREATE TRIGGER command.

When you modify a trigger by first issuing the SET SAFETY OFF command and then re-creating the trigger, the old trigger expression is automatically deleted and replaced by the re-created trigger expression.

Using Triggers to Build Referential Integrity

Visual FoxPro provides a Referential Integrity Builder to generate triggers and stored procedures that will enforce Referential Integrity (RI) for your database. For more information on using the RI Builder, see Developing Databases.

See Also

Removing or Deleting Triggers | Modifying the Table Structure | Working with Tables | Creating Triggers | Trigger Usage


Modifying the Table Structure

After you have built a table you can always modify the table structure and properties. You may want to add, change or delete field names, widths, data types, change default values or rules, or add comments or captions.

You can open the Table Designer to modify your table's structure, or you can make changes programmatically using the ALTER TABLE command. Make sure you have exclusive access to the table before modifying its structure.

To modify the structure of a table with the Table Designer

  • In the Project Manager, select the table name and then choose Modify. The structure of the table is displayed in the Table Designer.

    -or-

  • In the Database Designer, select the table in the schema and choose Modify from the Database menu.

    -or-

  • Use the MODIFY STRUCTURE command.

For example, you can modify the structure of the database table employee with the following commands:

OPEN DATABASE testdata
USE employee EXCLUSIVE
MODIFY STRUCTURE

Each of the previous options opens the Table Designer.

To modify the structure of a table programmatically

  • Use the ALTER TABLE command.

The ALTER TABLE command offers extensive clauses that enable you to add or drop table fields, create or drop primary or unique keys or foreign key tags, and rename existing fields. Some clauses apply only to tables associated with a database. A few specific examples are included in this section.

See Also

Modifying Triggers | Adding Fields | Working with Tables | Deleting Fields | Renaming Fields | Setting or Changing Field-Level or Table Rules


Working with Multiple Tables

To use multiple tables, you use data sessions to control the tables that are available to forms, and work areas to set which tables are open. A work area is a numbered region that identifies an open table. You can open and manipulate Visual FoxPro tables in 32,767 work areas. Work areas are normally identified in your application by using the table alias of the table open in the work area. A table alias is a name that refers to a table open in a work area.

Using Data Sessions

In addition to the work areas visible in the Data Session window, Visual FoxPro automatically provides a separate environment for each instance of a form or form set through data sessions. A data session is a representation of the current dynamic work environment used by a form, form set, or report. Each data session contains its own set of work areas. These work areas contain the tables open in the work areas, their indexes, and relationships. For information on using data sessions, see Programming for Shared Access.

Viewing Work Areas

You can see the list of tables open in a Visual FoxPro session by opening the Data Session window.

To open the Data Session window

  • From the Window menu, choose Data Session.

    -or-

  • Use the SET Command.

When you enter SET in the Command window, Visual FoxPro opens the Data Session Window and displays the work area aliases for the tables open in the current data session.

Opening a Table in a Work Area

You can open a table in a work area with the Data Session window or with the USE command.

To open a table in a work area

  • In the Data Session window, choose Open.

    -or-

  • Type USE in the Command window.

To open a table in the lowest available work area, use the IN clause of the USE command with work area 0. For example, if tables are open in work areas 1 through 10, the following command opens the customer table in work area 11.

USE customer IN 0

You can also choose Open from the File menu to open a table in a work area.

Closing a Table in a Work Area

You can close a table in a work area through the Data Session window or by using the language.

To close a table in a work area

  • From the Data Session window, select the alias of the table, and then choose Close.

    -or-

  • Type USE without a table name.

    -or-

  • Use the IN clause of the USE command to reference the work area of the table you want to close.

When you issue the USE command without a table name and a table file is open in the currently selected work area, the table is closed. For example, the following code opens the customer table, displays a Browse window, and then closes the table:

USE customer
BROWSE
USE

You also close a table automatically when you open another table in the same work area, or issue the USE command with the IN clause and reference the current work area. The following code opens, displays, and then closes the customer table by issuing USE IN and the table alias customer:

USE customer
BROWSE
USE IN customer

You can't have more than one table open in a work area at one time.

Referencing a Work Area

You can reference the next available work area before you open a table by using the work area number as shown below:

SELECT 0

See Also

Enhancing the Efficiency of Indexes | Working with Table Aliases | Working with Records | Setting Temporary Relationships Between Tables | Establishment of Persistent Relationships with Indexes | Ordering by Multiple Fields


Working with Table Aliases

A table alias is the name that Visual FoxPro uses to refer to a table open in a work area. Visual FoxPro automatically uses the file name for the default alias when you open a table. For example, if you open the file Customer.dbf in work area 0 with the following commands, the default alias customer is automatically assigned to the table:

SELECT 0
USE customer

You can then use the alias customer to identify the table in a command or function. You can also create your own alias.

Creating a User-Defined Alias

You can assign your own user-defined alias to a table when you open it.

To open a table with a user-defined alias

  • Type USE with a table alias name.

For example, to open the file Customer.dbf in work area 0 and assign it an alias of people, use the following command:

SELECT 0
USE customer ALIAS people

You must then use the alias people to refer to the open table. An alias can consist of up to 254 letters, digits, or underscores and it must begin with a letter or an underscore. Visual FoxPro automatically creates an alias if the alias you provide contains an unsupported alias character.

Using a Visual FoxPro-Assigned Alias

Visual FoxPro automatically assigns an alias to a table in certain instances:

  • If you open a single table simultaneously in multiple work areas by including the AGAIN clause with the USE command and you don't specify an alias when opening the table in each work area.
  • If a conflict occurs with aliases.

The default aliases assigned in the first 10 work areas are the work area letters "A" through "J"; the aliases assigned in work areas 11 through 32767 are W11 through W32767. You can use these Visual FoxPro-assigned aliases just as you would any default or user-defined alias to refer to a table open in a work area.

Selecting a Work Area Using an Alias

You can move to a work area from another work area with the SELECT command. For example, if Customer.dbf is open in a work area and the default alias of CUSTOMER is assigned, you can move to this work area with the following SELECT command:

SELECT customer

Referring to Tables Open in Other Work Areas

You can also refer to fields in other work areas by prefacing the field name with the alias name and a period, or the –> operator. For example, if you're in a work area and you want to access the field contact from the Customer table open in a different work area, you could use the following to reference the field:

customer.contact

If the table you want to reference is opened with an alias, you can use the alias name. For example, if the Customer table is opened with the alias people, you can reference the lastname field with the following to refer to the field:

people.lastname

Using the table name or table alias specifically identifies the desired table independently from the work area in which the table is open.

See Also

Working with Multiple Tables | Setting Temporary Relationships Between Tables | Working with Records | Establishment of Persistent Relationships with Indexes | USE Command


Setting Temporary Relationships Between Tables

When you establish a temporary relationship between tables, you cause the record pointer of one table (the child table) to automatically follow the movements of the record pointer in the other, or parent, table. This allows you to select a record on the "one" or parent side of a relationship and automatically access the related records on the "many" or child side of the table relationship.

For example, you may want to relate the customer and orders tables so that when you move the record pointer in the customer table to a particular customer, the record pointer in the orders table moves to the record with the same customer number.

You can use table work areas and table aliases to establish relationships between two open tables with the SET RELATION command. If you're using a form to work with tables, you can store these relationships as part of the data environment for the form.

Temporarily Relating Tables

You can use the Data Session window or the language to create temporary relationships between tables.

To temporarily relate tables

  • In the Data Session window, select tables and use the Relations button to create relationships.

    -or-

  • Use the SET RELATION Command.

You use the SET RELATION command to establish a relationship between a table open in the currently selected work area, and another table open in another work area. You typically relate tables that have a common field, and the expression you use to establish the relationship is usually the index expression of the controlling index of the child table.

For example, a customer may have many orders. If you create a relationship between the field that is common to both customer and order tables, you can easily see all the orders for any customer. The following program uses a field, cust_id, that is common to both tables and creates a relationship between the two tables based on the field cust_id in the customer table and the cust_id index tag in the orders table.

Using SET RELATION to Establish Relationship Between Two Tables

Code Comments
USE customer IN 1
 Open the customer table (parent table) in work area 1.
USE orders IN 2
 Open the orders table (child table) in work area 2.
SELECT orders
 Select the child work area.
SET ORDER TO TAG cust_id
 Specify the table order for the child table using the index tag cust_id.
SELECT customer
 Select the parent work area.
SET RELATION TO cust_id
INTO orders
 Create the relationship between the parent table and the controlling index in the child table.
SELECT orders
BROWSE NOWAIT
SELECT customer
BROWSE NOWAIT
 Open two Browse windows; notice that moving the record pointer in the parent table changes the set of data viewed in the child table.

The Data Session window displays the two open tables, Orders and Customer, and the relationship established by the SET RELATION command.

The Data Session window displays open table aliases and temporary relationships.

You created an index on the child table, orders, to organize records in the orders table into groups, according to the customer who placed the order. When you create a relationship between the parent table and the index of the child table, Visual FoxPro selects only those child table records whose index key matches the index key of the parent record you've selected.

The previous example established a single relationship between two tables. You can also use the SET RELATION command to establish multiple relationships between a single parent table and various child tables.

Saving Table Relationships in a Data Environment

If you are creating a form that uses more than one table, you can use the data environment to create table relationships and store them with the form. Relationships you establish in the data environment are opened automatically when you run the form. For information on creating a data environment, see Creating Forms.

Relating Records in a Single Table

You can also create a relationship between records in a single table. This relationship, known as a self-referential relation, can be useful in situations where you have all the information you need stored in a single table. For example, you may want to move through the managers in the Employees table and have the employees who report to each manager automatically change as you move the record pointer from manager to manager.

To temporarily relate records in a single table

  • In the Data Session window, select tables and use the Relations button to create relationships.

    -or-

  • Use the SET RELATION Command.

To create a self-referential relation, open the same table twice: once in one work area and then a second time, with the USE AGAIN command, in another work area. Then use an index to relate the records. For example, the following code establishes and browses a self-referential relationship by creating an index tag named mgr_id that orders the Employee table by the reports_to field:

SELECT 0
USE employee ALIAS managers
SELECT 0
USE employee AGAIN ALIAS employees
INDEX ON reports_to TAG mgr_id
SET ORDER TO mgr_id
SELECT managers
SET RELATION TO emp_id INTO employees
BROWSE
SELECT employees
BROWSE

When you move the record pointer in the managers Browse window, the employees Browse window is refreshed to show only those employees who report to the selected manager.

See Also

Working with Table Aliases | Establishment of Persistent Relationships with Indexes | Working with Records | Data Session Window | SET RELATION COMMAND | Working with Multiple Tables


Data Access Management Using CursorAdapters

In Visual FoxPro, you can retrieve data from local and remote data sources that have the following data source types using cursor adapters:

  • Native
  • Open Database Connectivity (ODBC)
  • ActiveX Data Object (ADO)
  • Extensible Markup Language (XML)

The CursorAdapter class expands support for working with different data source types as native Visual FoxPro cursors. CursorAdapter objects provide the following capabilities:

  • Use different data sources dynamically.
  • Use either the data source of the CursorAdapter object or the data environment.
  • Share data sources within the limits of the data source technology.
  • Optionally define the structure of the cursor associated with a CursorAdapter object.
  • Control the loading of data from the data source into a Visual FoxPro cursor associated with a CursorAdapter object.
  • Render data from different data sources into Visual FoxPro cursors based on the data source type.
  • Control how data is added, updated, and deleted with CursorAdapter properties and methods.
  • Add CursorAdapter objects to containers other than the data environment, such as forms, form sets, and other containers.
  • Use the CursorAdapter class as a standalone class without an associated data environment.

With CursorAdapter objects, the data source is only a pipe to the translation layer, which renders data from the data source into a Visual FoxPro cursor.

Note Visual FoxPro does not support using relations with the CursorAdapter objects. However, you can use relations with cursors associated with cursor adapters.

For more information about the CursorAdapter, DataEnvironment, and Cursor classes, see CursorAdapter Class, DataEnvironment Object, and Cursor Object.

Interaction with the TABLEUPDATE( ) and TABLEREVERT( ) Functions

The TABLEUPDATE( ) function recognizes and can work with CursorAdapter objects. TABLEUPDATE( ) delegates its operations to the cursor adapter associated with the cursor. TABLEREVERT( ) operates on CursorAdapter objects in the same way as other buffered cursors.

For more information about how CursorAdapter objects affect the way the TABLEUPDATE( ) and TABLEREVERT( ) functions behave, see TABLEUPDATE( ) Function and TABLEREVERT( ) Function.

Automatic Updating and CursorAdapters

Visual FoxPro automatically generates the SQL INSERT, UPDATE, and DELETE commands for local and remote views. When working with CursorAdapter objects, you can customize and control how Visual FoxPro generates these SQL INSERT, UPDATE, and DELETE commands.

When the CursorAdapter InsertCmd, UpdateCmd, and DeleteCmd properties are empty, Visual FoxPro generates the corresponding SQL commands automatically. You must determine whether automatic generation of these commands is appropriate for the data source you are using. To generate the SQL INSERT, UPDATE, and DELETE commands automatically, you must set the following CursorAdapter-specific properties:

  • Tables
  • KeyFieldList
  • UpdatableFieldList
  • UpdateNameList

The following general rules apply for the Tables and UpdateNameList properties:

  • Tables

    To enable automatic updating, you must provide a list of table names in the exact order you want them to appear in the SQL INSERT, UPDATE, and DELETE commands.

  • UpdateNameList

    You must specify a comma-delimited list consisting of pairs of local and full remote field names. Each pair of names consists of the local field name followed by the full remote field name. The full remote field name appears as <remote table name>, <remote field name>, where <remote table name> matches the name from the Tables property.

You must also set the appropriate key fields if you set the following CursorAdapter properties to True (.T.):

  • AllowInsert
  • AllowUpdate
  • AllowDelete

For more information about the SQL commands used for automatic updating, see INSERT - SQL Command, UPDATE - SQL Command, and DELETE - SQL Command.

Batch Updates

CursorAdapter objects use batch updating if the value of CursorAdapter BatchUpdateCount property is greater than 1, and one of the following conditions are true:

  • The CursorAdapter object is set up to use the same ODBC statement handle for all permitted operations, namely, INSERT, UDPATE, and DELETE, as defined by the AllowInsert, AllowUpdate, and AllowDelete properties.
  • The CursorAdapter object is set up to use the same ADODB Command object for all operations permitted.
  • The CursorAdapter object uses "XML" as the data source type for all permitted operations.

If batch updating is used, the following CursorAdapter events do not occur:

  • BeforeInsert
  • AfterInsert
  • BeforeUpdate
  • AfterUpdate
  • BeforeDelete
  • AfterDelete

If an update fails for a batch, Visual FoxPro attempts to send a separate update for each row in the batch; however, the listed events still do not occur.

For more information, see BatchUpdateCount Property.

Automatic Updating and ActiveX Data Objects (ADO)

When working with ADO, you can send updates using two different methods:

  • Use the CursorAdapter object to send updates with the ADO RecordSet object used by the CursorAdapter CursorFill method.

    When performing automatic updates using an ADO RecordSet, the following rules apply when setting the CursorAdapter InsertCmdDataSource, UpdateCmdDataSource, and DeleteCmdDataSource properties:

    • The ADO RecordSet must be read/write and have bookmarks available. Bookmarks are always available when using a client-side RecordSet object. Bookmarks might be available when using Keyset or Static server-side cursors when supported by the OLE DB Provider.
    • Updates are performed on a field-by-field basis. For every updated record, the CursorAdapter object locates the original record in the ADO RecordSet, changes the values for updateable fields, and calls the ADO RecordSet Update method. The CursorAdapter object does not call the ADO RecordSet UpdateBatch method; therefore, your application should explicitly call UpdateBatch when appropriate.

    When using this method, you should configure the CursorAdapter object as follows:

    THIS.DataSourceType="ADO"
THIS.UpdateCmdDataSourceType=""

    You can also use the DataEnvironment and CursorAdapter builders to build an updateable form or DataEnvironment and CursorAdapter class library and use the AutoUpdate tab in the CursorAdapter Builder to specify key fields, update fields, and other required information.

  • Use the CursorAdapter object to send updates directly to the database using a custom or automatically generated update command.

    When performing automatic updates directly, the CursorAdapter object needs an ADO Command object with its ActiveConnection property set to an open ADO Connection object.

    When using this method, you should configure the CursorAdapter object as follows:

    THIS.UpdateCmdDataSourceType="ADO"
THIS.UpdateCmdDataSource=NewADODBCommandObject

    Setting THIS.DataSourceType="ADO" does not apply when using this method.

Automatic Updating and XML

CursorAdapter objects do not automatically generate SQL INSERT, UPDATE, or DELETE commands as they do for other data sources when the data source is XML because of the numerous ways that exist for generating XML. However, you can use the CursorAdapter object to generate an XML UpdateGram and assign it to the CursorAdapter UpdateGram property.

Though the CursorAdapter object can generate the XML UpdateGram, you must implement the actual update operation using the appropriate protocols, such as SQL XML using HTTP, SQL XML OLE DB, or XML Web service to .NET.

The following rules apply when working with XML data sources and generating XML UpdateGrams:

  • You must specify command text for the CursorAdapter InsertCmd, UpdateCmd, and DeleteCmd properties that Visual FoxPro can execute for the appropriate insert, update, or delete operation. If using batch updating, that is CursorAdapter BatchUpdateCount property is greater than 1, UpdateCmd is executed only once per batch.
  • The following CursorAdapter properties must be set to "XML":
    • InsertCmdDataSourceType
    • UpdateCmdDataSourceType
    • DeleteCmdDataSourceType

    If these properties are not set to "XML", Visual FoxPro executes the command text in the UpdateCmd, InsertCmd, or DeleteCmd properties but does not generate an XML UpdateGram.

  • To construct the XML UpdateGram correctly, CursorAdapter requires that the Tables, UpdatableFieldList, and UpdateNameList properties contain valid values. CursorAdapter can generate a multiple table UpdateGram by specifying the tables and fields in the Tables, UpdatableFieldList, and UpdateNameList properties as appropriate. Therefore, you can update a cursor that represents a multi-table join using the XMLUPDATEGRAM( ) function. For more information, see XMLUPDATEGRAM( ) Function.
  • CursorAdapter uses the WhereType property to generate the before section for the XML UpdateGram. Therefore, when you perform an update or delete operation, the KeyFieldList and UpdatableFieldList properties must contain the appropriate key fields. For more information, see WhereType Property.
  • If row buffering is enabled, or BatchUpdateCount is 1, Visual FoxPro creates an XML UpdateGram for each update, insert, or delete operation.

    If table buffering is enabled, and if using batch updating, that is, BatchUpdateCount is greater than 1, Visual FoxPro creates an XML UpdateGram for the entire batch of changes. In this mode, you must call the TABLEUPDATE( ) function as expected to initiate the update and generation of the XML UpdateGram.

See Also

Working with Tables | CursorAdapter Class | CursorAdapter Object Properties, Methods, and Events


Working with Records

When you have designed and created the structure for a table, you can store data in the table by adding new records. Later, you will change and delete existing records. Each of these tasks can be accomplished either through the interface or by using commands. This section focuses primarily on working with records programmatically.

In This Section

Adding Records
Provides instructions on how to add records to a table, add a new blank record, append records from another file, display records for editing, and store a null value in a field.
Deleting Records
Provides instructions on how to mark a record for deletion, unmark a record marked for deletion, and remove records marked for deletion from disk.
Index Creation for Tables
Offers background on the capabilities of index tables and their importance in application development.

Related Sections

Working with Data
Find out how to create effective applications with indexes, tables, and databases based on your data requirements.
Designing Databases
Take advantage of relational database technology in Microsoft Visual FoxPro with well-planned databases.
Developing Databases
Use databases in Microsoft Visual FoxPro to establish relationships between tables, enforce referential integrity, and manage local and remote data.
Working with Tables
Make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.
Importing and Exporting Data
Information is copied between Microsoft Visual FoxPro and other applications by importing to and exporting from Visual FoxPro.
Working with Multiple Tables
Explains how to open a Data Session window, open a table in a work area, and close a table in a work area.


Adding Records

When you first create a Visual FoxPro table, it is open but empty. If you try to store data to a table without first creating a record in the table, nothing happens. The first step in adding records to a new table is to add rows to store the new data.

To add records to a table

  • Use the INSERT – SQL Command.

The INSERT – SQL Command can be used to insert values specified with the command or to insert values from an array or variable. For example, to insert a new record into the TasTrade database customer table, you could issue the following command:

INSERT INTO customer (cust_id, company, contact) ;
   VALUES ("SMI007", "Smith's Delicatessen", "Sarah Smith")

The INSERT – SQL Command is useful with remote data, as it uses ANSI-compliant SQL syntax.

Adding New Blank Records to a Table

To quickly add new records to a table, you can place the Browse or Edit windows into Append mode. In Append mode, a blank set of fields appears at the bottom of the file, so you can fill them in to create a new record.

To add a new blank record

  • From the View menu, select Append Mode.

Fill in the fields in the new record, tabbing from field to field. A new record is created at the bottom of the file as you complete each record.

You can also use the APPEND BLANK command followed by the REPLACE command to add a blank record to a table and then store data in a field. The APPEND BLANK appends a new, blank record to a table. The REPLACE command replaces the current value of a field, even an empty field, with a new value.

The REPLACE Command requires:

  • An open table.
  • An existing record.
  • The name of the field in which to store the value.
  • A value for each field that is valid for the field's data type.

The following example uses the APPEND Command to create one record in which you can store data using the REPLACE command:

APPEND BLANK                     && record now available
REPLACE lastname WITH "SMITH"   && store character value to the field

You can use the UPDATE - SQL command instead of the REPLACE command to update records in a table.

Adding Records in Browse Mode

If you want to add a new record while viewing a table in browse mode, you can choose Append Record from the Table menu. Conversely, if you want to prevent users from being able to append a new record while in browse mode, you can use the NOAPPEND clause of the BROWSE Command.

Appending Records from Another Table

Another way to store data in records is to copy them from other tables or files. For example, you can append records from another table or file.

To append records from another file

  • Use the APPEND FROM Command.

    -or-

  • Use the IMPORT Command.

Records can accept data directly, as in the previous example, where the INSERT command specified the text to be inserted into specific fields in the customer table, as well as from constants, variables, arrays, objects, and other data sources. For more information, see Importing and Exporting Data.

Entering Data in a Table

You can enter data in a table interactively, through a Browse window, or programmatically, with the REPLACE Command or UPDATE - SQL Command. When you use the REPLACE or UPDATE - SQL in a multiuser application, you can turn on record or table buffering, which enables you to edit data without locking the record until you want to commit changes. For more information, see Programming for Shared Access.

Editing Records in a Table

You can display and edit existing records in a table through the interface or programmatically.

To display records for editing

  • Use the EDIT Command.

    -or-

  • Use the CHANGE Command.

For example, the following code displays the customer table in a Browse window in edit mode:

USE customer
EDIT

If you want to use a form to edit a record, create a text box in your form and set its DataSource property to the name of the table you want to edit. For more information about forms, see Creating Forms.

You can also use the CHANGE COMMAND and EDIT COMMAND to make changes to specific fields in a table.

Adding Graphics to a Table

You can store graphics in a Visual FoxPro table by creating a General Field Type and importing or pasting OLE objects, such as bitmaps or charts, into the field. The APPEND GENERAL COMMAND places an OLE object into a General field. The following example stores a Microsoft Excel chart file from the default Visual FoxPro directory into a General field named Chart:

APPEND GENERAL Chart FROM "CHART1.CLX" CLASS EXCELCHART

For more information about working with OLE objects in Visual FoxPro tables, see Sharing Information and Adding OLE.

Entering Null Values in Fields

You can enter a null value in a field through the language with the NULL token, or through the interface with a key combination if the field accepts null values.

To store a null value in a field

  • In a Browse Window or form control, press CTRL+0 (zero).

    -or-

  • Use the NULL token.

For example, the following code replaces the existing value in the field automobile with a null value:

REPLACE automobile WITH NULL
Note Use the SET NULLDISPLAY Commandto specify the text displayed for null values.

See Also

Working with Records | Deleting Records | INSERT – SQL COMMAND | Index Creation for Tables | REPLACE Command | APPEND COMMAND | BROWSE Command | APPEND FROM Command | Table Creation | Ordering by Multiple Fields


Deleting Records

You delete records by marking them for deletion, then removing the deleted records. Until you remove the records that are flagged for deletion, they are still on disk and can be unmarked and restored. This section describes how to mark, unmark, and remove records from your table.

Marking Records for Deletion

You can mark records for deletion through the interface or with the DELETE - SQL Command.

To mark a record for deletion

  • In a Browse Window, click the deletion marker to flag the record.

    -or-

  • From the Table menu, choose Delete Records.

    -or-

  • Use the DELETE - SQL Command.

You can use the DELETE - SQL command to specify a range of records, as well as a condition based on a logical expression that records must meet to be marked for deletion. For example, the following code marks for deletion all product records with 'T' in the Discontinu field:

USE products
DELETE FROM products WHERE discontinu = .T.
BROWSE

You can also select a group of records for deletion by setting conditions in the Delete dialog box. Choose Delete Records from the Table menu to enter deletion criteria.

Choose the Scope button to set the range of records to be deleted.

If you can describe a set of records you want to delete, you can build an expression based on that description. Choose the FOR button to bring up the Expression Builder so you can build an expression. For example, using the expression FOR Country = 'UK' selects all the records from the UK and marks them for deletion.

Records you mark for deletion are not physically removed from the table until you issue a PACK Command. When you view the table in the Browse window, you'll see that the deletion marker is flagged for each deleted record, but the record is still visible in the table, if SET DELETED is set to off. If SET DELETED is set to on, the records marked for deletion are excluded from the Browse window.

The setting of the SET DELETED command also affects whether records marked for deletion are accessible by commands that operate on records.

Retrieving Records Marked for Deletion

You can unmark records that were marked for deletion with the RECALL command. The RECALL command can recover records only if you have not issued a PACK or ZAP command, which physically deletes the records from the table.

To unmark a record marked for deletion

  • In a Browse Window, click the deletion marker to unmark the record.

    -or-

  • From the Table menu, choose Recall Records.

    -or-

  • Use the RECALL Command.

You can use the RECALL command to specify a range of records, as well as a condition based on a logical expression that records must meet to be unmarked for deletion. For example, the following code unmarks for deletion all product records with 'T' in the discontinu field:

USE products
RECALL FOR discontinu = .T.
BROWSE

When you view the table in the Browse window, you'll see that the deletion marker is not flagged for the records.

Removing Records Marked for Deletion

After you've marked records for deletion, you can permanently remove them from disk through the interface or the language.

To remove records marked for deletion from disk

  1. In a Browse Window, choose Remove Deleted Records from the Table menu.
  2. Choose Yes in response to the prompt that asks if you want to pack the table.

    -or-

  • Use the PACK Command.

The PACK command has two clauses: MEMO and DBF. When you issue PACK without the MEMO or DBF clauses, records in both the table file and the associated memo file are removed. Make sure you have exclusive access to the table. For example, the following code removes records marked for deletion:

USE customer EXCLUSIVE
PACK

To delete records in the table file only and leave the memo file untouched, use PACK DBF.

Conserving Space

Information in table memo fields is stored in an associated memo file with the same name as the table and an .fpt extension. If you want to remove unused space from the memo file without removing records that are marked for deletion, issue the PACK Command with the MEMO clause. Make sure you have exclusive access to the table.

Removing All Records from a Table

If you want to remove all records from a table, and leave just the table structure, you can use the ZAP Command. Issuing ZAP is equivalent to issuing DELETE ALL followed by PACK, but ZAP is much faster. Make sure you have exclusive access to the table.

Caution Records zapped from the current table cannot be recalled.

See Also

Adding Records | Index Creation for Tables | Working with Records | DELETE - SQL Command | Browse Window | PACK Command | SET DELETED Command | RECALL COMMAND | Ordering by Multiple Fields


Index Creation for Tables

When you want to navigate, view, or manipulate table records in a particular order, you use an index. Visual FoxPro uses indexes as ordering mechanisms to provide you with flexibility and power as you develop your application. You have the flexibility to create and use many different index keys for the same table, enabling you to work with records in different orders, according to your application's requirements. You have the power to create custom relationships between tables based on their indexes, enabling you to access exactly the records you want.

A Visual FoxPro index is a file that contains pointers that are logically ordered by the values of an index key. The index file is separate from the table's .dbf file, and does not change the physical order of the records in the table. Rather, when you create an index, you create a file that maintains pointers to the records in the .dbf file. When you want to work with table records in a particular order, you choose an index to control the order and increase the speed in which the table is viewed and accessed.

Note Indexes are so easy to create, you might be tempted to define one for every field. However, indexes that you use only rarely can slow performance. Other types of index files are better for storing indexes you don't use regularly.

See Also

Deleting Records | Creating One Index | Working with Records | Index File Creation | Index Information Display | Setting a Primary or Candidate Index | Permitting Duplicate Values | Creating Multiple Indexes | Table Creation | Ordering by Multiple Fields | Index Creation for Tables


Creating One Index

When you first create a table, Visual FoxPro creates the table's .dbf file and, if your table includes Memo or General fields, the associated .fpt file. You can choose to quickly add an index to a field as you define the field; otherwise, no index files are generated at that time. Records you enter into the new table are stored in the order you entered them; when you browse the new table, they appear in the order they were entered.

Typically, you'll want to be able to view and access the records in your new table in a specific order. For example, you may want to view the records in your customer table alphabetically by company name. When you want to control the order in which records are displayed and accessed, you create an index file for your table by creating the first ordering scenario, or index key, for your table. You can then set the order of the table to the new index key, and access the table's records in the new order.

To create an index key for a table

  1. In the Project Manager, select the table you want to add an index to, and then choose Modify.
  2. In the Table Designer, select the Indexes tab.
  3. In the Name box, type a name for the index.
  4. From the Type list, select Regular as the index type.
  5. In the Expression box, type the name of the field you want to order the records by.

    -or-

    Build an expression by choosing the dialog button at the end of the box to display the Expression Builder.

  6. If you want to select records, enter a filter expression in the Filter box or select the button at the end of the box to build an expression.
  7. Choose OK.

    -or-

  • Use the Index Command.

For example, the following code uses the table customer and creates an index key on the city field. The keyword TAG and the word "city" afterward specifies a name, or tag, for the new index key on the city field.

USE customer
INDEX ON city TAG city

In the previous example, the tag for the index key uses the same name as the field you're indexing. The names don't have to match — you could also choose to give the index key a different name.

When you first create an index using the INDEX command, Visual FoxPro automatically uses the new index to set the order of the records in the table. For example, if you entered some data into the sample table created in the previous example, and then browsed the table, the records would appear in order by city.

Once you create an index for the table, you can use it to order your records.

To order records using an index

  1. In the Project Manager, select the table with the index you created.
  2. Choose Browse.
  3. From the Table menu, choose Properties.
  4. In the Index order box, select the index you want to use.
  5. Choose OK.

The table appears in the Browse window, displaying the records in the order your index specifies. You can also order the results of queries or reports by running them while the index is selected.

See Also

Index Creation for Tables | Index File Creation | Working with Records | Index Information Display | Setting a Primary or Candidate Index | Permitting Duplicate Values | Creating Multiple Indexes | Optimization of Tables and Indexes | INDEX COMMAND | Ordering by Multiple Fields


Index File Creation

As you created the first index key for your table in the topic Creating One Index, Visual FoxPro automatically created a new file, Customer.cdx, to store the new index key. The .cdx index file, called a structural compound index, is the most common and important type of index file you'll create in Visual FoxPro. The structural .cdx file:

  • Opens automatically when you open a table.
  • Can contain multiple ordering scenarios, or index keys, in the same index file.
  • Is automatically maintained as you add, change, or delete table records.

If a Visual FoxPro table has any index file associated with it at all, it is typically a structural .cdx file. The term "structural" refers to the fact that Visual FoxPro treats the file as an intrinsic part of the table and opens it automatically when you use a table. Whether you use the Table Designer or the simplest form of the INDEX command, as shown in the previous example, Visual FoxPro creates the .cdx file with the same base name as the current table, and stores the index information for the new key, or tag, inside. You use the structural .cdx file for frequently used index keys, such as those used for ordering records for daily viewing, data entry, SET RELATION linkages, Rushmore Query Optimization on viewing records, or frequently printed reports.

Visual FoxPro offers you two additional types of index files: the non-structural .cdx file and the single-key .idx file. Because the .cdx (or structural compound compact index) is the most important index type, most of the examples in related topics will discuss using index keys in the .cdx file to order table records. The other two index file types are less frequently used and are discussed at the end of this section.

See Also

Index Information Display | Working with Records | Setting a Primary or Candidate Index | Permitting Duplicate Values | Creating Multiple Indexes | Index Creation for Tables | Ordering by Multiple Fields


Index Information Display

You can see how many records are indexed during the indexing process by setting TALK to ON. The record interval displayed during indexing can be specified with SET ODOMETER COMMAND. For more information about open index files, use the DISPLAY STATUS Command. This command lists the names of all open index files, their types (structural, .cdx, .idx), their index expressions, and the name of the master index file or master tag.

Only the supply of memory and system resources can limit the number of index files (.idx or .cdx) you can open.

Controlling Duplicate Values

Visual FoxPro supports four types of indexes: primary, candidate, unique, and regular. These index types control whether duplicate values are permitted or prohibited in table fields and records.

Preventing Duplicate Values

A primary index is an index that never permits duplicate values on the specified fields or expression. Primary indexes are principally used within the primary or "referenced" table for establishing referential integrity in a persistent relationship. You can create only one primary index for a table. Visual FoxPro returns an error if you specify a primary index on any field that already contains duplicate data.

A candidate index is an index that never permits duplicate values on the specified fields or expression. The name "Candidate" refers to the status of the index; since candidate indexes prohibit duplicate values, they qualify as "candidates" to be selected as the primary index on a table. You can create multiple candidate indexes for a table. You use candidate indexes as either the referenced or referencing index in a persistent relationship for establishing referential integrity. Visual FoxPro returns an error if you specify a candidate index on any field that already contains duplicate data.

For compatibility with previous versions, you can also create a unique index that selects and orders a subset of records based on the first occurrence of a value in the field you specify. If you want to select records this way, you might want to create a query or view instead.

A regular index determines the order in which a record is processed but allows duplicate values to be entered into a field. You can add more than one regular index to a table.

See Also

Index File Creation | Setting a Primary or Candidate Index | Working with Records | Index Creation for Tables | Permitting Duplicate Values | Creating Multiple Indexes | Ordering by Multiple Fields


Setting a Primary or Candidate Index

You create primary and candidate indexes with the CREATE TABLE or ALTER TABLE commands. You can use both candidate and primary indexes in defining the "one" side of a one-to-many or a one-to-one persistent relationship.

To create a primary or candidate index

  • In the Table Designer, select the Index tab and create an index, selecting Primary or Candidate as the index type.

    -or-

  • Use the ALTER TABLE – SQL Command.

For example, either of the following commands make cust_id the primary key of the customer table:

ALTER TABLE customer ADD PRIMARY KEY cust_id TAG cust_id
ALTER TABLE customer ALTER COLUMN cust_id c(5) PRIMARY KEY

Primary and candidate indexes are stored in the structural .cdx file for a given table. The database stores the names of the indexes in the .cdx file and whether or not the indexes are Primary or Candidate. It is not possible to store these types of indexes in other .cdx files, nor is it possible to use .idx files for these types of indexes. The principal reason is that the index file that contains these indexes should always be open whenever their associated table is opened.

Primary keys are part of a table within a database. If you free a table from a database, the primary key is removed.

If you use a user-defined function in an index expression associated with a database, Visual FoxPro handles the expression in the same way it handles rule and trigger expressions that contain UDFs.

Controlling Entry of Duplicate Values in a Field

You might want to control entry of duplicate values in a field. For example, each customer should have a unique value in the Cust_ID field of the Customer table.

You can use the field as a key field that uniquely identifies a record. If your table is part of a database, you can use either a primary or candidate index. If your table is a free table or already has a primary index, you must use a candidate index.

To create an index that enforces unique values in a field

  1. In the Project Manager, select the table you want to add an index to and choose Modify.
  2. In the Indexes tab, create an index.
  3. In the Type column, select Primary or Candidate.
  4. Choose OK.

See Also

Index Information Display | Permitting Duplicate Values | Working with Records | Creating Multiple Indexes | Creating One Index | Ordering by Multiple Fields | Project Manager Window | Index Creation for Tables


Permitting Duplicate Values

In Visual FoxPro, a unique index does not prevent duplicate values from being created; rather, a unique index stores only the first occurrence of the value in the index file. In this sense, the word "unique" refers to the entries in the index file, which contains only unique values, because it doesn't store a particular key more than once, and ignores the second or later occurrence of a non-unique value. The table indexed by a unique index could contain duplicate values. Unique index types are provided primarily for backward compatibility.

A regular index is simply an index that is not unique, primary, or candidate. You use a regular index for ordering and seeking records, but not to enforce the uniqueness of the data in those records. You also use a regular index as the many side of a one-to-many persistent relationship.

To create a regular index

  • In the Table Designer, select the Index tab and create an index, by selecting Regular as the index type.

    -or-

  • Use the INDEX Command.

For example, the following commands make city a regular key for the customer table:

USE customer
INDEX ON city TAG city

See Also

Setting a Primary or Candidate Index | Creating Multiple Indexes | Working with Records | Setting Record Order at Run Time | Creating One Index | Ordering by Multiple Fields | Index Creation for Tables


Creating Multiple Indexes

As you work with the records in your table, you'll discover the need for accessing table records in several different sequences. For example, you might want to order the customer table by contact to quickly find a name you're looking for, or by postal code to generate mailing labels that are presorted for more efficient mailing.

You can create and store many different ordering scenarios for your table by creating multiple index keys for the same table. This enables you to order table records at different times according to different purposes.

To create additional index keys for a table

  • In the Table Designer choose the Index tab and enter the information for additional index keys.

    -or-

  • Use the INDEX Command.

For example, the following code creates two new index keys on the employee table: one on the last_name field and another on the country field:

USE employee
INDEX ON last_name TAG last_name
INDEX ON country TAG country

When you create an index tag without specifying the name of an index file, the tag is added automatically to the table's structural .cdx index file. The following diagram shows a .cdx index file with three index tags.

.cdx index contains multiple tags representing multiple record-ordering scenarios.

Two of the tags in the diagram, emp_id and last_name, represent indexes based on single fields. The cntry_last index orders records using a simple two-field index expression.

Controlling the Order in which Records Are Accessed

After you create index keys for the customer table on the company, city, and country fields, you can access and display the table in different orders, simply by choosing the index key you prefer. You use the SET ORDER Command to choose a specific index key as the ordering key for the table.

For example, the following code opens a Browse Window displaying the records in the customer table in order by country:

SET ORDER TO country
BROWSE

See Also

Permitting Duplicate Values | Setting Record Order at Run Time | Working with Records | Table Designer | INDEX Command | Using Other Index Types | Creating One Index | Ordering by Multiple Fields | Index Creation for Tables


Ordering by Multiple Fields

To increase the speed of queries or views that have filters on more than one field, you can order your records by specifying multiple fields in the index expression. The fields are evaluated in the same order they appear in the expression. If you create an index expression using numeric fields, the index orders the records by the sum of the fields, not the fields themselves.

To order records using multiple fields

  1. In the Project Manager, select the table you want to add an index to and choose Modify.
  2. In the Indexes tab, enter a name and type for the index.
  3. In the Expression box, enter an expression that lists the fields you want to order by.

    For example, you might want to order the records by country, postal code within the country, and the company name within the postal code. You can use a plus sign (+) to create the index expression from character fields.

    customer.country + customer.postalcode + customer.company

    Notice that the field that changes the least is the first one in the list.

  4. Choose OK.

If you want to use fields of different data types, you can convert the non-character fields to characters by enclosing the field with STR( ). For example, you can try ordering the records by the Maximum Order Amount field, then by the company name. In this expression, maxordamt is a Currency field and company is a Character field.

STR(customer.maxordamt,20,4) + customer.company

See Also

Permitting Duplicate Values | Setting Record Order at Run Time | Working with Records | Table Designer | INDEX Command | Using Other Index Types | Creating One Index | Creating Multiple Indexes | Index Creation for Tables


Setting Record Order at Run Time

Using the SET ORDER Command, you can designate the controlling index file or tag. A table can have many index files open simultaneously. However, you determine the order in which the records in a table are displayed or accessed by setting one single-index (.idx) file (the controlling index file) or tag from a compound index (.cdx) file (the controlling tag) as the controlling index. Certain commands, such as SEEK, use the controlling index tag to search for records. You do not need to SET ORDER for running queries.

Setting Record Order Interactively in a Form

You can use SET ORDER at run time to change the order of records in a form. For example, you might want to enable your application's users to reorder the records in a grid by clicking on the header of the column they want to order by.

To sort the records in a grid by columns

  1. Create a form with a Grid Control.
  2. Set the ColumnCount Property of the grid to the number of fields you want displayed in the grid.
  3. In the Click Event for the header of each column in the grid, insert code that:
    • Sets the record order to an index key based on the column.
    • Refreshes the form.

For example, if you created a form based on the Customer table in the Testdata database with a grid containing four columns — company, contact, postal code, and phone — the grid would first appear sorted alphabetically because the records in that table were entered alphabetically.

You could then enable the user to view the grid in contact or postal_code order by inserting the following code in the Click event of each column header:

Sample event code to order records in a Grid by clicking on the column header

Code Comment
SET ORDER TO company
GO TOP
THISFORM.Refresh
 In the Company header Click event code, reorder the grid by the company index key and refresh the form to display records in order by company.
SET ORDER TO contact
GO TOP
THISFORM.Refresh
 In the Contact header Click event code, reorder the grid by the contact index key and refresh the form to display records in order by contact name.
SET ORDER TO
postalcode
GO TOP
THISFORM.Refresh
 In the Postal_Code header Click event code, reorder the grid by the postalcode index key and refresh the form to display records in order by postal code.
Because sorting by phone number is not relevant to this application, leave the Phone header Click event code blank.

In this example, when the form is first displayed, the grid appears in alphabetical order by company. When the user clicks the header of the Contact column, Visual FoxPro displays the records in the grid in alphabetical order by contact name.

If the user clicks on the Postal_code column header, the grid is resorted and displayed in order by postal code.

Since there isn't a pressing need in our example application to sort contacts by phone numbers, no SET ORDER code is inserted into the Click event for the phone column header. When the user clicks the Phone column header, the grid display does not change.

See Also

Creating Multiple Indexes | Using Other Index Types | Working with Records | SET ORDER COMMAND | Grid Control | ColumnCount Property | Click Event | Deleting an Index | Creating One Index | Ordering by Multiple Fields | Index Creation for Tables


Using Other Index Types

In addition to the most common index — the compact compound structural .cdx index — Visual FoxPro supports two other types of index files: the non-structural .cdx, and the stand-alone .idx index. Non-structural .cdx indexes are used for less frequently used multiple-key tags. Stand-alone, or .idx indexes are used for temporary or infrequently used single-key indexes, and are available primarily for backward compatibility.

The following table is a summary of the three index types, how they are named, the number of keys they can contain, and the character limitations for each.

Visual FoxPro Index Types

Index type | Description | Number of keys | Limits
Structural .cdx | Uses same base name as the table file name; opens with table automatically | Multiple-key expressions, called tags | 240-character limit on evaluated expression
Non-structural .cdx | Must be opened explicitly; uses a different name from the base table name | Multiple-key expressions, called tags | 240-character limit on evaluated expression
Stand-alone .idx | Must be opened explicitly; base name of .idx file is user-defined | Single key expression | 100-character limit on evaluated expression

Using Non-Structural .cdx Indexes

A non-structural .cdx index is useful when you want to create multiple index tags for a special purpose, but don't want to burden your application with maintaining these indexes on an ongoing basis. For example, your application may have a special set of reports that analyzes data based on fields not normally indexed. Your application program can create a non-structural .cdx index with the necessary index tags, run the special reports, then delete the non-structural .cdx file.

To create a non-structural .cdx index tag

  • Use the TAG and OF clauses with the INDEX Command.

You use the OF clause with the INDEX command to direct Visual FoxPro to store the tag in a file other than the structural .cdx index file for the table. For example, the following command creates tags called title and hire_date on the employee table and stores them in a non-structural .cdx file named QRTLYRPT.CDX:

USE employee
INDEX ON title TO TAG title OF QRTLYRPT
INDEX ON hire_date TO TAG hiredate OF QRTLYRPT

Using Stand-Alone Indexes

The stand-alone index file, based on a single key expression, is stored as an .idx file. In contrast to .cdx indexes, which can store multiple key expressions, the .idx index stores only a single key expression.

You typically use stand-alone indexes as temporary indexes, creating or re-indexing them right before you need them. For example, you may have an index that you use only for a quarterly or annual summary report. Rather than include this infrequently used index in the structural .cdx, where it would be maintained every time you use the table, you can create a stand-alone .idx index. You can create as many .idx files as you want for a particular table.

To create a stand-alone .idx index

  • Use the COMPACT clause of the INDEX Command.

    -or-

  • Use the COPY TAG Command.

Using the INDEX command with the COMPACT clause creates a new stand-alone index in a small, quickly accessed index file. You can omit the COMPACT clause if you want to create a non-compact stand-alone .idx file for compatibility with the older FoxBASE+® and FoxPro® version 1.0 index formats.

The following code creates a stand-alone .idx file on order_date in the orders table, sets the order to the new index, then opens a Browse Window showing the orders in order_date sequence:

USE ORDERS
INDEX ON order_date TO orddate COMPACT
SET ORDER TO orddate
BROWSE

You can use the COPY TAG command to generate a stand-alone index file from an index tag in an existing .cdx file. For example, you may find that one of the indexes you currently maintain in the structural .cdx is used only for quarterly or annual reports. The following code creates a stand-alone index from a tag birth_date in the employee table:

COPY TAG birth_date to birthdt COMPACT

After you've created a stand-alone index from a tag in a .cdx file, you'll typically delete this now unneeded tag from the .cdx file. The next section describes deleting an index.

See Also

Setting Record Order at Run Time | Deleting an Index | Working with Records | Index Creation Based on Expressions | Creating One Index | Ordering by Multiple Fields | Index Creation for Tables


Deleting an Index

You can delete indexes you're no longer using by deleting the tag within the .cdx file, or by deleting the .idx file itself for stand-alone indexes. Deleting unused index tags improves performance by removing the need for Visual FoxPro to update unused tags to reflect changes in a table's data.

Deleting a Tag from the Structural .cdx File

You can remove a tag from the structural .cdx file using the Table Designer or the language.

To delete an index tag in the structural .cdx

  • In the Table Designer, use the Index tab to select and delete the index.

    -or-

  • Use the DELETE TAG Command.

    -or-

  • Use the DROP PRIMARY KEY or DROP UNIQUE TAG clauses of the ALTER TABLE – SQL Command.

For example, if your employee table contained a tag called title, you could delete it using the following code:

USE employee
DELETE TAG title

If the tag you wanted to delete was the primary key for the employee table, you could use the ALTER TABLE command:

USE employee
ALTER TABLE DROP PRIMARY KEY

Deleting a Tag from a Non-Structural .cdx File

A non-structural .cdx index and its tags are not visible in the Table Designer. You use the language to delete a tag from a non-structural .cdx file.

To delete an index in a non-structural .cdx file

  • Use the OF clause of the DELETE TAG Command.

You use the OF clause with the DELETE TAG command to direct Visual FoxPro to delete a tag from a .cdx other than the structural .cdx file. For example, if you have a non-structural .cdx file named QRTLYRPT.CDX with a tag called title, you could delete the title tag with the following command:

DELETE TAG title OF qtrlyrpt

You delete all the tags in a structural or non-structural .cdx file with the ALL clause of the DELETE TAG command.

Deleting a Stand-Alone .idx Index File

Because a stand-alone index file contains only a single index key expression, you delete the expression by deleting the .idx file from disk.

To delete a stand-alone .idx file

  • Use the DELETE FILE Command.

For example, the following code deletes the stand-alone .idx index file Orddate.idx:

DELETE FILE orddate.idx

You could also use a utility, such as Windows Explorer, to delete an unneeded stand-alone .idx file.

See Also

Deleting an Index | Index Creation Based on Expressions | Working with Records | Table Designer | Creating One Index | Creating Multiple Indexes | Ordering by Multiple Fields | Index Creation for Tables


Index Creation Based on Expressions

You can increase the power of your applications by creating indexes based on expressions. These expressions can be simple or complex, depending upon what you want to accomplish.

Indexing on Simple Expressions

Simple index expressions are indexes based on single fields, or on the concatenation of two or more character fields to form a multifield key. For example, you might want to create an index for the Customer table in the TasTrade database based on the expression:

country + region + cust_id

When you browse the Customer table sorted by this index tag, you see the customers ordered by country, then region, then customer ID.

Preventing Duplicates in a Combination of Fields

If you want to prevent duplicating values across multiple fields, you can create a primary or candidate index based on an expression combining multiple fields.

For example, you may have a table that stores the area code and phone number in two columns:

Area Code | Phone Number
206 | 444-nnnn
206 | 555-nnnn
313 | 444-nnnn

Both the area code field and the phone number field contain values that duplicate the values in other rows. However, no phone numbers are duplicated, because it is the combination of the two fields that makes up the value. Yet, if the primary or candidate index specified both columns in the index expression, the rows in the example would not be considered duplicates. If you attempted to enter a value that was exactly the same area code and phone number as one of the existing rows, Visual FoxPro would reject the entry as a duplicate.

Using Null Values in Index Expressions

You can create indexes on fields that contain null values. Index expressions that evaluate to .NULL. are inserted into the .cdx or .idx file before non-null entries. All null values are placed at the beginning of the index.

The following example demonstrates one effect of indexing null values. This is the state of the table before the index is applied:

Null values appear in the SocSec field for two records.

The value .NULL. in two records represents the fact that Social Security numbers for Anne Dunn and Alan Carter are either unknown or unavailable. You then create an index with the Social Security number using the following example:

INDEX ON SocSec + LastName + FirstName TAG MyIndex

When you view the table sorted by this index, you see the sort order as shown in the following figure.

After indexing on SocSec, records containing null SocSec values appear first.

When the index expression contains null values, the records whose SocSec values are .NULL. are sorted first (by LastName), followed by the records whose SocSec values are non-null. Notice that there are two entries for Alan Carter. Because record 5 contains a null value, record 5 is indexed before record 2.

Indexing on Complex Expressions

You can also create indexes based on more complex expressions. Visual FoxPro index key expressions can include Visual FoxPro functions, constants, or user-defined functions.

The expression you create must evaluate to no more than 100 characters for a stand-alone (.idx) index or 240 characters for a .cdx index tag. You can use fields of different data types together in a single tag by converting the individual components of the expression to character data.

To take advantage of Rushmore Query Optimization, the index expression must exactly match the criteria.

Using Visual FoxPro Functions in an Index Tag

You can use Visual FoxPro functions in an index tag. For example, you can use the STR( ) function to convert a numeric value into a character string. If you wanted to create an index tag for the customer table that combined the cust_id field with the maxordamt field, you could convert the maxordamt field from a Currency field with a width of 8 to an 8-character field with 2 decimal places using the following code:

INDEX ON cust_id + STR(maxordamt, 8, 2) TAG custmaxord

If you want to reduce the size of indexes for fields with integer values, you can convert the integer values to a binary character representation using the BINTOC( ) function. You can also convert the binary values to integer values using the CTOBIN( ) function.

If you want to create an index to sort a table in chronological order, you can use the DTOS( ) function to convert a date field to a character string. To access the employee table by hire_date and emp_id, you can create this index key expression:

INDEX ON DTOS(hire_date) + emp_id TAG id_hired

Including Stored Procedures or User-Defined Functions

You can increase the power of your index by referencing a stored procedure or a user-defined function in your index expression. For example, you can use a stored procedure or a UDF to extract the street name from a single field that includes both the street number and street name. If the street number is always numeric, the stored procedure or UDF can return the character portion of the field and pad the field with spaces as needed to create a constant-length index key. You can then use this index key to access records in the table in street-name order.

You may prefer to use a stored procedure rather than a UDF in your index tag, if your table is associated with a database. Because a UDF is stored in a file that is separate from the database, it is possible to move or delete the UDF file, which then causes the index tag referencing the UDF to become invalid. In contrast, stored procedure code is stored in the .dbc file and can always be located by Visual FoxPro.

Another benefit to using a stored procedure in an index tag is that referencing a stored procedure guarantees that the index is based on the exact code you specify. If you use a UDF in your index expression, any UDF that is in scope at the time of indexing and has the same name as the UDF referenced in your index will be used.

Note Exercise care when referencing a stored procedure or UDF in an index expression, as it increases the time required to create or update the index.

Using Data in a Field in Another Table

You can create an index tag that refers to a table open in another work area. It's wise to use a stand-alone index (.idx) for any tag that refers to more than one table. This is because if you were to include a tag referring to another table in a structural .cdx file, Visual FoxPro wouldn't allow you to open the table until you opened the table referenced in the index tag.

See Also

Deleting an Index | Accessing Records in Descending Order | Working with Records | STR( ) Function | BINTOC( ) Function | Filtering Data | Creating One Index | Creating Multiple Indexes | Ordering by Multiple Fields | Index Creation for Tables


Accessing Records in Descending Order

You can view records in descending order by creating a descending index, or by reading an existing index in descending order.

To create a descending index

  • In the Index tab of the Table Designer, choose the arrow button to the left of the Name box so that the arrow points down.

    -or-

  • Use the DESCENDING clause with the INDEX Command to create a descending index.

To create a compound structural index file, you can use either method. To create other types of index files, you can use the second method. For example, you could create a new descending index ordering your product table from highest to lowest unit_price and browse the table in the new order with the following code:

USE products
INDEX ON unit_price TAG unit_price DESCENDING
BROWSE

To read an existing index in descending order

  • Use the DESCENDING clause of the SET ORDER Command to read an existing index in descending order.

Reading an existing index in descending order enables you to leverage an existing index rather than create a new one. For example, you may have already created an index ordering your product table by unit_price with the following code:

USE products
INDEX ON unit_price TAG unit_price

By default, the order is ascending. You could browse the table in descending order with the following code:

USE products
SET ORDER TO unit_price DESCENDING
BROWSE

The previous examples focus on accessing information in descending order. Both the SET ORDER and INDEX commands also offer an ASCENDING clause. You can combine these two commands to gain tremendous flexibility in your application. For example, if you use the ASCENDING or DESCENDING clause to create an index in the most frequently used order, you can then use the opposite clause with the SET ORDER command to view or access the information in the opposite order, when that order is more convenient.

See Also

Index Creation Based on Expressions | Filtering Data | Working with Records | Table Designer | Creating One Index | Creating Multiple Indexes | Ordering by Multiple Fields | Index Creation for Tables


Filtering Data

You can limit the records you access to only the data you want by using a filtered index. When you create a filtered index, only records that match the filter expression are available for display and access.

To filter data using a filtered index

  • In the Table Designer, select the Index tab and enter a filter expression in the Filter box for the index you want to filter.

    -or-

  1. In the Project Manager, select the table you want to add an index to and choose Modify.
  2. In the Indexes tab, create or select an index.
  3. In the Filter box, enter a filter expression.

    For example, try creating a filter that selects only the records for customers in Canada:

    customer.country = "Canada"
  4. Choose OK.

    -or-

  • Use the optional FOR clause with the Index command.

If you include the optional FOR clause with the INDEX command, the index file acts as a filter on the table. Index keys are created in the index file for just those records that match the filter expression. For example, if you were preparing a mailing to go to the sales representatives in your company, and you wanted to sort the mailing by country, you could create an index that filtered the employee table so that only the records for sales representatives appeared, ordered by their country and their last name. The following code creates a filtered index and displays the filtered data in a Browse window:

USE employee
INDEX ON country+last_name FOR title = "Sales Representative" ;
TAG reps_cntry
BROWSE

When you view the Browse window, only the sales representatives are shown; the records for other employees do not appear at all in the Browse window.

A filtered index builds an index only for records that match the filter expression.

Filtering Data Temporarily

You can use the SET FILTER Command to filter data temporarily, without building a special filtered index. This command is particularly useful when you want to specify a temporary condition that records in a table must meet in order to be accessible. To turn off the filter for the current table, you can issue SET FILTER TO without an expression. For example, you could issue the following command to filter the customer table to show only the customers in Germany:

USE customer
SET FILTER TO country = "Germany"
BROWSE

The SET FILTER command accepts any valid Visual FoxPro logical expression as the filter condition. Once you issue the SET FILTER command, only the records that satisfy the filter condition are available in the table. All commands that access the table respect the SET FILTER condition. You can set a separate filter for every open table.

See Also

Accessing Records in Descending Order | Enhancing the Efficiency of Indexes | Working with Records | Table Designer | INDEX Command | Creating One Index | Creating Multiple Indexes | Ordering by Multiple Fields | Index Creation for Tables


Enhancing the Efficiency of Indexes

You can improve the performance of indexed tables by keeping indexes current and using optimizable expressions in your indexes.

Rebuilding an Active Index File

Index files become outdated when you open a table without opening its corresponding index files and make changes to the key fields in the table. Index files can also become invalid as a result of a system crash, or potentially by accessing and updating a table from a program other than Visual FoxPro. When index files become outdated, you can update them by re-indexing with the REINDEX command.

To rebuild an active index file

  • From the Table menu, choose Rebuild Indexes.

    -or-

  • Use the REINDEX Command.

For example, the following code updates the index file for the Customer table:

USE customer
REINDEX

REINDEX updates all index files open in the selected work area. Visual FoxPro recognizes each index file type (compound index .cdx files, structural .cdx files, and single index .idx files) and re-indexes accordingly. It updates all tags in .cdx files, and updates structural .cdx files, which open automatically with the table.

You can also update outdated index files with the REINDEX command.

Re-Indexing at Run Time

Re-indexing takes time, particularly when you're re-indexing large tables. You should re-index only when necessary. You can enhance performance by re-indexing during the initialization or termination portion of your program, rather than performing indexing maintenance during the main portion of an application.

Using Indexes to Optimize Queries

You can use indexes to speed queries and other operations. For information on creating Rushmore-optimizable index expressions, see Optimizing Applications.

See Also

Filtering Data | Working with Multiple Tables | Working with Records | Working with Table Aliases | Creating One Index | Creating Multiple Indexes | Ordering by Multiple Fields | Index Creation for Tables


Establishment of Persistent Relationships with Indexes

Indexes are used to establish persistent relationships between tables in a database. Persistent relationships are relationships between database tables that are stored in the database file and are automatically used as default join conditions in the Query and View Designers. Persistent relationships are also displayed in the Database Designer as lines joining table indexes, and as default relationships when you use the tables in the data environment.

Unlike temporary relationships set with the SET RELATION Command, persistent relationships do not need to be re-created each time you use tables. However, because persistent relationships do not control the relationship between record pointers in tables, you will use both temporary SET RELATION relationships as well as persistent relationships in developing Visual FoxPro applications. For more information on setting persistent relationships, see Developing Databases.

See Also

Setting Temporary Relationships Between Tables | Working with Records | Working with Table Aliases | Working with Multiple Tables | Enhancing the Efficiency of Indexes


Working with Queries

When your application includes tables, you can select and display data from those tables using queries. You can use queries for various tasks:

  • Answering a question quickly. For example, you can find out information such as:
    • Customer name and address associated with a particular ID number
    • Number of outstanding orders
    • Number of customers with overdue balances
    • Region or salesperson with the best sales record
  • Viewing a relevant subset of your data
  • Organizing and generating data for a report. You can also run reports separately without using a query.

You can create queries from tables, define and organize query results, collect user input using queries, and customize queries. You can also direct queries to different destinations so that you can use them in other parts of your application.

In This Section

Creating Queries
Describes the different methods you can use to create queries.
Querying Multiple Tables and Views
Describes how to create queries from multiple tables.
Controlling Record Selection with Joins
Describes how to use join conditions between tables to expand or narrow results.
Defining Query Results
Describes how you can define the data appearing in the results of a query.
Organizing Query Results
Describes how you can organize the data results appearing in the query output.
Customizing Queries
Describes ways to customize queries in the Query Designer, such as narrowing or expanding queries, eliminating duplicate queries, extracting percentage of top records, and adding expressions for filtering.
Customizing Queries Using SQL SELECT Statements
Describes how to customize queries by viewing and editing the SQL SELECT statement generated for views by the View Designer.
Collecting User Input with Queries
Describes how you can collect user input from a form to use in SQL SELECT statements for queries.
Running Queries
Describes how to run queries after they are defined, and explains the different destinations for directing the results.

Related Topics

Working with Data
Provides information to help you create effective applications by analyzing data requirements and designing your application components to meet those needs.
Working with Tables
Discusses how to make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.
Working with Records
Explains how to store data in the table by adding new records and how to change and delete existing records through the interface or by using commands.


Creating Queries

The basic process for creating a query is generally the same regardless of the method you use. The following general process describes creating a query from a single table. You can also create queries from multiple tables.

To create a query

  1. Determine the kind of information you need to find and the table or view from which you need to retrieve the data.
  2. Select the table or view and the corresponding fields that you want data from.
  3. Specify any additional criteria for extracting records from the tables or views.
  4. Generate the query and direct the results to an output source.

When you have created a query you want to keep, you can save it by giving it a name. Queries are stored as files with the .qpr extension.

You can use different methods to create queries:

  • Use the Query Wizard to guide you through the steps of creating queries.
  • Use the Query Designer to create and customize queries quickly.
  • Use SQL SELECT statements, which offer more powerful and flexible ways to generate queries using code.

Creating Queries Using the Query Wizard

If you want help with creating queries, use the Query Wizard. The wizard prompts you to select the tables or views that you want information from and creates a query based on your answers to a series of questions. For more information about the wizard, press the F1 key for Help while you are using the wizard or see Query Wizard.

To create a query using the Query Wizard

  1. Open a free table, or in Project Manager, open a database or a database table.
  2. On the Tools menu, point to Wizards, and click Query.
  3. Select Query Wizard and click OK.
  4. Follow the instructions on the wizard screens.

You can also begin creating a query in the Query Wizard, save the query, and then use the Query Designer to modify it.

Creating Queries Using the Query Designer

If you do not need help with creating your query, you can use the Query Designer. The Query Designer provides a way for you to search for records that meet specified criteria for retrieving information stored in tables and views. You can also organize and group the records as needed and create reports, tables, and graphs based on the results. For more information, see Query and View Designers.

Selecting Tables for Queries

If you are creating queries from free tables or views, you can select the tables or views after starting the Query Designer. However, if you want to select tables or views from a database, open the database before starting the Query Designer. If your tables, databases, or views are in a project, open the Project Manager before starting the Query Designer. For more information about using multiple tables and views, see Querying Multiple Tables and Views.

When adding more than one table to your query, you can specify join conditions to modify the scope of the results returned. Visual FoxPro displays the Join Condition dialog box for you to specify the join condition for each additional table you add to your query. For more information specifying join conditions, see Controlling Record Selection with Joins, Join Conditions for Tables, Queries, and Views, and Join Condition Dialog Box.

To select a free table for a query

  1. From the File menu, click New.
  2. In the New dialog box, click Query, and then New File.
  3. In the Add Table or View dialog box, click Other.
  4. Select a table, and click Close.

To select a database table for a query

  1. Open either a stand-alone database, or in Project Manager, select a database.
  2. On the File menu, click New.
  3. In the New dialog box, click Query, and then New File.
  4. In the Add Table or View dialog box, select a database table, and click Add.
  5. When you are finished selecting tables, choose Close.

    The tables appear on the Query Designer surface.

You can also create queries by using the CREATE QUERY command to open the Query Designer. For more information, see CREATE QUERY Command.

Instead of using the automatically generated alias when you add a table or view, you can specify an alias for each table you use by typing it in the Alias box that appears in the Add Table or View dialog box.

Removing and Adding Other Tables

You can remove tables from and add other tables to your query.

To remove a table from and add another table to a query

  1. In the Query Designer, click the table you want to remove.
  2. On the Query Designer toolbar, click Remove Table to remove the table and then Add Table to select another table or view you want.

Building Queries in the Query Designer

After selecting the tables you want to use for your query, you can begin building queries in the Query Designer. You can also select tables and create a query in the Query Wizard, save the query, and then use the Query Designer to modify the query.

To build a query using the Query Designer

  1. In the Query Designer, click the Fields tab.
  2. In the Available fields list, select a field, and click Add.

    To select multiple fields, press the SHIFT key while selecting fields, and then click Add.

  3. To specify the order in which fields appear in output, click and hold the vertical double arrow button appearing to the left of the field you want to move in the Selected fields list. Move your mouse to position the field the way you want.

You can customize or define your query further in the Query Designer by performing the following tasks:

  • Change the join condition of the selected tables in the Join tab.
  • Filter results by field in the Filter tab.
  • Organize results by field in the Order By tab.
  • Group results by field in the Group By tab.
  • Select a different type of output in the Miscellaneous tab.

For more information about defining your query, see Defining Query Results. For more information about customizing your query and using the tabs in the Query Designer, see Customizing Queries and Query and View Designers. For more information about organizing the results of your query, see Organizing Query Results.

Adding Comments to Queries

You can also add comments or notes about the query to describe its purpose.

To add a comment to a query

  1. Click the Query Designer surface to bring it into the foreground.
  2. On the Query menu, click Comments.
  3. In the Comment box, type comments you want to make about the query.

Comments that you add to a query are stored with the SQL SELECT statement generated by the Query Designer. You can view comments by clicking the View SQL button on the Query Designer toolbar to open the SQL window. Comments that you insert using the Comment box appear above the SQL SELECT statement and are preceded by an asterisk (*).

Note When you modify comments using the Comment box, changes are made only to the first comment and do not affect any other comments you might manually insert into the SQL window.

For more information about the SQL SELECT statement generated by a query, see SELECT - SQL Command. For more information about customizing queries in the Query Designer and using the SQL SELECT command in the SQL window, see Customizing Queries and Customizing Queries Using SQL SELECT Statements.

See Also

Working with Queries | Defining Query Results | Querying Multiple Tables and Views | Organizing Query Results | Running Queries | Query and View Designers | Updating Data in a View | Creating Views


Querying Multiple Tables and Views

When you need access to information stored in two or more tables, add all the needed tables to the query or view and join them on common fields. You can then search the records in all the tables for the information you need. You can use any combination of database tables, free tables, and local or remote views in your queries.

The term "view" can refer to either an input source or an object you create in the View Designer; therefore, the term "table" is used for both tables and views used as input sources.

Adding Views and Tables to a Query

When you add tables or views to your query, Visual FoxPro suggests a possible join between the tables or views, based on matching field names.

For example, if you add the Customer table in the Visual FoxPro ...\Samples\Data directory to the Query Designer, and then add the Orders table, Visual FoxPro suggests a join between the tables based on the matching fields Customer.cust_id and Orders.cust_id.

If you are using a database that contains persistent relationships defined between the views or tables within it, Visual FoxPro uses the existing relationships as default joins.

If you want to add database tables or views to your query, you may need to open the appropriate database to make them available.

To add a table or view to a query

  1. In the Query Designer toolbar, choose Add Table.
  2. In the Add Table or View dialog box, select the database you want to use, choose Tables or Views, select the table or view you want to add, and choose OK.

    -or-

    If you want to add a table that is not part of the database, choose Other, locate the table in the Open dialog box, and choose OK.

  3. In the Join Condition dialog box, verify the suggested join and choose OK.

    If Visual FoxPro cannot suggest a likely match between fields, select the matching fields in the Join Condition dialog box yourself.

See Also

Add Table or View dialog box | Join Condition dialog box | Controlling Record Selection with Joins | Customizing Queries | Creating Queries | Creating Queries | Running Queries


Controlling Record Selection with Joins

When you have multiple tables in a query or view, you can control which records the query or view retrieves by adding or altering join conditions between the tables. Working with joins is similar for both queries and views; therefore, the procedures use queries as examples. Although you can run a query or view without joins, the results usually have little practical value and might require large amounts of time to process.

For more information about join conditions, see Join Conditions for Tables, Queries, and Views. For more information about creating queries and views, see Creating Queries and Creating Views.

Adding Join Conditions

Joins usually appear automatically when you add tables to the query or view. However, if the field names of the related fields do not match, you might need to specify the join you want to have for the table you add using the Join Condition dialog box in the Query and View designers.

The process for adding a join is similar between the Query and View designers. The following procedure describes adding a join in the Query Designer.

To create a join between tables using the Query Designer

  1. Create or open a query.
  2. Add a table to the query so that you have two or more tables.
  3. On the Query Designer toolbar, click Add Join.
  4. In the Join Condition dialog box, select the related field names in the two tables.
    Note Set joins for columns only if they have the same size and data type.
  5. Select a join type and click OK.

You can also add joins for tables that already appear on the Query or View designer surface by clicking and dragging the mouse between the fields in the tables or choosing the Add Join button on the Query or View designer toolbar to display the Join Condition dialog box. You can also create a join type using the using the FROM clause in the SQL SELECT statement.

For more information about the Join Condition dialog box, see Join Condition Dialog Box. For more information about SQL SELECT statements generated by the Query and View designers, see Creating Queries, Creating Views, and the SELECT - SQL Command.

For example, suppose you wanted to retrieve order information, including information about the customer who placed the order. The following example creates a view using two tables, Customers and Orders. Both the Customer and Orders tables have a customer ID field. The tables are related based on an inner join, which specifies that the results include only those rows from the Customer table that match one or more records from the Orders table.

The following code opens the sample database called TestData.dbc, creates a view using the CREATE SQL VIEW command as described in the example, and uses the FROM clause to specify the join condition as described:

OPEN DATABASE testdata
CREATE SQL VIEW cust_orders_view AS ;
   SELECT * FROM testdata!customer ;
      INNER JOIN testdata!orders ;
      ON customer.cust_id = orders.cust_id

Modifying Join Conditions

You can modify existing joins in the following ways:

  • Choose a different join type to modify the scope of the records returned.
  • Select different fields in the table for the join.
  • Change the comparison operator.
  • Change the order of joins

The process for modifying a join is similar for both the Query and View designers. The following procedure describes modifying a join in the Query Designer.

To modify a join

  1. Open a query containing the tables with joins that you want to modify.
  2. In the Join tab of the Query Designer, select the join, and change the join conditions as needed.

You can also modify join types using FROM clause in the SQL SELECT command. For more information about SQL SELECT statements generated by the Query and View Designers, see Creating Queries, Creating Views, and the SELECT - SQL Command.

Removing Join Conditions

You can remove joins from between tables. The process for removing a join is similar for both the Query and View designers. The following procedure describes removing a join in the Query Designer.

To delete a join

  1. Open the query that contains the tables with the join you want to remove.
  2. In the Join tab of the Query Designer, select the join condition, and click Remove.

You can also select the join line that you want to remove between two tables on the Query or View Designer surface. On the Query menu, click Remove Join Condition.

See Also

Working with Queries | Creating Queries | Querying Multiple Tables and Views | Customizing Queries | Running Queries | Logical Operators | Join Condition Dialog Box


Defining Query Results

After you have opened the Query Designer and selected the table or view that contains the information you want, you can define your results. At a minimum, you need to select the fields you want. You can also define your results by setting the order the selected fields appear and setting filters to select which records appear.

Selecting Fields You Want

Before you can run a query, you must select some fields to include in the results. In some cases, you might want to use all the fields from the table or view. At other times, you might want to focus the query on a few selected fields, such as fields you want to include in a report.

Be sure to include any fields you might want to use to sort or group the results of your query. When you select the fields, you can also set the order they appear in your output.

Use the Fields tab in the lower pane of the Query Designer to select the fields you want to include in the results of your query.

To add a field to the query output

  • Select the name of the field and choose Add.

    -or-

  • Drag the field name to the Selected fields box.

Selecting All Fields for Output

You can select all of the fields by name or use the asterisk wild card. If you select the fields by name, the exact names of the fields are included in the query. If you run the query after adding fields to the table, the new fields are not included in the results.

If you use the wild card, the asterisk is included in the query and includes all fields that are in the table at the time of the query. If the table structure has changed since the query was created, the new fields also appear in the query results.

To add all available fields to a query at once

  • Choose Add All to add fields by name.

    -or-

  • Drag the asterisk at the top of the table into the Selected fields box.

Displaying an Alias for a Field

You can make your query results easier to read and understand by adding a descriptive caption to a results field. For example, you might want to display the word "SumMaxOrd" at the top of the results column instead of the field name or expression, SUM(MaxOrdAmount).

To add an alias for a field

  1. In the Functions and expressions box, type the field name, and then type AS and the alias, as in this example:
    SUM(maxorderamt) AS SumMaxOrd
  2. Choose Add to place the field with the alias in the Selected fields box.

Setting the Order for Output Fields

The order that fields appear in the Fields tab determines the order of the columns of information in your query output.

To change the column order of the query output

  • Drag the mover box, located to the left of a field name, up or down.

If you want to change the order that rows of information will be sorted, use the Order By tab instead.

Selecting the Records You Want

Selecting the records you want to find is the key step that determines the results of your query. With the Filter tab in the Query Designer, you can formulate the WHERE clause of a select statement to tell Visual FoxPro which records to search for and retrieve.

You may want to find a specific subset of data to include in a report or other output: for example, all customers with outstanding balances, all customers in a specific region or postal code, and so on. To see only the records you want, enter a value or range of values to compare the records against.

In Visual FoxPro, you use the Filter tab to specify which field you want to use for selecting records, choose a comparison criterion, and enter an example of the value you want the field to be compared to.

To specify a filter

  1. From the Field Name list, choose a field you want to use as the basis for selecting records.
    Note You can't use General or Memo fields in a filter.
  2. From the Criteria list, choose the type of comparison to use.
  3. Enter the comparison criterion in the Example box.
    • Use quotation marks only if the string is the same as the name of a field in a table in the query; otherwise, do not enclose character strings in quotation marks.
    • If you use dates, do not enclose them in braces.
    • Place a period before and after a logical literal (.T.).
    • If you enter a field name from a table in the query, Visual FoxPro will recognize it as a field.
  4. If you want capitalization to be ignored in searches on character data, select the Case button.

If you want to reverse the meaning of a logical operator, select the Not button. For example, if you want to find customers in all regions except Washington, use the selection expression in the following example:

Customer.region Not Like WA

To further tune your search, you can add more filters in the Filter tab. For more information, see the topic Fine-Tuning Your Search.

If you are using more than one table or view in your query, you can expand the records you select by the join type you choose.

Selecting a Number or Percentage of Records

If you only need a certain number or percentage of records from the result set that your query would return, you can use the Top property on the Miscellaneous tab in the Query or View Designers or you can add a TOP clause to your SELECT - SQL statement. The number you provide in a TOP clause can range from 1 to 32,767. For a percentage, you can use from 0.001 to 99.99.

For example, if you want to select the top 10 customers with the highest order amounts, you can specify a GROUP BY on CUST_ID to show one aggregate record for each customer and sort by ORDER_AMT in the ORDER BY clause. To get a true TOP 10, you need to specify a descending sort on the ORDER_AMT so that the records with the highest order amounts appear first in the results. If you use an ascending sort, the result records are ordered from the least order amount to the most. The top records you select from the result set would actually have the lowest values.

SELECT TOP 10 *;
FROM testdata!customer INNER JOIN testdata!orders ;
ON Customer.cust_id = Orders.cust_id;
GROUP BY Customer.cust_id;
ORDER BY Orders.order_amt DESC

Specifying Destinations for Query Results

By using clauses of the SELECT - SQL statement, you can specify several destinations to store your query results.

To send results to this destination | Use this clause
Separate table | INTO TABLE mytable
Array | INTO ARRAY aMyArray
Temporary table | INTO CURSOR mycursor
Active window | TO SCREEN
Browse window | The default if no other destination is specified.

Once the results are stored, you can use commands to control how the stored results are integrated for display or printing.

See Also

Working with Queries | Creating Queries | Organizing Query Results | Fields Tab, Query and View Designers | Querying Multiple Tables and Views | Updating Data in a View


Organizing Query Results

With the output of your query defined, you can now organize the records that appear in your results by ordering and grouping on the output fields. If you want, you can also filter the groups that appear in your results.

Ordering Query Results

Ordering determines the order in which records or rows will be sorted when they appear in the output of your query. For example, you could sort records by State and then by City, or sort them in ascending order based on the outstanding account balance.

Use the Order By tab to set the sort order for your query. The sort order determines the order in which rows or records will appear in your query output.

First select the fields you want to use from the Selected Fields box and move them to the Ordering Criteria box. Then arrange the fields in the order you want them to appear in the query results.

To set ordering criteria

  1. In the Selected fields box, select a field name.
  2. Choose Add.

To remove ordering criteria

  1. Select one or more fields that you want to remove.
  2. Choose Remove.

The order in which fields appear in the Ordering criteria box determines the order of importance when the query results are sorted. The first field determines the primary sort order.

For example, if the first field in the Ordering criteria box is Customer.region and the second field in the Ordering criteria box is Customer.city, the results will be ordered by Customer.region. If more than one record in the customer table has the same region field value, these records are additionally ordered by Customer.city.

To adjust the importance of a sort order field, use the button to the left of the field to drag the field to the desired location in the Ordering criteria box.

You can sort in ascending or descending order by setting the buttons in the Order options area. Each order field appears in the Output fields box on the Filter tab with an up arrow or down arrow next to it, indicating whether the sort on that field is to be made in ascending or descending order.

Grouping Query Results

Grouping consolidates or gathers similar records into one record so you can perform calculations based on groups of records. For example, you might want to find the sum of all orders to a specific region. Instead of looking at all the records individually, you can group all the records from the same region into one record, and get the sum of all the orders from that region. To control how records are grouped, use the Group By tab in the Query Designer.

Grouping is most useful when used in conjunction with an aggregate function, such as SUM, COUNT, AVG, and so on.

For example, suppose you want to see the total dollar amount of orders for each customer ID number in your orders table. You need to group all the order records for a given customer ID into one record, and find the sum of the order amounts.

You first use the Fields tab to add the expression SUM(Orders.order_net) to the output of your query, then use the Group By tab to group the results by customer ID number. The results show total net orders for each customer:

To set grouping options

  1. In the Fields tab, type the expression in the Functions and expressions box.

    -or-

    Choose the dialog button to use the Expression Builder to enter an expression in the Functions and expressions box.

  2. Choose the Add button to place the expression in the Selected fields box.
  3. In the Group By tab, add the expression to group results by.

You can also set a filter on the grouped results.

Selecting the Groups You Want

To set a filter on grouped or consolidated records rather than on individual records, choose Having on the Group By tab. You can use a field name, an aggregate function on a field name, or another expression in the Field Name box.

Building on the previous example, you could use the query that shows total sales by customer number, then use the Having button to restrict the output to customers having more than $50,000 in net orders:

To set a Having option on a group

  1. In the Group By tab, choose Having.
  2. In the Having dialog box, select a function and field name in the Field Name field.
  3. Choose OK.

See Also

Working with Queries | Defining Query Results | Running Queries | Customizing Queries | Order By Tab, Query and View Designers | Querying Multiple Tables and Views | Updating Data in a View | Creating Queries


Customizing Queries

Other options available with the Query Designer make it easy to further customize your queries. You can use filters to expand or narrow your search. You can also add expressions to perform calculations or functions on the data in your fields.

Fine-Tuning Your Search

You might find that you want more control over the results returned by a query. For example, you might want to find records that meet more than one criterion, such as customers from a given state who have outstanding balances greater than $1,000. Or, you might need to retrieve records that meet either one criterion or another: customers from Washington or from California. In either case, you need to add more statements to the Filter tab.

In Visual FoxPro, filter statements are automatically combined with a logical AND when you enter them in successive rows in the Filter tab. If you want to retrieve records that meet two or more alternative conditions, you can insert a logical OR operator between rows with the Add Or button.

Narrowing Your Search

If you want your query to retrieve only records that meet more than one criterion, list the criteria on separate lines in the Filter tab. Criteria in a series are combined with an implicit AND statement, so that only records that meet all the criteria listed will be retrieved.

For example, suppose you are searching an employee table, and you want to see all the Sales Representatives in the United Kingdom. You would enter the two conditions you are searching for on separate lines.

To set AND conditions

  • Enter filters in the Filter tab, and choose AND in the Logical column.

Expanding Your Search

If you want your query to retrieve records that meet any of a series of filters, combine filters by inserting OR conditions between them.

For example, you might want to search for customers who live in Washington or California.

To set OR conditions

  • Select a filter, and then choose OR in the Logical column.

Combining Conditions

You can also combine AND and OR conditions to select specific sets of records.

For example, you might want to retrieve records for customers from Washington or California who have maximum order amounts larger than $5,000.

Eliminating Duplicate Records from a Query

Duplicate records are records in which every field of the result matches. If you want to remove duplicate records from the query results, select the No Duplicates box on the Miscellaneous tab. Otherwise, make sure the No Duplicates box is cleared.

Note If No Duplicates is selected, the word DISTINCT precedes the fields in the SELECT portion of the SELECT command.

Retrieving a Number or Percentage of Top Records

You can specify how many or what percentage of records with the highest or lowest values in a particular field you want the query to return. For example, the query can display those records with the 10 highest or lowest values in a specific field or the records with the highest or lowest 10 percent of values in the field.

Using the Top setting on the Miscellaneous tab, you can either set a number or a percentage of records you want to see. To set whether you are choosing the top or bottom, you set the sort order for your query to either descending to see the top or ascending to see the bottom.

To retrieve a number or percentage of top records

  1. In the Order By tab, select the field you want to retrieve top values for, then choose Descending to display the highest values or Ascending to display the lowest values. If you are sorting on additional fields, place them after the top values field in the order by list.
  2. In the Miscellaneous tab, type the number for the percentage or the number of highest or lowest values you want retrieved in the Number of records box. To display a percentage, choose Percent.
  3. If you do not want duplicate records included in the number or percentage, choose No duplicates.

Adding Expressions to a Query

You can create more flexible and powerful queries if you incorporate expressions, either in a filter or as result fields.

Adding Expressions to Results

You can also include functions and expressions in the output of your query, using the box at the bottom of the Fields tab. If you want to name the field holding the expression, you can add an alias.

For example, you might want your query results to include the sum of all order amounts with the alias Total:

SUM(orders.order_amt) AS Total

You can type an expression directly into the box or use the Expression Builder on the Fields tab.

To add an expression to your query output

  1. In the Fields tab, type the expression in the Functions and Expressions box.

    -or-

    Choose the dialog button to use the Expression Builder and enter an expression in the Functions and expressions box.

  2. Choose the Add button to place the expression in the Selected fields box.
    Note Null values are ignored in calculations. For more information on null values in expressions, search for "Null Values".

Filtering with Expressions

Instead of simply searching for records that match one or more fields, you can use an expression to combine two fields, or perform a calculation based on a field and search for records that match the combined or calculated field.

You can type expressions directly into the Example box. If you want some help, you can use the Expression Builder, which is available from the dialog button next to the Expressions and Functions box in the Fields tab.

For example, using the Orders table, you might want to check total discounts for a customer by combining order amount and order discount in an expression like the following:

Orders.order_amt * Orders.order_dsc

See Also

Working with Queries | Customizing Queries Using SQL SELECT Statements | Running Queries | Organizing Query Results | Expression Builder Dialog Box | Fields Tab, Query and View Designers | Querying Multiple Tables and Views | Updating Data in a View | Creating Queries | Customizing Views


Customizing Queries Using SQL SELECT Statements

When you create a query in the Query Designer, Visual FoxPro actually uses a SQL SELECT statement to retrieve the information from the fields in the tables. SQL SELECT statements offer you a more powerful way to manipulate your query and provide more control over your query results and where the results are stored. To verify your query or add comments, you can display the SQL SELECT statement in the SQL window and modify it to further customize your query.

When you add queries to your application, you can use SQL SELECT statements to combine a variety of data sources, filter records more precisely, manipulate data, and sort the results. You can use SQL SELECT statements with queries created in the Query Designer, views in the View Designer, or in code for an event or procedure in a program (.prg) file. For more information about where you can use SQL SELECT statements and the SQL SELECT command, see Creating Queries and SELECT - SQL Command.

Viewing SQL SELECT Statements Created by Queries

You can view the SQL statement that your query builds in the SQL window at any time while you create your query. By viewing the SQL statement created by the Query Designer, you can make sure the query is properly defined.

To view the SQL SELECT statement created by a query

  1. Create your query using the Query Designer.
  2. On the Query menu, choose View SQL.

The SQL window opens to display the SQL SELECT statement your query created. The first statement is the SQL SELECT statement. For example, you can select all the records from the Customer table in the TasTrade database where the country field contains the value "Canada":

SELECT *;
   FROM tastrade!customer;
   WHERE Customer.country = Canada

The script for the SQL SELECT statement appearing in the SQL window is automatically generated when loading or modifying a query in the Query Designer.

To run the SQL SELECT statement immediately, enter the statement in the Command window. If you want each clause to appear on a separate line in the window, end each line except the last one with a semicolon (;) so that Visual FoxPro processes the command only after the last line.

To include the SELECT statement in code, copy the SQL SELECT statement into a .prg file.

Editing SQL SELECT Statements in the SQL Window

In the SQL window, you can edit the SQL SELECT statement for the query.

Note The Query Designer parses only the first SQL SELECT statement in the SQL window, the clauses directly involved with the SELECT statement, and the first comment appearing in the query. The Query Designer disregards all other text.

To edit the SQL SELECT statement in the SQL window

  1. Create or open a query.
  2. Open the SQL window, and edit the SQL SELECT statement.

You can specify an asterisk, table.*, or a comma-delimited list of fields for the SELECT statement in the SQL window. For example, you can specify the SQL statement as SELECT * FROM or SELECT field1, field2, ... FROM. Your preferences are preserved during the loading or generation of the query. You can also include the same field multiple times in the SELECT list.

For more information about using syntax for the SQL SELECT command, see SELECT - SQL Command.

Loading SQL SELECT Statement Changes into the Query Designer

After editing the SQL SELECT statement in the SQL window, you can reload the changes into the Query Designer.

To update the query in the Query Designer

  • Close the SQL window.

You can also update the query by clicking the Query Designer to bring it to the foreground.

If the Query Designer cannot reload your changes after you make changes in the View SQL window, a dialog box appears and asks the following:

"View/Query designer is unable to reload your changes. Would you like to rebuild content from the designer?"

If you select Yes, your changes are discarded in the SQL window, and Visual FoxPro returns you to the Query Designer. If you select No, Visual FoxPro returns you to the SQL window.

To save a statement that cannot be parsed such as a call to a stored procedure, select No and click the Save button on the toolbar. Visual FoxPro saves the query. You can also click the Save button after entering the command in the SQL window to save the query. You do not need to click the Query Designer window, which causes the Query Designer to try to load and parse the query.

See Also

Working with Queries | Customizing Queries | Collecting User Input with Queries | Running Queries


Collecting User Input with Queries

If you want to collect values that the application user enters from a form, you can create variables to store those values and then use them immediately in the SQL SELECT statement or execute the statement later. For more information about customizing queries using SQL SELECT statements, see Customizing Queries Using SQL SELECT Statements and SELECT - SQL COMMAND.

To collect user input values for immediate use

  • In the SQL SELECT statement, include the name of the form or a reference to the form where appropriate.

The following example illustrates how to collect user input values from a form using a shortcut reference that appears in the WHERE clause of the SQL SELECT statement. The shortcut reference, THISFORM, refers to the currently active form. You should substitute control names for ControlName1 and ControlName2.

SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = ;
    THISFORM.ControlName1.Value ;
   AND customer.region =
THISFORM.ControlName2.Value ;
   GROUP BY customer.postal_code ;
   ORDER BY customer.postal_code,
customer.company_name

To collect user input values for later use

To store user input values from a form when you do not need to use them while the form is active, use variables in code. For example, if you do not want to use references to a control, you can define variables in the code to store the values returned by the control.

  1. Define the variable you want to use for storing the user input value.
  2. In the SQL SELECT statement, include the name of the variable where appropriate.

The following example illustrates how to collect user input values from a form using the variable, cValue, to store the value returned from a control on the currently active form. The shortcut reference, THISFORM, refers to the currently active form. The variable appears in the WHERE clause of the SQL SELECT statement to select the country that matches cValue.

cValue = THISFORM.ControlName.Value
SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = cValue ;
   GROUP BY customer.postal_code ;
   ORDER BY customer.postal_code, ;
     customer.company_name

If you don't define the variable before you run the query, an error message appears stating that the variable couldn't be found. If the variable isn't defined in code, Visual FoxPro assumes that the variable is pre-initialized.

See Also

Working with Queries | Customizing Queries Using SQL SELECT Statements | Creating Queries | Integrating Queries and Reports | Saving a Report as HTML | Creating Reports and Labels


Running Queries

After you finish building your query, you can execute the query to obtain the results. Visual FoxPro executes the SQL SELECT statement generated by the Query Designer, and sends the results to a browse window. For more information about building queries, see Creating Queries.

To run a query from the Query Designer

  1. Open the query in the Query Designer before you run it.
  2. From the Query menu, select Run Query.

Visual FoxPro displays the results of the query in a browse window.

You can also run a query from the Project Manager without opening the query by selecting the name of the query from the Queries node in the file tree view and choosing Run.

Directing the Results of Your Query

You can send the results of your query to a different destination for output, such as a cursor, table, or screen. By default, Visual FoxPro displays the results of your query in a browse window.

When you choose Query Destination on the Query menu, or choose the Query Destination button on the Query toolbar, the Destination dialog box displays, so you can choose where to send your query results.

To choose a query destination

  1. From the Query menu, choose Query Destination.
  2. In the Query Destination dialog box, choose an output destination, and fill out any additional fields as required.

The following table describes destinations for query output.

Output option | Destination
Browse | Display the results of the query in a browse window.
Cursor | Save the results of the query in a temporary read-only table with a name that you specify.
Table | Save the results of the query as a table with a name that you specify.
Screen | Display the results of the query in the main Visual FoxPro window or in the currently active output window.

See Also

Organizing Query Results | Customizing Queries | Browse window | SELECT - SQL COMMAND | Query Destination Dialog Box | Querying Multiple Tables and Views | Updating Data in a View | Creating Queries


Storing Query Results in a Table, Array, or Cursor

You can store your query results in a table, array, or cursor for other uses such as populating forms and printing reports and labels. If you want to store the results only temporarily, send the results to an array or cursor. If you want to store the results permanently, send the results to a table.

To specify a table as the destination

  • Use the INTO clause of the SELECT - SQL statement to specify a destination.

The following example shows an INTO clause for a table:

SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = "Canada" ;
   INTO TABLE mytable

To specify an array as the destination

  • Use the INTO clause of the SELECT - SQL statement to specify a destination.

The following example shows an INTO clause for an array:

SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = "Canada" ;
   INTO ARRAY aMyArray

To specify a cursor as the destination

  • Use the INTO clause of the SELECT - SQL statement to specify a destination.

The following example shows an INTO clause for a cursor named mycursor:

SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = "Canada" ;
   INTO CURSOR mycursor

If you create a table or an array, you can use it like any other table or array in Visual FoxPro. If you create a cursor, you can browse through its contents. The cursor is opened in the lowest available work area. You can access it by using the name you gave it in the SELECT - SQL statement.

The following two procedures describe two common ways to include query results stored in tables and cursors into an application.

See Also

Populating Query Results in a Form Control | Printing Query Results in a Report or Label


Populating Query Results in a Form Control

If you want to display your query results in a form, you can use a table, array, or cursor to populate a grid, list box, or combo box.

To populate a list box or combo box control with a table or cursor

  1. In the Form Designer, modify the form that has the control you want to populate.
  2. Set the RowSourceType property to 3 - SQL Statement.
  3. In the control's RowSource property, enter a SELECT - SQL statement that includes an INTO TABLE or INTO CURSOR clause.

To populate a grid control with a table or cursor

  1. In the Form Designer, modify the form that has the control you want to populate.
  2. In the form's Load event, enter a SELECT - SQL statement that includes an INTO TABLE or INTO CURSOR clause.
  3. Set the grid's RecordSource property to the name of the table or cursor you created in Step 2.
  4. Set the grid's RecordSourceType property to 0 – Table (for a table) or 1 – Alias (for a cursor).

See Also

Storing Query Results in a Table, Array, or Cursor | Printing Query Results in a Report or Label | Displaying Query Results in a Window


Printing Query Results in a Report or Label

If your report or label includes groups or you otherwise need to order the data, you can use the various clauses of the SELECT - SQL statement to get the exact results you need.

To send results to an existing report or label

  • Use the SELECT - SQL statement with a REPORT or LABEL command.

    The following example uses the GROUP BY and ORDER BY clauses as well as the REPORT FORM command:

    SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = "Canada" ;
   GROUP BY customer.region ;
   ORDER BY customer.postal_code, customer.company_name ;
   INTO CURSOR MyCursor
REPORT FORM MYREPORT.FRX

    The following example uses a LABEL FORM command:

    SELECT * ;
   FROM tastrade!customer ;
   WHERE customer.country = "Canada" ;
   GROUP BY customer.region ;
   ORDER BY customer.postal_code, customer.company_name ;
   INTO CURSOR mycursor
LABEL FORM MYLABEL.LBX

While the SELECT - SQL statement is the most flexible method for populating your report or label, it is not the only method.

See Also

Populating Query Results in a Form Control | Displaying Query Results in a Window | SELECT - SQL COMMAND | Integrating Queries and Reports


Displaying Query Results in a Window

If you want to display the results of your SELECT - SQL statement, you can send the results to a window. The Browse window is the default destination for query results and you don't need to include a destination clause. You can also send the results to the main Visual FoxPro window or another active window.

To display results in the main Visual FoxPro window

  • Use the TO SCREEN clause of a SELECT - SQL statement.

To display results in another active window

  • Define a window, show it to activate it, and then run a SQL query or other command that displays results in a window.

This code example shows the definition for a temporary window titled "Top Customers" that displays the names of companies with more than $5,000 in total orders for the year.

Displaying query results in a window

Code Comment
frmMyForm=createobj("form")
frmMyForm.Left = 1
frmMyForm.Top = 1
frmMyForm.Width = 130
frmMyForm.Height = 25
frmMyForm.Caption = "Top Customers"
frmMyForm.Show
 Create and start a temporary window object.
SELECT customer.company_name,;
  SUM(orders.freight) ;
  FROM tastrade!customer,
  tastrade!orders ;
  WHERE customer.customer_id =
  orders.customer_id ;
  GROUP BY customer.company_name ;
  HAVING SUM(orders.freight) > 5000 ;
  ORDER BY 2 DESC
 Enter a SELECT - SQL statement.

See Also

Printing Query Results in a Report or Label | Creating Reports and Labels | SELECT - SQL Command


Working with Views

When you want a customized and updateable data set for your application, you can create and use views. Views combine the qualities of tables and queries by providing a way to extract a set of data from one or more related tables.

You can retrieve data from local or remote data sources by creating and using local and remote views, create views from multiple tables or based on other views, update data from multiple tables, customize views, use views to display data, update views, and move data offline for manipulation.

In This Section

Creating Views
Describes how to create views in general.
Creating Local Views
Describes how to create views from data stored locally.
Accessing Remote Data with Views
Describes how to create views from data stored on a remote server.
Creating a Multitable View
Describes how to access related information that is stored in separate tables by creating or modifying views and adding tables.
Combining Views
Describes how to create views based on other views.
Customizing Views
Describes ways to customize views in the View Designer, such as defining how fields in a view appear, controlling the update method, adding expressions to remote views, prompting for parameters, and setting timeout intervals.
Customizing Views Using SQL SELECT Statements
Describes how to customize views by viewing and editing the SQL SELECT statement generated for views by the View Designer.
Modifying, Renaming, and Deleting Views
Describes how to modify existing views.
Displaying Data with Views
Describes how to use views to display and update data.
Manipulating Offline Data
Offers conceptual information on using Visual FoxPro offline view features to change, collect, and display data outside of the host database.
Optimizing View Performance
Explains how to set performance and data fetching options.

Related Sections

Working with Data

Provides information to help you create effective applications by analyzing data requirements and designing your application components to meet those needs.

Working with Tables

Discusses how to make sure your tables have the structure that your application requires. Data type and index choices are essential to the success of your application.

Working with Records

Explains how to store data in the table by adding new records and that you can change and delete existing records through the interface or by using commands.

Creating Queries
Describes how to create and use queries to select and display data from tables or views.


Creating Views

The basic process for creating a view is generally the same regardless of the method you use and is similar to the way you create queries. For information about creating queries, see Creating Queries.

Note The tables you use must be part of a project or database before you can use the View Wizard or View Designer to create a view.

The following process generally describes how to create a view.

To create a view

  1. Determine whether you need to create a local or remote view.
  2. Specify the tables from which you want to include data in the view and specify their join conditions.
  3. Select the fields in the tables that you want to retrieve data from and specify any additional criteria for retrieving records from those tables.
  4. Specify whether to send changes to the original or base tables that the view was built from.
  5. Generate the view.

When you create a view you want to save, give it a name. Visual FoxPro adds a definition of the view to the current database. The view definition contains the table names, selected fields, and property settings for the view.

When you use the view, Visual FoxPro builds and runs a SQL statement that defines the data set for the view using the view definition. For information about view properties, see Displaying the Structure of a View, DBGETPROP( ) Function, or CURSORGETPROP( ) Function.

You can create two types of views, local and remote views. For more information, see Creating Local Views and Accessing Remote Data with Views. You can also create views from multiple tables. For more information, see Creating a Multitable View.

See Also

Working with Views | Combining Views | Customizing Views | Modifying, Renaming, and Deleting Views | Displaying Data with Views | Manipulating Offline Data | Optimizing View Performance


Creating Local Views

Local views use Visual FoxPro SQL syntax to select information from tables or views stored locally on your computer. You can create a local view using the View Wizard, View Designer, or the CREATE SQL VIEW command.

You can also add one or more remote views to a local view, so that you can access information from Visual FoxPro and remote ODBC data sources using the same view. For more information, see Accessing Remote Data with Views.

You can use different methods to create views:

  • Use the Local View Wizard to guide you through the steps of creating views.
  • Use the View Designer to create and customize views quickly.
  • Use SQL SELECT statements, which offer more powerful and flexible ways to generate views using code.
    Note The tables you want to use must be part of a project or database before you can use the Local View Wizard or View Designer to create a view.

Creating Local Views Using the Local View Wizard

If you want help with creating local views, use the Local View Wizard. The wizard prompts you to select the tables or views from which you want information and creates a query based on your answers to a series of questions. For more information about the wizard, press the F1 key for Help while you are using the wizard or see Local View Wizard.

To create a local view using the Local View Wizard

  1. Open a stand-alone database, or in Project Manager, select a free table, database, or database table.
  2. On the Tools menu, point to Wizards, and click All Wizards.
  3. In the Wizard Selection dialog box, click Local View Wizard, and click OK.
  4. Follow the instructions on the wizard screens.

You can also begin creating a view in the Local View Wizard, save the view, and then use the View Designer to modify it. For more information about the Project Manager, see Project Manager Window.

Creating Local Views Using the View Designer

If you do not need help with creating local views, use the View Designer. The View Designer provides a way for you to search for records that meet specified criteria for retrieving information stored in tables or other views. You can also organize and group the records as needed. For more information about the View Designer, see Query and View Designers.

Selecting Tables for Views

When adding more than one table to your view, you can specify join conditions to modify the scope of the results. Visual FoxPro displays the Join Condition dialog box for you to specify the join condition for each additional table you add to your query. For more information specifying join conditions, see Controlling Record Selection with Joins, Join Conditions for Tables, Queries, and Views, and Join Condition Dialog Box.

To select tables for a local view using the View Designer

  1. Open either a stand-alone database, or in Project Manager, select a database.
  2. On the File menu, click New.
  3. In the New dialog box, click View, and then New File.
  4. In the Add Table or View dialog box, select the table you want to use, and click Add.
  5. When you are finished selecting tables, choose Close.

    The tables appear on the View Designer surface.

Instead of using the automatically generated alias when you add a table or view, you can specify an alias for each table you use by typing it in the Alias box that appears in the Add Table or View dialog box.

You can also open the View Designer using the CREATE SQL VIEW command when a database is open or create a view by using the CREATE SQL VIEW command with the AS clause to specify a SQL statement. For more information, see CREATE SQL VIEW Command.

For example, the following code creates a view called product_view and contains all the fields in the products table:

CREATE SQL VIEW product_view AS SELECT * ;
   FROM testdata!products

When created, the name of the view appears in the Project Manager. If you open the Database Designer, the view is displayed in the same manner as a table in the schema, with the view name in place of a table name.

In the example, the table name is preceded, or qualified, by the table's database name and an exclamation point (!). If you qualify the table name when you create a view, Visual FoxPro searches for the table in the open database list, including current and previous databases, and in the default search path for the table. If you do not qualify a table with a database name in a view definition, the database must be open before you can use the view.

Tip When you create or use a view that appears in the Project Manager, the Project Manager opens the database automatically. If you subsequently use a view outside the project, you must open the database or make sure the database is in scope before you can use the view.

Removing and Adding Other Tables

You can remove tables from and add other tables to your view.

To remove a table from and add another table to a view

  1. In the View Designer, click the table you want to remove.
  2. On the View Designer toolbar, click Remove Table to remove the table and then Add Table to select another table or view you want.

For more information about adding multiple tables to views, see Creating a Multitable View.

Building Local Views in the View Designer

After selecting the tables you want to use for your local view, you can begin building local views in the View Designer. You can also select tables and create a local view in the Local View Wizard, save the view, and then use the View Designer to modify it.

To build a local view using the View Designer

  1. In the View Designer, click the Fields tab.
  2. In the Available fields list, select a field, and click Add.

    To select multiple fields, press the SHIFT key while selecting fields, and then click Add.

  3. To specify the order in which fields appear in output, click and hold the vertical double arrow button appearing to the left of the field you want to move in the Selected fields list. Move your mouse to position the field the way you want.

You can customize or define your view further in the View Designer by performing the following tasks:

  • Change the join condition of the selected tables in the Join tab.
  • Filter results by field in the Filter tab.
  • Organize results by field in the Order By tab.
  • Group results by field in the Group By tab.
  • Specify update criteria in the Update Criteria tab.
  • Select a different type of output in the Miscellaneous tab.

For more information about customizing your view and using the tabs in the View Designer, see Customizing Views and Query and View Designers.

Adding Comments to Views

You can also add comments or notes about the view to describe the its purpose.

To add a comment to a view

  1. Click the View Designer surface to bring it to the foreground.
  2. On the Query menu, click Comments.
  3. In the Comment box, type comments you want to make about the view.

Comments that you add to a view are stored in the database container (DBC). You can view comments by clicking the View SQL button on the View Designer toolbar to open the SQL window. You can modify comments by editing the DBSETPROP( ) function call in the SQL window following the SQL SELECT statement.

For more information about the SQL SELECT statement generated by a view, see SELECT - SQL Command. For more information about customizing views in the View Designer and using the SQL SELECT command in the SQL window, see Customizing Views and Customizing Views Using SQL SELECT Statements.

Running Local Views

After you finish creating the view, you can run it.

To run a view and view results

  • On the Query menu, click Run Query.

    Visual FoxPro displays the results in a browse window.

See Also

Working with Views | Creating Views | Accessing Remote Data | Creating a Multitable View | Modifying, Renaming, and Deleting Views | Displaying Data with Views


Accessing Remote Data with Views

Accessing remote data requires a working connection to a valid remote data source. A valid remote data source is typically a remote server for which you've installed an Open Database Connectivity (ODBC) driver and set up an ODBC data source name. From within Visual FoxPro, you can define a data source and its connections. For more information, see Setting Up an ODBC Data Source.

To retrieve data from a remote data source, use remote views. Remote views use remote SQL syntax to select information from tables stored in an ODBC data source.

Defining a Connection

In Visual FoxPro, you can create and store a named connection definition in a database, which you can then refer to by name when you create a remote view. You can also set properties of the named connection to optimize the communication between Visual FoxPro and the remote data source. When you activate a remote view, the view's connection becomes the pipeline to the remote data source.

Note Before you can create a connection, you must have a database open.

To create a new connection

  1. In the Project Manager, select a database.
  2. Select Connections and choose New.
  3. In the Connection Designer, enter the options that correspond to your server requirements.
  4. From the File menu, choose Save.
  5. In the Save dialog box, enter a name for the connection in the Connection Name box.
  6. Choose OK. You can also create a connection by choosing New from the File menu and selecting the Connection option.

    -or-

  • Open a database and use the CREATE CONNECTION command to open the Connection Designer.

    -or-

  • Use the CREATE CONNECTION command with a connection name.

For example, to create a connection in the testdata database that stores the information needed to connect to the ODBC data source sqlremote, you can enter the following code:

OPEN DATABASE testdata
CREATE CONNECTION remote_01 DATASOURCE sqlremote userid password

Visual FoxPro displays remote_01 as the name of the connection in the Project Manager.

Creating a named connection in your database does not use any network or remote resources, because Visual FoxPro doesn't activate the connection until you use the view. Until you activate the connection, the named connection merely exists as a connection definition stored as a row in the database's .dbc file. When you use a remote view, Visual FoxPro uses the named connection referenced in the view to create a live connection to the remote data source, and then sends the request for data to the remote source using the active connection as the pipeline.

You can optionally create a view that specifies only the name of the data source, rather than a connection name. When you use the view, Visual FoxPro uses the ODBC information about the data source to create and activate a connection to the data source. When you close the view, the connection is closed.

Naming Precedence for Connections and Data Sources

When you use the CREATE SQL VIEW command with the CONNECTION clause, you specify a name that represents either a connection or a data source. Visual FoxPro first searches the current database for a connection with the name you specified. If no connection with the specified name exists in the database, then Visual FoxPro looks for an established ODBC data source with the specified name. If your current database contains a named connection with the same name as an ODBC data source on your system, Visual FoxPro will find and use the named connection.

Displaying ODBC Login Prompts

When you use a view whose connection login information is not fully specified, Visual FoxPro might display a data source -specific box that prompts you for the missing information.

You can control whether Visual FoxPro prompts you for information that was left unspecified at connection time.

To control the display of ODBC login prompts

  1. In the Project Manager, select the name of the connection, and then choose Modify to open the Connection Designer.
  2. In the Display ODBC login prompts area, choose an option.

    -or-

  • Use the DispLogin property of the DBSETPROP( ) or SQLSETPROP( ) functions.

Using an Existing Connection

You can use an existing named connection to create a remote view. You can see a list of the connections available in a database by using the Project Manager or the DISPLAY CONNECTIONS command.

To determine existing connections

  • In the Project Manager, select a database, and then select Connections.

    -or-

  • Use the DISPLAY CONNECTIONS command.

For example, the following code displays the connections in the testdata database:

OPEN DATABASE testdata
DISPLAY CONNECTIONS

Creating a Remote View

Once you have a valid data source or named connection, you can create a remote view using the Project Manager or the language. A remote view is similar to a local view, but you add a connection or data source name when you define the view. The remote view's SQL statement uses the native server dialect.

To create a remote view

  1. In the Project Manager, select a database, then select Remote Views and choose New to open the View Designer.
  2. Choose New View.
  3. In the Select Connection or Data Source dialog box, select the Available data sources option.

    -or-

  • Use the CREATE SQL VIEW command with the REMOTE and/or the CONNECTION clause.

If you use the CONNECTION clause with the CREATE SQL VIEW command, you don't need to include the REMOTE keyword. Visual FoxPro identifies the view as a remote view by the presence of the CONNECTION keyword. For example, if you have the products table from the Testdata.dbc database on a remote server, the following code creates a remote view of the products table:

OPEN DATABASE testdata
CREATE SQL VIEW product_remote_view ;
   CONNECTION remote_01 ;
   AS SELECT * FROM products

You can use a data source name rather than a connection name when you create a remote view. You can also choose to omit a connection or data source name when you use the CREATE SQL VIEW command with the REMOTE clause. Visual FoxPro then displays the Selection Connection or Data Source dialog box, from which you can choose a valid connection or data source.

Creating a New Remote View

To gain access to your remote data in a view, you can use an existing connection or create a connection to use with your new view.

To create a new remote view

  1. Select a data source or connection and choose OK.
  2. If required, in the Microsoft SQL Server or other login dialog box, enter your login ID and password.

    -or-

    If you have previously defined and saved a connection, select the Connections option.

You can also choose New from the File menu and select the Remote View option.

Once the connection is established, the Open dialog box appears so you can select a table on the remote server.

After you select a table, the View Designer appears.

To continue creating your remote view, you can select output fields and set filters just as you would a local view.

Using a View Wizard

You can also create a remote view with a view wizard. To set up an updateable view using tables on an ODBC data source, use the Remote View Wizard.

To create a remote view with a wizard

  1. In the Project Manager, select a database.
  2. Select Remote Views, and choose New.
  3. Choose View Wizard.
  4. Follow the instructions on the wizard screens.

After you create a view, you can open the Database Designer and see that the view is in the schema displayed in the same manner as a table, with the view name and icon in place of a table name and icon.

If you join two or more tables in the Remote View Designer, the Designer uses inner joins (or equi-joins) and places the join condition in the WHERE clause. If you want to use an outer join, the Remote View Designer provides only left outer joins, the syntax supported by ODBC. If you need right or full outer joins or just want to use a native syntax for a left outer join, create the view programmatically.

See Also

Working with Views | Creating a Multitable View | Displaying Data with Views | Creating Queries | Project Manager | Connection Designer | DBSETPROP( ) | SQLSETPROP( ) | Remote View Wizard | Customizing Views


Creating a Multitable View

To access related information stored in separate tables, you can add tables to a new or existing view. When adding tables, you can control records returned in the view by defining a join condition between tables, if one does not already exist. Defining and specifying a join condition between two tables help determine which records from the two tables should be compared and returned. For more information about specifying join conditions, see Controlling Record Selection with Joins and Join Conditions for Tables, Queries, and Views.

Adding Tables to a Local View

To add a table to a local view

  1. From the Project Manager, create a new or open an existing local view.
  2. Click the View Designer to bring it to the foreground.
  3. From the Query menu, select Add Tables and the table or view you want to add.

You can also open a database and add table names to the FROM clause and join conditions using the CREATE SQL VIEW command. Adding tables using the CREATE SQL VIEW command produces a cross product.

Note You must specify a join condition in either the FROM or WHERE clause of the SQL statement passed to CREATE SQL VIEW to match related records between the tables. If persistent relationships between the tables exist, they are automatically used as join conditions.

For more information, see CREATE SQL VIEW Command.

Adding Tables to a Remote View

When you connect to a remote data source, you can obtain access to many related tables. You can select the tables you need and adjust the relationships between them, if necessary, to get the information you need.

To create a remote view with multiple tables

  1. From the File menu, choose New, select Remote View, and choose New File.
  2. In the Select Connection or Data Source dialog box, select a predefined connection or an available data source.
  3. If required, log on to the server.
  4. In the Open dialog box, select the tables you want to use.
  5. In the Join Condition dialog box, set the join condition by accepting the default join, or set up the join as needed.

As with local views, you can control how updates are made to the source tables by using the options in the Update Criteria tab in the View Designer.

See Also

Working with Views | Creating Views | Accessing Remote Data with Views


Combining Views

You can build a view that is based on other views. You might want to do this if you need a subset of the information available in multiple other views, or if you want to combine local and remote data in a single view. A view based on other views, or on a combination of local tables and local or remote views, is called a multitiered view. The view that combines other views is the top-level view. You can have multiple levels of views between the top-level view and the local or remote base tables. When you use a multitiered view, the views on which the top-level view is based and any Visual FoxPro base tables used in the top-level or intermediate-level views appear in the Data Session window. Remote tables do not appear in the Data Session window.

Combining Local and Remote Data in a View

To combine remote and local data in a view

  1. Create a remote view and add one or more tables from the remote server.
  2. Create a new local view and add the remote view you just created to it.
  3. Add the related local table to the view and join them on a common field.
  4. Set a filter in the local view and run it.
  5. Update the view results to update both the local table and the remote view.
  6. Close the local view and then the remote view to update the data on the remote server.

You can also combine local and remote data in a view by creating a new local view based on a local view and a remote view.

To create a view that combines local and remote data

  • In the Project Manager, select a database, choose Local Views, and choose New to open the View Designer. Add any combination of tables, local views, and remote views into your view.

    -or-

  • Use the CREATE SQL VIEW command.

For example, to create a local view that combines information from the local Employee table and the remote Orders table, you can use the following code:

OPEN DATABASE testdata
CREATE SQL VIEW remote_orders_view ;
   CONNECTION remote_01 ;
   AS SELECT * FROM orders
CREATE SQL VIEW local_employee_remote_orders_view ;
   AS SELECT * FROM testdata!local_employee_view, ;
   testdata!remote_orders_view ;
   WHERE local_employee_view.emp_id = ;
      remote_orders_view.emp_id

Updating Local and Remote Data in a View

When you update data in a multiple tiered view, the updates go down one level, to the view on which the top-level view is based. If you want to update the base tables on which a multiple tiered view is built, you must issue a TABLEUPDATE command for each view in the structure.

See Also

Working with Views | Creating Rules on View Fields and Rows | Manipulating Offline Data | Creating Queries | Data Session window | Creating Offline Views | Customizing Views


Customizing Views

You can customize views by defining how a field in a view displays, by controlling field display and data entry, by using expressions in views, by setting views up to prompt for values, and by setting advanced options to fine tune how data is exchanged with a server.

Controlling Field Display and Data Entry

Because your view is part of a database, you can take advantage of some of the same properties that a database provides for fields in a table. For example, you can assign captions, enter comments, or set validation rules to control data entry.

To control field display and data entry

  1. Create or modify a view in the View Designer.
  2. In the Fields tab, select a field in the Selected fields list.
  3. Choose Properties.
  4. In the View Field Properties dialog box, enter validation, display, and field type settings.

Controlling the Update Method

To control how information in key fields is actually updated on the server, use the options in the Update Using option group. These options determine what SQL command is used in the update statement sent to the server or source tables when key fields in records are updated.

You can specify that records be deleted and then replaced with the new values entered in the view (SQL DELETE then INSERT), or that server records be changed via the SQL UPDATE function supported by the server.

Adding Expressions to Remote Views

As with queries, you can include functions and expressions as filters in views.

To add an expression to a view

  • In the Filter tab, select Expression from the Field Name box.

If you are basing a view on a remote data source, the functions shown in the Expression Builder reflect the functions supported by that server. Check your server documentation for a listing of the functions your server supports. Visual FoxPro does not attempt to parse the expressions you build; instead, it passes them on to the remote server.

Prompting for Parameters

You can set up views that prompt for the entry of a value to complete the query. For example, suppose you want to create a query to find customers located in a specific country. To do this, you need to define a filter on the country field and specify a parameter as the example in the filter. Parameter names can be any combination of alphabetic characters, numbers, and single quotes.

To set up a parameter for a view

  1. In the View Designer, add a new filter or select an existing filter in the Filter tab.
  2. In the Example box, type a question mark (?) and the name of the parameter.

When you use the view, a message box appears prompting for a value to include in the filter.

Setting Timeout Intervals

If you need to adjust how Visual FoxPro interacts with your server, you can set timing options.

To set timeout intervals

  1. In the Project Manager, select a connection and choose Modify.
  2. In the Timeout intervals area, set the options you need.
  3. From the File menu, choose Save.

See Also

Working with Views | Updating Data | Connection Designer | Manipulating Offline Data | Query and View Designers | Working with Tables | Creating Queries | View Field Properties Dialog Box | Project Manager Window | Combining Views


Customizing Views Using SQL SELECT Statements

When you create a view in the View Designer, Visual FoxPro uses a SQL SELECT statement to retrieve the information from the fields in the tables. SQL SELECT statements offer you a more powerful way to manipulate your view and provide more control over the results. To verify your view or add comments, you can display the SQL SELECT statement in the SQL window and add comments.

You can use SQL SELECT statements with views in the View Designer, queries created in the Query designer, or in code for an event or procedure in a program (.prg) file. For more information about using the SQL SELECT command, see SELECT - SQL Command.

Viewing SQL SELECT Statements Created by Views

You can view the SQL statement that your view builds in the SQL window at any time while you create your view. By viewing the SQL statement created by the View Designer, you can make sure the view is properly defined.

To view the SQL SELECT statement created by a view

  1. Create your query using the View Designer.
  2. On the Query menu, choose View SQL.

The SQL window opens to display the SQL SELECT statement your view created. The first statement is the SQL SELECT statement. For example, you can select all the records from the Customer table in the TasTrade database where the country field contains the value "Canada":

SELECT *;
   FROM tastrade!customer;
   WHERE Customer.country = Canada

The script for the SQL SELECT statement appearing in the SQL window is automatically generated when loading or modifying a view in the View Designer and contains view properties set by DBSETPROP( ) function calls that you can edit.

To run the SQL SELECT statement immediately, enter the statement in the Command window. If you want each clause to appear on a separate line in the window, end each line except the last one with a semicolon (;) so that Visual FoxPro processes the command only after the last line.

To include the SELECT statement in code, copy the SQL SELECT statement into a .prg file.

Creating Views with Stored SQL SELECT Statements

You can use macro substitution to store the SQL SELECT statement into a variable that you use with the AS clause in the CREATE SQL VIEW command. For example, the following code stores a SQL SELECT statement into the variable emp_cust_sql, which is then used to create a new view:

emp_cust_sql = "SELECT employee.emp_id, ;
   customer.cust_id, customer.emp_id, ;
   customer.contact, customer.company ;
   FROM employee, customer ;
   WHERE employee.emp_id = customer.emp_id"
CREATE SQL VIEW emp_cust_view AS &emp_cust_sql

Editing SQL SELECT Statements in the SQL Window

You can edit the SQL SELECT statement and properties, which are set by DBSETPROP( ) function calls, created for the view. For more details about view properties, see DBSETPROP( ) Function, DBGETPROP( ) Function, or CURSORGETPROP( ) Function.

To edit the SQL SELECT statement in the SQL window

  • Open the SQL window, and modify the SQL SELECT statement.

You can specify an asterisk, table.*, or a comma-delimited list of fields for the SELECT statement in the SQL window. For example, you can specify the SQL statement as SELECT * FROM or SELECT field1, field2, ... FROM. Your preferences are preserved during the loading or generation of the view. You can also include the same field multiple times in the SELECT list.

For more information the syntax for the SQL SELECT command, see SELECT - SQL Command.

Loading SQL SELECT Statement Changes into the View Designer

After editing the SQL SELECT statement in the SQL window, you can reload the changes into the View Designer.

To update the view in the View Designer

  • Close the SQL window.

You can also update the view by clicking the View Designer to bring it to the foreground.

If the View Designer cannot reload your changes after you make changes in the View SQL window, a dialog box appears and asks the following:

"View/Query designer is unable to reload your changes. Would you like to rebuild content from the designer?"

If you select Yes, your changes are discarded in the SQL window, and Visual FoxPro returns you to the View Designer. If you select No, Visual FoxPro returns you to the SQL window.

To save a statement that cannot be parsed such as a call to a stored procedure, select No and click the Save button on the toolbar. Visual FoxPro saves the query. You can also click the Save button after entering the command in the SQL window to save the query. You do not need to click the View Designer window, which causes the View Designer to try to load and parse the query.

See Also

Working with Views | Creating Local Views | Creating a Multitable View | Customizing Views


Modifying, Renaming, and Deleting Views

You can modify existing views in the View Designer using the Project Manager or the Visual FoxPro language.

To modify a view in the View Designer

  • In the Project Manager, select the name of the view, and then choose Modify to open the View Designer.

    -or-

  • Open a database and use the MODIFY VIEW command with the name of the view.

In the View Designer, you can use the Query menu or the View Designer toolbar to add a new table to the view. The following code displays product_view in the View Designer:

OPEN DATABASE testdata
MODIFY VIEW product_view

You can also modify the SQL statement for the view. For more information, see Creating Views.

Tip To programmatically create a view, you can open an existing view, copy the SQL string, and paste it into your code.

Renaming a View

You can rename a view from the Project Manager or with the RENAME VIEW command.

To change the name of a view

  • In the Project Manager, select a database, and then select the view name, and then choose Rename File from the Project menu.

    -or-

  • Use the RENAME VIEW command.

For example, the following code renames product_view to products_all_view:

RENAME VIEW product_view TO products_all_view

The database containing the view must be open before you can rename the view.

Deleting a View

You can delete a view definition from a database using the Project Manager or the DELETE VIEW command. Before deleting the view, make sure the database containing the view is open and set as the current database.

To delete a view

  • In the Project Manager, select a database, and then the view name, and then choose Remove.

    -or-

  • Use the DELETE VIEW or DROP VIEW command.

For example, the following code deletes product_view and customer_view from the database:

DELETE VIEW product_view
DROP VIEW customer_view
Note These commands have the same effect; DROP VIEW is the ANSI SQL standard syntax for deleting a SQL view.

See Also

Working with Views | Creating a Local View | Creating a Multitable View | Creating Queries | Accessing Remote Data | Project Manager |


Displaying Data with Views

After you've created a view, you can use the view to display and update data. You can also modify the properties of a view to increase view performance. You treat a view like a table:

  • Open the view with the USE command and include the name of the view.
  • Close the view with the USE command.
  • Display view records in a Browse window.
  • Display open view aliases in the Data Session window.
  • Use the view as a data source, such as in a text or Grid control, form, or report.

You can use a view through the Project Manager or the language.

To use a view

  • In the Project Manager, select a database, choose the name of the view, and then choose Browse to display the view in a Browse window.

    -or-

  • Access the view programmatically with the USE command.

The following code displays product_view in a Browse window:

OPEN DATABASE testdata
USE product_view
BROWSE

When you use a view, the view is opened as a cursor in its own work area. If the view is based on local tables, Visual FoxPro also opens the base tables in separate work areas. The base tables for a view are the tables accessed by the SELECT - SQL statement you include in the CREATE SQL VIEW command when you create a view. In the previous example, using product_view automatically opens the products table as well.

Data Session window displays the view and its base table

When a view is based on remote tables, the base tables are not opened in work areas. Only the name of the remote view appears in the Data Session window.

See Also

Working with Views | Accessing Remote Data | Limiting the Scope of a View | Creating Queries | Opening Multiple Instances of a View | Displaying the Structure of a View | Customizing Views


Limiting the Scope of a View

When you access a remote data source, you're accessing potentially massive amounts of data. You can limit the scope of data selected into your view to be just the records you need at a given moment. This reduces network traffic and increases the performance of your view. For example, if you want to view information about customers in a particular country and their orders, you gain performance by downloading only the records for that country, rather than all customers, into your view.

One method you can use to limit the scope of your view is to add a WHERE clause to your view's SQL statement. If you want to look at the records for the customers in Sweden, you would create this SQL WHERE clause for your view:

SELECT * FROM customer ;
   WHERE customer.country = 'Sweden'

This code would effectively limit the scope of your view by downloading records for just the Swedish customers, but it would also require that you create a separate view for each country, because the actual value for one country's customer.country is hard-coded into your view's SELECT statement.

Creating a Parameterized View

You can limit the scope of a view without creating a separate view for each subset of records by creating a parameterized view. A parameterized view creates a WHERE clause in the view's SQL SELECT statement that limits the records downloaded to only those records that meet the conditions of the WHERE clause built using the value supplied for the parameter. This value can be supplied at run time, or passed programmatically to the view.

In the case of the previous example, you can create one view that allows you to download records for any country, simply by entering the country's name as you use the view.

To create a parameterized view

  • In the View Designer, choose View Parameters from the Query menu.

    -or-

  • Use the CREATE SQL VIEW command with a "?" symbol and a parameter.

The parameter you supply is evaluated as a Visual FoxPro expression and the value is sent as part of the view's SQL statement. If the evaluation fails, Visual FoxPro prompts for the parameter value. For example, if you have the customer table from the Testdata database on a remote server, the following code creates a parameterized remote view that limits the view to those customers whose country matches the value supplied for the ?cCountry parameter:

OPEN DATABASE testdata
CREATE SQL VIEW customer_remote_view ;
   CONNECTION remote_01 ;
   AS SELECT * FROM customer ;
   WHERE customer.country = ?cCountry

You can supply a value for ?cCountry programmatically when you use the view. For example, you could type the following code:

cCountry = 'Sweden'
USE Testdata!customer_remote_view IN 0
BROWSE

Visual FoxPro displays the customer records for Swedish companies in the Browse window for Customer_remote_view.

Prompting for User Input of a Parameter Value

If your parameter is not a variable or expression, you might want to prompt the user to supply the parameter value by using a quoted string as your view parameter. When you create a view parameter using a quoted string after the "?" symbol, Visual FoxPro does not interpret the string as an expression. Rather, you are prompted to enter the value for the parameter at run time. For example, the following code creates a parameterized remote view that prompts the user to supply a value for the ?'my customer id' parameter:

OPEN DATABASE testdata
CREATE SQL VIEW customer_remote_view ;
   CONNECTION remote_01 ;
   AS SELECT * FROM customer ;
   WHERE customer.cust_id = ?'my customer id'
USE customer_remote_view

When you use the view in the previous example, the View Parameter dialog box is displayed.

After you enter a valid customer ID, Visual FoxPro retrieves the record that matches that ID. If you enter the value "ALFKI" in the previous example and then browse Customer_remote_view, you see the customer record displayed in the Browse window.

By using a quoted string as a view parameter, you ensure that Visual FoxPro will always prompt the user for the parameter value.

See Also

Displaying Data with Views | Opening Multiple Instances of a View | Creating Queries | View Designer | CREATE SQL VIEW | Displaying the Structure of a View


Opening Multiple Instances of a View

You can open multiple instances of a view in separate work areas, just as you can open a table in more than one work area. Unlike tables, views fetch a new data set by default each time you use the view.

To open a view in multiple work areas

  • In the Project Manager, choose the name of the view, and then choose Browse to display the view in a Browse window. Repeat this process to open the view in additional work areas.

    -or-

  • In the Data Session window, choose Open, and then the name of the view. Repeat this process to open the view in additional work areas.

    -or-

  • Access the view programmatically with the USE command.

When you access the view programmatically with the USE command, you can choose to open another instance of a view without requerying the data source. This is particularly useful when you want to open a remote view in multiple work areas without waiting for data to be downloaded from a remote data source.

To use a view again without downloading data

  • Use the NOREQUERY clause with the USE command.

    -or-

  • Use the AGAIN clause with the USE command.

The following code uses the NOREQUERY clause to display the cursor fetched from the first instance of product_remote_view in two Browse windows without requerying the remote data source:

OPEN DATABASE testdata
CREATE SQL VIEW product_remote_view ;
   CONNECTION remote_01 ;
   AS SELECT * FROM products
USE product_remote_view
BROWSE
SELECT 0
USE product_remote_view NOREQUERY
BROWSE

You can specify a session number with the NOREQUERY clause. If you don't specify a session number, Visual FoxPro searches in all sessions. If an opened result set is found for the view, a cursor is opened again on the same result set. If no open result set is found, a new result set is fetched for the view. As is true for tables, if the view is not found, a new view cursor is opened for you.

If you want Visual FoxPro to search only the current session for an opened result set for your view, you can use the AGAIN clause. The following code displays product_remote_view in two Browse windows:

OPEN DATABASE testdata
USE product_remote_view
BROWSE
USE product_remote_view AGAIN in 0
BROWSE

When you use the AGAIN clause, Visual FoxPro looks for an existing view cursor in the current session, and opens an additional alias pointing to this view cursor. Opening another instance of a view with the AGAIN clause is the equivalent of issuing a USE with the NOREQUERY clause with the current session number.

See Also

Limiting the Scope of a View | Displaying the Structure of a View | Creating Queries | Project Manager | Updating Data in a View


Displaying the Structure of a View

You can open and display just the structure of a view with the NODATA clause of the USE command. This option is particularly useful when you want to look at the structure of a remote view without waiting to download data.

To open a view without data

  • Access the view programmatically with the USE command and the NODATA clause.

The following code displays customer_remote_view without data in a Browse window:

OPEN DATABASE testdata
USE customer_remote_view NODATA in 0
BROWSE

Using a view with the NODATA clause always opens a new view cursor. The NODATA clause is the fastest way to get the view's structure because it creates the smallest cursor possible on the remote data source. When you use the NODATA clause, Visual FoxPro creates a WHERE clause for the view that always returns a false value. Because no records on the data source can meet the WHERE clause condition, no rows are selected into the remote data source's cursor. Your view is retrieved quickly because you're not waiting for the remote data source to build a potentially large cursor.

Tip Using the NODATA clause is more efficient than using a MaxRecords property setting of 0 on your view or cursor. When you use the MaxRecords property, you must wait while the remote data source builds a cursor for the view containing all data rows that meet the view's normal WHERE clause conditions. Rows from the full remote view cursor are then downloaded according to the setting of the MaxRecords property.

Creating an Index on a View

You can create local indexes on a view, just as on a table, using the INDEX ON command. Unlike indexes you build on a table, local indexes you create on a view are not stored persistently: they vanish when you close the view.

Tip Consider the size of your view's result set when deciding whether to create a local index on a view. Indexing a large result set can take a long time, and slow down performance of your view.

For more information on creating indexes, see Working with Tables, or see INDEX Command.

Creating Temporary Relationships on Views

You can create temporary relationships between view indexes or between view indexes and table indexes with the SET RELATION command.

For better performance, when you use the SET RELATION command to relate a view and a table, make the view the parent and the table the child in the relationship. Making the table the child is more efficient because the structural index of the table is constantly maintained, quickly accessed, and can be used by the data environment to order the records. The index on the view must be rebuilt each time the view is activated and takes more time than the index on the table. An index on a view is not part of the view definition; so, if you use a data environment, the view cannot be the child because the index on the child has to exist as part of the definition, which views don't support.

Setting View and Connection Properties

When you create a view, the view inherits property settings, such as UpdateType and UseMemoSize, from the environment cursor, or cursor 0 of the current session. You can change these default property settings by using the CURSORSETPROP( ) function with 0 as the cursor number. After the view has been created and is stored in a database, you can change view properties with the DBSETPROP( ) function. The changes you make to view properties in a database are stored persistently in the database.

When you use a view, the property settings stored for the view in the database are inherited by the active view cursor. You can change these properties on the active cursor using the CURSORSETPROP( ) function for the view cursor. Changes you make with the CURSORSETPROP( ) function are temporary. The temporary settings for the active view disappear when you close the view; the temporary settings for cursor 0 go away when you close the Visual FoxPro session.

Connections inherit properties in a similar fashion. Default properties for connection 0 are inherited when you create and store a named connection in a database. You can change these default property settings for connection 0 with the SQLSETPROP( ) function. After the connection has been created and is stored in a database, you can change connection properties with the DBSETPROP( ) function. When you use a connection, the property settings stored for the connection in the database are inherited by the active connection. You can change these properties on the active connection using the SQLSETPROP( ) function for the connection handle.

Both views and connections can use a named ODBC data source. If you use an ODBC data source in a view, the connection inherits properties from the session defaults.

The following diagram illustrates property inheritance for views and connections. The gray lines represent the flow of property inheritance; the black lines represent Visual FoxPro commands.

View and Connection properties and their inheritance

Changing Default Data Types When Downloading Remote Views

When you create a view, the DataType property for all fields in the view is set to a default value. The value is the data type letter (D, G, I, L, M, P, T, Y) for fixed-length data types and the letter followed by precision and scale parameters in parentheses (B(d), C(n), N(n,d)) for variable length types. This property is read-only for local views. For a list of default data types, see Downloading and Uploading Remote View Data in Implementing a Client/Server Application.

You can modify the setting of the DataType property for the remote view field with the DBSETPROP( ) function as shown in this table.

ODBC data type of remote field | Possible data types in Visual FoxPro cursor
SQL_CHAR SQL_VARCHAR SQL_LONGVARCHAR | Character or Memo1 (default); also General or Picture
SQL_BINARY SQL_VARBINARY SQL_LONGVARBINARY | Memo (default); also Character, General, or Picture
SQL_DECIMAL SQL_NUMERIC | Numeric or Currency2 (default); also Character, Integer, or Double
SQL_BIT | Logical (default); also Character
SQL_TINYINT SQL_SMALLINT SQL_INTEGER | Integer (default); also Character, Numeric, Double, or Currency
SQL_BIGINT | Character (default); also Integer, Numeric, Double, or Currency
SQL_REAL SQL_FLOAT SQL_DOUBLE | Double (default); the number of decimal places is the value of SET DECIMALS in Visual FoxPro; also Character, Integer, Numeric, or Currency
SQL_DATE | Date (default); also Character or DateTime
SQL_TIME | DateTime3 (default); also Character
SQL_TIMESTAMP | DateTime4 (default); also Character or Date

1. If the ODBC field width is less than the value of the cursor property UseMemoSize, it becomes a Character field in the Visual FoxPro cursor; otherwise, it becomes a Memo field.

2. If the server field is a money data type, it becomes a Currency data type in Visual FoxPro.

3. The day defaults to 1/1/1900.

4. If the value in the SQL_TIMESTAMP field contains fractions of seconds, the fractions are truncated when the value is converted to a Visual FoxPro DateTime data type.

Using the DataType Property

You can use the DataType property to choose a different data type than the default. For example, you might want to download a server timestamp field to Visual FoxPro, but the default data type mapping into a Visual FoxPro DateTime field would truncate any fractions of seconds stored in the server timestamp. You might use the DataType property to map the remote timestamp field into a Visual FoxPro character field to preserve the fractions of seconds.

Closing a View's Base Tables

The local base tables opened automatically when you use a view are not automatically closed when you close a view; you must explicitly close them. This is consistent with the SELECT - SQL command.

See Also

Opening Multiple Instances of a View | Updating Data in a View | Creating Queries | USE | SET RELATION | Updating Multiple Tables in a View | Updating Data


Updating Data in a View

You update data in a view just as you would update data in a table. With a view you can also update the view's base tables. Views are, by default, buffered with optimistic row buffering. You can change this to table buffering; for more information on buffering, see Programming for Shared Access.

You can update data in a view through the interface or the language. The first step in updating view data is to make the view updateable. In most cases, the default property settings automatically prepare the view to be updateable, but updates are not sent to the data source until you instruct Visual FoxPro to do so by setting the SendUpdates property to On.

A view uses five properties to control updates. These properties are listed here with their default settings:

View Update Properties and Default Settings

View Property | Default Setting
Tables | Includes all tables that have updateable fields and have at least one primary key field.
KeyField | Database key fields and remote primary keys on the table.
UpdateName | Table_name.column_name for all fields.
Updateable | All fields except the primary key fields.
SendUpdates | Defaults to the session default, which is originally set to false (.F.); if you change it to true (.T.), that becomes the default for all views created in the session.
CompareMemo | Defaults to true (.T.), means that memo fields are included in the WHERE clause and are used for detecting update conflicts.

While all five properties are required to update data, the SendUpdates property serves as a "master switch" controlling whether or not updates are sent. As you develop your application, you might set the SendUpdates property off and then configure the other properties to enable updates to the fields you want updated. When you're ready to test your application, you can set the SendUpdates property on to start updates flowing.

In some more complex situations, the default update settings may not provide updates for a view you create through the language. To enable updates, look at the default settings for each of the update properties and adjust them as needed. You can also specify additional properties, such as UpdateType, WhereType, and so on, according to your preferences. For a complete list of view properties, see DBGETPROP( ).

To make a view updateable from the View Designer

  • In the View Designer, select the Update Criteria tab and verify the default settings.

The default settings for views you create through the View Designer usually prepare the view to be updateable; you only need to select the Send SQL Updates check box to turn updates on. You can further modify the tables, fields, SQL WHERE clause, and Update options as you desire.

To make a view updateable by setting view update properties

  • Examine the current default settings with the DISPLAY DATABASE command, and then modify properties for the view definition as you desire with the DBSETPROP( ) function.

The following example lists the steps you would follow to specify the five view update properties programmatically:

Note The default View properties may supply all the information needed to update your view.
  1. Set the Tables property with at least one table name.

    For example, if you have a view based on the customer table called cust_view, you could set the table name with the following function:

    DBSETPROP('cust_view','View','Tables','customer')
    Tip If a table appears as a qualifier in the UpdateName property but is not included in the default list for the Tables property, the table might not have a primary key field specified. Make the table updateable by adding the field you consider to be a key field to the KeyField property list, and then add the table to the Tables property list.
  2. Set the KeyField property with one or more local Visual FoxPro field names that together define a unique key for the update table.

    Using the same example, you could make cust_id the key field using the following code:

    DBSETPROP('cust_view.cust_id','Field','KeyField',.T.)
    Caution Be sure the key field(s) you specify define a unique key both in the base table you want to update and in the view.
  3. Map the view fields to their base table fields with the UpdateName property. This property is particularly useful when your view is based on a join of two tables with a common field name, or when the fields are aliased in the view. To update the desired base table, you map the Visual FoxPro view field name to the base table field and table name.
    DBSETPROP('cust_view.cust_id','Field','UpdateName',;
         'customer.cust_id')
    Tip To avoid creating synonym fields in your view, you can qualify field names in the SQL statement you use to build your view. Then use the Visual FoxPro UpdateName property of the view to map each qualified field to the correct base table and field name.
  4. Specify the scope of fields you want to update with the Updateable property. You should specify only those fields also specified with the UpdateName property.
    DBSETPROP('cust_view.cust_id','Field','Updateable',;
         .T.)
  5. Set the SendUpdates property to true (.T.). This is the master switch that instructs Visual FoxPro to create and send updates to any of the tables and fields you've specified as updateable.
    DBSETPROP('cust_view','View','SendUpdates',.T.)

When you use DBSETPROP( ) to set properties on a view before you use the view, the settings are stored in the database and are used automatically whenever you activate the view. Once the view is active, you can use CURSORSETPROP( ) to change property settings on the active view. Property settings you set on an active view with CURSORSETPROP( ) are not saved when you close the view.

See Also

Displaying the Structure of a View | Updating Multiple Tables in a View | Creating Queries | DBGETPROP( ) | View Designer | Updating Data


Updating a Table in a View

You can use either local or remote views to update your tables.

Sending Updates to Tables

In the View Designer, the Update Criteria tab allows you to control how the changes you make to remote data (updates, deletes, and inserts) are sent back to the remote data source. You can also enable and disable updating for specific fields in the tables and set the SQL update method appropriate to your server.

Making a Table Updateable

If you want to have the changes you make to the local version of a table sent back to the source table, you need to set the Send SQL Updates option. You must set at least one key field to use this option. If the table you select has a primary key field defined and you have selected it in the Fields tab, the View Designer automatically uses the primary key field for the table as a key field for the view.

To enable updating of source tables

  • In the Update Criteria tab, set the Send SQL updates option.

Setting Key Fields

When you first open a table in the View Designer, the Update Criteria tab shows which fields in the table are defined as key fields. Visual FoxPro uses key fields to uniquely identify the update records in remote tables that you have modified locally.

To set a key field

  • In the Update Criteria tab, click the key column next to the name of the field.

If you have changed the key fields and want to restore them to the original setting in the source table, choose Reset Key. Visual FoxPro will check the remote tables and use the key fields from those tables.

Updating Specific Fields

You can specify that only certain fields in any given table are updateable. You must have a key field defined for a table in order to make any fields in that table updateable. If fields are not marked as updateable, users can make changes to the field in a form or Browse window, but these changes are not sent to the remote table.

To make a field updateable

  • In the Update Criteria tab, click the updateable ("pencil") column next to the name of the field.

Updating All Fields

If you want to be able to make changes to all the fields in a table, you can set all the fields in a table as updateable.

To make all fields updateable

  • In the Update Criteria tab, choose Update All.
    Note You must have a key field defined in a table in order to use Update All. Update All does not affect key fields.

See Also

Updating Data in a View | Update Criteria tab | Displaying the Structure of a View | Updating Multiple Tables in a View | Creating Queries | Creating Views | Displaying Data with Views | Table Creation | Programming for Shared Access


Updating Multiple Tables in a View

You can update multiple base tables from a view. When your view combines two or more tables, you set properties to ensure that only the many side of the view query is updateable.

Views are updated on a table-by-table basis. You must ensure that for each table accessed in a view, the key field set is a unique key for both the view result set and the base table.

To make a multitable view updateable

  • In the View Designer, choose the Update Criteria tab, and then select the tables and field names you want to update.

    -or-

  • Use the DBSETPROP( ) function.

In most cases, the default values provided by Visual FoxPro prepare a multitable view to be updateable, even when you create the view programmatically. The following code example creates and explicitly sets properties to update a two-table view. You can use this example as a guide for customizing update property settings on a view.

Updating Multiple Tables in a View

Code Comments
CREATE SQL VIEW emp_cust_view AS ;
   SELECT employee.emp_id, ;
   employee.phone, customer.cust_id, ;
   customer.emp_id, customer.contact, ;
   customer.company ;
   FROM employee, customer ;
   WHERE employee.emp_id = customer.emp_id
 Create a view that accesses fields from two tables.
DBSETPROP('emp_cust_view', 'View', 'Tables',
'employee, customer')
 Set the tables to be updated.
DBSETPROP('emp_cust_view.emp_id', 'Field', ;                'UpdateName', 'employee.emp_id')
DBSETPROP('emp_cust_view.phone', 'Field', ;                'UpdateName', 'employee.phone')
DBSETPROP('emp_cust_view.cust_id', 'Field', ;             'UpdateName', 'customer.cust_id')
DBSETPROP('emp_cust_view.emp_id1', 'Field', ;             'UpdateName', 'customer.emp_id')
DBSETPROP('emp_cust_view.contact', 'Field', ;             'UpdateName', 'customer.contact')
DBSETPROP('emp_cust_view.company', 'Field', ;             'UpdateName', 'customer.company')
 Set update names.
DBSETPROP('emp_cust_view.emp_id', 'Field', ;                'KeyField', .T.)
 Set a single-field unique key for the Employee table.
DBSETPROP('emp_cust_view.cust_id', 'Field', ;
            'KeyField', .T.)

DBSETPROP('emp_cust_view.emp_id1', 'Field', ;
            'KeyField', .T.)
Set a two-field unique key for the Customer table.
DBSETPROP('emp_cust_view.phone', 'Field', ;
            'Updateable', .T.)

DBSETPROP('emp_cust_view.contact', 'Field', ;             'Updateable', .T.)
DBSETPROP('emp_cust_view.company', 'Field', ;             'Updateable', .T.)
Set the updateable fields. Typically, key fields are not updateable.
DBSETPROP('emp_cust_view', 'View', ;
            'SendUpdates', .T.)
 Activate the update functionality.
GO TOP

REPLACE employee.phone WITH "(206)111-2222"
REPLACE customer.contact WITH "John Doe"
Modify data in the view.
TABLEUPDATE()
 Commit the changes by updating both the Employee and Customer base tables.

Customizing Views with the Data Dictionary

Because views are stored in a database, you can create:

  • Captions
  • Comments for the view and view fields
  • Default values for view fields
  • Field- and row-level rules and rule error messages

The data dictionary features for views are similar in function to their counterparts for database tables. However, you use the language rather than the Table Designer to create captions, comments, default values and rules for views.

See Also

Updating Data in a View | Creating Default Values for View Fields | Creating Rules on View Fields and Rows | View Designer | DBSETPROP( ) | Updating Data | Customizing Views


Creating Default Values for View Fields

Like default values for table fields, view field default values are stored in the database and are available each time you use the view. Visual FoxPro doesn't compare the default values you create locally with any default values established on the remote data source. You must create default values that are acceptable for the data source.

To assign a default value to a view field

  • In the Fields tab in the View Designer, select a field, and then choose Properties and enter the default value for the field.

    -or-

  • Use the DefaultValue property of the DBSETPROP( ) function.

For example, you may want your application to limit the amount of merchandise a new customer can order until you've had time to complete a credit check and determine the amount of credit you're willing to extend to that customer. The following example creates a maxordamt field with a default value of 1000:

OPEN DATABASE testdata
USE VIEW customer_view
?DBSETPROP ('Customer_view.maxordamt', 'Field', 'DefaultValue', 1000)

You might also use default values to populate some rows automatically for the user. For example, you might add a Grid control to an order entry form that is based on a remote view of an order line items table. The order_id field is the key field that maps each row of the Grid to its counterpart in the remote order line items table. Because the order ID for each row in the grid will be the same for one order, you can use a default value to save keystrokes by populating the order_id field automatically.

Tip If one of your application's business rules requires that a field contain an entry, providing a default value helps to ensure that a particular field-level or record-level rule will not be violated.

See Also

Updating Multiple Tables in a View | Creating Rules on View Fields and Rows | Creating Queries | Combining Views | Updating Data in a View


Creating Rules on View Fields and Rows

You can create local versions of remote data source rules to:

  • Reduce response time.
  • Reduce impact on network resources.
  • Test data before sending it to the remote data source.
  • Prevent sending faulty data to the remote data source.

Visual FoxPro doesn't compare the rules you create locally with remote rules. You must create rules that are acceptable for the data source. If remote rules change, you must change your local rules to match.

To create a rule on a view field or row

  • In the Fields tab in the View Designer, select a field, and then choose Properties and enter the rule expression and message text for the field.

    -or-

  • Use the RuleExpression and RuleText properties of the DBSETPROP( ) function.

For example, the following code creates a field-level rule on orditems_view that prevents entering a quantity of less than 1:

OPEN DATABASE testdata
USE VIEW orditems_view
DBSETPROP('Orditems_view.quantity','Field', ;
         'RuleExpression', 'quantity >= 1')
DBSETPROP('Orditems_view.quantity','Field', ;
         'RuleText', ;
'"Quantities must be greater than or equal to 1"')

You can also use the DBSETPROP( ) function to create row-level rules.

See Also

Creating Default Values for View Fields | Combining Views | Creating Queries | Manipulating Offline Data | Creating Offline Views | Displaying Data with Views | Creating Views


Manipulating Offline Data

There are times when you might want to display, collect, or modify data independent of the host database. By using the offline view features in Visual FoxPro, you can use views to connect to a host database and create a subset of data for use offline. Then, working offline, you can use the view directly or through an application you create. When you are done, you can upload the changes stored in the view back to the host database.

Some scenarios where offline views are useful include:

  • A data warehousing situation, where large databases are maintained centrally on MIS servers. If you are only interested in data pertaining to, for example, the Marketing department, you can construct a view including only the data that is relevant to you. You can then take the data offline, allow multiple users in the Marketing department to update the data, and then commit the changed data to the source database.
  • A geographically remote location which requires that you take a subset of data with you on a laptop, modify the data independently of the host database, then update the host database with the changed data at a later time.
  • Time-sensitive data. For example, you might want to update data reflecting employee pay raises before the new pay rates actually take effect.

Working with offline views

Using the offline view, you can display and update data much as you do online with the same forms, reports, or applications.

To create and use view data offline, you can use the following language features

  • The CREATEOFFLINE( ) function
  • The USE SQLViewName command with the ADMIN and ONLINE clauses

    For example, the following code opens the Showproducts view:

    USE Showproducts
  • The TABLEUPDATE function
  • The DROPOFFLINE( ) function

If you are not getting the subset of data that you expected, check the optimization settings for the remote view. If you set the MaxRecords property using the DBSETPROP( ) function, only that many records appear in your views offline. However, if you include a Memo field in the field list of your view, it is automatically included in the result set even if FetchMemo is set to false (.F.).

If you plan to use the offline view on a machine other than the one on which you created the offline view, you must prepare the offline destination by creating a copy of the host database file (.dbc); making sure the ODBC data source used by the view exists on the destination machine; and analyzing your data requirements to determine the contents of the view you need.

Note Use the ODBC Administrator program to install data sources on a machine. You can access the ODBC Administrator program from either the Visual FoxPro program group or from the Control Panel.

After you create the view for your offline data, you can use it as you would any view in your application: you can add, change, and delete records. Multiple users can access the offline view concurrently using the same database in shared mode. If you decide you do not want to keep any of the changes, you can revert the information to reflect the original information.

Administering Data Offline

In some cases — especially in a multiple-user environment where numerous people modify data — you might want to examine changes made to the offline view before committing the changes to the source database. With the USE command and the ADMIN clause, you can see all changes that have been committed to a view since it was taken offline. You can then selectively revert changes that have been made without being connected to the data source. For example, the following code opens the view Showproducts in administrator mode:

USE Showproducts ADMIN

See Also

Working with Views | Combining Views | Creating Offline Views | Creating Queries | Updating to Online Data | Customizing Views


Creating Offline Views

As with online data, analyze your requirements before creating offline views to determine the design of the views you will need in the offline database. Once you know the subset of data you want to use offline, you can start with an existing view or create a new view. If a view already exists that returns the records you want to use offline, you can use it, or you can create one programmatically. The view you take offline is stored in a .dbf file in the offline database container.

Note If you plan to modify data in an offline view, be sure to make the view updateable before you take it offline. Once a view is offline, you can only set its update properties programmatically; you cannot modify an offline view in the View Designer.

To use an existing view offline

  • Use the CREATEOFFLINE( ) function and the name of the view.

For example, if you want to go to client sites to update accounts, add customers, and record new sales, you need the customer information as well as current orders and the online product descriptions. You might have a view called customerinfo that combines information from the Customers table, Orders table, and OrderItems table. To create the view, use this code:

CREATEOFFLINE("customerinfo")

To programmatically create a view offline

  • Use the CREATE SQL VIEW command, followed by the CREATEOFFLINE( ) command.

For example, the following code creates a view that displays data from the Products table and the Inventory table from the online database. Since no update criteria are specified, this view is read-only:

CREATE SQL VIEW showproducts ;
   CONNECTION dsource ;
   AS SELECT * FROM Products INNER JOIN Inventory ;
   ON Products.ProductID = Inventory.ProductID ;
CREATEOFFLINE("showproducts")

See Also

Manipulating Offline Data | Creating Queries | Updating to Online Data | Optimization of View Performance


Updating to Online Data

After you're finished offline, you can update the data on the server using the same table update transactions you usually use with online data. When working with remote data, keep in mind the following tips:

  • For single record updates, use automatic transactions.
  • For batch updates, use manual transactions.
  • As necessary, include code to detect update conflicts, create a log of conflicts, and resolve conflicts.

Before you can process your updates, you need to use the USE command and the ONLINE keyword to reconnect to the host database. After you issue the command, Visual FoxPro attempts to locate the host database using the data source information stored in the view. After the connection is established, you can use TABLEUPATE( ) to process the updates stored in the offline data.

To make sure the connection information is correct regardless of the location of either the host or view tables, you need to use connection string syntax rather than a named connection.

Updating Batches of Records in Local Tables

To process a batch of changes against local tables, you can use manual transactions that allow you to process the entire batch of changes within a single transaction rather a series of separate transactions.

Updating local tables with offline views

Code Comments
USE myofflineview ONLINE EXCLUSIVE
 Reconnect to the host and open the view.
BEGIN TRANSACTION
IF TABLEUPDATE (2, .F., "myofflineview")
   END TRANSACTION
ELSE
   MESSAGEBOX("Error Occurred: Update unsuccessful.")
   ROLLBACK
ENDIF
 Check for update conflicts and update as appropriate.

Updating Batches of Records in Remote Tables

To process a batch of changes against remote tables, use manual transactions: begin with TABLEUPDATE( ) and finish processing with either SQLCOMMIT( ) or SQLROLLBACK( ).

To set the connection to manage your transactions manually, you need to use CURSORGETPROP( ) on the view cursor to get the connection handle, then set the Transactions property to manual mode.

In the following code, the current connection identification for the view, myview, is stored into hConn1. hConn1 is used to set the Transactions property to "2" for manual transactions.

hConn1 = CURSORGETPROP("CONNECTHANDLE","myview") ;
SQLSETPROP(hConn1,"TRANSACTIONS",2)

After you set the connection to handle the updates, you can use TABLEUPDATE( ) to handle your transactions.

If the host tables reside on a remote server, such as SQL Server, you might use the following code as a guideline.

Updating remote tables with offline views

Code Comment
USE myofflineview ONLINE EXCLUSIVE
 Reconnect to the host and open the view.
SQLSetProp(liviewhandle,"transactions",2)
SQLSetProp(custviewhandle,"transactions",2)
SQLSetProp(ordviewhandle,"transactions",2)
Setting the connections on the views to handle transaction manually.
IF NOT TABLEUPDATE(.T.,.F.,"lineitemsview")
   =SQLROLLBACK(ordviewhandle)
   =MESSAGEBOX("Can't update line items table")
   IF NOT TableUpdate(.T.,.F.,"ordersview")
      =SQLROLLBACK(liviewhandle)
      =MESSAGEBOX("unable to update the orders table")
      IF NOT TABLEUPDATE(.T.,.F.,"customerview")
         =SQLROLLBACK(custviewhandle)
         =MESSAGEBOX("Can't update customer table")
      Else *# check out failure scenarios
         IF NOT SQLCOMMIT(liviewhandle)
            =SQLROLLBACK(liviewhandle)
            IF NOT SQLCOMMIT(ordviewhandle)
               =SQLROLLBACK(ordviewhandle)
               IF NOT SQLCOMMIT(custviewhandle)
                  =SQLROLLBACK(custviewhandle)
               ENDIF
            ENDIF
         ENDIF
      ENDIF
   ENDIF
ENDIF
 Handling updates and update conflicts.

Updating One Record

If you are updating a single row, you can use automatic transactions. Because each statement to process an update, delete, or insert is handled as a separate transaction, rollbacks against prior transaction statements are not possible.

USE customerview ONLINE EXCLUSIVE
GO TO 3
   IF TABLEUPDATE (0, .F. workarea)
      * conflict handling code
   ENDIF
Tip To update a single record in a local table, use the GETNEXTMODIFIED( ) function.

Canceling Offline Updates

If you decide you want to delete the offline data and convert the view back to an online view, you can use the DROPOFFLINE( ) function.

To cancel offline updates

  • Use DROPOFFLINE( ) with the name of the view.

Be sure to check the return values. True (.T.) indicates success and false (.F.) indicates that the view was not closed before the command was issued.

The following code drops all of the changes made to the subset of data in myview. The view remains part of the database, but its current set of data is dropped:

DROPOFFLINE("myview")

You can delete offline records, but you can't use the PACK, ZAP, or INSERT commands with an offline view.

See Also

Optimization of View Performance | Creating Queries | Setting the Maximum Number of Records Downloaded | USE | TABLEUPATE( ) | SQLCOMMIT( )


Optimizing View Performance

You can optimize your views by setting data fetching and performance options. Use the Advanced Options dialog box to fine tune how records are retrieved in a view or how updates are made to the server or source tables.

To set advanced options

  1. From the Query menu, choose Advanced Options.
  2. In the Advanced Options dialog box, set the connection information and data fetching options you need.
  3. Choose OK.

Controlling Progressive Fetching Fetch Size

You can control the number of rows Visual FoxPro progressively fetches at one time from the host database with the FetchSize property of the view and the active view cursor. You use DBSETPROP( ) and CURSORSETPROP( ) to set these properties.

Controlling Memo Fetching

You can use the delayed memo-fetching feature to speed retrieval of view data. When you choose delayed memo fetching, Visual FoxPro does not retrieve the contents of a Memo field until you choose to open and display the field. Because Visual FoxPro needs the key field and table name to locate a row on the remote data source, you must set the UpdateName or UpdateableFieldList property, the KeyField or KeyFieldList property, and the Tables property for delayed Memo fetching to work. However, you don't have to set the SendUpdates or Updateable properties to on in order to make delayed memo fetching work.

See Also

Working with Views | Updating to Online Data | Setting the Maximum Number of Records Downloaded | Creating Queries | Optimizing Filters and Joins | Sharing Connections for Multiple Remote Views | Advanced Options | DBSETPROP( ) | CURSORSETPROP( )


Setting the Maximum Number of Records Downloaded

You can control the amount of data downloaded when you open a view by setting the MaxRecords property. When Visual FoxPro sends a SQL statement to the data source to create a view, the data source builds and stores a result set. The MaxRecords property specifies the maximum number of rows fetched from the remote result set into your view. The default setting is –1, which downloads all rows in the result set.

To control the number of rows downloaded into a view

  • From the Tools menu, choose Options and select the Remote Data tab; then in the Remote view defaults area, next to the Maximum records to fetch box, clear All, enter a value in the text box, and then choose OK.

    -or-

  • Use the MaxRecords property of the DBSETPROP( ) or CURSORSETPROP( ) function.

For example, the following code alters the view definition to limit the number of rows downloaded into the view to 50, regardless of the size of the result set built on the remote data source:

OPEN DATABASE testdata
USE VIEW remote_customer_view
?DBSETPROP ('Remote_customer_view', ;    'View','MaxRecords', 50)

You can use the CURSORSETPROP( ) function to set the MaxRecords limit for an active view.

Tip You can't use the MaxRecords property to stop a runaway query, because the MaxRecords property doesn't control the building of the result set. Use the QueryTimeOut property to control the execution time on the remote data source.

See Also

Optimization of View Performance | Optimizing Filters and Joins | Creating Queries | Sharing Connections for Multiple Remote Views | Testing a Connection for Busyness


Optimizing Filters and Joins

To make optimization decisions for a view or query, you might need to know the execution plan: the order that joins and filter clauses will be evaluated. Using the SYS(3054) function, you can display one of three Rushmore Query Optimization levels. The three levels indicate the degree to which the filter conditions or join conditions were able to use Rushmore optimization. The levels are completely (Full), partially (Partial) or not at all (None).

To display the execution plan for filters

  1. In the Command window, type SYS(3054,1) to enable SQL ShowPlan.
  2. Type your SQL SELECT statement.

    For example, you might type:

    SELECT * FROM customer, orders ;
AND Upper(country) = "MEXICO"
  3. On the screen, read the execution plan.

    For this example, the screen might display:

    Using Index Tag Country to optimize table customer
Rushmore Optimization Level for table customer: Full
Rushmore Optimization level for table orders: none
  4. In the Command window, type SYS(3054,0) to turn off SQL ShowPlan.

You can then pass 11 to the SYS function to evaluate joins in the FROM or WHERE clauses.

To display the execution plan for joins

  1. In the Command window, type SYS(3054,11) to enable SQL ShowPlan.
  2. Enter your SQL SELECT statement.

    For example, you might type:

    SELECT * ;
FROM customer INNER JOIN orders ;
   ON customer.cust_id = orders.cust_id ;
WHERE Upper(country) = "MEXICO"
  3. On the screen, read the execution plan.

    For this example, the screen might display:

    Using Index Tag Country to optimize table customer
Rushmore Optimization Level for table customer: Full
Rushmore Optimization level for table orders: none
Joining table customer and table orders using Cust_id
  4. In the Command window, type SYS(3054,0) to turn off SQL ShowPlan.

Controlling Join Evaluation

If the execution plan for your joins does not match your specific needs, you can force your join order to execute exactly as written without optimization from the processor. To force the evaluation order of the join, you need to add the FORCE keyword and place your join conditions in the FROM clause. Join conditions placed within the WHERE clause are not included in a forced join evaluation.

Note You can't use the FORCE keyword in SQL pass-through statements or remote views because this keyword is a Visual FoxPro extension of the ANSI standard and is not supported in other SQL dictionaries. The FORCE clause is global and therefore applies to all tables in the JOIN clause. Be sure that the order in which the join tables appear is exactly the order in which they should be joined. You can also use parentheses to control the evaluation order of joins.

In this example, the first join specified is also the first join evaluated. The Customer table is joined with the Orders table first. The result of that join is then joined with the OrdItems table:

SELECT * ;
   FROM FORCE Customers ;
   INNER JOIN Orders ;
      ON Orders.Company_ID = Customers.Company_ID ;
   INNER JOIN OrItems;
      ON OrdItems.Order_NO = Orders.Order_NO

In this example, the join within the parentheses for the table Orders and OrdItems is evaluated first. The result of that join is then used in the evaluation of the join with Customers:

SELECT * ;
FROM FORCE Customers ;
   INNER JOIN (orders INNER JOIN OrdItems ;
      ON OrdItems.Order_No = Orders.Order_No) ;
      ON Orders.Company_ID = Customers.Company_ID

See Also

Setting the Maximum Number of Records Downloaded | Creating Queries | Sharing Connections for Multiple Remote Views | Testing a Connection for Busyness | SYS(3054)


Sharing Connections for Multiple Remote Views

You can use one active connection as the information pipeline for multiple remote views by sharing a connection. When you share an active connection, you:

  • Reduce the number of connections on a remote server.
  • Reduce costs for connections to servers that charge on a per-connection basis.

You share connections by setting the view definition to use a shared connection upon activation. When the view is used, Visual FoxPro connects to the remote data source using the existing shared connection (if any). If a shared connection isn't in use, Visual FoxPro creates a unique connection when the view is opened, which can then be shared with other views.

Only one active instance of a named connection definition is shared during a Visual FoxPro session. If multiple instances of the same connection definition are active, the first instance to be used as a shared connection becomes the designated shared connection. All views that use that connection definition and employ connection sharing will access the remote server through the designated shared connection.

Connections other than the designated shared connection are not shared. Connection sharing is not scoped to sessions.

To share a connection

  • From the Tools menu, choose Options and select the Remote Data tab; then select Share connection in the Remote view defaults area and choose OK.

    -or-

  • Use the View Designer.

    -or-

  • Use the CREATE SQL VIEW command with the SHARE clause.

The following code creates a view that, when activated with the USE command, shares a connection:

CREATE SQL VIEW product_view_remote ;
   CONNECTION remote_01 SHARE AS ;
   SELECT * FROM products
USE product_view_remote

See Also

Optimizing Filters and Joins | Creating Queries | Testing a Connection for Busyness | Setting the Maximum Number of Records Downloaded | Optimization of View Performance


Testing a Connection for Busyness

When a connection is busy, such as when Visual FoxPro is progressively fetching data into a cursor, you don't want to start another fetch or send updates on the same connection. You can determine whether a connection is busy with the ConnectBusy property, which returns a value of true (.T.) if the connection is busy. You can use this property in your application to test a connection before sending a request over a shared connection to a remote data source.

To determine whether a connection is busy

  • Use the ConnectBusy property of SQLGETPROP( ).

You need the connection handle to use the SQLGETPROP( ) function. You can identify the connection handle for an active view with the ConnectHandle property of the CURSORGETPROP( ) function. The following code identifies a connection handle and then uses the connection handle to test whether the connection is busy:

nConnectionHandle=CURSORGETPROP('ConnectHandle')
SQLGETPROP(nConnectionHandle, "ConnectBusy")

See Also

Sharing Connections for Multiple Remote Views | Creating Queries | Optimizing Filters and Joins | Setting the Maximum Number of Records Downloaded | Optimization of View Performance


Importing and Exporting Data

You can copy data between Visual FoxPro and other applications by importing to and exporting from Visual FoxPro. The data can be in any one of a variety of text, spreadsheet, and table file formats. You can create a new Visual FoxPro table, add to an existing Visual FoxPro table, or copy data to a different file type.

In This Section

Importing and Exporting Concepts
When you import or append data, you bring the data from another application into Visual FoxPro. When you export data, you send data from a Visual FoxPro table to a file type used by another application.
Process of Importing Data
If you want to import from your source file, you can either let Visual FoxPro define the structure of the new table or use the Import Wizard to specify its structure.
Process of Appending Data
You can add your text, spreadsheet, or table data to an existing Visual FoxPro table. By default, Visual FoxPro uses the file type to map the source fields to the destination table.
Process of Exporting Data
You can export data from your Visual FoxPro tables to text files, spreadsheets, or tables used in other applications.

Related Sections

Working with Data
Find out how to create effective applications with indexes, tables, and databases based on your data requirements.
Using Visual FoxPro
Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
This section includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Importing and Exporting Concepts

You can choose from three ways to copy data into or out of Visual FoxPro:

  1. Importing
  2. Appending
  3. Exporting

When you import or append data, you bring the data from another application into Visual FoxPro. When you export data, you send data from a Visual FoxPro table to a file type used by another application. These methods allow you to copy and use, rather than link or share, the data.

When you import data, you copy data from a source file, create a new table, and populate the table with the file's data. For example, you can import the data from a dBASE table to create a Visual FoxPro table. After importing a file, you can use it like any other Visual FoxPro table.

When you append data, you add the source data to a Visual FoxPro table after the last record in the table. You can specify fields to import and select records that meet a condition in an expression. After appending from the file, you can view and edit the records in the Visual FoxPro table.

When you export, you copy data from a Visual FoxPro table into a new file formatted for use in another application. For example, you can export Visual FoxPro data to a Microsoft Excel worksheet file.

You select the source and destination files. You can also specify fields to export, set the scope of records to export, and select records that meet a condition.

See Also

Importing and Exporting Data | Process of Importing Data | Importing Data with the Import Wizard | Importing Data into a New Table | Importing from Lotus 1-2-3 | Process of Appending Data | Process of Exporting Data


Process of Importing Data

If you want to import from your source file, you can either let Visual FoxPro define the structure of the new table or use the Import Wizard to specify its structure. Visual FoxPro uses the field order in the source file to define the structure of the destination table. If you want to define the structure, you can modify the file in the source application or use the Import Wizard.

If you no longer have access to the application that supports the source file and you want to change the order or data type of the fields, you can import the source file, then create a query that outputs the fields in the order you want to another new table.

When you import a file, you must choose the file type you want to import and specify the source file and destination table names.

Choosing a File Type to Import

The following table lists the file types you can import into Visual FoxPro:

File Type | File Extension | Description
Microsoft Excel | xls | A Microsoft Excel (versions 2.0, 3.0, 4.0, 5.0, and 97) worksheet format. The column cells become fields, and rows become records.
Lotus 1-2-3 | wks wk1 wk3 | A Lotus 1-2-3 spreadsheet for releases 1-A, 2.x, and 3.x. The column cells become fields and rows become records.
Borland Paradox | db | A Paradox table for versions 3.5 and 4.0.

If you want to use tables from a previous version of FoxPro or use dBASE files, you can open and use them without importing. Visual FoxPro will ask if you want to convert the table to the latest version of Visual FoxPro. Once you convert a table from a previous version, this table cannot be opened in the previous version.

For more information on importing files, see the IMPORT command.

For considerations that affect importing Microsoft Excel, Lotus, and Microsoft Access data, see Choosing a File Type to Import.

See Also

Importing and Exporting Data | Importing and Exporting Concepts | Importing Data with the Import Wizard | Importing Data into a New Table | Importing from Lotus 1-2-3 | Translating Lotus Date Fields


Importing Data with the Import Wizard

The Import Wizard helps you to create a new table from your source file. The wizard asks you a series of questions, imports the file based on your answers, and allows you to control how the new table is structured.

To import a file with the Import Wizard

  1. From the File menu, choose Import.
  2. From the Import dialog box, choose Import Wizard.
  3. Follow the instructions on the wizard screens.

See Also

Process of Importing Data | Importing Data into a New Table | Importing and Exporting Data | Importing from Lotus 1-2-3 | Translating Lotus Date Fields | Importing from Microsoft Excel


Importing Data into New Tables

You can import data from a table or spreadsheet format using the source file's structure to define the new table.

To import data to a new table

  1. From the File menu, choose Import.
  2. In the Type box, enter the format of the file you want to import.
  3. In the From box, enter the name of the source file.
  4. If you selected a spreadsheet in the Type box, enter the sheet number in the Sheet box that appears.
  5. Choose OK.

    Visual FoxPro creates a new table using the source file.

If you want to import to a new table from a text file without using the Import Wizard, you need to create a new table with fields that match the order, data type, and width of the fields in the text file and then append the text to the new table.

After importing the file, you can add the new table to the database of your choice. You can also modify the new table using the Table Designer.

See Also

Table Creation | Table Designer | Adding Tables to a Database | Importing Data with the Import Wizard | Importing from Lotus 1-2-3 | Importing and Exporting Data | Translating Lotus Date Fields | Importing from Microsoft Excel | Process of Appending Data


Importing from Lotus 1-2-3

When you import spreadsheet data, Visual FoxPro uses the first row in your Lotus 1-2-3 spreadsheet to determine the data types of the fields in the new table. If the first row has literal text headings for each column, all the fields in the table will be character fields, even if the rest of the rows contain numeric data.

To make sure fields have the appropriate data type

  • In Lotus 1-2-3, modify the spreadsheet so that the first row contains the first record of data you want in the table.
    Caution If your worksheet is from version 2.x or 3.x (file extension .wk1 or .wk3) and has columns with more than eight or nine characters, Visual FoxPro truncates character fields to nine characters for version 2.x worksheets and eight characters for version 3.x. To prevent truncated fields in your table, you can use the Import Wizard or create a Visual FoxPro table, then append records from the worksheet.

Lotus stores dates as the non-negative number of days from January 1, 1900. If the new table does not have the correct data type, you can translate the Lotus date fields in Visual FoxPro.

See Also

Importing Data into a New Table | Translating Lotus Date Fields | Importing and Exporting Data | Importing from Microsoft Excel | Process of Appending Data | Importing Data with the Import Wizard | Importing Data into a New Table


Translating Lotus Date Fields

If Lotus date fields imported incorrectly, you can translate them by adding the Julian date for January 1, 1900 (the value 2415019) to the date value in the field.

To translate Lotus date fields

  1. Import the spreadsheet to a Visual FoxPro table.
  2. Use the Table Designer to modify the table and add a new date field to the table.
  3. If the date was imported as a numeric value, use the REPLACE command and CTOD( ) function to copy the date to the new field:
    REPLACE ALL NewDateField ;
   WITH CTOD(SYS(10,OldDateField+2415019))

    -or-

    If the date was imported as a character value, use the following command to copy the date to the new field:

    REPLACE ALL NewField ;
   WITH CTOD(SYS(10,VAL(OldField)+2415019))
  4. From the table, delete the original, incorrect date field.

See Also

Importing from Lotus 1-2-3 | Importing from Microsoft Excel | Importing and Exporting Data | Process of Appending Data | Importing Data into a New Table | Importing Data with the Import Wizard


Importing from Microsoft Excel

When you import worksheet data, Visual FoxPro uses the first row in your Microsoft Excel worksheet to determine the data types of the fields in the new table. If the first row has literal text headings for each column, all the fields in the table will be character fields, even if the rest of the rows contain numeric data.

To make sure fields have the appropriate data type

  • In Microsoft Excel, modify the worksheet so that the first row contains the first record of data you want in the table.
    Caution If a field in your Microsoft Excel worksheet has a field length of 255, that field is truncated to 254 when it is imported to a Visual FoxPro table.

See Also

Translating Lotus Date Fields | Process of Appending Data | Importing and Exporting Data | Importing from Lotus 1-2-3 | Importing Data with the Import Wizard | Process of Importing Data


Process of Appending Data

You can add your text, spreadsheet, or table data to an existing Visual FoxPro table. By default, Visual FoxPro uses the file type to map the source fields to the destination table. You can also select fields and records to append. If you want to control the field mapping, you can use the Import Wizard, but field selection and logical expression options are not available.

Choosing a File Type to Append

The following table lists the file types you can append to Visual FoxPro:

File Type | File Extension | Description
Table | dbf | A FoxPro® table from a database outside the current database or a dBASE file.
Tab delimited | txt | A text file with a tab separating each field.
Comma delimited | txt | A text file with a comma separating each field.
Space delimited | txt | A text file with one space separating each field.
System Data Format | sdf | A text file with fixed length records ending with a carriage return and line feed.
Microsoft Excel | xls | A Microsoft Excel (versions 2.0, 3.0, 4.0, 5.0, and 97) worksheet format. The column cells become fields and rows become records.
Lotus 1-2-3 | wks wk1 wk3 | A Lotus 1-2-3 spreadsheet for releases 1-A, 2.x, and 3.x. The column cells become fields and rows become records.
Borland Paradox | db | A Paradox table for versions 3.5 and 4.0.

For more information on appending files, see the APPEND FROM command.

See Also

Importing from Microsoft Excel | Appending Data with the Import Wizard | Importing and Exporting Data | Appending Data to an Existing Table | Selecting Fields to Append | Process of Importing Data


Appending Data with the Import Wizard

The Import Wizard asks you a series of questions and appends the data from the source file based on your answers. Using the wizard, you can choose to map the source fields to the destination fields by changing the column numbers.

To append from a file with the Import Wizard

  1. From the File menu, choose Import.
  2. From the Import dialog box, choose Import Wizard.
  3. Follow the instructions on the wizard screens.

See Also

Process of Appending Data | Appending Data to an Existing Table | Importing and Exporting Data | Selecting Fields to Append | Selecting Records to Append | Process of Exporting Data


Appending Data to Existing Tables

You can add records to the active table from another file. By default, Visual FoxPro adds all of the records and fields to the table. Using Append From options, you can specify fields or select records. For more information about field and record selection, see the sections Selecting Fields to Append and Selecting Records to Append.

To append data

  1. Browse the destination table.
  2. From the Table menu, choose Append Records.
  3. In the Type box, enter the format of the source file.
  4. In the From box, enter the name of the source file.
  5. In the To box, make sure the correct table name is showing.
    Tip If the table name is not correct, choose Cancel, and then open the correct destination table. The To box shows the table active at the time you selected the Append From command.
  6. If you want to specify fields or select records to append, choose Options and complete the Options dialog box.
  7. Choose OK.

    Visual FoxPro adds the records to the table.

See Also

Appending Data with the Import Wizard | Selecting Fields to Append | Importing and Exporting Data | Selecting Records to Append | Process of Exporting Data


Selecting Fields to Append

You may want to append only certain fields from your source file. You can select the fields to include in the Append From process.

To select fields to append

  1. From the Table menu, choose Append Records.
  2. In the Append From dialog box, enter the source file type and name, and then choose Options.
  3. In the Append From Options dialog box, choose Fields. The Field Picker dialog box displays the fields in the destination table.
  4. Select fields that match those you want to append from the source file and choose move, then choose OK.

    The fields you select appear in the Selected Fields box.

  5. Choose OK.

See Also

Appending Data to an Existing Table | Importing and Exporting Data | Selecting Records to Append | Process of Exporting Data | Appending Data with the Import Wizard


Selecting Records to Append

If you only want to append certain records, you can use a FOR expression. Visual FoxPro uses the expression to search the entire file and append only records that match the expression you provide. The fields you specify in the FOR expression must exist in both the source and destination files.

To select records to append

  1. Browse the destination table, and then from the Table menu, choose Append Records.
  2. Enter the source file type and name, and then choose Options.
  3. Choose For to build an expression in the Expression Builder dialog box.
    Note You do not need to enter the command FOR because it is implied. For example, type customer.country = "Canada" to append only Canadian information.
  4. Choose OK.

Appending Text Files

If you append from a text file, Visual FoxPro assumes your fields are separated by commas and that each character field is enclosed by quotation marks. If you have set the decimal point character to display as a comma, numeric and currency data might be parsed into separate fields.

Appending Numeric or Currency Text

If you changed the Visual FoxPro decimal point character to a comma, numeric and currency data might be parsed into separate fields when you append or export the data. For example, Visual FoxPro would translate the value 100,00 into two fields because it appears to be delimited with a comma. Choose one of two methods to make sure the comma is properly translated:

  • Use tabs to separate fields in the text file
  • Change the decimal point character back to a period

If you want to append from a text file, change the field separators to tabs, then use the APPEND FROM command with the keywords DELIMITED WITH TAB.

If you want to change the decimal point character to a period before appending text files, you can change the character back to a comma after you append the file.

To change the decimal point character

  1. In the Command window, type the following command.
    SET POINT TO
  2. Import the file using the DELIMITED keyword.
  3. In the Command window, type the following command to reset the decimal point character to a comma.
    SET POINT TO ','

See Also

Selecting Fields to Append | Process of Exporting Data | Importing and Exporting Data | Appending Data to an Existing Table | Appending Data with the Import Wizard | Process of Appending Data


Process of Exporting Data

You can export data from your Visual FoxPro tables to text files, spreadsheets, or tables used in other applications. The exporting process requires a source table and the destination's file type and name. If you want, you can select which fields and record to export. You can use the new file in any application that supports the file type you select.

Choosing a File Type to Export

The following table lists the file types you can export from Visual FoxPro:

File type | File extension | Description
Tabs delimited | txt | A text file with a tab separating each field.
Comma delimited | txt | A text file with a comma separating each field.
Spaces delimited | txt | A text file with one space separating each field.
System Data Format | sdf | A text file with fixed length records ending with a carriage return and line feed.
Table | dbf | A Visual FoxPro, FoxPro, FoxBASE+®, dBASE, or Paradox 3.5 or 4.0 table.
Microsoft Excel | xls | A Microsoft Excel (versions 2.0, 3.0, 4.0, 5.0, and 97) worksheet format. The column cells become fields and rows become records. You can export a maximum of 65,535 rows, which includes one row reserved for the field header.
Lotus 1-2-3 | wks wk1 | A Lotus 1-2-3 spreadsheet for releases 1-A, 2.x, and 3.x. The column cells become fields and rows become records.

For more information on exporting, see the COPY TO command.

See Also

Selecting Records to Append | Exporting Data to a New File | Importing and Exporting Data | Exporting a Quantity or Range of Records | Exporting Records That Match a Condition | Controlling the Record Export Process


Exporting Data to New Files

You can copy all of the fields and records from your Visual FoxPro table to a new file or you can copy only the fields and records you select.

To export data

  1. From the File menu, choose Export.
  2. In the Type box, enter the destination file type.
  3. In the To box, enter the destination file name.
  4. In the From box, enter the source file name.
  5. If you want to select fields or records to export, choose Options and complete the Export Options dialog box.
  6. Choose OK.

Selecting Fields to Export

By default, Visual FoxPro exports all of the fields in the source table to the destination file. You can select which fields to export by using the Export Options dialog box.

To select fields to export

  1. From the File menu, choose Export.
  2. In the Export dialog box, enter the destination file type and name.
  3. In the From box, enter the source file name.
  4. Choose Options.
  5. Choose Fields and select the fields from the Field Picker dialog box.
  6. Choose OK.

Selecting Records To Export

When you export data, you might want to limit the number of records that are copied to the new file by providing selection criteria. You can:

  • Choose a scope of records by specifying a quantity or range.
  • Build a FOR expression that selects records that match a condition.
  • Build a WHILE expression that selects records until one record is found that does not match a condition.

You can use any combination of these options. The WHILE expression overrides the other criteria.

See Also

Process of Exporting Data | Exporting a Quantity or Range of Records | Importing and Exporting Data | Exporting Records That Match a Condition | Controlling the Record Export Process | Exporting Text Files


Exporting a Quantity or Range of Records

One way you can limit the number of records is to specify a quantity or range of records. Using the Scope option, you can export a single record or a group of records positioned sequentially in the file.

Note The active index and the current record pointer affect the results of the scope options Next and Rest. For example, the next record in a table indexed by last name is probably different than one in a table indexed by state. This does not affect the Record option because the number for a record does not change when the table is indexed.

To export a limited number of records

  1. From the File menu, choose Export.
  2. Enter the source table and destination file information.
  3. Choose Options.
  4. Choose Scope.
  5. Select the appropriate Scope option and complete the Scope dialog box.
    To export | Choose
    Every record from the source file | All
    A range of records starting with current record | Next
    A specific record by number | Record
    The current record plus all of those after it to the end of the file | Rest
  6. Choose OK.

    Visual FoxPro exports records within the scope you select.

See Also

Exporting Data to a New File | Exporting Records That Match a Condition | Importing and Exporting Data | Controlling the Record Export Process | Exporting Text Files | Exporting Numeric or Currency Values | Process of Exporting Data


Exporting Records That Match Conditions

If the records you want to export are not sequential within the table, you can build a logical expression that specifies the selection criteria a record must meet to be exported. For example, you can choose to export all records with a particular value in a field.

To enter criteria for exporting records

  1. From the File menu, choose Export.
  2. Enter the source table and destination file information.
  3. Choose Options.
  4. Choose For to build an expression in the Expression Builder dialog box.
    Note You do not need to include the FOR command in the expression. For example, type customer.country = "Canada" to export only Canadian data.
  5. Choose OK.

    Visual FoxPro evaluates all of the records and exports those that match the condition in the expression.

See Also

Exporting a Quantity or Range of Records | Controlling the Record Export Process | Importing and Exporting Data | Exporting Text Files | Exporting Numeric or Currency Values | Process of Exporting Data


Controlling the Record Export Process

When exporting, you can specify a condition that must be met to continue evaluating and selecting records. You enter this condition as a WHILE expression.

As long as the WHILE expression remains true, Visual FoxPro processes the source table. After finding a record that does not meet the condition, Visual FoxPro ends the evaluation process and exports the selected records. This option allows you to export records based on information outside of the values contained in the fields.

Tip If you use a WHILE expression on a file that has not been indexed, the export process may end before evaluating all of the appropriate records. Before performing the export procedure, be sure the source table has the appropriate index active for the WHILE expression you want to use.

To enter criteria for ending record export

  1. From the File menu, choose Export.
  2. Enter the source table and destination file information.
  3. Choose While to build an expression in the Expression Builder dialog box.
    Note You do not need to include the WHILE command in the statement. For example, type sales > 1000 to see only sales above one thousand dollars.
  4. Choose OK.

    Visual FoxPro exports the records it evaluates while the expression is true.

See Also

Exporting Records That Match a Condition | Exporting Text Files | Importing and Exporting Data | Exporting Numeric or Currency Values | Process of Exporting Data


Exporting Text Files

If you export to a text file, Visual FoxPro assumes that your fields are separated by commas and that each character field is enclosed by quotation marks. If you have set the decimal point character to display as a comma, numeric and currency data might be parsed into separate fields.

To export to a text file, use the COPY TO command with the appropriate DELIMITED clause as shown in the following table:

For these separators | Use this DELIMITED clause
Commas between fields and quotation marks enclosing character fields | DELIMITED
Character fields enclosed by a character other than quotation marks | DELIMITED WITH delimiter
Tabs between fields | DELIMITED WITH TAB
Spaces between the fields | DELIMITED WITH BLANK1

1 Date and times separated by a space will be parsed as two fields with these keywords

See Also

Controlling the Record Export Process | Importing and Exporting Data | Exporting Numeric or Currency Values | Exporting Records That Match a Condition | Exporting a Quantity or Range of Records | Process of Exporting Data


Exporting Numeric or Currency Values

If you changed the Visual FoxPro decimal point character to a comma, numeric and currency data might be parsed into separate fields when you append or export the data. For example, Visual FoxPro would translate the value 100,000 into two fields because it appears to be delimited with a comma. Choose one of two methods to make sure the comma is properly translated:

  • Use tabs to separate fields in the text file
  • Change the decimal point character back to a period

If you want to export the text, use the COPY TO command with the keywords DELIMITED WITH TAB.

If you want to change the decimal point character to a period before exporting text files, you can change the character back to a comma after you export the file.

To change the decimal point character

  1. In the Command window, type the following command.
    SET POINT TO
  2. Export the file using the DELIMITED keyword.
  3. In the Command window, type the following command to reset the decimal point character to a comma.
    SET POINT TO ','

See Also

Exporting Text Files | Controlling the Record Export Process | Importing and Exporting Data | Exporting Records That Match a Condition | Exporting a Quantity or Range of Records | Process of Exporting Data


Upsizing Visual FoxPro Databases

When you have designed your client/server application, you are ready to build and upsize a local prototype. A local prototype is a working model of your application using Microsoft Visual FoxPro tables, views, and databases to represent data that eventually will be accessed on a remote server. Use the upsizing wizards to move databases, tables, and views from your system to a remote Microsoft SQL Server server.

In This Section

Goals for Prototyping
When you use Microsoft Visual FoxPro to build a prototype of your application, you are leveraging the power of visual forms, wizards, builders, designers, and the Project Manager to quickly develop a working application.
Building a Local Prototype of an Application
When you build a local prototype of your application, you might be starting from scratch, or you might be converting an existing Microsoft Visual FoxPro application to a client/server application.
Database Creation with Upsizing Wizards
The Visual FoxPro SQL Server Upsizing Wizard creates SQL Servers that duplicate, as much as possible, the functionality of a set of tables in a Microsoft Visual FoxPro database.
SQL Server Upsizing Wizard Preparation
Before you run the SQL Server Upsizing Wizard, you must prepare both the client and server sides.

Related Sections

Developing Visual FoxPro Applications
This section includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Creating the Application
Discusses how to create Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Setting the Starting Point
Describes how the main file is the starting point for your application, and can consist of a program or form. When your application is run, Visual FoxPro launches the main file for your application, which in turn runs all other components as needed.
Initializing the Environment
Setting up the application environment is the first task that a main file or application object must accomplish.
Controlling the Event Loop
Learn how to establish an event loop to, which causes Visual FoxPro to begin processing user events such as mouse clicks and keystrokes. This occurs after the environment is set up and you've displayed the initial user interface.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application builder.
Client/Server Performance Optimization
Learn how you can fine-tune your application to gain maximum performance by increasing data throughput.
Creating the User Interface
Learn how creating forms, classes, controls, and toolbars can provide a rich set of tools for your user interface.
Creating International Applications
Describes how you can design and develop your Visual FoxPro applications so they are as effective internationally as domestically.


Goals for Prototyping

When you use Visual FoxPro to build a prototype of your application, you're leveraging the power of visual forms, wizards, builders, designers, and the Project Manager to quickly develop a working application. While your ultimate goal is to implement your application across client/server platforms, you gain a great deal by choosing to build a solid prototype.

Reducing Development Time

By building a quick prototype, you can refine your application's design and local architecture quickly and easily, without having to access the remote server to rebuild server tables and databases. You can also test and debug your application's forms against smaller data stores, allowing you to more quickly correct and enhance your application's user interface. Because you're keeping architectural overhead low, you prevent wasting development time in rebuilding, reindexing, and reconnecting remote data just to test your prototype.

Decreasing Development Costs While Increasing Customer Satisfaction

Because the local prototype is self-contained on your computer, you can easily demonstrate a working model of your application to the end user early in the development cycle. Being able to see your application as it progresses gives clients confidence in your ability to deliver a solution that meets their needs. It also provides you with the opportunity to get customer feedback about the user interface and reports before you've invested resources in implementing it against a remote server.

As users see and interact with your prototype, they can begin to identify areas they'd like to change, as well as see the potential for adding additional functionality into their application. You can implement changes and redemonstrate the application in an iterative process until both you and the customer are satisfied with the design and function of the prototyped application. Your prototype then serves as a working specification for the final, implemented client/server application.

Contributing to Successful Implementation

You can also potentially provide the prototyped application as a demonstration for your users, allowing them to experiment with the working model as you move forward in the implementation process of the actual application. As they gain experience with the prototype, their learning curve decreases and they become better partners with you in refining and fine-tuning the application. They're also positioned to be more productive and satisfied in the final implementation stage because they already understand the basic framework of the application.

Having a working model increases the lead-time the end user has to become familiar and comfortable with the application. It also provides a framework to allow staff at your company or the customer site to design and develop a training plan for the application. The prototype can even be used to train end users before the final application is delivered, thus contributing to a successful implementation of the final, implemented client/server application.

See Also

Upsizing Visual FoxPro Databases | Building a Local Prototype of an Application | Database Creation with Upsizing Wizards | SQL Server Upsizing Wizard Preparation


Building a Local Prototype of an Application

When you build a local prototype of your application, you might be starting from scratch, or you might be converting an existing Visual FoxPro application to a client/server application. The primary difference between building a local prototype of a client/server application and developing any other Visual FoxPro application is in using local views and tables to represent data that will eventually be upsized.

To build and upsize a local prototype

  1. Create your application using local views and local tables to represent data you want to move to a remote server.
  2. Use local views in your application's data environment for forms and reports.
  3. Upsize local views and tables using the SQL Server Upsizing Wizard:
    • In the Set Upsizing Options step, in the Changes to make locally area, select Redirect views to remote data.

      When you select this option, the Upsizing Wizard copies the local tables you select to the remote server, and redirects local views to use remote data where applicable.

For more information on creating views, see Creating Views. For information on creating forms and using a data environment, see Creating Forms.

See Also

Goals for Prototyping | Database Creation with Upsizing Wizards | Upsizing Visual FoxPro Databases | SQL Server Upsizing Wizard Preparation


Database Creation with Upsizing Wizards

The Visual FoxPro SQL Server Upsizing Wizard creates SQL Server that duplicate, as much as possible, the functionality of a set of tables in a Visual FoxPro database. You can also choose to redirect Visual FoxPro views so that they use the newly created remote data instead of local data. You can use the Upsizing wizards to:

  • Move local data to a remote server.
  • Transform local base tables and local views into remote base tables and remote views.
  • Migrate a local application to a client/server application.
    Note Though the Upsizing Wizard accesses SQL Server, you can create a client/server application for any remote ODBC data source. For servers other than SQL Server, you can use SQL pass-through functions to create remote tables, then use Visual FoxPro to create remote views that access server tables. For more information on using SQL pass-through functions, see Implementing a Client/Server Application. For information on creating remote views, see Creating Views.

See Also

Building a Local Prototype of an Application | SQL Server Upsizing Wizard Preparation | Upsizing Visual FoxPro Databases | Goals for Prototyping


SQL Server Upsizing Wizard Preparation

Before you run the SQL Server Upsizing Wizard, you must prepare both the client and server sides.

Preparing the SQL Server Side

Before upsizing, you must ensure that you have necessary permissions on the server, estimate the size of your database, and check that the server has sufficient disk space. There are also special preparations for upsizing to multiple disks or devices.

Checking Free Disk Space

Make sure you have enough disk space on the server.

Caution If the SQL Server Upsizing Wizard runs out of disk space on the server, it halts, leaving a partial database and any devices it created on the server. You can remove devices, databases, and tables with the SQL Server Administration tool.

Setting Permissions on SQL Server Databases

In order to run the SQL Server Upsizing Wizard, you must have certain permissions on the SQL server to which you will be upsizing. The permissions you need depend on the tasks you want to accomplish.

  • To upsize to an existing database, you need CREATE TABLE and CREATE DEFAULT permissions.
  • To build a new database, you need CREATE DATABASE and SELECT permissions on the system tables in the master database.
  • To create new devices, you must be a system administrator.

For more information on granting server permissions, see your SQL Server documentation.

Estimating SQL Server Database and Device Size

When you create a new database, the SQL Server Upsizing Wizard asks you to select devices for your database and log. It also asks you to set the size of the database and your devices.

Estimating SQL Server Database Size

When SQL Server creates a database, it sets aside a fixed amount of space for that database on one or more devices. Not all this space is necessarily used by the database — the database size simply limits how large a database can grow before it runs out of space.

Note You can increase the size of a SQL Server database after it's created. For more information, see the ALTER DATABASE command in your SQL Server documentation.

To estimate the space needed for your database, calculate the total size of your Visual FoxPro .dbf files for the tables you want to upsize plus the rate at which your new SQL Server database will grow. In general, every megabyte of Visual FoxPro data requires at least 1.3 to 1.5 MB in the SQL Server.

If you have ample disk space on your server, multiply the size of your Visual FoxPro tables by two. This ensures that the SQL Server Upsizing Wizard has enough space to upsize your database and also leaves some room to grow. If you expect to add a lot of data to the database, increase the multiple.

Estimating SQL Server Device Sizes

All SQL Server databases and logs are placed on devices. A device is both a logical location at which to put databases and logs, and a physical file. When a device is created, SQL Server creates a file, thus reserving a set amount of disk space for its own use.

The SQL Server Upsizing Wizard displays the amount of free space available on the existing SQL Server devices. Select a device that has at least enough free space for your estimated database size.

If no existing devices have enough free space, you can use the SQL Server Upsizing Wizard to create a new device. New devices should be at least as big as your estimated database size. If possible, make the device larger than your database size, so you can expand your database later, or place other databases or logs on the same device.

Note Device size cannot be changed. Make sure you create sufficiently large devices.

Using Multiple SQL Server Disks or Devices

In most cases, the SQL Server Upsizing Wizard provides more than enough control over SQL Server devices. However, if your server has multiple disks or if you want to place a database or log on multiple devices, you might want to create devices before running the SQL Server Upsizing Wizard.

Servers with Multiple Physical Disks

If your server has more than one physical hard disk, you might want to place your database on one disk and the database log on a different disk. In the event of a disk failure, you'll be more likely to recover your database if the log and the database are stored on different physical disks.

The SQL Server Upsizing Wizard allows you to create new devices but only on one physical disk — the same disk as the Master database device.

To place a database and log on separate disks, make sure you have devices that are big enough on both disks, creating new devices if necessary. Then run the SQL Server Upsizing Wizard.

Placing Databases or Logs on Multiple Devices

SQL Server allows databases and logs to span several devices. However, the SQL Server Upsizing Wizard allows you to specify only one device for your database and one device for the log.

If you want to specify multiple devices for a database or log, make those devices (and no other devices) the default devices. Then run the SQL Server Upsizing Wizard and choose Default for the database or log device.

Note If the new SQL Server database or log sizes don't require using all the default devices, SQL Server uses only the devices necessary to accommodate the database or log.

Preparing the Client

Before upsizing, you must have access to a SQL Server through an ODBC data source or named connection. You must also have a Visual FoxPro database, which you should back up before running the SQL Server Upsizing Wizard.

Creating an ODBC Data Source or Named Connection

When you create a new remote database, you select an ODBC data source or named connection in your Visual FoxPro database that accesses the SQL Server to which you want to upsize. Because you can't proceed through the Upsizing Wizard until you select a named connection or data source, you should create the appropriate named connection or data source before you start the upsizing process.

For information on creating a named connection, see Creating Views. If you want to create an ODBC data source, run the ODBC Administrator. For information on setting up ODBC data sources, see Installing Visual FoxPro.

Backing Up Your Database

It's a good idea to create a backup copy of your database (.dbc, .dct, and .dcx files) before upsizing. While the SQL Server Upsizing Wizard doesn't modify .dbf files, it does operate on the .dbc directly by opening the .dbc as a table at times and indirectly by renaming tables and views when creating new remote views. If you back up your database, you can revert your database to its original pre-upsizing state by overwriting the upsized .dbc, .dct, and .dcx files with the original backup copies, which reverses the renaming and creation of new views.

Closing Tables

The SQL Server Upsizing Wizard attempts to exclusively open all the tables in the database to be upsized; if any tables are already open and shared, the wizard closes them and reopens them exclusively. Opening tables exclusively before upsizing protects against other users attempting to modify records in the tables you're exporting during data export. If any tables can't be opened exclusively, the SQL Server Upsizing Wizard displays a message; those tables are not available for upsizing.

See Also

Database Creation with Upsizing Wizards | Starting the SQL Server Upsizing Wizard | Upsizing Visual FoxPro Databases | How the SQL Server Upsizing Wizard Works | SQL Server Upsizing Process Completion | Goals for Prototyping |


Starting the SQL Server Upsizing Wizard

After you create an ODBC data source and complete the necessary preparations on the client and server, you're ready to begin upsizing.

To start the SQL Server Upsizing Wizard

  1. From the Tools menu, choose Wizards, and then choose Upsizing.
  2. From the Wizard Selection dialog box, choose SQL Server Upsizing Wizard.
  3. Follow the directions in the wizard screens, as described in the following sections.

    You can choose Cancel at any time to exit the wizard; the wizard performs no actions on the server until you choose Finish.

  4. When you're ready to upsize, choose Finish.

After you choose Finish, the SQL Server Upsizing Wizard begins exporting the database to the server.

The Finish button is available after you provide the basic information needed for upsizing. If you choose Finish before you complete all the wizard screens, the SQL Server Upsizing Wizard uses default values for the remaining screens.

See Also

SQL Server Upsizing Wizard Preparation | How the SQL Server Upsizing Wizard Works | Upsizing Visual FoxPro Databases | SQL Server Upsizing Process Completion


How the SQL Server Upsizing Wizard Works

The SQL Server Upsizing Wizard makes upsizing a Visual FoxPro database to SQL Server practically transparent. This section explains exactly what happens after you choose Finish — how the SQL Server Upsizing Wizard exports data and maps Visual FoxPro objects to SQL Server objects.

Data Export Methods

The SQL Server Upsizing Wizard exports data using one of two methods. The first method creates a stored procedure that performs multiple row inserts. This method can be very fast, because stored procedures are precompiled and execute quickly.

However, stored procedures can't accept variable length binary variables as parameters. If you're exporting data that's to be stored in SQL Server tables using text or image data types, or tables with more than 250 fields, the SQL Server Upsizing Wizard uses a different exporting method. This second method creates a SQL INSERT statement for each row in the table and then executes the statement.

If the SQL Server Upsizing Wizard encounters errors while exporting data using the SQL INSERT method, and the number of errors exceeds 10 percent of the number of records in the table or 100 records (whichever is larger), the wizard cancels the export for that table and saves the number of export errors for the error report. The exported server table is not dropped, however, and any records that were successfully exported are left in the server table.

Overview of Object Mapping

To upsize a Visual FoxPro database to a server, the SQL Server Upsizing Wizard creates server objects that, as far as possible, do everything the Visual FoxPro database did. Mapping some Visual FoxPro objects to server objects is very straightforward: Visual FoxPro databases, tables, fields, defaults, and indexes map to SQL Server databases, tables, fields, defaults, and indexes in a direct, one-to-one mapping.

However, not all local objects map directly to server objects. Validation rules and referential integrity in Visual FoxPro are part of the data dictionary and are enforced at the engine level. SQL Server validation rules and referential integrity aren't part of the data dictionary, and are enforced through code bound to a table. These differences, as well as design decisions made by the SQL Server Upsizing Wizard, mean that much of the Visual FoxPro data dictionary cannot be mapped directly to SQL Server constructs.

The following table summarizes how objects are mapped from Visual FoxPro to SQL Server:

Visual FoxPro objects | SQL Server objects
Database | Database
Table | Table
Indexes | Indexes
Field | Field
Default | Default
Table validation rule | SQL Server stored procedures, called from UPDATE and INSERT triggers
Field validation rule | SQL Server stored procedures, called from UPDATE and INSERT triggers
Persistent relationships (where used for referential integrity constraints) | Update, Insert, and Delete triggers or table constraints

The following sections discuss each Visual FoxPro object and the SQL Server object (or objects) to which it maps.

Naming Conventions for Upsized Objects

As it migrates objects to a data source, the SQL Server Upsizing Wizard creates named objects on the server. The wizard uses prefixes for objects that need new names because no such stand-alone object existed in Visual FoxPro (defaults and rules, for example). Following the prefix is a table name and then a field name, if appropriate. This naming convention enables all objects of the same kind to have the same prefix and sort together when viewed with data source administration tools. Objects created on the same table also group together when viewed.

Database and Table Objects

A Visual FoxPro database maps directly to a SQL Server database. A Visual FoxPro table, excluding part of its data dictionary, maps to a SQL Server table.

Database, table, index, and field names might change during upsizing, if they violate SQL Server naming conventions. SQL Server names must be 30 characters or less, and the first character must be a letter or the symbol "@". The remaining characters may be numbers, letters, or the "$", "#", and "_" symbols; no spaces are allowed. The SQL Server Upsizing Wizard replaces any illegal characters with the "_" symbol.

Any names that are identical to SQL Server reserved words are given a suffix of "_". For example, FROM and GROUP become FROM_ and GROUP_. The SQL Server Upsizing Wizard also places the "_" symbol in front of object names that begin with a number.

Tables

The SQL Server Upsizing Wizard gives each upsized table the same name as the local table unless the table name contains a space or is a keyword for the data source.

Views of New Server Tables

If you select Create Remote Views On Tables, the SQL Server Upsizing Wizard creates remote views and gives them many of the properties of the fields in the original local table.

Mapping Visual FoxPro Field Names and Data Types to SQL Server Equivalents

Field names and data types are automatically translated into SQL Server fields when a Visual FoxPro table is exported by the SQL Server Upsizing Wizard.

Visual FoxPro data types map to SQL Server data types as follows:

Abbreviation Visual FoxPro Data Type SQL Server Data Type
C Character
char
Y Currency
money
D Date
datetime
T DateTime
datetime
B Double
float
F Float
float
G General
image
I Integer
int
L Logical
bit
M Memo
text
M (binary) Memo binary
image
C (binary) Character binary
binary
N Numeric
float

Timestamp and Identity Columns

Timestamp columns are created using the Transact-SQL timestamp datatype. When you select the Timestamp column checkbox for a specific table in Step 4 - Map Field Data Types, the SQL Server Upsizing Wizard creates a timestamp field for that table.

If a table contains one or more memo (M) or picture (P) fields, the SQL Server Upsizing Wizard selects the Timestamp column check box for that table by default and creates a timestamp field on the upsized version of the table.

Identity columns are created using the Transact-SQL IDENTITY property fields.

Indexes

SQL Server and Visual FoxPro indexes are very similar. The following table shows how Visual FoxPro index types are converted to SQL Server index types:

Index Type Conversion

Visual FoxPro Index Type | SQL Server Index Type
Primary | Clustered Unique
Candidate | Unique
Unique Regular | Non-unique

The SQL Server Upsizing Wizard uses Visual FoxPro tag names as names for indexes on SQL Server. If the tag name is a reserved word on the server, the wizard alters the tag name by appending the "_" character.

Note SQL Server doesn't support ascending or descending indexes, or permit expressions within server indexes. The SQL Server Upsizing Wizard removes Visual FoxPro expressions from index expressions as the index is upsized; only field names are sent to the server.

SQL Server Defaults

A Visual FoxPro default expression maps directly to a single SQL Server default. The SQL Server Upsizing Wizard tries to create a SQL Server default based on the default expression for a Visual FoxPro field. If the default is successfully created, the SQL Server Upsizing Wizard binds it to the appropriate SQL Server field. The upsizing report on fields indicates if the SQL Server Upsizing Wizard was successful in translating the Visual FoxPro expression to SQL Server Transact-SQL. For details on translation, see Expression Mapping.

While SQL Server and Visual FoxPro defaults are largely similar, there are some differences in the way defaults are created and behave in the two products. SQL Server defaults are stand-alone objects, independent of any particular field or table. Once a default has been created, it can be used by, or bound, to any number of different fields.

Naming Conventions for Defaults

The SQL Server Upsizing Wizard names defaults using the prefix Dflt_ plus the table name and field name. For example, a default value for the ordamt field in the Customer table might be named Dflt_Customer_Ordamt on the server. If combining the prefix with the table and field names causes the default name to exceed 30 characters, Visual FoxPro truncates the excess characters.

Fields with a default expression of zero are bound to a default named UW_ZeroDefault. If two or more fields have the same non-zero default expression, the SQL Server Upsizing Wizard creates two defaults, with two different names, that are functionally identical.

Default Values for Visual FoxPro Logical Fields

Logical fields in SQL Server prohibit null values; Visual FoxPro logical fields allow them. To manage this difference, the SQL Server Upsizing Wizard automatically creates and binds a default value called UW_ZeroDefault to each exported logical field, whether or not you chose to export defaults. This default sets the value of the server field to 0 (or false (.F.), if you look at the field in Visual FoxPro) when you don't supply a value.

If the local Visual FoxPro table contains a default value for a logical field that sets the field equal to true (.T.), the SQL Server Upsizing Wizard doesn't bind the UW_ZeroDefault default to the server table. Instead, the wizard creates a default that sets the field equal to 1, and names the default according to the naming conventions outlined earlier in this topic.

SQL Server defaults behave differently than Visual FoxPro defaults.

SQL Server Triggers

A SQL Server trigger is a series of Transact-SQL statements associated with a particular SQL Server table. When you choose to upsize Validation rules and Relationships in Step 8, the SQL Server Upsizing Wizard converts Visual FoxPro field- and record-level validation rules and persistent table relationships into stored procedures that are called from SQL Server triggers. Each server trigger can contain code to emulate the functionality of several validation and referential integrity rules.

Note The SQL Server Upsizing Wizard does not upsize Visual FoxPro triggers.

A server table can have three triggers, one for each of the commands that can modify data in the table: UPDATE, INSERT, and DELETE. The trigger is automatically executed when the associated command is carried out.

The following table describes the triggers created by the SQL Server Upsizing Wizard. Any specific trigger might contain code to emulate some or all of the Visual FoxPro functionality listed.

Trigger | Visual FoxPro Functionality Emulated
UPDATE | Validation rules (Field- and record-level validation) Referential integrity
INSERT | Validation rules (Field- and record-level validation) Referential integrity (Child table triggers only)
DELETE (Parent table only) | Referential integrity

Naming Conventions for Triggers

The SQL Server Upsizing Wizard names server triggers by combining a prefix that indicates the type of trigger being created with the table name of the SQL Server table to which the trigger belongs. The prefix ("TrigU_" for UPDATE triggers, "TrigD_" for DELETE triggers, and "TrigI_" for INSERT triggers) is placed in front of the table name. For example, the UPDATE trigger on the Customer table might be called TrigU_Customer.

Validation Rules

The SQL Server Upsizing Wizard can export Visual FoxPro field- and record-level validation rules, which it converts to stored procedures on SQL Server. The wizard names field-level rules by combining a prefix "vrf" (for "validation rule, field") with the names of the table and the field; an example might be vrf_customer_lname. Table validation rules are named with the prefix "vrt" (for "validation rule, table") plus the name of the table, to create a name such as vrt_customer.

The SQL Server Upsizing Wizard uses triggers that call stored procedures rather than SQL Server rules to enforce field level validation because SQL Server rules don't allow you to display custom error messages. For more information about SQL Server rules, see the CREATE RULE command in your SQL Server documentation.

Referential Integrity

Your Visual FoxPro application supports referential integrity through triggers on UPDATE, DELETE, and INSERT events on persistent table relationships that are enforced at the engine level. You can choose to implement referential integrity constraints on SQL Server using either of two methods:

  • Trigger-based referential integrity

    -or-

  • Declarative referential integrity

When you choose trigger-based referential integrity, the SQL Server Upsizing Wizard creates triggers that include the Transact-SQL code required to duplicate Visual FoxPro referential integrity constraints. If you choose to implement declarative referential integrity, the SQL Server Upsizing Wizard creates SQL Server constraints using the ALTER TABLE command with the CONSTRAINT keyword.

Trigger-based Referential Integrity

In the trigger-based method, referential integrity is enforced on SQL Server by Transact-SQL code in triggers. You can use triggers to provide restrictions on UPDATE, DELETE, and INSERT statements, and to cascade changes resulting from DELETE and INSERT statements.

The SQL Server Upsizing Wizard creates SQL Server triggers by evaluating the Visual FoxPro triggers used to enforce referential integrity on persistent relationships in your Visual FoxPro database. The following table lists the mapping between Visual FoxPro Referential Integrity constraints and the SQL Server triggers generated by the SQL Server Upsizing Wizard.

Visual FoxPro Referential
Integrity Constraint SQL Server Trigger

UPDATE | Cascade | Cascade UPDATE trigger
 | Restrict | Restrict UPDATE trigger
 | Ignore | No trigger generated
DELETE | Cascade | Cascade DELETE trigger
 | Restrict | Restrict DELETE trigger
 | Ignore | No trigger generated
INSERT | Restrict | Restrict INSERT trigger
 | Ignore | No trigger generated

A Visual FoxPro persistent relationship that's used in a referential integrity constraint can become up to four triggers on a SQL Server data source: two for the parent table and two for the child table.

Note If only one of the tables in a relationship is upsized, or if referential integrity isn't enforced in Visual FoxPro, the relationship isn't exported.

Parent Table

The SQL Server Upsizing Wizard creates an UPDATE trigger that either prevents the user from changing the parent table's primary key or cascades that change through the child table, depending on the type of relationship that was created in Visual FoxPro.

The SQL Server Upsizing Wizard also creates a DELETE trigger that prevents the user from deleting a record with related child records, or that deletes the child records, again depending on the type of relationship between the tables in Visual FoxPro.

Child Table

The SQL Server Upsizing Wizard creates an UPDATE trigger that prevents the user from making changes to the foreign key that would orphan the record. Similarly, an INSERT trigger is created to prevent the user from adding a new record that has no parent.

Custom Error Values

If, at run time, the referential integrity established by the SQL Server Upsizing Wizard-created triggers is violated, SQL Server places a custom error value into the @@ERROR variable. Potential error values are defined by the SQL Server Upsizing Wizard as a part of the trigger code. The specific error value returned at run time depends on the action the user was attempting: updating, inserting, or deleting.

The following table lists the error numbers generated for each action:

Action | SQL Server Error
Violated validation rule | 44444
Attempted delete | 44445
Attempted update | 44446
Attempted insert | 44447
Update or Delete statement affected more than one row; statement is automatically rolled back | 44448

Declarative Referential Integrity

If you choose to implement declarative referential integrity, the SQL Server Upsizing Wizard creates SQL Server constraints using the ALTER TABLE command with the CONSTRAINT keyword. The parent table constraint uses the PRIMARY KEY keyword. The child table constraint uses the FOREIGN KEY and REFERENCES keywords. Declarative referential integrity is supported at the RESTRICT, RESTRICT updates, and RESTRICT deletes levels.

You can use SQL Server constraints to provide restrictions on UPDATE, DELETE, and INSERT statements.

Expression Mapping

Although Visual FoxPro and Transact-SQL have some functions in common, many Visual FoxPro functions aren't supported by SQL Server. The SQL Server Upsizing Wizard attempts to convert Visual FoxPro expressions in field- and record-level validation rules and default values to Transact-SQL, using the following expression mapping.

Visual FoxPro expression | SQL Server expression
True (.T.) | 1
False (.F.) | 0
# | <>
.AND. | AND
.NOT. | NOT
.NULL. | NULL
.OR. | OR
=< | <=
=> | >=
ASC( ) | ASCII( )
AT( ) | CHARINDEX( )
CDOW( ) | DATENAME(dw, ...)
CHR( ) | CHAR( )
CMONTH( ) | DATENAME(mm, ...)
CTOD( ) | CONVERT(datetime, ...)
CTOT( ) | CONVERT(datetime, ...)
DATE( ) | GETDATE( )
DATETIME( ) | GETDATE( )
DAY( ) | DATEPART(dd, ...)
DOW( ) | DATEPART(dw, ...)
DTOC( ) | CONVERT(varchar, ...)
DTOR( ) | RADIANS( )
DTOT( ) | CONVERT(datetime, ...)
HOUR( ) | DATEPART(hh, ...)
LIKE( ) | PATINDEX( )
MINUTE( ) | DATEPART(mi, ...)
MONTH( ) | DATEPART(mm, ...)
MTON( ) | CONVERT(money, ...)
NTOM( ) | CONVERT(float, ...)
RTOD( ) | DEGREES( )
SUBSTR( ) | SUBSTRING( )
TTOC( ) | CONVERT(char, ...)
TTOD( ) | CONVERT(datetime, ...)
YEAR( ) | DATEPART(yy, ...)

The following expressions are the same on Visual FoxPro and on SQL Server.

Expressions that map directly from Visual FoxPro to SQL Server

CEILING( ) | LOG( ) | LOWER( )
LTRIM( ) | RIGHT( ) | RTRIM( )
SOUNDEX( ) | SPACE( ) | STR( )
STUFF( ) | UPPER( ) |

Files Created by the SQL Server Upsizing Wizard

The SQL Server Upsizing Wizard creates tables for its own use during the upsizing process. These files are removed from the hard disk unless:

  • You choose to produce an upsizing report.
  • You want to save the generated SQL.
  • Errors occur during upsizing and you choose to save the error information.

If any of the conditions above are true, the SQL Server Upsizing Wizard creates a project (named Report, Report1, Report2, and so on) and a database (named Upsize, Upsize1, and so on) in a subdirectory (named UPSIZE) of the defined by the SET DEFAULT command for your Visual FoxPro session. The wizard adds to the database the tables used to produce the Upsizing Report, a table to store the generated SQL, and any error tables. The following table lists the files potentially created by the upsizing process.

Local Tables Created During Upsizing

File Purpose | Table Name | Contents
Report Tables | Errors_uw | Information on any error that occurred during upsizing.
 | Fields_uw | Information about all the tables upsized.
 | Indexes_uw | Information about all the indexes upsized.
 | Misc_uw | Miscellaneous upsizing information.
 | Relations_uw | Information about all the referential integrity constraints stored in the Visual FoxPro database.
 | Tables_uw | Information on all the tables in the database you choose to upsize.
 | Views_uw | Information about the local views redirected to access remote data.
Script Table | SQL_uw | One memo field containing all the SQL code generated by the SQL Server Upsizing Wizard.
Data Export Error Tables | ExportErrors_table_name | For each table that experiences a data export error during upsizing, the SQL Server Upsizing Wizard generates a table containing the records that aren't successfully exported.

If the wizard is canceled during processing or if the wizard halts because of an error, no tables are left on your hard disk.

Using Generated SQL

The Script table stored on your hard disk contains all the SQL code generated by the SQL Server Upsizing Wizard, whether it executes without error on the server or not. If you want to use this code, the best approach is to look at the generated SQL, copy the parts of it you want to use, run the extracted pieces of code, and repeat the process to obtain the results you want. You can't run the entire SQL script as a substitute for running the SQL Server Upsizing Wizard, because the wizard performs additional steps that aren't reflected in the generated SQL code.

See Also

Starting the SQL Server Upsizing Wizard | SQL Server Upsizing Process Completion | Upsizing Visual FoxPro Databases | Expression Mapping


SQL Server Upsizing Process Completion

You can now take additional steps, both on your server and in your Visual FoxPro application, to ensure your application and data are secure and functioning properly.

You can also use the information in this section when you build an application from remote views rather than by upsizing. Regardless of how you created remote tables, you take certain steps to ensure the server and client are prepared to work together in your client/server application.

SQL Server Steps

You can complete the upsizing process on your server by:

  • Making sure the tables you want to edit from Visual FoxPro are updatable.
  • Setting permissions on the database so that users can access the objects they need.
  • Protecting your work by making your new database recoverable, in case it's damaged or lost.

Adding Unique Indexes for Updatability

A remote table should have a unique index to be updatable in Visual FoxPro. The SQL Server Upsizing Wizard can export an existing unique index, but it doesn't create one where none exists. Make sure that tables you want to edit from Visual FoxPro are updatable.

Setting Permissions

The new SQL Server database and its objects receive a set of default permissions from the SQL Server. Set permissions on the remote database so that your users have access to the objects they need.

Database Logon Permissions

The default permissions of a new database make it accessible only to system administrators and the database owner.

You can add new users and groups by using the SQL Server Security Manager or the system procedures sp_adduser and sp_addgroup.

For more information on adding users and groups, see SQL Server Security Manager Help and the documentation of the system procedures sp_adduser and sp_addgroup in the Microsoft SQL Server Transact-SQL Reference.

Object Permissions

All objects created by the Visual FoxPro-to-SQL Server Upsizing Wizard, including tables, triggers, and defaults, are accessible initially only to the database owner and system administrators. This is true whether you upsized to a new or existing database. If you overwrite existing objects, you also overwrite all object permissions.

Ensuring Recoverability

Protect your work by making your new database recoverable in case it's damaged or lost.

Dumping the Master Database

When a database is created on a SQL Server, new records are added to the system tables in the Master database. Dumping the Master database also provides you with a backup copy, including all the latest changes.

Scheduling Backups

Schedule regular backups of your database, so you can restore your database from this backup copy in the event of a serious problem.

Device Mirroring

Mirroring a device continuously duplicates the information from one SQL Server device to another. In the event that one device fails, the other contains an up-to-date copy of all transactions.

If you anticipate that many changes will be made to a database between backups and you can't afford to lose those changes, consider device mirroring. Device mirroring is most effective when the devices are located on separate disks, as both devices might be lost if they're on the same disk and the disk fails.

Visual FoxPro Client Steps

Once you've transferred objects from Visual FoxPro to a SQL Server, you probably need to modify code in the original Visual FoxPro database so that it functions properly with the new SQL Server database.

Optimizing Views

Views created by the SQL Server Upsizing Wizard aren't parameterized and therefore are not optimized. For most efficient processing, add parameters to views created by the SQL Server Upsizing Wizard to download just the data you need. For information on adding a parameter to a view, see Creating Views.

SQL Server doesn't support some Visual FoxPro functions. If the remote view created by the SQL Server Upsizing Wizard uses functions that couldn't be mapped to Transact-SQL functions, the view will not work. For more information on mapping Visual FoxPro expressions to Transact-SQL expressions, see Expression Mapping.

Creating Stored Procedures and Triggers

The SQL Server Upsizing Wizard doesn't upsize Visual FoxPro stored procedures and triggers. If you want to create SQL Server stored procedures or triggers, you can use Transact-SQL on the server or use SQL pass-through in Visual FoxPro. For more information on using Transact-SQL, see your SQL Server documentation. For information on using SQL pass-through, see Implementing A Client/Server Application.

Comparing Event Order

In Visual FoxPro, some events occur in a different order, depending on whether your application is using SQL Server data or Visual FoxPro data. These differences might require changes to your code.

Default Values

Visual FoxPro default field values appear when you begin editing a new record. Default values generated by SQL Server defaults appear only after a record has been inserted. You need to change any code that depends on having values before the record is committed, such as the code for lookups.

Validation Rules

In Visual FoxPro, field validation occurs when the focus leaves a field. When you edit SQL Server data in attached tables, triggers and rules aren't fired until you leave the record. You might need to modify any record validation rules that rely on field validation occurring when a field is exited.

Handling Unconverted Expressions

The upsizing report indicates whether each Visual FoxPro table validation rule, field validation rule, and default expression was successfully converted. If a default expression or validation rule was not translated, you should rewrite it in Transact-SQL.

You can also perform validation at the form level in Visual FoxPro. However, if server data is then modified without using a particular form, the validation will not be applied and invalid data might be entered.

For more information about expression conversion, see Expression Mapping. For more information about Transact-SQL functions, see your SQL Server documentation.

Record Locking

Visual FoxPro uses optimistic locking internally when accessing tables on a SQL server. Optimistic locking means that the row is locked only when the edited value is committed and the update process occurs — usually a very brief interval.

Optimistic locking is used rather than pessimistic locking on SQL Server because pessimistic locking on SQL Server is provided by page locking, potentially locking many records at a time. While page locking prevents other users from making changes to the same record you're editing, it can also prevent users from accessing many other records in the same (locked) page. Optimistic locking provides the best multiuser access for a Visual FoxPro client/server application.

You can optimize updates and control how update conflicts are handled with the SQL WhereType property. For more information on controlling update conflicts, see Creating Views.

See Also

SQL Server Upsizing Process Completion | Upsizing Visual FoxPro Databases | Implementing A Client/Server Application | SQL Server Upsizing Wizard Preparation


Database Container Events

You can enable Database Container (DBC) events and add code to specific events on data contained in a database. You can create this code manually in an external file, or you can use the Database Properties dialog box, which provides a template for you to complete in the location you specify. The following table describes the available DBC events:

DBC Events | Description
DBC_Activate | Occurs when an open database becomes current.
DBC_Deactivate | Occurs when a database ceases to be current.
DBC_BeforeAddRelation | Occurs before a relation is added to the database.
DBC_AfterAddRelation | Occurs after a relation is added to the database successfully.
DBC_BeforeAddTable | Occurs before a table is added to an open database.
DBC_AfterAddTable | Occurs after a table is added to an open database.
DBC_BeforeAppendProc | Occurs before the append operation in the current DBC stored procedure completes. Use to prevent the append operation. Also, use to discover the name of the DBC involved.
DBC_AfterAppendProc | Occurs after the APPEND PROC operation completes.
DBC_BeforeCloseTable | Occurs before the table or view is closed.
DBC_AfterCloseTable | Occurs after a table or view is closed.
DBC_BeforeCopyProc | Occurs before the copy procedure operation in the current DBC begins. Use to prevent the operation. Also, use to discover the name of the DBC involved.
DBC_AfterCopyProc | Occurs after the copy procedure operation in the current DBC completes. Use to discover the name of the DBC involved.
DBC_BeforeCreateConnection | Occurs before a connection is created. Use to prevent connection creation or connection designer opening.
DBC_AfterCreateConnection | Occurs after a connection is created.
DBC_BeforeCreateOffline | Occurs before a view is taken offline. Use to prevent offline view.
DBC_AfterCreateOffline | Occurs after CREATEOFFLINE( ) has completed.
DBC_BeforeCreateTable | Occurs before a table is created in an open database.
DBC_AfterCreateTable | Occurs after a table is created in an open database.
DBC_BeforeCreateView | Occurs before a view is created. Use to prevent view from being created or view designer from being opened.
DBC_AfterCreateView | Occurs after view creation is completed.
DBC_BeforeDBGetProp | Occurs before DBGetProp( ) runs.
DBC_AfterDBGetProp | Occurs after DBGetProp( ) completes.
DBC_BeforeDBSetProp | Occurs before DBSetProp( ) runs. Event also fires when "Event" property is changed.
DBC_AfterDBSetProp | Occurs after DBSetProp( ) completes. Event also fires when "Event" property is changed.
DBC_BeforeDeleteConnection | Occurs before a connection is dropped.
DBC_AfterDeleteConnection | Occurs after a connection is dropped.
DBC_BeforeDropOffline | Occurs before a view is returned to online. Use to prevent bringing offline view back online.
DBC_AfterDropOffline | Occurs after DROPOFFLINE( ) has completed.
DBC_BeforeDropRelation | Occurs before a relation is dropped from a database.
DBC_AfterDropRelation | Occurs after a relation is dropped from a database successfully.
DBC_BeforeDropTable | Occurs before the table is removed from the DBC and deleted from disk.
DBC_AfterDropTable | Occurs after a table is removed from the DBC and deleted from disk.
DBC_BeforeDropView | Occurs before a view is removed from the DBC. Use to prevent view from being dropped.
DBC_AfterDropView | Occurs after view is removed from the DBC.
DBC_BeforeModifyConnection | Occurs before a connection is modified.
DBC_AfterModifyConnection | Occurs after a connection is modified.
DBC_BeforeModifyProc | Occurs before the DBC-stored procedure in an open DBC is modified. Use to prevent modification. Also, use to discover the name of the current DBC.
DBC_AfterModifyProc | Occurs after modifications have been made and the stored procedure file for the DBC has been closed.
DBC_BeforeModifyTable | Occurs before a table is modified.
DBC_AfterModifyTable | Occurs after a table is modified.
DBC_BeforeModifyView | Occurs before a view is modified.
DBC_AfterModifyView | Occurs after a view is modified.
DBC_BeforeOpenTable | Occurs before a table or view is opened.
DBC_AfterOpenTable | Occurs after a table or view is opened.
DBC_BeforeRemoveTable | Occurs before a table is removed from the DBC.
DBC_AfterRemoveTable | Occurs after table removal is complete.
DBC_BeforeRenameConnection | Occurs before a connection is renamed.
DBC_AfterRenameConnection | Occurs after a connection is renamed.
DBC_BeforeRenameTable | Occurs before a table is renamed.
DBC_AfterRenameTable | Occurs after a table is renamed.
DBC_BeforeRenameView | Occurs before a view is renamed.
DBC_AfterRenameView | Occurs after a view is renamed.
DBC_BeforeValidateData | Occurs before VALIDATE DATABASE executes. Return .F. to prevent the DBC from being validated.
DBC_AfterValidateData | Occurs after VALIDATE DATABASE completes.
DBC_ModifyData | Occurs immediately after Modify Data is issued. Use to prevent opening of Schema window. Also, can open a closed database.
DBC_OpenData | Occurs when a database opens or when a MODIFY DATABASE command is issued against a closed database. Use to close an open database.
DBC_CloseData | Closes an open database.
DBC_PackData | Occurs before PACK DATABASE executes. Use to prevent the DBC from being packed.

See Also

Enabling or Disabling DBC Events | Adding Code to a DBC Event


Adding Code to a DBC Event

You can add method code to a DBC event in a program file or to the stored procedures file of your database. If you set DBC events to On in your database, the database becomes incompatible with earlier versions of Visual FoxPro. To regain compatibility with earlier versions of Visual FoxPro, set DBC Events to Off.

When you use the Database Properties dialog box to add code to DBC events, Visual FoxPro inserts a Procedure template for each selected DBC event in the procedure file so you can immediately add your code.

To add code to a DBC Event

  1. In an open database, from the Database or the Shortcut menu, select Properties.
  2. From the Event or Code Name list, select an event.

    You can select multiple events by holding the control or shift keys as you make your selections.

  3. If you want to place the code in a stored procedure in the current database, click Edit Code.

    -or-

    If you want to place the code in an external file, select Set Events On, click Events File, specify or select the file you want to edit, and click Edit Code.

The editor opens in the procedures file, so you can add code to the DBC event method template(s) added by Visual FoxPro.

See Also

Database Container Events | Enabling or Disabling DBC Events


Enabling or Disabling DBC Events

You can enable Database Container (DBC) events directly in code or through the Database Properties Dialog Box.

To enable DBC Events

  1. With the Database Designer open, from the Database menu or the Shortcut menu, select Properties.
  2. In the Database Properties dialog box, select Set Events On.

    This enables the Events File check box, so you can choose to add DBC Event code to an external file instead of stored procedures in the current database. It also changes the structure of the database, so it is no longer compatible with versions of Visual FoxPro prior to version 7, or the Visual FoxPro ODBC Driver. Setting it off again will make it compatible again.

-Or-

  • Enable Database Events programmatically by using the DBSetProp( ) Function as in the following code:
    DBSetProp(<DBCName>,'Database','DBCEvents',.T.)

    The database must be open and current before this function is used. When DBC events are turned on in a database, events and methods (in associated procedure code) in the stored procedures will run.

To disable DBC Events

  1. In an open database, from the Database or the Shortcut menu, select Properties.
  2. In the Database Properties dialog box, clear Set Events On.

    This disables the Events File check box.

-or-

  • Disable Database Events programmatically by using the following code:
    DBSetProp(<DBCName>,'Database','DBCEvents',.F.)

DBC events are not available in earlier versions of Visual FoxPro. Attempting to access a DBC events-enabled database from a version of Visual FoxPro prior to version 7 generates an error.

See Also

Database Container Events | Adding Code to a DBC Event


Programming for Shared Access

If you create an application that will run on several machines in a network environment or if several instances of a form will access the same data, then you must program for shared access. Shared access means providing efficient ways of using and sharing data among users, as well as restricting access when necessary.

Microsoft Visual FoxPro provides support for shared or exclusive access to data, locking options, data sessions, record and table buffering, and transactions. Although these features are useful particularly in shared environments, you can use them in single-user environments too.

In This Section

Controlling Access to Data
Discusses effective data management in a shared environment, and how you must choose how to access the data and when and where to limit that access.
Updating Data
Explains how to update data using buffers, transactions, or views.
Management of Conflicts
Discusses how you can anticipate and manage the inevitable conflicts that result from data update operations.

Related Sections

Extending Applications
Describes how to extend a basic Visual FoxPro application to enable it to work for multiple users, take advantage of Microsoft ActiveX controls and automation-enabled applications, and add international capabilities.
Sharing Information and Adding OLE
Discusses using ActiveX controls and object linking and embedding in your application to link to data and use the strengths of other applications.
Developing International Applications
Describes how to move your applications into the world market by designing them for effective international use.


Controlling Access to Data

Since you access data in files, effective data management begins with control over the environment of these files. You must choose how to access the data and how and when to limit that access.

Accessing Data

In a shared environment, you can access data in two ways: from exclusive files or from shared files. If you open a table for shared access, other users also have access to the file. If you open a table for exclusive access, no other user can read or write to that file. Because exclusive use defeats many of the benefits of sharing data on a network, it should be used sparingly.

Using a Table with Exclusive Access

The most restrictive way to open a file is to open it exclusively. When you open a table through the interface, it opens for exclusive use by default. You can also explicitly open a table for exclusive use by using Visual FoxPro commands.

To open a table for exclusive use

  • Type the following commands in the Command window:
    SET EXCLUSIVE ON
USE cMyTable

    -or-

  • Type the following command in the Command window:
    USE cMyTable EXCLUSIVE

The following commands require you to open a table for exclusive use:

  • ALTER TABLE
  • INDEX when creating, adding, or deleting a compound index tag.
  • INSERT [BLANK]
  • MODIFY STRUCTURE To use this command to change a table structure, you must open the table exclusively. You can, however, use this command in read-only mode when you open the table for shared use.
  • PACK
  • REINDEX
  • ZAP

Visual FoxPro returns the error, "Exclusive open of file is required," if you try to execute one of these commands on a shared table.

You can restrict access to a table by using the FLOCK( ) function. If you use FLOCK( ) to lock the table, other users cannot write to the table but they can read it.

Using a Table with Shared Access

When you open a table for shared use, more than one workstation can use the same table at the same time. When you open a table through the interface, you can override the default ON setting for SET EXCLUSIVE. You can explicitly open a table for shared use by using Visual FoxPro commands.

To open a table for shared use

  • Type the following commands in the Command window:
    SET EXCLUSIVE OFF
USE cMyTable

    -or-

  • Type the following command in the Command window:
    USE cMyTable SHARED

When you add or change data in a shared table, you must first lock the affected record or the entire table. You can lock a record or a table opened for shared use in the following ways:

  • Use a command that performs an automatic record or table lock.
  • Manually lock one or more records or an entire table with the record and table locking functions.
  • Initiate buffering with the CURSORSETPROP( ) function.

Associated memo and index files always open with the same share status as their table.

If your application uses a table for lookup purposes only and all users of the application access it, then you can improve performance by marking the table as read-only.

See Also

Programming for Shared Access | Locking Data | ALTER TABLE | INDEX | INSERT [BLANK] | MODIFY STRUCTURE | Using Data Sessions | Buffering Data


Locking Data

If you share access to files, you must also manage access to data by locking tables and records. Locks, unlike access permissions, can provide both long- and short-term control of data. Visual FoxPro provides both automatic and manual locking.

Choosing Record or Table Locks

Record locking, whether automatic or manual, prevents one user from writing to a record that's currently being written to by another user. Table locking prevents other users from writing to, but not reading from, an entire table. Because table locking prohibits other users from updating records in a table, it should only be used sparingly.

Choosing Automatic or Manual Locks

In addition to record or table locking, you can also choose automatic or manual locking. Many Visual FoxPro commands automatically attempt to lock a record or a table before the command is executed. If the record or table is successfully locked, the command is executed and the lock is released.

Commands that Automatically Lock Records and Tables

Command | Scope of lock
ALTER TABLE | Entire table
APPEND | Table header
APPEND BLANK | Table header
APPEND FROM | Table header
APPEND FROM ARRAY | Table header
APPEND MEMO | Current record
BLANK | Current record
BROWSE, CHANGE and EDIT | Current record and all records from aliased fields in related tables once editing of a field begins
CURSORSETPROP( ) | Depends on parameters
DELETE | Current record
DELETE NEXT 1 | Current record
DELETE RECORD n | Record n
DELETE of more than one record | Entire table
DELETE – SQL | Current record
GATHER | Current record
INSERT | Entire table
INSERT - SQL | Table header
MODIFY MEMO | Current record when editing begins
READ | Current record and all records from aliased fields
RECALL | Current record
RECALL NEXT 1 | Current record
RECALL RECORD n | Record n
RECALL of more than one record | Entire table
REPLACE | Current record and all records from aliased fields
REPLACE NEXT 1 | Current record and all records from aliased fields
REPLACE RECORD n | Record n and all records from aliased fields
REPLACE of more than one record | Entire table and all files from aliased fields
SHOW GETS | Current record and all records referenced by aliased fields
TABLEUPDATE( ) | Depends on buffering
UPDATE | Entire table
UPDATE – SQL | Entire table

Record Lock Characteristics

Commands that attempt record locks are less restrictive than commands that lock tables. When you lock a record, other users can still add or delete other records. If a record or table is already locked by another user, an attempted record or table lock fails. Commands that attempt to lock the current record return the error, "Record is in use by another," if the record cannot be locked.

The BROWSE, CHANGE, EDIT, and MODIFY MEMO commands do not lock a record until you edit the record. If you're editing fields from records in related tables, the related records are locked if possible. The lock attempt fails if the current record or any of the related records are also locked by another user. If the lock attempt is successful, you can edit the record; the lock is released when you move to another record or activate another window.

Header and Table Lock Characteristics

Some Visual FoxPro commands lock an entire table while others only lock a table header. Commands that lock the entire table are more intrusive than commands that only lock the table header. When you lock the table header, other users cannot add records, but they can still change data in fields.

Users can share the table without causing a conflict when you issue the APPEND BLANK command, but an error can occur while another user is also appending a BLANK record to the table. You can trap for the error, "File is in use by another," which is returned when two or more users execute APPEND BLANK simultaneously. Commands that lock an entire table return the error, "File is in use by another," if the table cannot be locked. To cancel the attempted lock, press ESC.

Example: Automatic Locking

In the following example, the user automatically locks the table header by appending records from another table, even though customer was opened as a shared file:

SET EXCLUSIVE OFF
USE customer
APPEND FROM oldcust FOR status = "OPEN"

Locking Manually

You can manually lock a record or a table with locking functions.

To manually lock a record or a table

  • Use one of the following commands:
    RLOCK()
LOCK()
FLOCK()

RLOCK( ) and LOCK( ) are identical and lock one or more records. FLOCK( ) locks a file. The LOCK( ) and RLOCK( ) functions can apply to a table header. If you provide 0 as the record to LOCK( ) or RLOCK( ) and the test indicates the header is unlocked, the function locks the header and returns true (.T.).

Once you lock a record or table, be sure to release the lock by using the UNLOCK command as soon as possible to provide access to other users.

These manual locking functions perform the following actions:

  • Test the lock status of the record or table.
  • If the test indicates the record is unlocked, lock the record or table and return true (.T.).
  • If the record or table cannot be locked, attempt to lock the record or table again, depending on the current setting of SET REPROCESS.
  • Return true (.T.) or false (.F.), indicating whether the lock attempt was successful.
    Tip If you want to test the lock status of a record in your session without locking the record, use the ISRLOCKED( ) or ISFLOCKED( ) function.

If an attempt to lock a record or table fails, the SET REPROCESS command and your current error routine determine if the lock is attempted again. SET REPROCESS affects the result of an unsuccessful lock attempt. You can control the number of lock attempts or the length of time a lock is attempted with SET REPROCESS.

Example: Manual Locking

The following example opens the customer table for shared access and uses FLOCK( ) to attempt to lock the table. If the table is successfully locked, REPLACE ALL updates every record in the table. UNLOCK releases the file lock. If the file cannot be locked because another user has locked the file or a record in the file, a message is displayed.

SET EXCLUSIVE OFF
SET REPROCESS TO 0
USE customer    && Open table shared
IF FLOCK()
 REPLACE ALL contact ;    && Replace and unlock
  WITH UPPER(contact)
 UNLOCK
ELSE  && Output message
 WAIT "File in use by another." WINDOW NOWAIT
ENDIF

Unlocking Data

After you establish a record or file lock and complete a data operation in a shared environment, you should release the lock as soon as possible. There are several ways to release locks. In some cases, simply moving to the next record is enough to unlock the data. Other situations require explicit commands.

To unlock a record that's been automatically locked, you need only move the record pointer, even if you set MULTILOCKS ON. You must explicitly remove a lock from a record that you've manually locked; simply moving the record pointer is not enough.

The following table describes the effects of commands on manual and automatic record and table locks.

Command | Effect
UNLOCK | Releases record and file locks in the current work area.
UNLOCK ALL | Releases all locks in all work areas in the current session.
SET MULTILOCKS OFF | Enables automatic release of the current lock as a new lock is secured.
FLOCK( ) | Releases all record locks in the affected file before locking the file.
CLEAR ALL, CLOSE ALL, USE, QUIT | Releases all record and file locks.
END TRANSACTION | Releases automatic locks.
TABLEUPDATE( ) | Releases all locks after updating the table.
Caution If a record was automatically locked in a user-defined function and you move the record pointer off and then back on the record, the lock will be released. Use table buffering to avoid this problem.

See Also

Controlling Access to Data | Using Data Sessions | Programming for Shared Access | RLOCK( ) | LOCK( ) | FLOCK( ) | UNLOCK


Using Data Sessions

To ensure that each user in a shared environment has a secure, exact duplicate of the working environment, and to ensure that multiple instances of a form can operate independently, Visual FoxPro provides data sessions.

A data session is a representation of the current dynamic work environment. You might think of a data session as a miniature data environment running inside one open Visual FoxPro session on one machine. Each data session contains:

  • A copy of the items in the form's data environment.
  • Cursors representing the open tables, their indexes, and relationships.

The concept of a data session is easily understood when you consider what happens when you open the same form simultaneously from separate workstations in a multiuser application. In this case, each workstation is running a separate Visual FoxPro session, and therefore has its own set of work areas: cursors representing open base tables, indexes, and relationships.

However, if you open multiple instances of the same form in a single project, on one machine, within the same Visual FoxPro session, the forms share the Default data session, representing a single dynamic work environment. Each instance of the open form open in the same Visual FoxPro session uses the same set of work areas, and actions in one instance of a form that move the record pointer in a work area automatically affect other instances of the same form.

Using Private Data Sessions

If you want to have more control over multiple instances of form, you can implement Private data sessions. When your form uses private data sessions, Visual FoxPro creates a new data session for each instance of the Form, FormSet, or Toolbar control your application creates. Each private data session contains:

  • A separate copy of each table, index, and relationship in the form's data environment.
  • An unlimited number of work areas.
  • Record pointers for each copy of each table that are independent from the base tables for the form.

The number of available data sessions is limited only by available system memory and disk space.

You implement private data sessions by setting the DataSession property for the form. The DataSession property has two settings:

  • 1 – Default data session (the default setting).
  • 2 – Private data session.

By default, the DataSession property of a form is set to 1.

To enable private data sessions

Choose one of the following options:

  • In the Form Designer, set the DataSession property of the form to 2 – Private data session.

    -or-

  • In code, set the DataSession property to 2.

    For example, type:

    frmFormName.DataSession = 2
    Note You can only set the DataSession property at design time. The DataSession property is read-only at run time.

When a form uses private data sessions, each instance of a form open on a single machine in a single Visual FoxPro session uses its own data environment. Using private data sessions is similar to running the same form simultaneously from separate workstations.

Equivalent multiple data sessions

Identifying Data Sessions

Each private data session is identified separately. You can see the contents of each data session in the Data Session window. You can also change the data session description through commands in the Load event code.

You can view the identification number for each data session by using the DataSessionID run-time property. The following example displays the DataSessionID property of a form named frmMyForm:

DO FORM frmMyForm
? frmMyForm.DataSessionID

If you activate the form using the NAME clause, you can use the form's name to access the DataSessionID property, as in the following code:

DO FORM MyForm NAME one
? one.DataSessionID

The DataSessionID property is designed only to identify a particular data session. Avoid changing the DataSessionID of a form instance because data-bound controls lose their data sources when you change the DataSessionID.

Updating Data Using Multiple Form Instances

While private data sessions generate separate work areas containing separate copies of a form's open tables, indexes, and relationships, every copy of the form references the same underlying base tables and base index files. When a user updates a record from one instance of a form, the base table referenced by the form is updated. You see the changes made from another instance of the form when you navigate to the changed record.

Locks taken on records or tables in one private data session are respected by other private data sessions. For example, if the user of data session 1 takes a lock on a record, the user in data session 2 cannot lock the record. If the user in session 1 opens a table exclusively, the user in data session 2 cannot open the table. By respecting locks taken by other data sessions, Visual FoxPro protects the integrity of updates to the underlying base tables.

Customizing the Environment of a Data Session

Because data sessions control the scope of certain SET commands, you can use private data sessions to establish custom SET command settings within a single session of Visual FoxPro.

For example, the SET EXACT command, which controls the rules used when comparing character strings of different lengths, is scoped to the current data session. The default setting for SET EXACT is off which specifies that, to be equivalent, expressions must match, character for character, until the end of the expressions on the right side is reached. You might want to enable "fuzzy" or equivalent searches by leaving SET EXACT set to OFF for the default data session; however, your application might contain a specific form that requires exact matches. You could set the DataSession property for the form requiring exact matches to 2, to enable private data sessions, and then SET EXACT to ON for that form. By issuing a SET command only for the form using private data sessions, you preserve the global Visual FoxPro session settings while enabling customized session settings for a specific form.

Overriding Automatic Private Data Session Assignment

When private data sessions for a form are in use, changes you make to data in one form are not automatically represented in other instances of the same form. If you want all instances of a form to access the same data and to immediately reflect changes to common data, you can override automatic data session assignment.

To override automatic data session assignment

  • Use one of these commands:
    SET DATASESSION TO 1

    -or-

    SET DATASESSION TO

Both commands enable the default data session to be controlled by the Command window and the Project Manager.

See Also

Locking Data | Buffering Data | Programming for Shared Access | Form Designer | DataSession | DataSessionID


Buffering Data

If you want to protect data during updates, use buffers. Visual FoxPro record and table buffering help you protect data update and data maintenance operations on single records and on multiple records of data in multiuser environments. Buffers can automatically test, lock, and release records or tables.

With buffering, you can easily detect and resolve conflicts in data update operations: the current record is copied to a memory or disk location managed by Visual FoxPro. Other users can then still access the original record simultaneously. When you move from the record or try to update the record programmatically, Visual FoxPro attempts to lock the record, verify that no other changes have been made by other users, and then write the changes. After you attempt to update data, you must also resolve conflicts that prevent the changes from being written to the original table.

Choosing a Buffering Method

Before you enable buffering, evaluate the data environment to choose the buffering method and locking options that best suit the editing needs of your application, the record and table types and sizes, how the information is used and updated, and other factors. Once you enable buffering, it remains in effect until you disable buffering or close the table.

Visual FoxPro has two types of buffering: record and table.

Visual FoxPro record and table buffering

  • To access, modify, and write a single record at a time, choose record buffering.

    Record buffering provides appropriate process validation with minimal impact on the data update operations of other users in a multiuser environment.

  • To buffer the updates to several records, choose table buffering.

    Table buffering provides the most effective way to handle several records in one table or child records in a one-to-many relationship.

  • To provide maximum protection for existing data, use Visual FoxPro transactions.

    You can use transactions alone, but you gain additional effectiveness by using transactions as wrappers for record or table buffering commands.

Choosing a Locking Mode

Visual FoxPro provides buffering in two locking modes: pessimistic and optimistic. These choices determine when one or more records are locked, and how and when they're released.

Pessimistic Buffering

Pessimistic buffering prevents other users in a multiuser environment from accessing a particular record or table while you're making changes to it. A pessimistic lock provides the most secure environment for changing individual records but it can slow user operations. This buffering mode is most similar to the standard locking mechanism in previous versions of FoxPro, with the added benefit of built-in data buffering.

Optimistic Buffering

Optimistic buffering is an efficient way to update records because locks are only taken at the time the record is written, thus minimizing the time any single user monopolizes the system in a multiuser environment. When you use record or table buffering on views, Visual FoxPro imposes optimistic locking.

The value of the Buffering property, set with the CURSORSETPROP( ) function, determines the buffering and locking methods.

The following table summarizes valid values for the Buffering property.

To enable | Use this value
No buffering. The default value. | 1
Pessimistic record locks which lock record now, update when pointer moves or upon TABLEUPDATE( ). | 2
Optimistic record locks which wait until pointer moves, and then lock and update. | 3
Pessimistic table locks which lock record now, update later upon TABLEUPDATE( ). | 4
Optimistic table lock which wait until TABLEUPDATE( ), and then lock and update edited records. | 5

The default value for Buffering is 1 for tables and 3 for views. If you use buffering to access remote data, the Buffering property is either 3, optimistic row buffering, or 5, optimistic table buffering. For more information on accessing data in remote tables, see Querying Multiple Tables and Views.

Note Set MULTILOCKS to ON for all buffering modes above 1.

Enabling Record Buffering

Enable record buffering with the CURSORSETPROP( ) function.

To enable pessimistic record locking in the current work area

  • Use this function and value:
    CURSORSETPROP("Buffering", 2)

Visual FoxPro attempts to lock the record at the pointer location. If the lock is successful, Visual FoxPro places the record in a buffer and permits editing. When you move the record pointer or issue a TABLEUPDATE( ) command, Visual FoxPro writes the buffered record to the original table.

To enable optimistic record locking in the current work area

  • Use this function and value:
    CURSORSETPROP("Buffering", 3)

Visual FoxPro writes the record at the location of the pointer to a buffer and permits edits. When you move the record pointer or issue a TABLEUPDATE( ) command, Visual FoxPro attempts a lock on the record. If the lock is successful, Visual FoxPro compares the current value of the record on the disk with the original buffer value. If these values are the same, the edits are written to the original table; if these values are different, Visual FoxPro generates an error.

Enabling Table Buffering

Enable table buffering with the CURSORSETPROP( ) function.

To enable pessimistic locking of multiple records in the current work area

  • Use this function and value:
    CURSORSETPROP("Buffering", 4)

Visual FoxPro attempts to lock the record at the pointer location. If the lock is successful, Visual FoxPro places the record in a buffer and permits editing. Use the TABLEUPDATE( ) command to write the buffered records to the original table.

To enable optimistic locking of multiple records in the current work area

  • Use this function and value:
    CURSORSETPROP("Buffering", 5)

Visual FoxPro writes the records to a buffer and permits edits until you issue a TABLEUPDATE( ) command. Visual FoxPro then performs the following sequence on each record in the buffer:

  • Attempts a lock on each edited record.
  • Upon a successful lock, compares the current value of each record on the disk with the original buffer value.
  • Writes the edits to the original table if the comparison shows the values to be the same.
  • Generates an error if the values differ.

When table buffering is enabled, Visual FoxPro attempts updates only after a TABLEUPDATE( ) command.

Appending and Deleting Records in Table Buffers

You can append and delete records while table buffering is enabled: appended records are added to the end of the buffer. To access all records in the buffer, including appended records, use the RECNO( ) function. The RECNO( ) function returns sequential negative numbers on records you append to a table buffer. For instance, if you initiate table buffering, edit records 7, 8, and 9, and then append three records, the buffer will contain RECNO( ) values of 7, 8, 9, – 1, – 2, and – 3.

Note Tables containing automatically incrementing field values append table-buffered records approximately 35% slower than tables without automatically incrementing field values, which might affect performance. When using table buffering, the table header is locked when the record is appended.

Buffer after editing and appending records

You can remove appended records from the buffer only by using the TABLEREVERT( ) command. For any appended record, both TABLEUPDATE( ) and TABLEREVERT( ) delete the negative RECNO( ) value for that record while maintaining the sequence.

Buffer after editing, deleting an appended record, and appending another

While using a table buffer, you can use the GO command with the negative RECNO( ) value to access a specific appended record. For instance, using the previous example, you can type:

GO 7      && moves to the 1st buffered record
GO -3      && moves to the 6th buffered record (3rd appended)

To append records to a table buffer

  • Use the APPEND or APPEND BLANK command after you enable table buffering.

Appended records have sequential ascending negative RECNO( ) numbers.

To remove an appended record from a table buffer

  1. Use the GO command with a negative value to position the record pointer at the record to be deleted.
  2. Use the DELETE command to mark the record for deletion.
  3. Use the TABLEREVERT( ) function to remove the record from the buffer.
    Note The TABLEREVERT( ) function also affects the status of deleted and changed rows.

To remove all appended records from a table buffer

  • Use the TABLEREVERT( ) function with a value of true (.T.).

TABLEREVERT( ) removes appended records from a table buffer without writing the records to the table. TABLEUPDATE( ) writes all current buffered records to a table, even if they've been marked for deletion.

See Also

Using Data Sessions | Updating Data | Programming for Shared Access | Controlling Access to Data | CURSORSETPROP( )


Updating Data

To update data, you can use buffers, transactions, or views.

Performing Updates with Buffers

After choosing the buffering method and the type of locking, you can enable record or table buffering.

To enable buffering

Choose one of the following options:

  • In the Form Designer, set the BufferModeOverride property of the cursor in the data environment of the form.

    -or-

  • In code, set the Buffering property.

    For example, you can enable pessimistic row buffering by placing the following code in the Init procedure of a form:

    CURSORSETPROP('Buffering', 2)

You then place code for the update operations in the appropriate method code for your controls.

To write edits to the original table, use TABLEUPDATE( ). To cancel edits after a failed update operation in a table constrained by rules, use TABLEREVERT( ), which is valid even if explicit table buffering is not enabled. To specify a level of table integrity checking lower than the default setting, you can use the SET TABLEVALIDATE Command.

The following sample demonstrates how to update records when pessimistic record buffering is enabled.

Example of Updating Using Record and Table Buffers

Code Comment
OPEN DATABASE testdata
USE customers
CURSORSETPROP('Buffering', 2)
In the form Init code, open the table and enable pessimistic record buffering.
lModified = .F.
FOR nFieldNum = 1 TO FCOUNT()
   IF GETFLDSTATE(nFieldNum) = 2
      lModified = .T.
      EXIT
   ENDIF
ENDFOR
Go through fields, checking for any field that's been modified.

Note This code might be in the Click event of a "Save" or "Update" command button.

IF lModified
   nResult = MESSAGEBOX;
      ("Record has been modified. Save?", ;
      4+32+256, "Data Change")
 Locate the next modified record.
   IF nResult = 7
      TABLEREVERT (.F.)
   ENDIF
ENDIF
 Present the current value and give the user the option to revert the change to the current field.
SKIP
IF EOF()
   MESSAGEBOX( "already at bottom")
   SKIP -1
ENDIF
THISFORM.Refresh

SKIP guarantees that the last change is written.

Managing Updates with Transactions

Even with buffering, things can go wrong. If you want to protect update operations and recover from an entire section of code as a unit, use transactions.

Adding transactions to your application provides protection beyond Visual FoxPro record and table buffering by placing an entire section of code in a protected, recoverable unit. You can nest transactions and use them to protect buffered updates. Visual FoxPro transactions are available only with tables and views contained in a database.

Wrapping Code Segments

A transaction acts as a wrapper that caches data update operations to memory or to disk, rather than applying those updates directly to the database. The actual database update is performed at the end of the transaction. If for any reason the system cannot perform the update operations on the database, you can roll back the entire transaction and no update operations are performed.

Note Buffered update operations made outside a transaction are ignored within a transaction in the same data session.

Commands that Control Transactions

Visual FoxPro provides three commands and one function to manage a transaction.

To | Use
Initiate a transaction | BEGIN TRANSACTION
Determine the current transaction level | TXNLEVEL( )
Reverse all changes made since the most recent BEGIN TRANSACTION statement | ROLLBACK
Lock records, commit to disk all changes made to the tables in the database since the most recent BEGIN TRANSACTION, and then unlock the records | END TRANSACTION

You can use transactions to wrap modifications to tables, structural .cdx files, and memo files associated with tables within a database. Operations involving variables and other objects don't respect transactions; therefore, you cannot roll back or commit such operations.

Note When using data stored in remote tables, transaction commands control only updates to the data in the local copy of the view cursor; updates to remote base tables are not affected. To enable manual transactions on remote tables use SQLSETPROP( ), and then control the transaction with SQLCOMMIT( ) and SQLROLLBACK( ).

In general, you should use transactions with record buffers rather than with table buffering, except to wrap TABLEUPDATE( ) calls. If you place a TABLEUPDATE( ) command in a transaction, you can roll back a failed update, address the reason for the failure, and then retry the TABLEUPDATE( ) without losing data. This ensures the update happens as an "all-or-nothing" operation.

Though simple transaction processing provides safe data update operations in normal situations, it doesn't provide total protection against system failures. If power fails or some other system interruption occurs during processing of the END TRANSACTION command, the data update can still fail.

Use the following code template for transactions:

BEGIN TRANSACTION
* Update records
IF lSuccess = .F. && an error occurs
   ROLLBACK
ELSE && commit the changes
   * Validate the data
   IF && error occurs
      ROLLBACK
   ELSE
      END TRANSACTION
   ENDIF
ENDIF

Using Transactions

The following rules apply to transactions:

  • A transaction starts with the BEGIN TRANSACTION command and ends with the END TRANSACTION or ROLLBACK command. An END TRANSACTION statement without a preceding BEGIN TRANSACTION statement generates an error.
  • A ROLLBACK statement without a preceding BEGIN TRANSACTION statement generates an error.
  • A transaction, once begun, remains in effect until the corresponding END TRANSACTION begins (or until a ROLLBACK command is issued), even across programs and functions, unless the application terminates, which causes a rollback.
  • Visual FoxPro uses data cached in the transaction buffer before using disk data for queries on the data involved in transactions. This ensures that the most current data is used.
  • If the application terminates during a transaction, all operations roll back.
  • A transaction works only in a database container.
  • You cannot use the INDEX command if it overwrites an existing index file, or if any .cdx index file is open.
  • Transactions are scoped to data sessions.

Transactions exhibit the following locking behaviors:

  • Within a transaction, Visual FoxPro imposes a lock at the time a command directly or indirectly calls for it. Any system or user direct or indirect unlock commands are cached until the completion of the transaction by ROLLBACK or END TRANSACTION commands.
  • If you use a locking command such as FLOCK( ) or RLOCK( ) within a transaction, the END TRANSACTION statement will not release the lock. In that case, you must explicitly unlock any locks explicitly taken within a transaction. You should also keep transactions containing the FLOCK( ) or RLOCK( ) commands as brief as possible; otherwise, users could be locked out of records for a long time.

Nesting Transactions

Nested transactions provide logical groups of table update operations that are insulated from concurrent processes. BEGIN TRANSACTION...END TRANSACTION pairs need not be in the same function or procedure. The following rules apply to nested transactions:

  • You can nest up to five BEGIN TRANSACTION...END TRANSACTION pairs.
  • Updates made in a nested transaction aren't committed until the outermost END TRANSACTION is called.
  • In nested transactions, an END TRANSACTION only operates on the transaction initiated by the last issued BEGIN TRANSACTION.
  • In nested transactions, a ROLLBACK statement only operates on the transaction initiated by the last issued BEGIN TRANSACTION.
  • The innermost update in a set of nested transactions on the same data has precedence over all others in the same block of nested transactions.

Notice in the following example that because changes in a nested transaction aren't written to disk but to the transaction buffer, the inner transaction will overwrite the changes made to the same STATUS fields in the earlier transaction:

BEGIN TRANSACTION &&  transaction 1
   UPDATE EMPLOYEE ; &&  first change
      SET STATUS = "Contract" ;
      WHERE EMPID BETWEEN 9001 AND 10000
   BEGIN TRANSACTION &&  transaction 2
      UPDATE EMPLOYEE ;
         SET STATUS = "Exempt" ;
         WHERE HIREDATE > {^1998-01-01}  &&  overwrites
   END TRANSACTION &&  transaction 2
END TRANSACTION    &&  transaction 1

The following nested transaction example deletes a customer record and all its related invoices. The transaction will roll back if errors occur during a DELETE command. This example demonstrates grouping table update operations to protect updates from partial completion and to avoid concurrency conflicts.

Example of Modifying Records in Nested Transactions

Code Comments
DO WHILE TXNLEVEL( ) > 0
   ROLLBACK
ENDDO
 Cleanup from other transactions.
CLOSE ALL
SET MULTILOCKS ON
SET EXCLUSIVE OFF
 Establish environment for buffering.
OPEN DATABASE test
USE mrgtest1
CURSORSETPROP('buffering',5)
GO TOP

Enable optimistic table buffering.

REPLACE fld1 WITH "changed"
SKIP
REPLACE fld1 WITH "another change"
MESSAGEBOX("modify first field of both" + ;
   "records on another machine")
 Change a record.

Change another record.
BEGIN TRANSACTION
lSuccess = TABLEUPDATE(.T.,.F.)
 Start transaction 1 and try to update all modified records without force.
IF lSuccess = .F.
   ROLLBACK
   AERROR(aErrors)
   DO CASE
   CASE aErrors[1,1] = 1539
   ...
   CASE aErrors[1,1] = 1581
   ...
   CASE aErrors[1,1] = 1582
If the update failed, roll back the transaction.
Get the error from AERROR( ).
Determine the cause of the failure.
If a trigger failed, handle it.

If a field doesn't accept null values, handle it.
If a field rule was violated, handle it.
   CASE aErrors[1,1] = 1585
      nNextModified = getnextmodified(0)
      DO WHILE nNextModified <> 0
         GO nNextModified
         RLOCK()
         FOR nField = 1 to FCOUNT()
            cField = FIELD(nField)

            if OLDVAL(cField) <> CURVAL(cField)
 If a record was changed by another user, locate the first modified record.
Loop through all modified records, starting with the first record.
Lock each record to guarantee that you can update.
Check each field for any changes.

Check the buffered value against the value on disk, and then present a dialog box to the user.
               nResult = MESSAGEBOX;
               ("Data was changed " + ;
                "by another user — keep"+ ;
                "changes?", 4+48, ;
                "Modified Record")

               IF nResult = 7
                  TABLEREVERT(.F.)
                  UNLOCK record nNextModified
               ENDIF
 If user responded "No," revert the one record and unlock it.
               EXIT
            ENDIF
         ENDFOR
 Break out of the "FOR nField..." loop.
      ENDDO
 Get the next modified record.
      BEGIN TRANSACTION
      TABLEUPDATE(.T.,.T.)
      END TRANSACTION
      UNLOCK
 Start transaction 2 and update all non-reverted records with force.
End transaction 2.
Release the lock.
   CASE aErrors[1,1] = 109
   ...
   CASE aErrors[1,1] = 1583
   ...
   CASE aErrors[1,1] = 1884
   ...
   OTHERWISE
      MESSAGEBOX( "Unknown error "+;
      "message: " + STR(aErrors[1,1]))
   ENDCASE
 If the record is in use by another user, handle it.

If a row rule was violated, handle it.

If there was a unique index violation, handle it.

Otherwise, present a dialog box to the user.
ELSE
   END TRANSACTION
ENDIF
End transaction 1.

Protecting Remote Updates

Transactions can protect you from system-generated errors during data updates on remote tables. The following example uses a transaction to wrap data-writing operations to a remote table.

Example of a Transaction on a Remote Table

Code Comment
hConnect = CURSORGETPROP('connecthandle')
SQLSETPROP(hConnect, 'transmode',
DB_TRANSMANUAL)
 Get the connect handle
and enable manual transactions.
BEGIN TRANSACTION
 Begin the manual transaction.
lSuccess = TABLEUPDATE(.T.,.F.)
IF lSuccess = .F.
   SQLROLLBACK (hConnect)
   ROLLBACK
 Try to update all records without force.
If the update failed,
roll back the transaction on
the connection for the cursor.
   AERROR(aErrors)
   DO CASE
Get the error from AERROR( ).
   CASE aErrors[1,1] = 1539
   ...
 If a trigger failed, handle it.
   CASE aErrors[1,1] = 1581
   ...
 If a field doesn't accept null values, handle it.
   CASE aErrors[1,1] = 1582
   ...
 If a field rule was violated, handle it.
   CASE aErrors[1,1] = 1585
      nNextModified = GETNEXTMODIFIED(0)
      DO WHILE nNextModified <> 0
         GO nNextModified
 If a record was changed by another user, handle it.

Loop through all modified records, starting with the first record.
         FOR nField = 1 to FCOUNT()
            cField = FIELD(nField)
            IF OLDVAL(cField) <> CURVAL(cField)
               nResult = MESSAGEBOX;
               ("Data has been changed ;
               by another user. ;
               Keep changes?",4+48,;
               "Modified Record")
 Check each field for any changes.

Check the buffered value
against the value on disk, and then present a dialog box to the user.
               IF nResult = 7
                  TABLEREVERT(.F.)
               ENDIF
               EXIT
            ENDIF
         ENDFOR
         nNextModified = ;
         GETNEXTMODIFIED(nNextModified)
      ENDDO
 If user responded "No,"
revert the one record.

Break out of the "FOR nField..." loop.

Get the next modified record.
      TABLEUPDATE(.T.,.T.)
      SQLCOMMIT(hConnect)
 Update all non-reverted records with force and issue a commit.
   CASE aErrors[1,1] = 109
         * Handle the error
 Error 109 indicates that the record is in use by another user.
   CASE aErrors[1,1] = 1583
         * Handle the error
 Error 1583 indicates that a row rule was violated.
   CASE aErrors[1,1] = 1884
         * Handle the error
 Error 1884 indicates that the uniqueness of the index was violated.
   OTHERWISE
         * Handle generic errors.

      MESSAGEBOX("Unknown error message:" ;
        + STR(aErrors[1,1]))
   ENDCASE
 Present a dialog box to the user.

End of error handling.
ELSE
   SQLCOMMIT(hConnect)
   END TRANSACTION
ENDIF
If all errors were handled and the entire transaction was successful, issue a commit and end the transaction.

See Also

Buffering Data | Managing Performance | Programming for Shared Access | TABLEUPDATE( ) | TABLEREVERT( ) | Controlling Access to Data | Management of Conflicts


Managing Performance

Once you have a working multiuser application, you can use the following suggestions to improve performance:

  • Place temporary files on a local drive.
  • Choose between sorting and indexing files.
  • Schedule exclusive access to files.
  • Time the locking of files.

Place Temporary Files on a Local Drive

Visual FoxPro creates its temporary files in the Windows default Temp directory. Text editing sessions can also temporarily create a backup copy of the file being edited (a .bak file).

If local workstations have hard drives with plenty of free space, you can improve performance by placing these temporary work files on the local drive or in a RAM drive. Redirecting these files to a local drive or a RAM drive increases performance by reducing access to the network drive.

You can specify an alternate location for these files by including the EDITWORK, SORTWORK, PROGWORK and TMPFILES statements in your Config.fpw configuration file. For more information about managing files, see Optimizing Your System.

Choose between Sorting and Indexing Files

When the data contained in a table is relatively static, processing sorted tables sequentially without an order set improves performance. This doesn't mean that sorted tables cannot or should not take advantage of index files — the SEEK command, which requires an index, is incomparable for locating records quickly. However, once you locate a record with SEEK, you can turn ordering off.

Schedule Exclusive Access to Files

Commands that run when no other users require access to the data, such as overnight updates, can benefit by opening the data files for exclusive use. When files are open for exclusive use, performance improves because Visual FoxPro doesn't need to test the status of record or file locks.

Time the Locking of Files

To reduce contention between users for write access to a table or record, shorten the amount of time a record or table is locked. You can do this by locking the record only after it's edited rather than during editing. Optimistic row buffering gives you the shortest lock time.

For more information on improving performance, see Optimizing Your System . You can also find information on improving performance in your client/server applications in Optimizing Client/Server Performance.

See Also

Updating Data | Management of Updates with Views | Programming for Shared Access | Management of Conflicts | Buffering Data


Management of Updates with Views

You can use the update conflict management technology built into Visual FoxPro views to handle multiuser access to data. Views control what is sent to the base tables underlying the view by using the WhereType property. You can set this property for both local and remote views. The WhereType property provides four settings:

  • DB_KEY
  • DB_KEYANDUPDATABLE
  • DB_KEYANDMODIFIED (the default)
  • DB_KEYANDTIMESTAMP

By choosing one of these four settings, you control how Visual FoxPro builds the WHERE clause for the SQL Update statement sent to the view's base tables. You can choose the setting you want using the Update Criteria tab of the View Designer, or you can use DBSETPROP( ) to set the WhereType for a view definition. To change the WhereType setting for an active view cursor, use CURSORSETPROP( ).

To... | Choose this SQL WHERE option...
Have the update fail if a key field has been changed in the source table | Key fields only
Have the update fail if any of the fields marked as updatable have been changed on the remote table | Key and updatable fields
Have the update fail if any fields you change locally have been changed on the source table | Key and modified fields
Have the update fail if the timestamp of the record on the remote table has changed since you first retrieved it (only available if the remote table has a timestamp column) | Key and timestamp

For example, suppose you have a simple remote view based on the Customer table that includes seven fields: cust_id, company, phone, fax, contact, title, and timestamp. The primary key for your view is cust_id.

You've made only two fields updatable: contact_name and contact_title. You want the user to be able to change the company contact and their title from the view. However, if other facts about the company change, such as the company address, you want the changes to go through a coordinator who'll identify the impact of the changes on your company, such as whether the sales region for the customer will change. Now that your view has been set up to send updates, you can choose the WhereType according to your preferences.

Now suppose that you change the name in the contact field for a customer, but you don't change the value in the other updatable field, title. Given this example, the following section discusses how the WhereType setting would impact the WHERE clause that Visual FoxPro builds to send the new contact name to the base tables.

Comparing the Key Field Only

The least restrictive update uses the DB_KEY setting. The WHERE Clause used to update remote tables consists of only the primary key field specified with the KeyField or KeyFieldList property. Unless the value in the primary key field has been changed or deleted in the base table since you retrieved the record, the update goes through.

In the case of the previous example, Visual FoxPro would prepare an update statement with a WHERE clause that compares the value in the cust_id field against the cust_id field in the base table row:

WHERE OLDVAL(customer.cust_id) = CURVAL(customer_remote_view.cust_id)

When the update statement is sent to the base table, only the base table's key field is verified.

The key field in your view is compared against its base table counterpart.

Comparing the Key Field and Fields Modified in the View

The DB_KEYANDMODIFIED setting, the default, is slightly more restrictive than DB_KEY. DB_KEYANDMODIFIED compares only the key field and any updateable fields you've modified in the view against their base table counterparts. If you modify a field in the view, but the field isn't updateable, the fields are not compared to the base table data.

The WHERE clause used to update base tables consists of the primary fields specified with the KeyFieldList property and any other fields that are modified in the view. In the case of the previous example, Visual FoxPro would prepare an update statement that compares the values in the cust_id field because it is the key field, and the contact field because the contact name has been changed. Even though the title field is updateable, title is not included in the update statement because we haven't modified it.

The key and modified fields in your view are compared against their base table counterparts.

Comparing the Key Field and All Updateable Fields

The DB_KEYANDUPDATABLE setting compares the key field and any updateable fields (whether modified or not) in your view against their base table counterparts. If the field is updateable, even if you haven't changed it in the view, if anyone else has changed that field in the base table, the update fails.

The WHERE clause used to update base tables consists of the primary fields specified with the Key Field or KeyFieldList property and any other fields that are updateable. In the case of the example, Visual FoxPro would prepare an update statement that compares the values in the cust_id, contact, and title fields against the same fields in the base table row.

All the updateable fields in your view are compared against their base table counterparts.

Comparing the Timestamp for All Fields in the Base Table Record

The DB_KEYANDTIMESTAMP is the most restrictive type of update, and is only available if the base table has a timestamp column. Visual FoxPro compares the current timestamp on the base table record against the timestamp at the time the data was fetched into the view. If any field in the base table's record has changed, even if it's not a field you're trying to change, or even a field in your view, the update fails.

In the case of the example, Visual FoxPro prepares an update statement that compares the values in the cust_id field and the value in the timestamp field against those fields in the base table row.

The timestamp for your view's record is compared against the timestamp on the base table record.

In order to successfully update data using the DB_KEYANDTIMESTAMP setting with a multi-table view, you must include the timestamp field in your view for each table that is updateable. For example, if you have three tables in a view and want to update only two of them, and you choose the DB_KEYANDTIMESTAMP setting, you must bring down the timestamp fields from the two updateable tables into your result set. You can also use logical values in the CompareMemo property to determine whether memo fields are included in conflict detection.

See Also

Managing Performance | Management of Conflicts | Programming for Shared Access | Update Criteria | DBSETPROP( ) | CURSORSETPROP( )


Management of Conflicts

Whether you choose buffering, transactions, or views, you must manage conflicts during the update process.

Managing Buffering Conflicts

You can make data update operations more efficient by carefully choosing how and when to open, buffer, and lock data in a multiuser environment. You should limit the time a record or table is subject to access conflicts. Still, you must anticipate and manage the inevitable conflicts that result. A conflict occurs when one user tries to lock a record or table that's currently locked by another user. Two users cannot lock the same record or table at the same time.

Your application should contain a routine to manage these conflicts. If your application doesn't have a conflict routine, the system can lock up. A deadlock occurs when one user has locked a record or a table and tries to lock another record that's locked by a second user who, in turn, is trying to lock the record that's locked by the first user. While such occurrences are rare, the longer that a record or table is locked, the greater the chance of deadlock.

Trapping Errors

Designing a multiuser application or adding network support to a single-user system requires that you deal with collisions and trap for errors. Using Visual FoxPro record and table buffers simplifies some of this work.

If you attempt to lock a record or table already locked by another user, Visual FoxPro returns an error message. You can use SET REPROCESS to automatically deal with unsuccessful lock attempts. This command, in combination with an ON ERROR routine and the RETRY command, enables you to continue or cancel the lock attempts.

The following example demonstrates automatic reprocessing of a failed operation, using SET REPROCESS.

Using SET REPROCESS and ON ERROR to Manage User Collisions

Code Comment
ON ERROR DO err_fix WITH ERROR(),MESSAGE()
SET EXCLUSIVE OFF
SET REPROCESS TO AUTOMATIC
USE customer
IF !FILE('cus_copy.dbf')
   COPY TO cus_copy
ENDIF
 This routine runs if an error occurs.
Open the files non-exclusively.
Reprocessing of unsuccessful locks is automatic.
Open the table.

Create the APPEND FROM table if needed.

DO app_blank
DO rep_next
DO rep_all
DO rep_curr
DO add_recs
 The main routine starts here.
These commands are examples of codes that could be executed in the course of your program.
ON ERROR
 The main routine ends here.
PROCEDURE app_blank
   APPEND BLANK
RETURN
ENDPROC
 Routine to append a blank record.
PROCEDURE rep_next
   REPLACE NEXT 1 contact WITH ;
      PROPER(contact)
RETURN
ENDPROC
 Routine to replace data in the current record.
PROCEDURE rep_all
   REPLACE ALL contact WITH ;
      PROPER(contact)
   GO TOP
RETURN
ENDPROC
 Routine to replace data in all records.
PROCEDURE rep_curr
   REPLACE contact WITH PROPER(contact)
RETURN
ENDPROC
 Routine to replace data in the current record.
PROCEDURE add_recs
   APPEND FROM cus_copy
RETURN
ENDPROC
 Routine to append records from another file.

The following example demonstrates an error procedure that starts when the user presses ESC.

Error Handling Using the ESC Key

Code Comment
PROCEDURE err_fix
   PARAMETERS errnum, msg
 This program is called when an error is encountered and the user escapes from the wait process.
DO CASE
 Figure out what kind of error this is.
Is it "File is in use by another"?
   CASE errnum = 108
      line1 = "File cannot be locked."
      line2 = "Try again later..."

   CASE errnum = 109 .OR. errnum = 130
      line1 = "Record cannot be locked."
      line2 = "Try again later."
 Or "Record is in use by another"?
   OTHERWISE
      line1 = msg + " "
      line2 = ;
         "See your system administrator."
ENDCASE
 Or is it unknown?

=MESSAGEBOX( line1 + line2, 48, "Error!" )
RETURN
Display the error message in a dialog box with an exclamation point and an OK button.

See Also

Management of Updates with Views | Detecting and Resolving Conflicts | Programming for Shared Access | SET REPROCESS | ON ERROR | RETRY


Detecting and Resolving Conflicts

During data update operations, especially in shared environments, you might want to determine which fields have changed or what the original or the current values are in changed fields. Visual FoxPro buffering and the GETFLDSTATE( ), GETNEXTMODIFIED( ), OLDVAL( ) and CURVAL( ) functions, enable you to determine which field has changed, find the changed data, and compare the current, original, and edited values so you can decide how to handle an error or conflict.

To detect a change in a field

  • After an update operation, use the GETFLDSTATE( ) function.

GETFLDSTATE( ) works on unbuffered data; however, this function is even more effective when you've enabled record buffering. For instance, use GETFLDSTATE( ) in the code of a Skip button on a form. When you move the record pointer, Visual FoxPro checks the status of all fields in the record as in the following example:

lModified = .F.
FOR nFieldNum = 1 TO FCOUNT( ) && Check all fields
   if GETFLDSTATE(nFieldNum) = 2  && Modified
      lModified = .T.
      EXIT && Insert update/Save routine here.
   ENDIF && See the next example
ENDFOR

To detect and locate a changed record in buffered data

  • Use the GETNEXTMODIFIED( ) function.

GETNEXTMODIFIED( ), with zero as a parameter, finds the first modified record. If another user makes changes to the buffered table, any changes encountered by a TABLEUPDATE( ) command in your buffer will cause conflicts. You can evaluate the conflicting values and resolve them using the CURVAL( ), OLDVAL( ), and MESSAGEBOX( ) functions. CURVAL( ) returns the current value of the record on disk, while OLDVAL( ) returns the value of the record at the time it was buffered.

To determine the original value of a buffered field

  • Use the OLDVAL( ) function.

OLDVAL( ) returns the value of a buffered field.

To determine the current value of a buffered field on disk

  • Use the CURVAL( ) function.

CURVAL( ) returns the current value on disk of a buffered field before any edits were performed.

You can create an error-handling procedure that compares the current and original values, enabling you to determine whether to commit the current change or to accept an earlier change to data in a shared environment.

The following example uses GETNEXTMODIFIED( ), CURVAL( ), and OLDVAL( ) to provide the user with an informed choice in an update operation. This example continues from detection of the first modified record and might be contained in an Update or Save button on a form.

Click Event Code for an Update or Save Button

Code Comment
   nCurRec = GETNEXTMODIFIED(nCurRec)
   DO WHILE nCurRec <> 0
   GO nCurRec
   RLOCK( )
 Loop through buffer.

Lock the modified record.
   FOR nField = 1 TO FCOUNT(cAlias)
      cField = FIELD(nField)
      IF OLDVAL(cField) <> CURVAL(cField)
         nResult = MESSAGEBOX("Data was ;
            changed by another user. ;
            Keep changes?", 4+48+0, ;
            "Modified Record")
 Look for conflict.

Compare the original value to the current value on the disk, and then ask the user what to do about the conflict.

         IF nResult = 7
            TABLEREVERT(.F.)
            UNLOCK RECORD nCurRec
         ENDIF
      ENDIF
   ENDFOR
   nCurRec = GETNEXTMODIFIED(nCurRec)
ENDDO
 If the user selects "No," revert this record, and then remove the lock.

Find the next modified record.
TABLEUPDATE(.T., .T.)
Force update to all records.

Detecting Conflicts using Memo Fields

You can use the CompareMemo property to control when memo fields are used to detect update conflicts. This view and cursor property determines whether memo fields (types M or G) are included in the update WHERE clause. The default setting, True (.T.), means that memo fields are included in the WHERE clause. If you set this property to False (.F), memo fields don't participate in the update WHERE clause, regardless of the settings of UpdateType.

Optimistic conflict detection on Memo fields is disabled when CompareMemo is set to False. For conflict detection on memo values, set CompareMemo to True (.T.).

Rules for Managing Conflicts

Managing conflicts encountered in multiuser environments can require extensive and repetitive code. A complete conflict management routine does the following:

  • Detects a conflict.
  • Identifies the nature and location of the conflict.
  • Provides enough information so that the user can intelligently resolve the conflict.

For an example of a conflict management routine, see the data checker class in Samples.vcx, located in the Visual FoxPro ...\Samples\Classes directory. Just add the class to a form and call the CheckConflicts method before any operation that writes buffered data to the table, for example moving the record pointer if you're using row buffering, closing a table, or issuing TABLEUPDATE( ).

See Also

Management of Conflicts | Programming for Shared Access | Management of Updates with Views | GETFLDSTATE( ) | GETNEXTMODIFIED( )


Visual FoxPro Data Access Using the OLE DB Provider

You can access Visual FoxPro data from other programming languages and applications. Using the Microsoft OLE DB Provider for Visual FoxPro, you can connect to Visual FoxPro databases and tables and retrieve data from Visual FoxPro databases and tables to use in Visual Studio and Microsoft Office applications and files.

In This Section

OLE DB Provider for Visual FoxPro
Describes the Visual FoxPro OLE DB Provider, the tasks you can perform, and the functionality it provides.
Accessing Visual FoxPro Data in Visual Studio .NET
Describes ways to access data in Visual FoxPro databases and tables using the Visual FoxPro OLE DB Provider when developing applications in Visual Studio .NET.
Accessing Visual FoxPro Data in Microsoft Office XP
Describes how to access data in Microsoft Office applications, such as Word and Excel, from Visual FoxPro databases and tables using the OLE Provider.

Related Topics

Language Reference for OLE DB Development
Describes support in the OLE DB Provider for native Visual FoxPro language and syntax.


OLE DB Provider for Visual FoxPro

The Visual FoxPro OLE DB Provider (VfpOleDB.dll) exposes OLE DB interfaces that you can use to access Visual FoxPro databases and tables from other programming languages and applications.

The Visual FoxPro OLE DB Provider includes the following:

  • Support for most Open Database Connectivity (ODBC) driver functionality from earlier versions of FoxPro
  • Improved threading model for scalability
    Note Visual FoxPro OLE DB Provider does not support multiple result sets.
  • Enhanced functionality for and access to stored procedures

    Stored procedures return scalar results in row sets and can accept parameters. The Visual FoxPro OLE DB Provider implements the ICommandPersist interface so that you can create, modify, and delete stored procedure code and modules.

  • Support for DBC events and the capability to create, modify, and delete functions and procedures in the DBC stored procedure module
  • Support for the following Schema Rowsets: Table, Column, Provider Types, Indexes, Primary Keys, Procedures, Foreign Keys, Views, Table Constraints, Check Constraints, and Referential Constraints

You can perform the following functions through the Visual FoxPro OLE DB Provider:

  • Access Visual FoxPro data from external applications.
  • Create n-tier thin and fat clients that access legacy Visual FoxPro data.
  • Use a subset of the Visual FoxPro language in database stored procedures.
  • Create and maintain database containers (DBCs) through extended Data Manipulation Language (DML) functionality and ADOX enhancements to ADO.

The Visual FoxPro OLE DB Provider is supported by OLE DB System Components as provided by MDAC 2.6 or later. The requirements to run the Visual FoxPro OLE DB Provider are the same as for Visual FoxPro 8.0.

Note When you use Visual FoxPro OLE DB Provider as a SQL Server-linked server, only queries are supported. The Visual FoxPro OLE DB Provider does not support update, insert, or delete operations through a linked server.

Stored Procedures in the OLE DB Provider

The Visual FoxPro OLE DB Provider accepts stored procedure commands in the following formats:

  • Calling a stored procedure using the conventional syntax:
    myStoredProc( Param1, Param2, ... )
  • Calling a stored procedure using the SQL EXEC keyword with the following syntax:
    EXEC myStoredProc( Param1, Param2, ... )

    where each parameter is in the format expected for its data type or is a valid expression that returns that format as in the following example:

    EXEC myStoredProc( 'characterparm', {^2002/09/09}, dateTime(), 100, 99.99, .T.)
    Note Be sure to replace myStoredProc with the name of the stored procedure you want.
    Tip When you are using ADO or ADO.NET and setting the Command Type to Stored Procedure, you do not need to include the EXEC keyword. If the Command Type is not set to Stored Procedure, you must use the conventional syntax for stored procedures or use the EXEC keyword.

Registry Entries

When you install the Visual FoxPro OLE DB Provider, the installation program updates your system registry, HKEY CLASSES_ROOT, and adds the following new keys:

HKEY_CLASSES_ROOT\VFPOLEDB

HKEY_CLASSES_ROOT\VFPOLEDB.1

HKEY_CLASSES_ROOT\Vfpoledb.ConnectionPage

HKEY_CLASSES_ROOT\Vfpoledb.ConnectionPage.1

HKEY_CLASSES_ROOT\VFPOLEDB.ErrorLookup

HKEY_CLASSES_ROOT\VFPOLEDB.ErrorLookup.1

International Support

The Visual FoxPro OLE DB Provider provides international language support for the following:

  • Double-byte character sets (DBCS)
  • Multiple collating sequences

    A collating sequence defines the sort order for data stored in a Visual FoxPro table or database. The Visual FoxPro OLE DB Provider is configured to use collating sequences that support the language version of your operating system by default.

See Also

Visual FoxPro Data Access Using the OLE DB Provider | Accessing Visual FoxPro Data in Visual Studio .NET | Accessing Visual FoxPro Data in Microsoft Office XP | Language Reference for OLE DB Development


Accessing Visual FoxPro Data in Visual Studio .NET

You can access Visual FoxPro databases and tables in Visual Studio .NET using the Visual FoxPro OLE DB Provider. The Visual FoxPro OLE DB Provider is available through the Visual Studio Server Explorer or using connection strings in code.

Accessing Visual FoxPro Data Sources Using the Visual Studio Server Explorer

You can access Visual FoxPro databases and tables in Visual Studio by adding them to the list of data connections that appear in the Visual Studio Server Explorer pane. You need to first specify a connection through the Visual FoxPro OLE DB Provider to the databases and tables you want. You can then select the databases or tables so that they appear in the Visual Studio Server Explorer pane.

Note You must be able to specify the Visual FoxPro database or table folder you want to access by providing the path and file name or browsing to it.

To connect to a Visual FoxPro database or table through the Visual FoxPro OLE DB Provider

  1. Open Visual Studio.
  2. From the View menu, select Server Explorer.
  3. In the Server Explorer pane, right-click Data Connections, and click Add Connection.
  4. In the Data Link Properties dialog box, click the Provider tab.
  5. Select Microsoft OLE DB Provider for Visual FoxPro.

    The Connection tab in the Data Link Properties dialog box appears.

To add a Visual FoxPro database or table

  1. On the Connection tab and in the Select or enter a database name box, type path and name of the database or table folder you want.

    -or-

    To browse for a Visual FoxPro database or table folder, click the ellipsis (...) button to the right of the Select or enter a database name box to open the Configure Connection dialog box.

  2. Specify a different collating sequence if desired.
  3. To test the connection, click Test Connection. If connection is successful, click OK.

The database or table directory specified appears in the Visual Studio Server Explorer pane below the Data Connections node.

Accessing Visual FoxPro Data Sources Using Connection Strings

To access a Visual FoxPro data source in code, use a valid connection string to specify the Visual FoxPro OLE DB Provider, data source or data source name. For example, you can access the Visual FoxPro OLE DB Provider using Visual FoxPro code.

To connect to the Visual FoxPro OLE DB Provider in Visual FoxPro

  1. Establish an ActiveX Data Object (ADO) Connection object and create a data object in Visual FoxPro.
  2. Specify the Visual FoxPro OLE DB Provider and data source in a connection string as shown in the following code:
    oConn = CREATEOBJECT("ADODB.Connection")
oConn.ConnectionString = "provider=vfpoledb.1;;
   data source=.\MyTestDatabase.dbc"
oConn.Open

This code creates a data object you can use to retrieve data.

Note Be sure to replace MyTestDatbase with the appropriate database name.

Instead of a data source, you can use an existing Open Database Connectivity (ODBC) data source name (DSN) in the connection string for the Visual FoxPro OLE DB Provider. The Visual FoxPro OLE DB Provider accepts the argument, DSN = cDSNName, and uses the data source specified by the DSN as shown in the following example:

oConn=CREATEOBJECT("adodb.connection")
oConn.ConnectionString="Provider=vfpoledb;DSN=ODBCdataSourceName"
oConn.Open()
Note Be sure to replace ODBCdataSourceName with the appropriate ODBC DSN, for example, vfpTestData.

After the connection is open, you can query the value of ConnectionString to determine the data source evaluated.

A connection string includes the following attribute keywords and values:

Provider=cVFPOLEDBProvider
Specifies the Visual FoxPro OLE DB Provider (VFPOLEDB).
Data Source=cPath
Specifies the path to the Visual FoxPro database or a folder containing free tables. For example, c:\Microsoft Visual FoxPro\Samples\Data\Testdata.dbc
DSN=cDSNName
Specifies an existing ODBC DSN.
Mode=cMode
Specifies one of the following: Read, ReadWrite, Share Deny None (default), Share Deny Read, Share Deny Write, or Share Exclusive, which includes the previous two modes.

For a complete explanation of connection string syntax, see the Microsoft OLE DB 2.5 Programmer's Reference and SDK Guide.

Updating Visual FoxPro Data

You can update Visual FoxPro Data through the Visual FoxPro OLE DB Provider using ADO. The following procedure describes three ways you can update Visual FoxPro data using data from the sample database, NorthWind.dbc.

Note Be sure to replace NorthWind.dbc with the database you want to use.

To update Visual FoxPro data through the Visual FoxPro OLE DB Provider using ADO

  • Call an update, insert, or delete command directly.

    To call an update command directly, use the ADO Execute method. For example:

    CLEAR
LOCAL oConn as "adodb.connection"
LOCAL oRS as "adodb.recordset"
oConn = CREATEOBJECT('adodb.connection')
oRS = CREATEOBJECT('adodb.recordset')
cConnStrng = ;
   "Provider=vfpoledb;Data Source="+HOME(2)+"northwind\northwind.dbc"
oConn.Open(cConnStrng)
oConn.BeginTrans()
oConn.Execute("UPDATE Customers SET contactname = 'Patricio X. Simpson';
   WHERE customerid='CACTU'")
oRS = oConn.Execute("SELECT * FROM customers WHERE customerid = 'CACTU'")
?oRS.Fields("contactname").Value
oConn.RollbackTrans()
oRS.Requery()
?oRS.Fields('contactname').Value
oRS.Close()
oConn.Close()

    -or-

  • Use a client cursor.

    For example:

    CLEAR
LOCAL oConn as "adodb.connection"
LOCAL oRS as "adodb.recordset"
oConn = CREATEOBJECT('adodb.connection')
oRS = CREATEOBJECT('adodb.recordset')
cConnStrng = ;
   "Provider=vfpoledb;Data Source="+HOME(2)+"northwind\northwind.dbc"
oConn.CursorLocation= 3            && adUseClient
oConn.Open(cConnStrng)

*!* Open RecordSet using keyset cursor and optimistic locking.
oRS.Open(;
   "SELECT * FROM customers WHERE customerid = 'CACTU'",oConn,1,3,1)
? 'Current value:',oRS.Fields("contactname").Value
oRS.Fields("contactname").Value = "Patricio X. Simpson"
oRS.Update()
oRS.Requery()
? 'New value:',oRS.Fields("contactname").Value
oRS.Close()
oConn.Close()

    -or-

  • Use a server cursor.

    For example:

    LOCAL oRS as "adodb.recordset"
oConn = CREATEOBJECT('adodb.connection')
oRS = CREATEOBJECT('adodb.recordset')
cConnStrng = ;
   "Provider=vfpoledb;Data Source="+HOME(2)+"northwind\northwind.dbc"
oConn.Open(cConnStrng)

*!* Updatable server cursors must use the USE <table name> command to
*!* open the table, not a SELECT statement. Server cursor is updatable,
*!* opened keyset, and lock optimistic.
oRS.Open("USE customers",oconn,1,3,1)
? 'CursorLocation:',IIF(oRS.CursorLocation2,"adUseServer","adUseClient")

* Find CACTU.
? oRS.Find("customerid='CACTU'")
? 'Current value:',oRS.Fields("contactname").Value
oRS.Fields("contactname").Value = "Patricio Simpson"
oRS.Update()
oRS.Requery()
oRS.Find("customerid='CACTU'")
? 'New value:',oRS.Fields("contactname").Value
oRs.Close()
oRS =''
oConn.Close()oConn=''

Accessing Visual FoxPro Data from Different Languages

You can access the Visual FoxPro OLE DB Provider from other languages using different connection strings, depending on the language. For example, to connect to a Visual FoxPro database from a Visual C# application, you can use the following connection string, replacing myVFPDatabase with the appropriate data source name:

oleDbConnection1.ConnectionString = "Provider=VFPOLEDB.1;" +
   "Data Source=C:\\myVFPDatabase.DBC;";

The following code examples illustrate how to use connection strings that specify the Visual FoxPro OLE DB Provider and data source when accessing Visual FoxPro data from different languages.

Note Be sure to replace myVFPDatabase with the appropriate data source or DSN.

To access a Visual FoxPro data source in Visual C#

  • Use a connection string to specify the Visual FoxPro OLE DB Provider and access the data source as shown in the following code:
    OleDbConnection oleDbConnection1 = new   OleDbConnection("Provider=VFPOLEDB.1;"+
   "Data Source=C:\\myVFPDatabase.DBC;");
oleDbConnection1.Open();
OleDbConnection oleDbConnection1 = new OleDbConnection();
oleDbConnection1.ConnectionString = "Provider=VFPOLEDB.1;" +
      "Data Source=C:\\myVFPDatabase.DBC;";
oleDbConnection1.Open();

To access a Visual FoxPro data source in Visual Basic

  • Use a connection string to specify the Visual FoxPro OLE DB Provider and the data source as shown in the following code, where oConnection represents an ADO Connection object:
    oConnection.Open("Provider=vfpoledb.1;
   Data Source=.\myVFPDatabase.dbc")

To access Visual FoxPro data using ActiveX Data Objects (ADO) in Visual Basic .NET

  • Use a connection string to specify the Visual FoxPro OLE DB Provider and the data source as shown in the following code:
    Imports System.Data.OleDb
Public Class ConnectToVFP
    Public Function ADONETOpenVFPDatabase() As Boolean
        Dim bIsConnected As Boolean = True
        Try
            Dim cnn As New OleDbConnection("Provider=VFPOLEDB.1;" + _
               "Data Source=.\MyTestDatabase.dbc;")
            cnn.Open()
        Catch e As System.Exception
            bIsConnected = False
        End Try
        Return bIsConnected
    End Function
End Class
    Note Make sure to replace MyTestDatabase with the name of the database or table directory you want to access.

To access a Visual FoxPro data source in Visual C++

  • Set the database properties by specifying the DBSetProp array, DBProp array, and the IDBProperties pointer, followed by a connection string that specifies the Visual FoxPro OLE DB Provider as shown in the following code:
    HRESULT hr;
CLSID clsid;

// Set the DBProp array.
DBPROP iProp[1];
DBPROPSET rgIP;
IDBProperties* pIDBProperties = NULL;
IDBInitialize *pIDBInitialize = NULL;
VariantInit(&iProp[0].vValue);
iProp[0].dwOptions = DBPROPOPTIONS_OPTIONAL;    // Required
iProp[0].colid = DB_NULLID;

// Set the location of data source.
iProp[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
iProp[0].vValue.vt = VT_BSTR;
iProp[0].vValue.bstrVal = L"c:\myVFPDatabase.dbc"; // Data source

// Set DBpropset to point to the DBPROP array.
rgIP.guidPropertySet = DBPROPSET_DBINIT;
rgIP.cProperties = 1;
rgIP.rgProperties = iProp;
::CoInitialize(NULL);
hr = CLSIDFromProgID(L"vfpoledb.1",&clsid); // Specify OLE DB Provider.
hr = CoCreateInstance(clsid,
       NULL,
       CLSCTX_INPROC_SERVER,
       IID_IDBInitialize,
       (void**)&pIDBInitialize);

// Initialize.
hr = piDBInitialize->QueryInterface(_uuidof(IDBProperties), (void**)&pIDBProperties);
hr = pIDBProperties->SetProperties(1 , &rgIP) ;
hr = pIDBProperties->Release();
hr = pIDBInitialize->Initialize();

To access a Visual FoxPro data source in ASP using ActiveX Data Objects (ADO)

  1. Create an ASP page with appropriate HTML tags.
  2. To establish a connection and run commands using ADO, add Visual Basic Scripting Language (VBScript) code:
    <%
    Set conn = Server.CreateObject("ADODB.Connection")
    conn.ConnectionString="Provider=VFPOLEDB.1;
       Data Source=myVFPDatabase.dbc"
    conn.Open
    sql = "select * from tableName"
    Set rsArrival = conn.Execute(sql)
%>
    Note Be sure to replace tableName with the name of the table you want.

To access a Visual FoxPro data source in JScript

  • Use a connection string to specify the Visual FoxPro OLE DB Provider and data source as shown in the following code:
    var vbOKCancel = 0;
var vbInformation = 64;
var vbCancel = 2;
var L_Welcome_MsgBox_Message_Text = "This script demonstrates how to access VFP OLE DB Provider using the Windows Scripting Host.";
var L_Welcome_MsgBox_Title_Text = "VFP OLE DB Provider JScript Sample";
var sBuffer = "";
var sConnString = "Provider=vfpoledb.1;Data Source=myVFPDatabase.dbc";
var oConn = new ActiveXObject("ADODB.Connection");
var oRS = new ActiveXObject("ADODB.Recordset");
oConn.Open(sConnString);
oRS.Open("select * from tableName where fieldName1='fieldValue'",oConn,3,3);
// Get tableName.fieldName2
sBuffer = oRS.Fields('fieldName2').value;

var WSHShell = WScript.CreateObject("WScript.Shell");
var intDoIt;
intDoIt =  WSHShell.Popup(sBuffer,
   0,
   L_Welcome_MsgBox_Title_Text,
   vbOKCancel );
   if (intDoIt == vbOKCancel) {
      oRS.Close();
      oConn.Close();
      WScript.Quit();
}
    Note Be sure to replace myVFPDatabase, tableName, fieldName1, fieldName2, and fieldValue with the appropriate values. You must use a backslash (\) escape characters to include the backslash character in the file path, for example, "c:\\MyFolder\\MyVFP.dbc".

See Also

Visual FoxPro Data Access Using the OLE DB Provider | OLE DB Provider for Visual FoxPro | Accessing Visual FoxPro Data in Microsoft Office XP | Language Reference for OLE DB Development


Accessing Visual FoxPro Data in Microsoft Office XP

You can access data from Visual FoxPro databases and tables in Microsoft Office XP applications, such as Microsoft Excel or Microsoft Word, using the Visual FoxPro OLE DB Provider.

Note You can import Visual FoxPro data using the Visual FoxPro OLE DB Provider only in Office XP.

To connect to a Visual FoxPro database or table in Excel

  1. Open an Excel worksheet.
  2. From the Data menu, point to Import External Data, and click Import Data.
  3. In the Select Data Source dialog box, click New Source Data Connection.
  4. In the Data Connection Wizard, select Other/Advanced.
  5. In the Provider tab, select Microsoft OLE DB Provider for Visual FoxPro.

The Connection tab in the Data Link Properties dialog box appears.

To connect to a Visual FoxPro database or table in Word

  1. Open a Word document.
  2. From the View menu, point to Toolbars, and click Database.
  3. On the Database toolbar, click the Insert Database icon.
  4. In the Database dialog box, click Get Data.
  5. In the Select Data Source dialog box, click New Source Data Connection.
  6. In the Data Connection Wizard, select Other/Advanced.
  7. In the Provider tab, select Microsoft OLE DB Provider for Visual FoxPro.

The Connection tab in the Data Link Properties dialog box appears.

To add a Visual FoxPro database or table folder

  1. On the Connection tab and in the Select or enter a database name box, type path and name of the database or table folder you want.

    -or-

    To browse for a Visual FoxPro database or table folder, click the ellipsis (...) button to the right of the Select or enter a database name box to open the Configure Connection dialog box.

  2. Specify a different collating sequence if desired.
  3. To test the connection, click Test Connection. If connection is successful, click OK.

See Also

Visual FoxPro Data Access Using the OLE DB Provider | OLE DB Provider for Visual FoxPro | Accessing Visual FoxPro Data in Visual Studio .NET | Language Reference for OLE DB Development


Enhancing Applications Using SQL Pass-Through Technology

Whether you have created and upsized a working local prototype or developed your application against remote data using remote views, you have gained access to the large data stores typically available in a server database. In addition, you can take advantage of the security and transaction processing capabilities of the remote server. While remote views handle the main data management tasks, you can enhance your application by using SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.

The following topics discuss techniques for implementing client/server technology in a working application that uses remote views.

In This Section

Setting Up an ODBC Data Source
Describes how to install an ODBC driver and set up an ODBC data source, so you can create remote views or use SQL pass-through.
Using SQL Pass-Through Technology
Describes how remote views provide the easiest and most common method for accessing and updating remote data. The upsizing wizards can create remote views automatically in your database as part of upsizing, or you can use Microsoft Visual FoxPro to create remote views after upsizing.
Working with Remote Data Using SQL Pass-Through
Explains that after you retrieve a result set using SQL pass-through, you can view and control the properties of your result set cursor using the Microsoft Visual FoxPro functions CURSORGETPROP( ) and CURSORSETPROP( ).
Handling SQL Pass-Through Errors
Explains that Microsoft Visual FoxPro stores an error returned by a SQL pass-through function error message in an array.

Related Sections

Using Visual FoxPro
Describes Visual FoxPro programming features designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Application Planning
Describes how careful planning saves time, effort, and money and how many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating the Application
Discusses how to create a Visual FoxPro application, which may include one or more databases, a main program that sets up the application's system environment, and a user interface comprised of forms, toolbars, and menus.
Creating Web Services and Components
Explains how you can extend your Visual FoxPro application to work for multiple users, and take advantage of Microsoft ActiveX controls and automation-enabled applications.
Working with Data
Describes how to create effective applications with indexes, tables, and databases based on your data requirements.
Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Explains how to use the modular approach so you can verify the functionality of each component you create before you compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Describes Visual FoxPro debugging tools that help you find and correct any errors you discover in your applications.
Distributing Applications
Explains how to prepare to distribute your application by including all required files and creating distribution disks, after you have completed developing and testing your application.


Setting Up an ODBC Data Source

Before you can create remote views or use SQL pass-through, you must install an ODBC driver and set up an ODBC data source.

Choosing an ODBC Driver

To install the ODBC drivers for these types of data, use the Visual FoxPro Setup program. If you choose the Complete install option, all drivers are installed.

Once you've chosen a driver, you can use the default data source or add an ODBC data source for it.

To add an ODBC data source

  1. Choose the Administrative Tools icon from the Windows Control Panel.
  2. Choose the Data Sources shortcut.
  3. In the ODBC Data Source Administrator dialog box, click Add, then select the driver you want from the Installed ODBC Drivers list and choose OK.
  4. In the Setup dialog box, set option values as necessary and choose OK.

For information on setting up a data source specific to the driver you have chosen, choose the Help button in the ODBC Setup dialog box.

Installing ODBC Data Sources

You can get Open Database Connectivity (ODBC) support if you choose the Complete or Custom installation option. With ODBC, you can access a SQL Server data source from Visual FoxPro; however, before you can access the data source, you must define it.

Connecting Visual FoxPro with ODBC data sources

To define a data source

  1. Switch to the Windows Control Panel and choose the ODBC icon.
  2. In the Data Sources dialog box, choose Add.
  3. In the Add Data Source dialog box, select the SQL Server ODBC driver and choose OK.
  4. In the ODBC SQL Server Setup dialog box, enter the data source name, description, and other appropriate information, and then choose OK.
  5. In the Data Sources dialog box, choose Close.

See Also

Installing Visual FoxPro | Upgrading from Earlier Versions


Using SQL Pass-Through Technology

Your client/server application can access server data by using:

  • Remote views
  • SQL pass-through

Remote views provide the most common and easiest method for accessing and updating remote data. The upsizing wizards can automatically create remote views in your database as part of upsizing, or you can use Visual FoxPro to create remote views after upsizing. For more information on remote views, see Creating Views.

SQL pass-through technology enables you to send SQL statements directly to a server. SQL pass-through statements, because they execute on the back-end server, are powerful ways to enhance the performance of your client/server applications. The following table compares remote views with SQL pass-through.

Comparison of Remote View and SQL Pass-Through Technologies

Remote View | SQL Pass-Through
Based on a SQL SELECT statement. | Based on any native server SQL statement, enabling data definition statements or execution of server stored procedures.
Can be used as data source for controls at design time. | Can't be used as a data source for controls.
Provides no ability to execute DDL commands on data source. | Provides method for using DDL commands on data source.
Fetches one result set. | Fetches one or multiple result sets.
Provides built-in connection management. | Requires explicit connection management.
Provides built-in default update information for updates, inserts, and deletes. | Provides no default update information.
Provides implicit SQL execution and data fetching. | Provides explicit SQL execution and result fetching control.
Provides no transaction handling. | Provides explicit transaction handling.
Stores properties persistently in database. | Provides temporary properties for SQL pass-through cursor, based on session properties.
Employs asynchronous progressive fetching while executing SQL. | Fully supports programmatic asynchronous fetching.

SQL pass-through technology offers the following advantages over remote views:

  • You can use server-specific functionality, such as stored procedures and server-based intrinsic functions.
  • You can use extensions to SQL supported by the server, as well as data-definition, server administration, and security commands.
  • You have more control over SQL pass-through Update, Delete, and Insert statements.
  • You have more control over remote transactions.
    Tip Visual FoxPro can handle SQL pass-through queries that return more than a single result set.

SQL pass-through queries also have disadvantages:

  • By default, a SQL pass-through query always returns a non-updatable snapshot of remote data, which is stored in an active view cursor. You can make the cursor updatable by setting properties with the CURSORSETPROP( ) function. An updateable remote view, in contrast, usually doesn't require that you set properties before you can update remote data, because property settings are stored in the database with the view definition.
  • You must enter SQL commands directly into the Command window or into a program, rather than using the graphical View Designer.
  • You create and manage the connection to the data source.

Whether you use remote views or SQL pass-through, you can query and update remote data. In many applications, you'll use both remote views and SQL pass-through.

Using SQL Pass-Through Functions

To use SQL pass-through to connect to a remote ODBC data source, you first call the Visual FoxPro function SQLCONNECT( ) to create a connection. You then use the Visual FoxPro SQL pass-through functions to send commands to the remote data source for execution.

To use Visual FoxPro SQL pass-through functions

  1. Confirm your system's ability to connect your computer to your data source. Use a utility such as ODBC Test for ODBC.
  2. Establish a connection to your data source with the SQLCONNECT( ) or the SQLSTRINGCONNECT( ) function.

    For example, if you're connecting Visual FoxPro to the SQL Server data source sqlremote, you might log on with the following command:

    nConnectionHandle = SQLCONNECT('sqlremote','<userid>','<password>')
    Note You can also use the SQLCONNECT( ) function to connect to a named connection.
  3. Use Visual FoxPro SQL pass-through functions to retrieve data into Visual FoxPro cursors and process the retrieved data with standard Visual FoxPro commands and functions.

    For example, you might query the authors table and browse the resulting cursor using this command:

    ? SQLEXEC(nConnectionHandle,"select * from authors","mycursorname")
BROWSE
  4. Disconnect from the data source with the SQLDISCONNECT( ) function.

Visual FoxPro SQL Pass-Through Functions

The following table lists the Visual FoxPro SQL functions that support working with remote data sources, grouped according to task.

Task | Function | Purpose
Connection management | SQLCONNECT( ) | Connects to a data source for SQL pass-through operations.
 | SQLSTRINGCONNECT( ) | Connects to a data source using ODBC connection string syntax.
 | SQLDISCONNECT( ) | Breaks a connection to an ODBC data source, making the specified connection handle obsolete.
SQL statement execution and control | SQLCANCEL( ) | Cancels an asynchronously executing SQL query on an active connection.
 | SQLEXEC( ) | Executes a SQL pass-through query on an active connection; returns the number of result sets generated, or 0 if SQLEXEC( ) is still executing (asynchronous processing).
 | SQLMORERESULTS( ) | Puts another result set into a cursor. Returns 0 if the statement creating the result set is still executing.
 | SQLPREPARE( ) | Pre-compiles the SQL statement on the data source and binds the Visual FoxPro parameters, i.e. saves the actual parameter expressions for all the parameters in the SQL statement.
 | SQLCOMMIT( ) | Requests a transaction commitment.
 | SQLROLLBACK( ) | Requests a transaction rollback.
Data source information | SQLCOLUMNS( ) | Stores a list of column names and information about each to a cursor. Returns 1 if the function succeeds, or 0 if the function is still executing.
 | SQLTABLES( ) | Stores the names of tables in the source into a cursor. Returns 1 if the function succeeds, or 0 if the function is still executing.
Miscellaneous control | SQLGETPROP( ) | Gets a connection property from an active connection.
 | SQLSETPROP( ) | Sets a property of an active connection.

The SQLEXEC( ), SQLMORERESULTS( ), SQLTABLES( ), and SQLCOLUMNS( ) statements can be canceled in synchronous mode by pressing ESC if SET ESCAPE is set to ON. You can cancel these statements at any time in asynchronous mode by issuing SQLCANCEL( ). All other SQL pass-through statements function synchronously and are not interruptible.

Creating Result Sets

When you use the SQL pass-through functions SQLEXEC( ) or SQLMORERESULTS( ) to query data, Visual FoxPro returns the data to you in one or many result sets. Result sets originate from cursors in the server data source and become cursors in Visual FoxPro. The default name for a result set is SQLRESULT.

See Also

Implementing a Client/Server Application | Accessing Server Stored Procedures with SQL Pass-Through Functions | Returning Multiple Result Sets | Processing of Multiple Result Sets | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Accessing Server Stored Procedures with SQL Pass-Through Functions

You can use Visual FoxPro SQL pass-through technology to create and execute stored procedures on a remote server. Stored procedures can greatly enhance the power, efficiency, and flexibility of SQL, and dramatically improve the performance of SQL statements and batches. Many servers provide stored procedures for defining and manipulating server database objects and for performing server system and user administration.

Note The examples in this section use Microsoft SQL Server syntax unless otherwise noted.

To call a server stored procedure

  • Use the SQLEXEC( ) function with the stored procedure name.

For example, the following code displays the results of calling a stored procedure named sp_who on SQL Server using an active connection to the data source sqlremote:

nConnectionHandle = SQLCONNECT('sqlremote')
? SQLEXEC(nConnectionHandle, 'use pubs')
? SQLEXEC(nConnectionHandle, 'sp_who')
BROWSE

For more information on creating and executing server-stored procedures, see your server documentation.

See Also

Using SQL Pass-Through Technology | Returning Multiple Result Sets | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Returning Multiple Result Sets

If you execute a stored procedure that contains native server syntax SELECT statements, each result set is returned to a separate Visual FoxPro cursor. You can use these cursors to return values or parameters from a server stored procedure to the Visual FoxPro client.

To return multiple result sets

  • Use the SQLEXEC( ) function to select multiple results sets using your native server syntax.

For example, the following code creates and executes a SQL server stored procedure, my_procedure, that returns three Visual FoxPro cursors: sqlresult, sqlresult1, and sqlresult2:

=SQLEXEC(nConnectionHandle,'create procedure my_procedure as ;
      select * from sales; select * from authors;
      select * from titles')
=SQLEXEC(nConnectionHandle,'execute my_procedure')

How the Server Processes Result Sets and Errors

Because the server compiles each stored procedure when you create it, you receive any server syntax errors at create time. When you execute the stored procedure, the server executes the compiled SQL statements sequentially (as in a Visual FoxPro program) and Visual FoxPro fetches each result set from each SQL statement within the stored procedure separately, in the order executed.

Result sets and errors are returned in the order received, and processing stops if an error is encountered. For example, if a run-time error occurs when the server executes the third statement in a four-statement stored procedure, you receive the first two result sets and then receive the error that occurred upon processing the third result set. Processing stops after the error is returned; the fourth result set is not retrieved. You can use the AERROR( ) function to obtain information about the most recent error.

Note You can execute server stored procedures from Visual FoxPro only by using Visual FoxPro SQL pass-through functions. Views don't support server stored procedures, because each view contains an explicit SQL SELECT statement in its SQL definition.

Passing a SQL Statement to the Data Source

The SQLEXEC( ) function enables you to send a SQL statement to the data source without interpretation. In the simplest case, any string you enclose in the second parameter of the SQLEXEC( ) function is passed to your data source without interpretation. This allows you to execute any statement using your data source's native SQL.

You can also use the SQLEXEC( ) function to create a parameterized query, or to pass ODBC extensions to SQL to the data source.

See Also

Accessing Server Stored Procedures with SQL Pass-Through Functions | Creating a Parameterized Query | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Creating a Parameterized Query

Just as you can create parameterized views using the View Designer or the language, you can create a parameterized SQL pass-through query.

To create a parameterized query with SQL pass-through

  • Precede a Visual FoxPro parameter with a question mark (?), and then include the parameter in a SQL string you send with SQLEXEC( ).

The parameter you supply is evaluated as a Visual FoxPro expression, and the value is sent as part of the view's SQL statement. If the evaluation fails, Visual FoxPro prompts for the parameter value.

For example, if you have the customer table from the Testdata database on a remote server, the following code creates a parameterized query that limits the view to those customers whose country matches the value supplied for the ?cCountry parameter:

? SQLEXEC(1,'SELECT * FROM customer WHERE customer.country = ?cCountry')

If you want to prompt the user for a parameter value, enclose the parameter expression in quotation marks. For more information on prompting for a parameter value, see Creating Views.

Your ODBC data source doesn't accept parameters in the following locations:

  • In a SELECT fields or tables list
  • As both expressions in a comparison predicate
  • As both operands of a binary operator

An ODBC data source will not accept parameters in the following locations in the WHERE or HAVING clause of a SELECT statement:

  • As both the first and second operands of a BETWEEN predicate
  • As both the first and third operands of a BETWEEN predicate
  • As both the expression and the first value of an IN predicate
  • As the operand of a unary + or - operator
  • As the argument of a SET function

Using SQL Server Input/Output Parameters

You can use input/output parameters to pass values between Visual FoxPro and SQL Server. Input/output parameters are available only using SQL pass-through; they can't be used in views.

The following table provides an example using input/output parameters to pass values from Visual FoxPro to a SQL Server stored procedure, returning the result to a Visual FoxPro variable.

Using Input/Output Parameters with a SQL Server Stored Procedure

Code Comments
resultCode = SQLExec(connHand,
   "CREATE PROCEDURE sp_test;
      @mult1 int, @mult2 int, @result int;
   OUTPUT AS SELECT
      @result = @mult1 * @mult2")
 Create a stored procedure, sp_test, that multiplies two variables (mult1 and mult2), then stores the resulting amount in the variable result.
outParam = 0
 Create a Visual FoxPro variable to receive the output parameter value when it's passed from SQL Server to Visual FoxPro.
resultCode = SQLExec(connHand, ;
"{CALL sp_test (2, 4, ?@outParam)}")
 Execute the SQL Server stored procedure, passing the values '2' and '4' to be multiplied together in the stored procedure.
? "outParam =", outParam  && the value is 8
 Display the value of the output parameter.

Defining Parameters

The syntax for output parameters is:

?@parameter_name

When you implement input/output parameters, define the Visual FoxPro variables you want to include in your SQL pass-through command before you use the variables in the SQL statement. To successfully send and receive information with input/output parameters, you must define:

  • A stored procedure parameter, with an output type, that returns a value.

    For example, if your stored procedure parameter is @result, you must assign an output type, such as int, to @result, and you must assign a value to @result.

  • An output parameter (@parameter_name) expression that evaluates to an existing Visual FoxPro variable.

    For example, if your output parameter expression is ?@outParam, your application must have defined the Visual FoxPro variable outParam.

    Note If you don't use an output parameter, either in Visual FoxPro or in the stored procedure, or you don't define a Visual FoxPro variable to receive the return value, the Visual FoxPro parameter value will not change.

Converting Data Types

Visual FoxPro converts returned variable values using the following rules:

  • Floating point data type (N, F, B) variables are converted to N.
  • The display size is set to 20.
  • The decimal setting is set to the current session setting. The decimal setting affects only the default display format, and doesn't affect the decimal precision.
  • Date and time variables (D, T) are converted to time (T) variables.

You can't use Memo, General, Picture, or NULL data types in input/output parameters.

If your application uses cursor fields as parameters, Visual FoxPro will attempt to convert the result back to the original field data type.

Returning Parameter Values

Input/output parameters are available only after the last result set of a statement has been fetched. This means that input/output values are returned to Visual FoxPro only after:

  • SQLEXEC( ) returns (1) in batch mode

    -or-

  • SQLMORERESULTS( ) returns (2) in non-batch mode.

If your SQLEXEC( ) statement requests multiple result sets, the output parameters are only guaranteed to be available after the last result set has been fetched from the data source.

See Also

Returning Multiple Result Sets | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Execution of ODBC Extensions to SQL

You can use SQLEXEC( ) to execute ODBC extensions to SQL by enclosing the SQL statement with SQL Access Group standard or extended escape syntax. For more information about ODBC extensions to SQL, refer to the SQL Grammar appendix in your ODBC documentation.

Creating Outer Joins Using the ODBC Escape Clause

You can use SQL pass-through to perform outer joins on remote data using the ODBC escape syntax, if your server supports outer joins. An outer join combines information from one or more tables regardless of whether matching rows are found.

The syntax for outer joins using the ODBC escape clause is:

{oj outer-join expression}

The following example creates a result set of the names and departments of employees working on project 544:

SELECT employee.name, dept.deptname;
   FROM {oj employee LEFT OUTER JOIN dept;
            ON employee.deptid = dept.deptid};
   WHERE employee.projid = 544

For more information on outer join syntax and types of outer joins, see your server documentation. For information on creating a named connection, see "Defining a Connection" in Creating Views.

See Also

Managing Connections with SQL Pass-Through | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Managing Connections with SQL Pass-Through

When you create a remote view, you choose an ODBC data source name or a connection name that is then used as a pipeline to the remote server upon activation of the view. To access remote data directly with SQL pass-through, you must have the handle for an active connection. A handle is a value that refers to an object; in this case, the handle refers to a data source connection. To obtain a handle, you request a connection to the data source using the SQLCONNECT( ) or SQLSTRINGCONNECT( ) function. If the connection is successful, your application receives a connection handle for use in subsequent Visual FoxPro calls.

Your application can request multiple connections for one data source. You can also work with multiple ODBC data sources by requesting a connection to each data source you want to access. If you want to reduce the number of connections used, you can configure remote views to share the same connection. You disconnect from a data source with the SQLDISCONNECT( ) function.

Tip Visual FoxPro relies on the definition of the ODBC data source that is stored in Windows to connect to a data source. If you change the name or the logon information for a data source, keep in mind that these changes might affect whether an application using that data source can connect to the desired remote server.

Controlling Environment and Connection Properties

The client/server environment is established each time you open Visual FoxPro. The environment exists for that session of Visual FoxPro and disappears when you close Visual FoxPro. The client/server environment contains:

  • Global properties that act as the prototypes for new connections.
  • Error values for errors that occur outside a specific connection.

You can use a handle of 0, the environment handle, to refer to global property settings. You use the SQLSETPROP( ) function to control default property settings in the connection environment and properties within individual connections. The methods you use for entering SQLSETPROP( ) values are consistent for both the environment and individual connections:

  • Properties specified with one of two values can use a logical value (.F. or .T.) for eExpression.
  • A property name can be abbreviated to its shortest unambiguous truncation. For example, you can use "Asynchronous", "Asynch", or "A" to specify the Asynchronous property. Property names aren't case-sensitive.

When you initiate a connection, the connection inherits default connection property values. You can use SQLSETPROP( ) to change these values.

Setting Connection Properties

To view the current property settings for a connection, use SQLGETPROP( ) with the respective connection handle. The following table lists the connection properties you can access with SQLGETPROP( ).

Visual FoxPro Connection Properties

To | Use this property | Purpose
Display the information used to create the active connection | ConnectString | The login connection string.
 | DataSource | The name of the data source as defined by ODBC.
 | Password | The connection password.
 | UserID | The user identification.
Work with shared connections | ConnectBusy | True (.T.) if a shared connection is busy; false (.F.) otherwise.
Control interface display | DispLogin | Controls when the ODBC Login dialog box is displayed.
 | DispWarnings | Controls whether non-fatal warning messages are displayed or not.
Control time intervals | ConnectTimeout | Specifies the time (in seconds) to wait before returning a connection time-out error.
 | IdleTimeout | Specifies the idle time-out interval (in seconds). Qualifying active connections are deactivated after the specified time interval.1
 | WaitTime | Controls the amount of time in milliseconds that elapses before Visual FoxPro checks whether the SQL statement has completed executing.
 | QueryTimeout | Controls the time (in seconds) to wait before returning a general time-out error.
Manage transactions | Transactions | Determines how the connection manages transactions on the remote table.
Control fetching of result sets into view cursors | Asynchronous | Specifies if result sets are returned synchronously (the default) or asynchronously.
 | BatchMode | Specifies if SQLEXEC( ) returns result sets all at once (the default), or individually with SQLMORERESULTS( ).
 | PacketSize | Specifies the size of the network packet used by the connection.
Display internal ODBC handles | ODBChdbc2 | The internal ODBC connection handle that can be used by external library files (.fll files) to call the ODBC API functions.
 | ODBChstmt2 | The internal ODBC statement handle that can be used by external library files (.fll files) to call the ODBC API functions.

1. If in manual transaction mode, the connection is not deactivated.

2. If a connection is deactivated, the ODBChdbc and ODBChstmt values are no longer valid. Do not free or drop these values in a user library.

For more information on connection properties and their default settings, see SQLSETPROP( ).

Controlling Environment Property Settings

The values you set in the Visual FoxPro environment using handle 0 are used as prototypes or default values for each subsequent connection or attachment.

To view the current environment property settings

  • Use SQLGETPROP( ) with 0 as the value for the handle.

The following example displays the current environment's WaitTime property setting:

? SQLGETPROP(0, "WaitTime")

If you set the DispWarnings property to true (.T.), Visual FoxPro displays any environment errors from that point on, and also sets DispWarnings to true (.T.) for newly created connections.

Although the values you set for handle 0 are used as prototype values for each connection, you can also set custom properties for an individual connection by issuing SQLSETPROP( ) for that connection handle. The exceptions are the ConnectTimeout, PacketSize, and DispLogin properties, whose settings the connection inherits at connect time. If you change the setting of the ConnectTimeout, PacketSize, or DispLogin property, the new setting isn't used until you reconnect.

Controlling Connection and View Objects

You can control connections and views by setting properties on the connection or view object. Properties that control databases, tables, table fields, view definitions, view fields, named connections, active connections, or active view cursors are called engine properties. You can display or set engine properties with one of the following Visual FoxPro functions:

To display engine properties use | To set engine properties use
CURSORGETPROP( ) | CURSORSETPROP( )
DBGETPROP( ) | DBSETPROP( )
SQLGETPROP( ) | SQLSETPROP( )

The function you use depends on whether you want to set properties on object 0 (connection 0 and cursor 0), the object definition in a database (named connection or view definition), or the active object (active connection or active view cursor). The following table lists objects and the functions you use to set properties on each object:

To set properties for | Connection | View
Object 0 | SQLSETPROP( ) | CURSORSETPROP( )
Object definition in a database | DBSETPROP( ) | DBSETPROP( )
Active object | SQLSETPROP( ) | CURSORSETPROP( )

Engine Properties

The following table lists engine properties alphabetically along with the objects that use each property.

Engine property | Applies to
Asynchronous Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
BatchMode Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
BatchUpdateCount1 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
Buffering | Active view cursors: see CURSORSETPROP( ).
Caption | Fields in tables, fields in view definitions: see DBSETPROP( ).
Comment | Databases, tables, fields in tables, view definitions, fields in view definitions, connection definitions: see DBSETPROP( ).
CompareMemo View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
ConnectBusy | Active connections: see SQLGETPROP( ).
ConnectHandle | Active view cursors: see CURSORGETPROP( ).
ConnectName1 View definitions: see DBSETPROP( ).
Active connections: see SQLGETPROP( ).
Active view cursors: see CURSORGETPROP( ).
ConnectString Connection definitions: see DBSETPROP( ).
Active connections: see SQLGETPROP( ).
ConnectTimeout Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
Database | Active view cursors: see CURSORGETPROP( ).
DataSource Connection definitions: see DBSETPROP( ).
Active connections: see SQLGETPROP( ).
DataType | Fields in view definitions: see DBSETPROP( ).
DefaultValue | Fields in tables, fields in view definitions: see DBSETPROP( ).
DeleteTrigger | Tables: see DBGETPROP( ).
DispLogin Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
DispWarnings Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
FetchAsNeeded View definitions: see DBSETPROP( ).
Active view cursors: see CURSORGETPROP( ).
FetchMemo1 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORGETPROP( ).
FetchSize1 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
IdleTimeout Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
InsertTrigger | Tables: see DBGETPROP( ).
KeyField | Fields in view definitions: see DBSETPROP( ).
KeyFieldList2 | Active view cursors: see CURSORSETPROP( ).
MaxRecords1 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
ODBCHdbc | Active connections: see SQLGETPROP( ).
ODBCHstmt | Active connections: see SQLGETPROP( ).
Offline | View definitions: see DBGETPROP( ).
PacketSize Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
ParameterList View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
Password Connection definitions: see DBSETPROP( ).
Active connections: see SQLGETPROP( ).
Path | Tables: see DBGETPROP( ).
Prepared | View definitions: see DBSETPROP( ).
PrimaryKey | Tables: see DBGETPROP( ).
QueryTimeout Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
RuleExpression | Tables, fields in tables, view definitions, fields in view definitions: see DBSETPROP( ).
RuleText | Tables, fields in tables, view definitions, fields in view definitions: see DBSETPROP( ).
SendUpdates2 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
ShareConnection View definitions: see DBSETPROP( ).
Active view cursors: see CURSORGETPROP( ).
SourceName | Active view cursors: see CURSORGETPROP( ).
SourceType View definitions: see DBGETPROP( ).
Active view cursors: see CURSORGETPROP( ).
SQL View definitions: see DBGETPROP( ).
Active view cursors: see CURSORGETPROP( ).
Tables2 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
Transactions Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
Updatable | Fields in view definitions: see DBSETPROP( ).
UpdatableFieldList2 | Active view cursors: see CURSORSETPROP( ).
UpdateName | Fields in view definitions: see DBSETPROP( ).
UpdateNameList2 | Active view cursors: see CURSORSETPROP( ).
UpdateTrigger | Tables: see DBGETPROP( ).
UpdateType View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).
UseMemoSize1 View definitions: see DBSETPROP( ).
Active view cursors: see CURSORGETPROP( ).
UserID Connection definitions: see DBSETPROP( ).
Active connections: see SQLGETPROP( ).
Version | Databases: see DBGETPROP( ).
WaitTime Connection definitions: see DBSETPROP( ).
Active connections: see SQLSETPROP( ).
WhereType View definitions: see DBSETPROP( ).
Active view cursors: see CURSORSETPROP( ).

1. Property primarily useful for remote views; setting has no effect on performance of local views. You can set this property on local views if you want to pre-set the property on the local view and then upsize later to create a remote view.

2. Property must be set for updates to be sent to remote data source.

Using Transactions with Remote Data

You can wrap transactions around updates, deletes, and inserts to remote data using one of two methods:

  • Automatic transaction mode
  • Manual transaction mode

The transaction mode you select determines how Visual FoxPro handles transactions on your local machine.

See Also

Execution of ODBC Extensions to SQL | Using Automatic Transaction Mode | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Using Automatic Transaction Mode

By default, Visual FoxPro automatically wraps every transactable command sent to the remote server in a transaction. This default automatic transaction handling is provided when the Transactions property is set to 1, or DB_TRANSAUTO.

To use automatic transaction mode

  • Use the DBSETPROP( ) function to set the Transactions property on the connection to 1 or DB_TRANSAUTO.

    -or-

  • Use the SQLSETPROP( ) function to set the Transactions property on the active connection to 1 or DB_TRANSAUTO.

Transaction processing for the remote table is automatically handled.

Note The Visual FoxPro commands BEGIN TRANSACTION and END TRANSACTION create a transaction for the local Visual FoxPro cursor only. They don't extend the transaction to the remote server.

See Also

Managing Connections with SQL Pass-Through | Controlling Transactions Manually | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Controlling Transactions Manually

If you want to control transactions manually, you can set the Transactions property to 2, or DB_TRANSMANUAL. With manual transaction handling, Visual FoxPro automatically begins a transaction for you when you issue the first transactable SQL statement, but you must submit the Visual FoxPro SQLCOMMIT( ) or SQLROLLBACK( ) functions to end the transaction.

To use manual transaction mode

  • Use the DBSETPROP( ) command to set the Transactions property on the connection to 2 or DB_TRANSMANUAL.

    -or-

  • Use the SQLSETPROP( ) command to set the Transactions property on the active connection to 2 or DB_TRANSMANUAL.

Transaction processing is handled manually through SQLCOMMIT( ) and SQLROLLBACK( ).

After committing or rolling back the prior transaction, Visual FoxPro automatically begins a new transaction when you issue the next transactable SQL statement. For more information about transactions, see Programming for Shared Access.

Nested Transactions

Visual FoxPro supports transactions nested up to five levels for local data. A single level of transaction support is built into SQL pass-through.

If your server supports multiple levels of transactions, you can use SQL pass-through to manage transaction levels explicitly. Explicit transaction management is complex, however, because it can be difficult to control the interaction between the built-in transaction and the timing of remote server transactions. For more information on explicit transaction management, see your ODBC documentation.

See Also

Using Automatic Transaction Mode | Working with Remote Data Using SQL Pass-Through | Using SQL Pass-Through Technology | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Selecting the Right Methods

You can use remote views, SQL pass-through, or both to create your client/server application. You can combine both methods for powerful results: use views for the majority of your data management requirements and use SQL pass-through to enhance the power of your application.

Using Views

You can use views as the core method for developing a robust client/server application. Remote views are a powerful technology; they're designed to allow you to select just the data you need from a remote server into a local Visual FoxPro cursor, which you can then use to view and update remote data. A view is basically a result set from a SQL SELECT statement.

Views are persistent: the view definition is stored in a database. View definitions have properties that you can set and then customize further for the active view cursor. Views are the best tool for data definition of an updatable result set.

You can use local views to build a local prototype, and then use an Upsizing Wizard to transform local views into remote views. For more information, see Upsizing Visual FoxPro Databases.

If your application's users want to use data for mobile work, you can employ offline views. Offline views make data portable, allowing laptop or other portable computer users to work with a stored copy of source data that they can update while they're on the road. When the user reconnects to the server, your application can easily merge offline changes into the source tables.

You might also want to use offline view technology to allow local users to work with data "offline," merging their updates at a later time. For more information, see Creating Views.

Using SQL Pass-Through

SQL pass-through technology provides you with direct access to a remote server with the Visual FoxPro SQL pass-through functions. These functions permit additional server access and control beyond the capability of views. For example, you can perform data definition on the remote server, set server properties, and access server stored procedures.

SQL pass-through is the best tool for creating read-only result sets and for using any other native SQL syntax. In contrast to a view, which is a result set from a SQL SELECT statement, SQL pass-through enables you to send anything you want to the server using the SQLEXEC( ) function. The following table lists the Visual FoxPro SQL pass-through functions.

SQL pass-through functions

SQLCANCEL( ) | SQLCOLUMNS( ) | SQLCOMMIT( )
SQLCONNECT( ) | SQLDISCONNECT( ) | SQLEXEC( )
SQLGETPROP( ) | SQLMORERESULTS( ) | SQLPREPARE( )
SQLROLLBACK( ) | SQLSETPROP( ) | SQLSTRINGCONNECT( )
SQLTABLES( ) |  |

You can create cursors yourself using SQL pass-through technology. Though SQL pass-through provides more direct server access, it provides less persistent access than views. In contrast to views, whose definitions are stored persistently in a database, cursors created using SQL pass-through exist only for the current session. For more information, see Implementing a Client/Server Application.

Combining Views and SQL Pass-Through

The most powerful paradigm for building a Visual FoxPro client/server application combines view and SQL pass-through technologies. Because views are easy to build and provide automatic buffering and update capabilities, use views for the majority of your data management tasks. Then use SQL pass-through to accomplish specific tasks on the remote server, such as data definition and the creation and execution of server stored procedures.

See Also

Data Location on the Optimal Platform | Rapid Application Development | Client/Server Application Design | Application Creation with Accuracy and Data Integrity | Performance Enhancement through Set-Based Data Access | Client/Server Design for High Performance | Optimizing Client/Server Performance


Working with Remote Data Using SQL Pass-Through

After you retrieve a result set using SQL pass-through, you can view and control the properties of your result set cursor using the Visual FoxPro functions CURSORGETPROP( ) and CURSORSETPROP( ). These are the same functions you use to set properties on an active view cursor.

Note Cursors aren't objects and aren't tied to the object model. However, you can view their properties, or attributes, with CURSORGETPROP( ) and set their properties with CURSORSETPROP( ).

Setting Cursor Properties for Remote Data

The following table lists the Visual FoxPro cursor properties that support working with views and connected result sets, grouped according to task categories.

Visual FoxPro Cursor Properties

Task | Property | Purpose
View cursor definition | SQL | Contains the SQL statement from which the cursor was created.
Control interactions between Visual FoxPro and ODBC | ConnectHandle | Handle to remote connection that's used by cursor.
 | ConnectName | Name of connection used by the cursor.
 | Prepare | Specifies whether the query for the view is prepared before it's executed.
 | FetchAsNeeded | Specifies whether rows are fetched automatically during the idle loop or only on an as-needed basis.
 | CompareMemo | Specifies whether Memo and General fields participate in the WHERE clause of an UPDATE statement, regardless of the setting of the UpdateType property
 | FetchMemo | Specifies whether Memo and General fields are fetched automatically with result sets, or fetched later, on demand, as the Memo or General field is opened.
 | UseMemoSize | Specifies the minimum column size (1 to 255) in result sets for which columns are returned in Memo fields.
 | FetchSize | Specifies the number of rows that are fetched at one time from the remote result set.
 | MaxRecords | Specifies the maximum number of rows fetched when result sets are returned.
Update data | SendUpdates* | Specifies whether updates to the cursor are sent to the tables on which the cursor is based.
 | BatchUpdateCount | Specifies the number of update statements sent to the back end for buffered tables.
 | Tables* | Comma-delimited list of table names on the data source; used to define scope for UpdateNameList and UpdatableFieldsList properties.
 | KeyFieldList* | Comma-delimited list of Visual FoxPro fields that represent the primary key of the result set used for updates.
 | UpdateNameList* | Comma-delimited list pairing Visual FoxPro fields in the cursor with the table and column names of fields to which you want to send updates.
 | UpdatableFieldList* | Comma-delimited list of the Visual FoxPro fields for which updates are sent.
 | Buffering | Specifies the type of buffering being performed on the cursor.
 | UpdateType | Specifies whether updates should occur using UPDATE, or DELETE and then INSERT commands.
 | WhereType | Specifies what should be included in the WHERE clause for updates to table data.

* Properties that must be set before you can update data.

You use these properties to control the way your application interacts with remote data, such as establishing the number of rows retrieved during progressive fetching, and controlling buffering and updates to remote data.

Using the Remote Data Tab in the Options Dialog Box

Some cursor properties inherit their initial values from the environment; other properties only become available at the cursor level. Some properties are available to cursors representing remote views and ODBC or SQL pass-through connected tables.

You can control some cursor and connection property settings through the Remote Data tab of the Options dialog box. When you display the Remote Data tab, the values in the dialog box represent the cursor settings for the current session and the Visual FoxPro global default settings for the connection. When you change values in the Remote Data tab and choose OK, the new values are saved to the cursor's current session and the connection's global default settings. If you choose Set As Default, the values are written to the configurable system settings on your machine. The following diagram illustrates these interactions.

View and set global and session settings with the Options dialog box

Setting Properties with SQL Pass-Through

When you create a cursor, the cursor inherits property settings, such as UpdateType and UseMemoSize, from the environment cursor, or cursor 0 of the current session. You can change these default property settings by using the CURSORSETPROP( ) function with 0 as the cursor number.

After you create a view cursor with SQL pass-through, you can change the active cursor's property settings by using the CURSORSETPROP( ) function for the view cursor. Changes you make with CURSORSETPROP( ) are temporary: the temporary settings for the active view disappear when you close the view, and the temporary settings for cursor 0 go away when you close the Visual FoxPro session.

Connections inherit properties in a similar fashion. Default properties for connection 0 are inherited when you create and store a named connection in a database. You can change these default property settings for connection 0 with the SQLSETPROP( ) function. After the connection has been created and is stored in a database, you can change connection properties with the DBSETPROP( ) function. When you use a connection, the property settings stored for the connection in the database are inherited by the active connection. You can change these properties on the active connection using the SQLSETPROP( ) function for the connection handle.

Both SQL pass-through view cursors and named connections can use a named ODBC data source. If you use an ODBC data source in a SQL pass-through view cursor, the connection inherits properties from the session defaults.

The following diagram illustrates property inheritance for cursors and connections created with SQL pass-through. The gray lines represent the flow of property inheritance; the black lines represent Visual FoxPro commands.

SQL pass-through (SPT) connection and cursor property inheritance

See Also

Controlling Transactions Manually | Updating Remote Data with SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Updating Remote Data with SQL Pass-Through

When you use SQL pass-through functions to update data on a remote server, you control whether data is updated, as well as specific details about the updates, by setting properties on the result set cursor. Visual FoxPro checks these properties when an update is requested before committing the update.

To update remote data you must set five properties: Tables, KeyFieldList, UpdateNameList, UpdatableFieldList, and SendUpdates. You can specify additional properties such as Buffering, UpdateType, and WhereType to best fit the requirements of your application.

To enable updates on an active view cursor

  • Use the CURSORSETPROP( ) function to specify the view cursor's update properties: Tables, KeyFieldList, UpdateNameList, UpdatableFieldList, and SendUpdates.
    Tip SQL pass-through view cursors aren't updatable until you specify update properties for the view cursor. If you want to store update property settings persistently, create a view definition. Visual FoxPro supplies default values that prepare the view to be updatable when you create a view using the View Designer or the language. You can use the CURSORSETPROP( ) function to add additional information to supplement or customize the default values.

The update properties you set on the active view cursor have slightly different names than their DBSETPROP( ) counterparts. The following table lists the names used for both view definitions and active cursors.

View and Cursor Update Properties

Purpose | View definition properties1 | Active cursor properties2
Make remote table updatable. | Tables | Tables
Specify the remote names for view fields. | UpdateName (field-level property) | UpdateNameList
Specify view fields you want to use as keys. | KeyField (field-level property) | KeyFieldList
Specify the view fields that are updatable. | Updatable (field-level property) | UpdatableFieldList
Turn updates on. | SendUpdates | SendUpdates

1 Set with DBSETPROP( ).
2 Set with CURSORSETPROP( ).

For more information on setting update properties, see Creating Views, or see DBSETPROP( ) or CURSORSETPROP( ).

Controlling the Timing of Remote Updates

You control how updates to remote data are buffered by setting the cursor's Buffering property. Of the five possible buffering property settings, two are valid for remote views:

  • 3, or DB_BUFOPTROW, the default, which optimistically locks the row.
  • 5, or DB_BUFOPTTABLE, which optimistically locks the table.

Visual FoxPro supports only optimistic locking on remote cursors.

Note The pessimistic row and table buffering settings, 2 and 4, don't apply to remote views, because Visual FoxPro doesn't take locks on the server data. Buffering property setting 1 doesn't apply to remote views because views are always buffered.

Using Optimistic Row Buffering

The default Buffering setting, DB_BUFOPTROW, optimistically locks remote data on a row-by-row basis. For example, if you want changes to the titles table to be committed on a row-by-row basis, such as when using the SKIP command, you could set the Buffering property to 3:

CURSORSETPROP('buffering', 3, 'titles')

When Buffering is set to row buffering, you have two methods of sending updates to the remote server. You can:

  • Call the TABLEUPDATE( ) function.
  • Use a command that moves the record pointer off the row, such as SKIP or GO BOTTOM.

The TABLEUPDATE( ) function updates the server without moving the record pointer. Commands that move the record pointer send updates to the remote server as a by-product of moving off the updated record.

If you use row buffering and want to be able to revert changes to rows, you must wrap the changes in manual transactions using SQL pass-through transaction functions.

Using Optimistic Table Buffering

If you want changes to a table to be committed a batch at a time, such as when the user clicks a Save or OK button in a form, you can set the Buffering property to 5, or DB_BUFOPTTABLE. You must call the TABLEUPDATE( ) function to send the update to the server.

In the following example, you set the Buffering property in your form's initialization code and then commit the changes in the save code.

Code Comments
CURSORSETPROP('buffering', 5, 'sqltitles')
 Set in Init code
* Update batched changes;
* ignore changes made by others

TABLEUPDATE(.T., .T., 'titles')
 Set in Save code

To restore the original values to a table and prevent updates from being sent to the remote server, you call TABLEREVERT( ). You can control whether a single row or all rows are reverted by combining the setting of the cursor's Buffering property with the TABLEREVERT( ) command. The following example reverts only the current row. You might want to invoke this code when the user clicks on a Cancel button in a form:

= TABLEREVERT(.F., 'titles')      && Revert current row

If you wanted to revert all rows, such as when the user presses ESC to leave a form, you could use the same example, this time changing the settings of the Buffering property and TABLEREVERT( ) command to revert all rows, with the entire table buffered:

= TABLEREVERT(.T., 'titles')      && Revert all rows

For more information about buffering, see Programming for Shared Access.

Detecting Changes By Other Users

In multiuser applications, conflicts with other users' updates are detected by the SQL Update query, which is generated when a write is attempted locally. The level of detection depends on the setting of the WhereType property. For more information on setting the WhereType property, see Creating Views.

Forcing Updates

You can use the TABLEUPDATE( ) function to control whether changes made to a table or cursor by another user on a network are overwritten when you send your updates. If you set the Force parameter of TABLEUPDATE( ) to true (.T.), and the CURSORSETPROP( ) UpdateType property is set to the default value, 1, old data is updated with the new data you send, as long as the value in the record's key field on the remote table hasn't been changed. If the value in the remote table's key field has changed, or if the UpdateType property is set to 2, Visual FoxPro sends a DELETE and then an INSERT statement to the remote table.

Troubleshooting Update Error Messages

The following table lists the Visual FoxPro and ODBC error messages that apply specifically to remote updates. The Action column contains the action you take to resolve the error condition.

Error Message | Meaning | Action
No update table(s) specified. Use the Tables cursor property. | The cursor property Tables contains no remote table names. At least one table is required to enable updates to the remote server. | Use the Tables property to specify at least one table for the cursor.
No key column(s) specified for the update table table_name. Use the KeyFieldList cursor property. | The primary key for the remote table specified in the error message isn't included in the KeyFieldList property for the cursor; a primary key is required for each table being updated. | Use the KeyFieldList property to specify the primary key for the remote table.
No valid update table specified for column column_name. Use the UpdateNameList and Tables cursor properties. | The UpdateName property for column column_name has an invalid table qualifier. | Set the table qualifier with the UpdateNameList property, or add the table qualifier to the Tables property setting, or both.
The KeyField List cursor property doesn't define a unique key. | More than one remote record has the same key. | Use the KeyField List property to define a unique key for the remote table.
From ODBC: ODBC invalid object. | ODBC cannot find the remote table or column because it doesn't exist as named. Visual FoxPro field names are validated by Visual FoxPro; remote table and column names are validated only by the remote server. | Check the object name.

For more information on error handling, see Handling SQL Pass-Through Errors.

See Also

Working with Remote Data Using SQL Pass-Through | Selection of an Efficient SQL Pass-Through Processing Mode | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Selection of an Efficient SQL Pass-Through Processing Mode

Visual FoxPro provides two processing modes for retrieving and updating remote data using SQL pass-through: synchronous and asynchronous. When you use SQL pass-through functions you can choose the method you prefer. You don't need to choose a method for remote views; Visual FoxPro automatically employs progressive fetching and manages the processing mode for you for remote views.

Benefits of Synchronous Mode

By default, Visual FoxPro SQL functions are processed synchronously: Visual FoxPro doesn't return control to an application until a function call is completed. Synchronous processing is useful when you're working with Visual FoxPro interactively.

Benefits of Asynchronous Mode

Asynchronous processing provides greater flexibility than synchronous processing. For example, when your application is processing a function asynchronously, your application can build a progress indicator to display the progress of the executing statement, display movement of the mouse pointer, create loops, and set timers to allow interruption of processing that is taking too long.

See Also

Updating Remote Data with SQL Pass-Through | Using SQL Pass-Through Asynchronously | Working with Remote Data Using SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Using SQL Pass-Through Asynchronously

Your application can request asynchronous processing for the four functions that submit requests to a data source and retrieve data: SQLEXEC( ), SQLMORERESULTS( ), SQLTABLES( ), and SQLCOLUMNS( ). You enable asynchronous processing by setting the Asynchronous property of the connection with the SQLSETPROP( ) function. When asynchronous communication is established for the connection, all four of these functions operate asynchronously.

To check the setting of the Asynchronous property

  • Use the SQLGETPROP( ) function to view the Asynchronous property setting. In the following example, nConnectionHandle represents the handle number for your active connection:
    ? SQLGETPROP(nConnectionHandle,'Asynchronous')

To enable asynchronous processing

  • Use the SQLSETPROP( ) function to specify the Asynchronous property:
    ? SQLSETPROP(nConnectionHandle,'Asynchronous', .T.)

In Asynchronous mode, you must call each function repeatedly until it returns a value other than 0 (still executing). While the function is still executing, you can cancel processing of the function by pressing the ESC key if the SET ESCAPE property is set to true (.T.).

Until the function has finished processing, the application can use a connection handle only with SQLCANCEL( ) or with the asynchronous function — SQLEXEC( ), SQLMORERESULTS( ), SQLTABLES( ), or SQLCOLUMNS( ) — originally associated with the handle. You can't call any of the other three asynchronous functions or SQLDISCONNECT( ) with the same connection handle until the function has finished.

See Also

Selection of an Efficient SQL Pass-Through Processing Mode | Processing of Multiple Result Sets | Working with Remote Data Using SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Processing of Multiple Result Sets

Your application retrieves multiple result sets when you use the SQLEXEC( ) function to issue more than one SQL SELECT statement, or to execute a stored procedure that issues multiple SELECT statements. The results of each SQL SELECT statement are returned in a separate Visual FoxPro cursor.

The default name SQLRESULT is used for the first cursor; subsequent cursors are assigned unique names by indexing the default name. For example, the default names for the cursors returned by a SQLEXEC( ) statement requesting three result sets are Sqlresult, Sqlresult1, and Sqlresult2.

In batch mode, if a function returns multiple result sets, the respective cursor names in Visual FoxPro have unique suffixes and can have up to 255 characters. For example, the following example sets the BatchMode property to batch mode, and then issues a SQLEXEC( ) statement containing four SQL SELECT statements that build four result sets:

? SQLSETPROP(nConnectionHandle,'BatchMode', .T.)
? SQLEXEC(nConnectionHandle,'select * from authors ;
                     select * from titles ;
                     select * from roysched ;
                     select * from titleauthor','ITEM')

When the function above has completed processing, Visual FoxPro returns the four result sets as the Visual FoxPro cursors Item, Item1, Item2, and Item3.

You can change the default name by using the cCursorname parameter with the SQLEXEC( ) or SQLMORERESULTS( ) functions. If the name you specify for a result set has already been used, the new result set overwrites the existing cursor.

When your application retrieves multiple result sets, you can choose between asynchronous or synchronous processing and batch or non-batch modes.

Using Batch Mode Processing

The BatchMode property, set with SQLSETPROP( ), controls how SQLEXEC( ) returns multiple result sets. The default value is .T., for batch mode. Batch mode processing means that Visual FoxPro doesn't return any results from a still-executing SQLEXEC( ) call until all of the individual result sets have been retrieved.

Using Non-Batch Mode Processing

If you use SQLSETPROP( ) to set the BatchMode property to .F., for non-batch mode, each result set is returned individually. The first result set is returned by the SQLEXEC( ) function call. Your application must then call SQLMORERESULTS( ) repeatedly until a value of 2 is returned, indicating that no more results are available.

In non-batch mode, the cursor name can be changed in each subsequent SQLMORERESULTS( ) call. In the previous example, if the first cursor name in a SQLEXEC( ) sequence is Item, and the second SQLMORERESULTS( ) call changes the cCursorName parameter to Otheritem, the resulting cursors will be named Item, Item1, Otheritem, and Otheritem1.

The next section describes batch mode and non-batch mode processing with synchronous and asynchronous detail added. The following diagram provides a representation of the four possible processing combinations. The numbers 0, 1, and 2 represent the values returned when you call each function.

Visual FoxPro synchronous and asynchronous processing modes

The behavior of each type of processing is explained below: the labels A, B, C, and D reference the preceding diagram. Each explanation assumes the execution of a statement that will return three result sets, represented in the diagram by three horizontal bands.

Using Synchronous Processing

In synchronous mode, control doesn't return to your application until the execution of a function is complete.

A: Synchronous Batch Mode

When you execute a SQL pass-through statement synchronously in batch mode, control isn't returned until all result sets have been retrieved. You specify the name of the first cursor by using the cCursorname parameter in the original function. If the cursor you specify already exists, the result set overwrites the existing cursor. When you request multiple result sets in synchronous batch mode, Visual FoxPro creates the names of additional cursors by uniquely indexing the name of the first cursor.

B: Synchronous Non-Batch Mode

When you execute a SQL pass-through statement synchronously in non-batch mode, the first statement retrieves the first result set and returns a 1. You must then call the SQLMORERESULTS( ) function repeatedly, and optionally specify a new name for the cursor. If you don't specify a new name for the cursor, multiple names for multiple result sets are created by uniquely indexing the base name. When SQLMORERESULTS( ) returns a value of 2, there are no more results available.

Using Asynchronous Processing

In asynchronous mode, your application must continue calling the same SQL pass-through function until it returns a value other than 0 (still executing). The default result set name, Sqlresult, can be explicitly changed with the cCursorname parameter the first time you call the function. If the name you specify for a result set has already been used, the new result set overwrites the information in the existing cursor.

C: Asynchronous Batch Mode

When you execute asynchronously in batch mode, each repeat call of the original function returns a 0 (still executing) until all of the multiple result sets have been returned to the specified cursors. When all results have been retrieved, the return value is either the number of cursors, or a negative number indicating an error.

D: Asynchronous Non-Batch Mode

When processing asynchronously in non-batch mode, SQLEXEC( ) returns a value of 1 when it completes the retrieval of each result set. Your application must then call SQLMORERESULTS( ) repeatedly until a value of 2 is returned, indicating that no more results are available.

Tip Remote result sets are retrieved in two stages: first, the result set is prepared on the server; then the result set is fetched into a local Visual FoxPro cursor. In asynchronous mode, you can call the USED( ) function to see whether Visual FoxPro has started fetching the cursor you requested.

See Also

Using SQL Pass-Through Asynchronously | Data Type Conversion Control | Working with Remote Data Using SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Data Type Conversion Control

When you move data between a remote server and Visual FoxPro, you might encounter differences in data types available on your server or in Visual FoxPro. There is rarely a one-to-one correlation between data types available on a remote data source and those available in Visual FoxPro. To handle these differences, Visual FoxPro uses ODBC or ADO data types to map remote data types to local Visual FoxPro data types. By understanding how data types are mapped between ODBC or ADO and Visual FoxPro, you can predict how the server's remote data is handled in your Visual FoxPro application.

You can also adjust the data types used on the server or in your application. You can override the default Visual FoxPro field data type by creating a view for the remote data set and then setting the DataType view field property in the database. The DataType property is a character property indicating the desired data type for each field of a remote view. For more information on the DataType property, see DBSETPROP( ).

Data Type Conversion Between Remote Views and Visual FoxPro Cursors

When you retrieve data from a remote ODBC or ADO data source, Visual FoxPro converts the data type of each ODBC or ADO field into an equivalent Visual FoxPro data type in the resulting cursor.

Remote View Data Types to Visual FoxPro Data Types

The following table lists data types available when using remote views or CursorAdapter objects along with ODBC or ADO data sources and the equivalent Visual FoxPro data types. For more information about specifying cursor schema, see the CursorAdapter CursorFill Method.

ODBC/ADO data type | Visual FoxPro cursor acceptable data type
SQL_CHAR / adChar SQL_VARCHAR / adChar SQL_LONGVARCHAR / adChar SQL_BINARY / adBinary SQL_VARBINARY / adVarbinary SQL_LONGVARBINARY / adVarbinary | Character, Memo1, or General
SQL_WCHAR / adWchar SQL_WVARCHAR / adWchar SQL_WLONGVARCHAR / adWchar | Character, Memo
SQL_BIT / adBoolean | Logical or Character
SQL_REAL / adSingle SQL_FLOAT / adDouble SQL_DOUBLE / adSingle SQL_DECIMAL / adNumeric SQL_NUMERIC / adNumeric SQL_TINYINT / adVarbinary SQL_SMALLINT / adSmallInt SQL_INTEGER / adInteger SQL_BIGINT / adBigInt | Character, Integer, Numeric, Float, Double (number of decimal places is the value of SET DECIMAL in Visual FoxPro), or Currency2
SQL_DATE / adDBTimeStamp SQL_TIMESTAMP / adBinary | Character, Date, DateTime3
SQL_TIME / adDBTTimeStamp | Character, DateTime4

1 If the ODBC field width is less than the value of the cursor property UseMemoSize, it becomes a Character field in the Visual FoxPro cursor; otherwise, it becomes a Memo field.
2 If the server field is a money data type, it becomes a Currency data type in Visual FoxPro.
3 If the value in the SQL_TIMESTAMP field contains fractions of seconds, the fractions are truncated when the value is converted to a Visual FoxPro DateTime data type.
4 The day defaults to 1/1/1900.

Note Null values in ODBC data source fields become null values in the Visual FoxPro cursor, regardless of the SET NULL setting in Visual FoxPro at the time your application retrieves remote data.

The following table lists Visual FoxPro data types available when using remote views with CursorAdapter objects and native Visual FoxPro data and their equivalent Visual FoxPro data types.

Visual FoxPro native data type | Visual FoxPro cursor acceptable data type
Character, Memo, General | Character, Memo, or General
Numeric, Float, Currency, Integer, Double | Numeric, Float, Currency, Integer, Double, or Character
Logical | Character or Logical
Date, DateTime | Character, Date, or DateTime

Visual FoxPro Parameter Values to Remote View Data Types

If Visual FoxPro data exists in a cursor that originated from remote data, the data reverts to its original ODBC or ADO data type when sending data to the remote server. If you send data that originated in Visual FoxPro to the remote server using SQL pass-through, the table describes the conversions that apply.

Visual FoxPro data type | ODBC data type
Character | SQL_CHAR or SQL_LONGVARCHAR1
Currency | SQL_DECIMAL
Date | SQL_DATE or SQL_TIMESTAMP2
DateTime | SQL_TIMESTAMP
Double | SQL_DOUBLE
Integer | SQL_INTEGER
General | SQL_LONGVARBINARY
Logical | SQL_BIT
Memo | SQL_LONGVARCHAR
Numeric | SQL_DOUBLE

1 If the Visual FoxPro variable that maps to a parameter creates an expression whose width is less than 255, it becomes a SQL_CHAR type in the ODBC data source; otherwise, it becomes a SQL_LONGVARCHAR type.
2 Visual FoxPro Date data is converted to SQL_DATE for all ODBC data sources except SQL Server, where it becomes SQL_TIMESTAMP.

Visual FoxPro Parameter Values to Remote Data Type Mapping

You can map a Visual FoxPro parameter value to a particular remote data type by formatting the parameter as a character expression that uses the syntax for the desired remote data type. For example, if your server provides a DateTime data type, you can create your Visual FoxPro parameter as a character expression in the format used by your server to represent DateTime data. When your server receives the parameter value, it attempts to map the formatted data to the DateTime data type.

Note When you send a parameter to the remote server, be sure the data type in the WHERE clause matches the data type that's used for the parameter expression.

See Also

Processing of Multiple Result Sets | Handling SQL Pass-Through Errors | Working with Remote Data Using SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Handling SQL Pass-Through Errors

If a SQL pass-through function returns an error, Visual FoxPro stores the error message in an array. The AERROR( ) function provides information about errors that are detected in any of the component levels: Visual FoxPro, the ODBC data source, or the remote server. By examining the values returned by AERROR( ), you can determine the server error that occurred and its error message text.

Caution You must call AERROR( ) immediately to obtain error information. If you generate any other error before you call AERROR( ), the error information is lost.

See Also

Data Type Conversion Control | Processing of Multiple Result Sets | Working with Remote Data Using SQL Pass-Through | Implementing a Client/Server Application | Designing Client/Server Applications | Upsizing Visual FoxPro Databases | Creating Views


Compiling an Application

You can create event-driven, object-oriented applications one piece at a time. This modular approach makes it possible for you to verify the functionality of each component as you create it. After you have created all the functional components, you can compile them into an application, which assembles the executable components of your project — forms, reports, menus, programs, and so on — into a single file that you can distribute to your users along with your data.

To quickly create a complete project with Application Framework Files, you can use the Application Wizard. After the project is created, the new Application Builder opens, so you can add a database, tables, reports, and forms.

In This Section

Building Applications
Describes how to build standard applications and create distributable files from your application project.
Referencing Modifiable Files
Discusses how to identify specific files in your application that can be modified by end users.
Building an Application File from the Project
Discusses how to create the final file from your project.

Related Sections

Developing Visual FoxPro Applications
Provides conceptual information on Visual FoxPro application development, including instructions for creating databases and the user interface, and other tasks needed to create applications.
Application Planning
Discusses how careful planning saves time, effort, and money, and how many of the decisions you make during the planning phase will impact how you create elements of the application.
Creating the Application
Discusses how to create Visual FoxPro applications, which may include one or more databases, a main program that sets up the system environment, and a user interface comprised of forms, toolbars, and menus.
Creating Web Services and Components
Describes how you can extend your Visual FoxPro application by making it possible for it to work for multiple users, take advantage of Microsoft ActiveX controls and automation-enabled applications.
Enhancing Applications using SQL Pass-through Technology
Describes how you can use SQL pass-through (SPT) technology to create objects on the server, run server stored procedures, and execute commands using native server syntax.
Working with Data
Provides information on how to create effective applications with indexes, tables, and databases based on your data requirements.
Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Testing and Debugging Applications
Discusses the debugging tools provided by Visual FoxPro to help you find and correct any errors you discover in your applications.
Distributing Applications
Describes how to prepare to distribute your application by including all required files and creating distribution disks, after you have completed developing and testing your application.


Building Applications

When your application project contains all the necessary files, you're ready to build a distributable file. You can build your project as a standard application that only runs when Visual FoxPro is present, or as an executable application that runs without Visual FoxPro.

Note You can also build your application as an Automation server. For details, see Creating Automation Servers.

Building a Standard Visual FoxPro Application

You can build a standard Visual FoxPro application with the Project Manager or with the BUILD APP command. However, more build options are available when you create an application through the Project Manager.

To build a standard application

  • In the Project Manager, choose Build, then in the Build Options dialog box, choose Build Application.

    -or-

  • Use the BUILD APP command.

Building an Executable File

You can build a Visual FoxPro executable file with the Project Manager or with the BUILD EXE command.

To build an executable file

  • In the Project Manager, choose Build, then in the Build Options dialog box, choose Build Executable.

    -or-

  • Use the BUILD EXE command.

    If you include the STANDALONE or EXTENDED clauses of the BUILD EXE command, Visual FoxPro generates a "Command contains unrecognized phrase/keyword" error message. These clauses were used in FoxPro, but are irrelevant in Visual FoxPro.

You can also build an Automation server, which creates a DLL that can be called from other Windows programs.

To compile an Automation server

  • In the Project Manager, choose Build, then in the Build Options dialog box, choose Build OLE DLL.

    -or-

  • Use the BUILD DLL command.

See Also

Modifying the Appearance of Your Application | Creating Automation Servers


Referencing Modifiable Files

When you compile a project into an application, files included in the project are assembled into a single application file. After the project is built, files in the project that are marked "included" become read-only.

Often, files that are part of your project, such as tables, are intended to be modified by users. In those cases, you should add the files to your project but mark them as excluded. Excluded files are still part of your application, so Visual FoxPro still tracks them as part of your project, but they are not compiled in the application file, so users can update them.

Note Tables are marked as excluded by default, because Visual FoxPro assumes that tables will be modifiable in an application.

As a general rule, files containing executable programs (forms, reports, queries, menus, and programs) should be included in the application file, and data files should be excluded. However, you should determine whether to include or exclude files based on your application requirements. For example, a table that contains sensitive system information or information used only for lookup can be included in the application file to protect it from inadvertent change. Conversely, you might exclude a report (.frx) file if your application allows users to change it dynamically.

If you exclude a file, you must make sure that Visual FoxPro can find the excluded file when the application runs. For example, when a form references a visual class library, the form stores a relative path to that library. If you include the library in the project, it is made part of the application file, and the form will always be able to locate the library. However, if you exclude the library, the form must search for the library using the relative path or the Visual FoxPro search path (as set using the SET PATH command). If the library is not in the expected locations — for example, if you have moved the library since creating the form — Visual FoxPro displays a dialog box asking the user to locate the library. You might not want users to see this dialog box. To be safe, include all files that don't need to be updated by users.

Note You cannot include application (.app) files, and you should choose to exclude library files (.ocx, .fll, and .dll).

To exclude modifiable files

  1. In the Project Manager, select the modifiable file.
  2. From the Project menu, choose Exclude.

    If the file is already excluded, the Exclude command is not available; the Include command appears in its place.

Excluded files have the Æ symbol to the left of their names.

Note Files marked as main files cannot be marked as excluded. For details about main files, see Setting the Starting Point.
Tip To view all project files at once, choose Project Info from the Project menu and select the Files tab.

See Also

Adding Files to a Project | Compiling an Application | SET PATH | Project Manager


Building an Application File from the Project

To create a finished file from your application, you build it into an application file. An application file has an extension of .app. To run the application, users first start Visual FoxPro, then load the .app file.

You can choose to build either an application (.app) or an executable (.exe) file from your project. Users can run an .app file if they already have a copy of Visual FoxPro. Alternatively, you can create an .exe file. The .exe file works in conjunction with two Visual FoxPro dynamic link libraries (Vfp8r.dll and Vfp8renu.dll) that you ship with your application to provide a complete run-time environment for Visual FoxPro. The second file is specific to the region of the world your application targets. For more information, see Distributing Applications.

To build an application

  1. In the Project Manager, choose Build.
  2. In the Build Options dialog box, choose Build Application to build an .app file, or Build Executable to build an .exe file.
  3. Select any other options you need, then choose OK.

    -or-

  • Use the BUILD APP or BUILD EXE command.

For example, to build an application called Myapp.app from a project named Myproj.pjx, you can type:

BUILD APP myapp FROM myproj

To create an application called Myapp.exe from a project named Myproj.pjx, you can type:

BUILD EXE myapp FROM myproj
Note You can also use the Build dialog box to create an Automation server from your Visual FoxPro application. For more information, see Creating Automation Servers in "Adding OLE."

After you've created a finished application file for your project, you and your users can run it.

To run an application as an .app file

  • In Visual FoxPro, choose Do from the Program menu and select the application file.

    -or-

  • In the Command window, type DO and the name of your application file.

    For example, to run an application called MYAPP, type:

    DO myapp.app

If you have created an .exe file from your application, users can run it in a variety of ways.

To run an application as an .exe file

  • In Visual FoxPro, choose Do from the Program menu and select the application file, or in the Command window, type DO and the name of your application file.

    For example, to run an .exe file called Myapp.exe, type:

    DO myapp.exe

    -or-

  • In Windows, double-click the icon for the .exe file.

See Also

Testing a Project | Referencing Modifiable Files | Compiling an Application | Build Options | BUILD APP | BUILD EXE


Testing and Debugging Applications

Testing involves finding problems in your code; debugging consists of isolating and fixing the problems. Testing and debugging are necessary stages in the development cycle, and they are best incorporated early in the cycle. Thoroughly testing and debugging individual components makes testing and debugging integrated applications much easier.

Typically, developers look for different levels of robustness as they are testing and debugging their applications:

  1. Running without crashing or generating error messages.
  2. Appropriate action in common scenarios.
  3. Reasonable action or error messages in a range of scenarios.
  4. Graceful recovery from unexpected user interactions.

Visual FoxPro provides a rich set of tools to help you isolate and identify the problems in your code so that you can fix them effectively. However, one of the best ways to create a robust application is to look for potential problems before they occur.

In This Section

Creating Bookmarks and Task List Shortcuts
Discusses the use of bookmarks and shortcuts in the Editor to easily step through your code.
Testing a Project
Provides information about verifying your application before the final build.
Handling Run-Time Errors
Discusses what you can do when run-time errors occur after the application starts to execute.
Structured Error Handling
Discusses using the TRY...CATCH...FINALLY control structure to handle errors or exceptions that can occur in your code at run time.
Debugging Before Bugs Exist
Describes how good coding practices (using white space, including comments, adhering to naming conventions, and so on) automatically tend to reduce the number of bugs in your code.
Isolating Problems
Describes how to use the Visual FoxPro debugging environment to isolate those problems that are identified through testing.

Related Sections

Developing Visual FoxPro Applications
Provides conceptual information about how to develop Visual FoxPro applications, including instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Compiling an Application
Discusses how to use the modular approach to make it possible to verify the functionality of each component you create. Then you can compile them into an application, which assembles the executable components of your project.
Distributing Applications
Discusses how to prepare to distribute your application by including all required files and creating distribution disks, after you have completed developing and testing your application.


Creating Bookmarks and Task List Shortcuts

Bookmarks and shortcuts allow you to move easily through your code. You can set bookmarks and shortcuts, and then use shortcut keys to cycle through them. Bookmarks are temporary. They are retained when the editing window is closed and reopened, but they are not retained after exiting and restarting Visual FoxPro.

Shortcuts are similar to named bookmarks and are persisted between editing sessions. When you create a shortcut in your code, an entry is made in the Task List making it easy to move quickly to the marked code. You can step through shortcuts in the same way you step through bookmarks.

Bookmarks are related to the editor window rather than to content. During an edit session, bookmarks are related to the position within the window and not to the actual content of the file. Consequently, certain edit operations, such as text insertions before a bookmark, cause that bookmark to relate to a different line than the one with which it was previously associated. If the new line association is not desirable, you should remove the existing bookmark or shortcut and add a new one in the desired location.

Each line of code can contain either a bookmark or a shortcut, but not both on the same line.

If the Selection Margin is not available in the Editor, use the Editor Tab, Options Dialog Box to specify the margin.

To create bookmarks

  • In the Editor, place the mouse cursor in the Selection Margin next to the code line you want to mark, and then press SHIFT while double-clicking.

    -or-

    In the Editor, place the cursor in the code line you want to mark, and then press ALT + SHIFT + F2.

To create task list shortcuts

  • In the Editor, place the mouse cursor in the Selection Margin next to the code line you want to mark, and then press CTRL while double-clicking.

    -or-

    In the Editor, place the cursor in the code line you want to mark, and then press ALT + F2.

To move between bookmarks and shortcuts

  1. To move to the next bookmark, press F2.
  2. To move to the previous bookmark, press SHIFT + F2.

To remove a bookmark

  • In the Editor, place the mouse cursor in the Selection Margin on the bookmark icon, and then press SHIFT while double-clicking.

    -or-

    In the Editor, place the cursor in the code line you want to remove the mark from, and then press ALT + SHIFT + F2.

    -or-

    Delete the code containing the bookmark.

To remove a shortcut

  • In the Editor, place the mouse cursor in the Selection Margin on the bookmark icon, and then press CTRL while double-clicking.

    -or-

    In the Editor, place the cursor in the code line you want to remove the mark from, and then press ALT + F2.

    -or-

    Delete the code containing the shortcut.

See Also

Testing a Project | Editor Tab, Options Dialog Box | Using the Task List Manager | Task List Manager Window


Testing a Project

To verify references and check that all components are available before compiling an application, you can test the project. To do so, you rebuild the project, which forces Visual FoxPro to resolve file references and to recompile files that are out of date.

Use bookmarks, shortcuts, and breakpoints to mark locations in code so you can step easily through your code. For details, see Creating Bookmarks and Task List Shortcuts.

To test a project

  1. In the Project Manager, choose Build.
  2. In the Build Options dialog box, select Rebuild Project.
  3. Select any other options you need and choose OK.

    -or-

  • Use the BUILD PROJECT command.

For example, to build a project named Myproj.pjx, type:

BUILD PROJECT myproj

If errors occur during the build process, they are collected into a file in your current directory with the name of your project and an .err extension. The compilation error count is displayed on the status bar. You can also see the error file immediately.

To display the error file immediately

  • Select the Display Errors box.

After the project has been built successfully, you should try to run it before creating an application.

To run the application

  • In the Project Manager, highlight the main program, and then choose Run.

    -or-

  • In the Command window, issue a DO command with the name of the main program:
    DO MAINPROG.PRG

If the program runs properly, you're ready to build an application file that will contain all the files included in the project.

You should repeat the steps of rebuilding and running your project as you add components to your project. Unless you choose Recompile All Files in the Build Options dialog box, only files that have been modified since the last build are recompiled.

See Also

Building an Application File from the Project | Compiling an Application | Project Manager | Build Options | Using the Automated Test Harness


Handling Run-Time Errors

Run-time errors occur after the application starts to execute. Actions that would generate run-time errors include: writing to a file that doesn't exist, attempting to open a table that is already open, trying to select a table that has been closed, encountering a data conflict, dividing a value by zero, and so on.

At times, errors occur when users run your application. You can call your own error-handling routine by including ON ERROR. Typically, ON ERROR uses a DO command to run a routine that handles the error, as in:

ON ERROR DO My_Error

If your application contains no error-handling routines when an error occurs, the application pauses and Visual FoxPro displays an error message with the following options:

  • Cancel If a user chooses Cancel, Visual FoxPro immediately stops running the application and returns control to the system.
  • Ignore If a user chooses Ignore, Visual FoxPro ignores the line that caused the error and continues to the next line in the program.

For a complete list and explanation of Visual FoxPro error messages, see Error Messages.

Tip Be sure to provide documentation to your users that describes the errors that they might see, and suggests ways in which they can correct errors.

The following commands and functions are useful when anticipating and managing run-time errors.

To | Use
Fill an array with error information | AERROR( )
Open the Debugger or Trace window | DEBUG or SET STEP ON
Generate a specific error to test your error handling | ERROR
Return an error number | ERROR( )
Return an executing program line | LINENO( )
Return an error message string | MESSAGE( )
Execute a command when an error occurs | ON ERROR
Return commands assigned to error handling commands | ON( )
Return the name of the currently executing program | PROGRAM( ) OR SYS(16)
Re-execute the previous command | RETRY
Return any current error message parameter | SYS(2018)

Anticipating Errors

The first line of defense against run-time errors is anticipating where they could occur and coding around them. For example, the following line of code moves the record pointer to the next record in the table:

SKIP

This code works unless the record pointer is already past the last record in the table, at which point an error will occur.

The following lines of code anticipate this error and avoid it:

IF !EOF()
   SKIP
      IF EOF()
         GO BOTTOM
      ENDIF
ENDIF

As another example, the following line of code displays the Open dialog box to allow a user to open a table in a new work area:

USE GETFILE('DBF') IN 0

The problem is that the user could choose Cancel in the Open dialog box or type the name of a file that doesn't exist. The following code anticipates this by making sure that the file exists before the user tries to use it:

cNewTable = GETFILE('DBF')
IF FILE(cNewTable)
   USE (cNewTable) IN 0
ENDIF

Your end user may also type the name of a file that isn't a Visual FoxPro table. To circumvent this problem, you could open the file with low-level file I/O functions, parse the binary header, and make sure that the file is indeed a valid table. However, this would be a bit of work and it might noticeably slow down your application. You would be better off handling the situation at run time by displaying a message like "Please open another file. This one is not a table" when error 15, "Not a table," occurs.

You can't, and probably don't want to, anticipate all possible errors, so you'll need to trap some by writing code to be executed in the event of a run time error.

Handling Procedural Errors

When an error occurs in procedural code, Visual FoxPro checks for error-handling code associated with an ON ERROR routine. If no ON ERROR routine exists, Visual FoxPro displays the default Visual FoxPro error message. For a complete list of Visual FoxPro error messages and error numbers, see Help.

Creating an ON ERROR routine

You can include any valid FoxPro command or expression after ON ERROR, but normally you call an error-handling procedure or program.

To see how ON ERROR works, you can type an unrecognizable command in the Command window, such as:

qxy

You'll get a standard Visual FoxPro error message dialog box saying "Unrecognized command verb." But if you execute the following lines of code, you'll see the error number, 16, printed on the active output window instead of the standard error message displayed in a dialog box:

ON ERROR ?ERROR()
qxy

Issuing ON ERROR with nothing after it resets the built-in Visual FoxPro error messaging:

ON ERROR

In skeletal form, the following code illustrates an ON ERROR error handler:

LOCAL lcOldOnError

* Save the original error handler
lcOldOnError = ON("ERROR")

* Issue ON ERROR with the name of a procedure
ON ERROR DO errhandler WITH ERROR(), MESSAGE()

* code to which the error handling routine applies

* Reset the original error handler
ON ERROR &lcOldOnError

PROCEDURE errhandler
LOCAL aErrInfo[1]
AERROR(aErrInfo)
DO CASE
   CASE aErrInfo[1] = 1 && File Does Not Exist
      * display an appropriate message
      * and take some action to fix the problem.
   OTHERWISE
      * display a generic message, maybe
      * send high priority mail to an administrator
ENDPROC

Handling Errors in Classes and Objects

When an error occurs in method code, Visual FoxPro checks for error-handling code associated with the Error event of the object. If no code has been written at the object level for the Error event, the Error event code inherited from the parent class, or another class up the class hierarchy, is executed. If no code has been written for the Error event anywhere in the class hierarchy, Visual FoxPro checks for an ON ERROR routine. If no ON ERROR routine exists, Visual FoxPro displays the default Visual FoxPro error message.

Note The Error event does not occur if an ON ERROR routine is on the call stack.

The beauty of classes is that you can encapsulate everything a control needs, including error handling, so that you can use the control in a variety of environments. Later, if you discover another error the control might encounter, you can add handling for that error to the class, and all objects based on your class will automatically inherit the new error handling.

For example, the vcr class in the Buttons.vcx class library, located in the Visual FoxPro ...\Samples\Classes directory, is based on the Visual FoxPro container class.

Four command buttons in the container manage table navigation, moving the record pointer in a table with the following commands:

GO TOP
SKIP - 1
SKIP 1
GO BOTTOM.

An error could occur when a user chooses one of the buttons and no table is open. Visual FoxPro attempts to write buffered values to a table when the record pointer moves. So an error could also occur if optimistic row buffering is enabled and another user has changed a value in the buffered record.

These errors could occur when the user chooses any one of the buttons; therefore, it doesn't make sense to have four separate error handling methods. The following code associated with the Error event of each of the command buttons passes the error information to the single error-handling routine of the class:

LPARAMETERS nError, cMethod, nLine
THIS.Parent.Error(nError, cMethod, nLine)

The following code is associated with the Error event of the vcr class. The actual code differs because of coding requirements for localization.

Parameters nError, cMethod, nLine
DO CASE
CASE nError = 13 && Alias not found
   cNewTable = GETFILE('DBF')
   IF FILE(cNewTable)
      SELECT 0
      USE (cNewTable)
      This.SkipTable = ALIAS()
   ELSE
      This.SkipTable = ""
   ENDIF
CASE nError = 1585 && Data Conflict
* Update conflict handled by a datachecker class
   nConflictStatus = ;
      THIS.DataChecker1.CheckConflicts()
   IF nConflictStatus = 2
      MESSAGEBOX "Can't resolve a data conflict."
   ENDIF
OTHERWISE
* Display information about other errors.

   cMsg="Error:" + ALLTRIM(STR(nError)) + CHR(13) ;
      + MESSAGE()+CHR(13)+"Program:"+PROGRAM()

   nAnswer = MESSAGEBOX(cMsg, 2+48+512, "Error")
   DO CASE
      CASE nAnswer = 3   &&Abort
         CANCEL
      CASE nAnswer = 4   &&Retry
         RETRY
      OTHERWISE       && Ignore
         RETURN
   ENDCASE
ENDCASE

You want to make sure that you supply information for an error that you haven't handled. Otherwise, the error event code will execute but won't take any actions, and the default Visual FoxPro error message will no longer be displayed. You, as well as the user, won't know what happened.

Depending on your target users, you might want to supply more information in the case of an unhandled error, such as the name and phone number of someone to call for help.

Returning from Error Handling Code

After the error handling code executes, the line of code following the one that caused the error is executed. If you want to re-execute the line of code that caused the error after you've changed the situation that caused the error, use the RETRY command.

Note The Error event can be called when the error encountered wasn't associated with a line of your code. For example, if you call a data environment's CloseTables method in code when AutoCloseTables is set to true (.T.) and then release the form, an internal error is generated when Visual FoxPro tries to close the tables again. You can trap for this error, but there is no line of code to RETRY.

Using Shutdown Routines

Create your own shutdown routine by including the command ON SHUTDOWN in your code. Typically, ON SHUTDOWN uses a DO command to call a routine if you try to exit the application, as in the following example:

ON SHUTDOWN DO My_Shutdown

This routine typically includes a dialog box that asks if the user is sure they want to quit the current application. If the user wants to quit the application, the routine can close open files and clean up the environment, and then issue the QUIT command. If the user doesn't want to exit the current application, the routine can return control to the application.

See Also

The Logging of Code Coverage | Output Display | Testing and Debugging Applications | ON ERROR | Seeing Stored Values


Structured Error Handling

Visual FoxPro provides the TRY...CATCH…FINALLY control structure to handle errors, or exceptions, that can occur in your code at run time.

TRY...CATCH…FINALLY

TRY…CATCH…FINALLY contains code blocks for the TRY, CATCH, and FINALLY statements. In these code blocks, you can perform the following error handling tasks:

  • Generate an exception
  • Catch an exception
  • Nest TRY…CATCH blocks
  • Escalate an exception
  • Exit TRY…CATCH…FINALLY immediately
  • Use commands
  • Run final statements

The TRY...CATCH…FINALLY structure starts with the TRY statement, which marks the beginning of the TRY block. In the TRY block, you can specify a set of code statements that can produce errors at run time. If your program completes the TRY block without generating an exception, it skips the CATCH block and looks for the FINALLY block near the end of the structure, if it exists, and runs the corresponding statements. If the FINALLY block does not exist, the program moves outside the structure to the first statement after the ENDTRY statement, which marks the end of the TRY…CATCH…FINALLY structure.

Generating an Exception

If an error occurs in the TRY block, Visual FoxPro generates an exception, which is a condition that causes your computer to handle the error in a separate routine. When the error occurs, the code "throws" an exception, and appropriate statements in the CATCH block handle the specific exception. After the program resolves the error, the program moves to the FINALLY block to run any remaining statements and leaves the TRY…CATCH…FINALLY structure.

Catching an Exception

When an error occurs in the TRY block, Visual FoxPro generates an exception, and the program moves to the first CATCH statement. The program looks for CATCH statements only when an error occurs. You can specify any number of CATCH statements, including none. The program examines CATCH statements in the order that they appear in the CATCH block to see if one of them can handle the exception. If the program finds a CATCH statement that handles the exception, the program runs the corresponding code.

The CATCH statement can contain optional TO and WHEN clauses. You can specify a memory variable in the TO clause to store a reference to an Exception object, which is created only when an exception occurs. If you want to establish a condition for a CATCH block to run, you can specify an expression in the WHEN clause that must evaluate to True (.T.) before the CATCH block runs. CATCH statements work similarly to CASE statements in that the WHEN clause must evaluate to a logical expression. If the TO and WHEN clauses do not exist, the CATCH statement evaluates as CATCH WHEN .T. (True).

After the program runs statements in a CATCH block, it does not return to the TRY statement, and it does not look for other CATCH statements. Instead, the program proceeds directly to the FINALLY statement, if it exists. Otherwise, the program moves to the statement that immediately follows ENDTRY.

Note Visual FoxPro permits the existence of TRY...CATCH…FINALLY structures that do not have CATCH and FINALLY blocks. Visual FoxPro simply throws the generated error to a higher-level error handler.

Priority of Error Handlers

If an error occurs in the method of an object that is called from a TRY block, Visual FoxPro follows the error handling procedure for that particular object. This protocol provides a way for you to maintain encapsulation and control of your components. For example, suppose the line MyForm.Refresh()in a TRY block produces an error. If code for an Error event exists to handle the error, then the Error event takes precedence. If no Error event exists, then a CATCH statement attempts to handle the error.

The priority of error handlers for object code is described as follows:

  • TRY…CATCH in the method where the exception occurs. This applies to external procedures, not methods, that are called in the method.
  • Error event, if it exists
  • TRY...CATCH that is higher in the calling chain and can exist in a higher level method
  • Visual FoxPro system error handler
Caution The use of TRY...CATCH in a method for a class that does not have an Error event might impact existing code and possibly break backward compatibility. Therefore, TRY...CATCH statements appearing in methods should only call other methods of classes that contain an Error event.

The following example shows how the line of code, ? "BBB", never executes due to calling myMethod2 from myMethod1 without an Error event for myMethod2. However, if myMethod2 was called directly, ON ERROR DO errorHandler handles the error and returns execution back to the program so that ? "BBB" can execute.

ON ERROR DO errorHandler
x=CREATEOBJECT("myClass")
x.myMethod1()

DEFINE CLASS myClass AS Session
   PROCEDURE myMethod1
      TRY
         THIS.myMethod2()
      CATCH TO oErr
         ? "Catch:",oErr.ErrorNo
      ENDTRY
   ENDPROC
   PROCEDURE myMethod2
      ? "AAA"
      x=y         && The variable y does not exist.
                  && CATCH traps this error.
      ? "BBB"      && Does not execute if CATCH traps previous error.
   ENDPROC
ENDDEFINE

If an error occurs in a chain of TRY…CATCH blocks within the method of an object, the following rules apply:

  • If the code itself in the TRY block generates an exception, the CATCH statement handles the exception. If no CATCH statement exists to handle the exception, the Error event handles the exception. Otherwise, Visual FoxPro escalates the error to an appropriate handler. The same behavior applies if the error occurs with an external procedure that is called from a TRY block. For example:
    x=CREATEOBJECT("myClass")
x.myMethod()

DEFINE CLASS myClass AS Session
   PROCEDURE myMethod
      TRY
         DO myProc
      CATCH TO oErr
         ? "Catch:",oErr.Errorno
      ENDTRY
   ENDPROC
   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:",nError
   ENDPROC
ENDDEFINE

PROCEDURE myProc
   x=y   && The variable y does not exist. CATCH handles this error.
ENDPROC
  • If the method of an object that is called from the TRY block generates an exception, the Error event for the object's method handles the exception. This maintains object encapsulation because this method could have been called from another method. For example:
    x=CREATEOBJECT("myClass")
x.myMethod1()

DEFINE CLASS myClass AS Session
   PROCEDURE myMethod1
      TRY
         THIS.myMethod2()
      CATCH TO oErr
         ? "Catch:",oErr.Errorno
      ENDTRY
   ENDPROC
   PROCEDURE myMethod2
      x=y   && Error event handles this error.
   ENDPROC
   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:",nError
   ENDPROC
ENDDEFINE

Nesting TRY…CATCH Blocks

  • You can nest TRY...CATCH blocks. That is, you can insert a TRY...CATCH…FINALLY structure within a TRY, CATCH, or FINALLY block.

Escalating an Exception

You can include a THROW statement if you want to "rethrow" or escalate the exception to a higher-level error handler. You can call THROW from any code block of a TRY…CATCH…FINALLY structure. However, you can use THROW anywhere in code where an error handler exists to catch the exception. You cannot call THROW from the Command window.

Caution Calling the THROW command outside the TRY...CATCH...FINALLY structure and without an appropriate error handler causes your program to quit.

If you call THROW outside the TRY...CATCH section where the thrown exception is handled by an ON ERROR routine or the Visual FoxPro system handler instead of an Error event, program execution does not return to the location where the THROW statement occurs. The following example shows how the line of code, ?2, does not execute. This behavior differs from a traditional error behavior in which program execution returns to the location where the error occurred:

ON ERROR ? ERROR()
DO myProc1

PROCEDURE myProc1
   ?1
   THROW 11
   ?2
ENDPROC

Remember, the intention for calling THROW is to escalate the exception to a higher-level error handler.

If an outer TRY...CATCH block exists around a THROW statement when it is called from within a CATCH or FINALLY block, Visual FoxPro reassigns the memory variable specified in the TO clause from the object reference of the previous exception object to an object reference for the most recent exception object created by the thrown exception. If no outer TRY...CATCH structure exists, Visual FoxPro rethrows the exception to an ON ERROR routine or an error event, if they exist. Otherwise, Visual FoxPro calls the system handler.

Exiting TRY…CATCH…FINALLY

You can include an EXIT statement in a TRY or CATCH block to break out of the code block immediately. The program resumes running code at the FINALLY statement, if one exists, or at the line immediately following the ENDTRY statement.

Using Commands in TRY…CATCH…FINALLY

You can use different Visual FoxPro commands that affect how code normally runs from within a TRY or CATCH block. However, if you use one of these commands that are not permitted for a specific block, Visual FoxPro generates an error at run time. The FINALLY statements always run before handling these commands except when CANCEL or QUIT is used. The following table lists the Visual FoxPro commands you can and cannot use in a TRY, CATCH, or FINALLY block.

Command | TRY | CATCH | FINALLY
CANCEL | Yes | Yes | Yes
CLEAR ALL | Yes | No | No
CLOSE ALL | Yes | Yes | Yes
DOEVENTS | Yes | Yes | Yes
ERROR | Yes | Yes | Yes
EXIT | Yes | Yes | Yes
LOOP | No | No | No
QUIT | Yes | Yes | Yes
RELEASE | Yes | Yes | Yes
RESUME | Yes | Yes | Yes
RETRY | No | No | No
RETURN | No | No | No
RETURN TO MASTER | No | No | No
RETURN TO <ProcedureName> | No | No | No
SET STEP ON | Yes | Yes | Yes
SUSPEND | Yes | Yes | Yes
THROW | Yes | Yes | Yes
Note You can include commands such as LOOP in a block as long as you place it inside an embedded control statement such as FOR EACH...ENDOR or DO WHILE…ENDDO. You can call the ERROR command from the TRY, CATCH, or FINALLY blocks. TRY...CATCH…FINALLY handles the ERROR command like any other exception or use of the THROW command.

Running Final Statements

If the program finds the FINALLY statement, it runs the code that is in the FINALLY block. The FINALLY block usually cleans up any resources allocated by the TRY block and is always the last code to run before control leaves the TRY...CATCH…FINALLY structure.

The FINALLY block always runs when an exception, unhandled or otherwise, occurs, even if another exception handler such as the ON ERROR routine or an error event for an object, is in effect.

Note You cannot explicitly transfer control of your program directly to a CATCH or FINALLY block. You cannot bypass the FINALLY statement if it exists unless you use the CANCEL command to stop the program from continuing. If you wish to bypass the FINALLY statement, you need to provide code at the beginning of the FINALLY block that checks for a condition and breaks out of the block if that condition is met.

After the FINALLY block runs, the program then proceeds to the statement immediately following the ENDTRY statement. The ENDTRY statement ends the TRY...CATCH…FINALLY structure.

Exception Objects

When an error occurs in the TRY block, Visual FoxPro automatically creates an Exception object, which contains details about the error. A CATCH statement usually handles this exception, which is referenced by the memory variable specified by VarName in the TO clause.

The Exception object always exists as an instance of the Exception base class. You cannot run user code when the Exception object is created. If you wish to use a subclass of the Exception class, you should rethrow the exception in the CATCH or FINALLY block.

If an error or exception occurs in the CATCH or FINALLY block, the TRY...CATCH…FINALLY structure itself does not handle this exception. Instead, Visual FoxPro passes errors that occur in the CATCH or FINALLY blocks to an outer error handler, such as an error event or the ON ERROR command, which can include another TRY...CATCH…FINALLY structure. The outer handler takes care of errors in the event that TRY...CATCH…FINALLY does not contain any CATCH statements or if no CATCH statements exist that can handle the error. If you want to have a TRY...CATCH…FINALLY structure that catches all errors, make sure you have a CATCH statement that always evaluates to True (.T.).

Note Only Visual FoxPro program (.prg) files support Exception objects.

See Also

New Classes, Commands, and Functions | Testing and Debugging Applications | TRY...CATCH…FINALLY Command | Exception Class


Debugging Before Bugs Exist

Studies have shown that good coding practices (using white space, including comments, adhering to naming conventions, and so on) automatically tend to reduce the number of bugs in your code. In addition, there are some steps you can take early in the development process to make testing and debugging easier later on, including: creating a test environment, setting asserts, and seeing event sequences.

Creating a Test Environment

The system environment that you expect an application to run in is as important as the data environment you have set up for the application itself. To ensure portability and to create an appropriate context for testing and debugging, you need to consider hardware and software, system paths and file properties, and directory structure and file locations.

Hardware and Software

For maximum portability, you should develop applications on the lowest common platform you expect them to run on. To establish a baseline platform:

  • Develop your applications using the lowest common video mode.
  • Determine base requirements for RAM and media storage space, including any necessary drivers or concurrently running software.
  • Consider special memory, file, and record-locking scenarios for network versus stand-alone versions of applications.

System Paths and File Properties

To ensure all necessary program files are readily accessible on each machine that will run your application, you might also require a baseline file configuration. To help you define a configuration baseline, answer the following questions:

  • Does your application require common system paths?
  • Have you set appropriate file access properties?
  • Are network permissions set correctly for each user?

Directory Structure and File Locations

If your source code references absolute paths or file names, those exact paths and files must exist when your application is installed on any other computer. To avoid this scenario, you can:

  • Use Visual FoxPro configuration files. For additional information on using configuration files, see Customizing the Visual FoxPro Environment .
  • Create a separate directory or directory structure to keep source files apart from the generated application files. This way, you can test the references of the completed application and know exactly which files to distribute.
  • Use relative paths.

Setting Asserts

You can include asserts in your code to verify assumptions you have about the run-time environment for the code.

To set an assert

  • Use the ASSERT command to identify assumptions in your program.

    When the condition stipulated in the ASSERT command evaluates to false (.F.), an assert message box is displayed and echoed to the Debug Output window.

For example, you could be writing a function that expects a non-zero parameter value. The following line of code in the function alerts you if the value of the parameter is 0:

ASSERT nParm != 0 MESSAGE "Received a parameter of 0"

You can specify whether assert messages are displayed with the SET ASSERTS command. By default, assert messages are not displayed.

Seeing Event Sequences

When you see events occur in relation to other events, you can determine the most efficient place to include your code.

To track events

  • From the Tools menu in the Debugger window, choose Event Tracking.

    -or-

  • Use the SET EVENTTRACKING command.

The Event Tracking Dialog Box allows you to select the events that you want to see.

Note In this example, the MouseMove and Paint events have been removed from the Events to track list because these events occur so frequently that they make it more difficult to see the sequences of the other events.

When event tracking is enabled, every time a system event in the Events to track list occurs, the name of the event is displayed in the Debug Output window or written to a file. If you choose to have the events displayed in the Debug Output window, you can still save them to a file as described in Output Display.

Note If the Debug Output window is not open, events will not be listed, even if the Debugger Output Window box is set.

See Also

Setting Asserts | Isolating Problems | Testing and Debugging Applications | Debugger | Seeing Stored Values | Using the Automated Test Harness


Isolating Problems

Once your testing has identified problems, you can use the Visual FoxPro debugging environment to isolate those problems by:

  • Starting a debugging session
  • Tracing through code
  • Suspending program execution
  • Seeing stored values
  • Output Display

Starting a Debugging Session

You start a debugging session by opening the debugging environment.

To open the debugger

  • From the Tools menu, choose Debugger.
    Note If you're debugging in the Visual FoxPro environment, choose the debugging tool you want to open from the Tools menu.

You can also open the debugger with any of the following commands:

DEBUG

SET STEP ON

SET ECHO ON

The debugger opens automatically whenever a breakpoint condition is met.

Tracing Through Code

One of the most useful debugging strategies at your disposal is the ability to trace through code, see each line of code as it executes, and check the values of all variables, properties, and environment settings.

To trace through code

  1. Start a debugging session.
  2. If no program is open in the Trace window, choose Do from the Debug menu.
  3. Choose Step Into from the Debug menu or click the Step Into toolbar button.

An arrow in the gray area to the left of the code indicates the next line to execute.

Tip The following tips apply:
  • Set breakpoints to narrow the range of code you need to step through.
  • You can skip a line of code you know will generate an error by placing the cursor on the line of code after the problem line and choosing Set Next Statement from the Debug menu.
  • If you have much code associated with Timer events, you can avoid tracing through this code by clearing Display Timer Event in the Debugging tab of the Options dialog box.

If you isolate a problem when you're debugging a program or object code, you can immediately fix it.

To fix problems encountered while tracing code

  • From the Debug menu, choose Fix.

When you choose Fix from the Debug menu, program execution is canceled and the code editor is opened to the location of the cursor in the Trace window.

See Also

Seeing Event Sequences | Suspending Program Execution | Testing and Debugging Applications | DEBUG | Seeing Stored Values | Using the Automated Test Harness


Suspending Program Execution

Breakpoints allow you to suspend program execution. Once program execution has been suspended, you can check the values of variables and properties, see environment settings, and examine sections of code line by line without having to step through all your code.

Tip You can also suspend execution of a program running in the Trace window by pressing ESC.

Suspending Execution at a Line of Code

You can set breakpoints in your code to suspend program execution in several different ways. If you know where you want to suspend program execution, you can set a breakpoint directly on that line of code.

To set a breakpoint on a particular line of code

In the Trace window, locate the line of code you want to set the breakpoint on and do one of the following:

  1. Position the cursor on the line of code.
  2. Press F9 or click the Toggle Breakpoints button in the Debugger toolbar.

    -or-

  • Double-click in the gray area to the left of the line of code.

A solid dot is displayed in the gray area to the left of the line of code to indicate that a breakpoint has been set on that line.

Tip If you are debugging objects, you can locate particular lines of code in the Trace window by choosing the object from the Object list and the method or event from the Procedure list.

You can also set breakpoints by specifying locations and files in the Breakpoints dialog box.

Examples of Locations and Files for Breakpoints

Location File Where execution suspends
ErrHandler
 C:\Myapp\Main.prg The first executable line in a procedure named ErrHandler in Main.prg.
Main,10
 C:\Myapp\Main.prg The tenth line in the program named Main.
Click
 C:\Myapp\Form.scx The first executable line of any procedure, function, method or event named Click in Form.scx.
cmdNext.Click
 C:\Myapp\Form.scx The first executable line associated with the Click event of cmdNext in Form.scx.
cmdNext::Click
 The first executable line in the Click event of any control whose ParentClass is cmdNext in any file.

Suspending Execution When Values Change

If you want to know when the value of a variable or property changes, or when a run-time condition changes, you can set a breakpoint on an expression.

To suspend program execution when the value of an expression changes

  1. From the Tools menu in the Debugger window, choose Breakpoints to open the Breakpoints dialog box.
  2. From the Type list, choose Break when expression has changed.
  3. Enter the expression in the Expression box.

Examples of breakpoint expressions

Expression Use
RECNO( )
 Suspend execution when the record pointer moves in the table.
PROGRAM( )
 Suspend execution on the first line of any new program, procedure, method, or event.
myform.Text1.Value
 Suspend execution any time the value of this property is changed interactively or programmatically.

Suspending Execution Conditionally

Often you'll want to suspend program execution, not at a particular line, but when a certain condition is true.

To suspend program execution when an expression evaluates to true

  1. From the Tools menu in the Debugger window, choose Breakpoints to open the Breakpoints dialog box.
  2. From the Type list, choose Break when expression is true.
  3. Enter the expression in the Expression box.
  4. Choose Add to add the breakpoint to the Breakpoints list.

Examples of breakpoint expressions

Expression Use
EOF( )
 Suspend execution when the record pointer has moved past the last record in a table.
'CLICK'$PROGRAM( )
 Suspend execution on the first line of code associated with a Click or DblClick event.
nReturnValue = 6
 If the return value of a message box is stored to nReturnValue, suspend execution when a user chooses Yes in the message box.

Suspending Execution Conditionally at a Line of Code

You can specify that program execution be suspended at a particular line only when a particular condition is true.

To suspend program execution at a particular line when an expression evaluates to true

  1. From the Tools menu in the Debugger window, choose Breakpoints to open the Breakpoints dialog box.
  2. From the Type list, choose Break at location if expression is true.
  3. Enter the location in the Location box.
  4. Enter the expression in the Expression box.
  5. Choose Add to add the breakpoint to the Breakpoints list.
  6. Choose OK.
    Tip It is sometimes easier to locate the line of code in the Trace window, set a breakpoint, and then edit that breakpoint in the Breakpoints dialog box. To do this, change the Type from Break at location to Break at location if expression is true and then add the expression.

Removing Breakpoints

You can disable breakpoints without removing them in the Breakpoints dialog box. You can delete "break at location" breakpoints in the Trace window.

To remove a breakpoint from a line of code

In the Trace window, locate the breakpoint and do one of the following:

  • Position the cursor on the line of code, and then choose Toggle Breakpoints from the Debugger toolbar.

    -or-

  • Double-click the gray area to the left of the line of code.

See Also

Isolating Problems | Seeing Stored Values | Testing and Debugging Applications | Output Display | Trace | Debugger


Seeing Stored Values

In the Debugger window, you can easily see the run-time values of variables, array elements, properties, and expressions in the following windows:

  • Locals Window
  • Watch Window
  • Trace Window

Seeing Stored Values in the Locals Window

The Locals window displays all the variables, arrays, objects, and object members that are visible in any program, procedure, or method on the call stack. By default, values for the currently executing program are displayed in the Locals window. You can see these values for other programs or procedures on the call stack by choosing the programs or procedures from the Locals For list.

You can drill down into arrays or objects by clicking the plus (+) beside the array or object name in the Locals and Watch windows. When you drill down, you can see the values of all the elements in the arrays and all the property settings in objects.

You can even change the values in variables, array elements, and properties in the Locals and Watch windows by selecting the variable, array element, or property, clicking in the Value column, and typing a new value.

Seeing Stored Values in the Watch Window

In the Watch box of the Watch window, type any valid Visual FoxPro expression and press ENTER. The value and type of the expression appears in the Watch window list.

Note You can't enter expressions in the Watch window that create objects.

You can also select variables or expressions in the Trace window or other Debugger windows and drag them into the Watch window.

Values that have changed are displayed in red in the Watch window.

To remove an item from the Watch window list

Select the item and choose one of the following:

  • Press DEL.

    -or-

  • From the shortcut menu, choose Delete Watch.

To edit a watch

  • Double-click the watch in the Watch window and edit in place.

Seeing Stored Values in the Trace Window

Position the cursor over any variable, array element, or property in the Trace window to display its current value in a value tip.

A value tip in the Trace window

See Also

Suspending Program Execution | Output Display | Testing and Debugging Applications | The Logging of Code Coverage | Handling Run-Time Errors


Output Display

The DEBUGOUT command allows you to write values in the Debug Output window to a text file log. Alternatively, you can use the SET DEBUGOUT TO command or the Debug tab of the Options dialog box.

If you aren't writing DEBUGOUT commands to a text file, the Debug Output window must be open in order for the DEBUGOUT values to be written. The following line of code prints in the Debug Output window at the time that the line of code executes:

DEBUGOUT DATETIME( )

In addition, you can enable event tracking, and choose to have the name and parameters of each event that occurs displayed in the Debug Output window.

See Also

Seeing Stored Values | The Logging of Code Coverage | Testing and Debugging Applications | Handling Run-Time Errors | Suspending Program Execution


Distributing Applications

After you develop and test your application, you can prepare to distribute it by including all required files and creating distribution disks.

In This Section

Application Distribution Process
Describes an overview of the steps needed to distribute your application.
Preparation for Distributing Applications
Describes considerations you need to consider when preparing your application for distribution and the run-time environment, such as choosing the type of build, testing minimum operating environment requirements, ensuring correct run-time behavior, and including Visual FoxPro system menu options.
Resource Files in Applications
Describes resource files that you can include in your application to extend its functionality, such as FoxUser.dbf, external library files, ActiveX controls and COM components, configuration and help files, and so on.
Distributable and Restricted Visual FoxPro Features and Files
Describes restricted Visual FoxPro features and files you must remove from your application as well as those files you can distribute with your application.
Including Files with Applications for Distribution
Describes how you to add or include files that you want to distribute with your application.

Related Sections

Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Working with Projects
Defines a project a configuration and a group of files that produce a program or final binary file or files.
Creating Help
Describes how you can include Help files in your application to provide valuable information for users of your application.
Compiling an Application
Describes how to use the modular approach to make it possible for you to verify the functionality of each component you create. Then you can compile them into an application, which assembles the executable components of your project.
Testing and Debugging Applications
Discusses testing for errors within and across components when you develop an application. Visual FoxPro provides debugging tools to help you find and correct any errors you discover in your applications.


Application Distribution Process

The following list identifies the overall steps you need to follow to distribute a Visual FoxPro application:

  1. Create and debug the application using the Visual FoxPro development environment.
  2. Prepare and customize your application for the run-time environment. For details, see Preparation for Distributing Applications.
  3. Make sure your project includes all the necessary files for your application, including any resource files, graphics files, or templates. For more information about the types of files you can include in your application and how to include files, see Resource Files in Applications and Including Files with Applications for Distribution.
  4. Remove any restricted Visual FoxPro features or files from your application. Certain development environment features are not available in the run-time environment and need to be removed from your application. Make sure any files you plan to distribute meet the guidelines for redistributing files. For more information on restricted and distributable files, see Distributable and Restricted Visual FoxPro Features and Files.
  5. Create documentation and online Help. For more information about creating Help for your application, see Creating Help.
  6. Build an application (.app), executable (.exe) file, or a COM component (automation server) with a .dll or .exe extension. For more information about building an application, see Compiling an Application.
  7. Create an installation package using a Windows Installer deployment program. For more information about creating installation packages, see Walkthrough: Creating a Visual FoxPro Application Setup Program Using InstallShield Express.
    Note The setup creation program you use must use Windows Installer technology to create a Setup program (.msi) or merge modules (.msm) that are compatible with Microsoft Windows Installer. The Windows 2000 Logo guidelines require that setup programs be based on Windows Installer technology.
  8. Package and distribute your application disks and any printed documentation. Depending on the setup creation program you use, the program might create the disk images for you, or you might need to copy the files to the distribution location manually. Consult the documentation for the setup creation program for more information.

See Also

Distributing Applications | Preparation for Distributing Applications


Preparation for Distributing Applications

This section describes a number of issues you should consider when preparing your application for deployment.

  • Build Type Selection
  • Hardware, Memory, and Network Issues
  • Ensuring Correct Run-Time Behavior
  • Default Menu Options

Build Type Selection

Before you can distribute your application, you must build an application (.app) file, an executable (.exe) file, or a COM component (automation server) with a .dll or .exe extension. When choosing the type of build you want to create, consider the size of your final application file and whether users have Visual FoxPro installed on their computers.

The following table lists the differences between the types of builds.

Build type | Description
Application (.app) file | This file requires that the user have a copy of Visual FoxPro installed. An .app file is usually smaller than an .exe file.
Executable (.exe) file | This file includes the Visual FoxPro loader so users do not need have Visual FoxPro installed. You must provide the two support files Vfp8r.dll and Vfp8renu.dll. The letters, "en", denote the English version. These files must be placed in the same directory as the .exe file or along the DOS path. See BUILD EXE Command for details about creating and distributing executable files.
COM Server (.dll or .exe) files | This file is used to create a file that can be called by other applications. In Visual FoxPro, you can create two types of COM server (.dll, formerly, OLE) files. You must provide run-time support files, including the Vfp8r.dll, Vfp8t.dll, and Vfp8renu.dll files. For details, see Adding OLE Objects to Applications.

Hardware, Memory, and Network Issues

You should consider and test the minimum environment your application can operate in, including the amount of disk space and memory. The results of your testing and the resolution of other issues covered in this section can help determine the type of build you choose and the files you include with your application.

The applications you create have the same hardware, memory, and network requirements as Visual FoxPro. For more information on those requirements, see "System Requirements" in Installing Visual FoxPro. For additional information on creating applications for multiuser environments, see Programming for Shared Access.

Ensuring Correct Run-Time Behavior

An executable application (.exe) file always checks for the presence of the Visual FoxPro run-time library, Vfp8r.dll. In some cases, Visual FoxPro in-process servers, or .dll files, can use the lightweight Vfp8t.dll run time instead. For more information about run-time libraries, see VFP8R.DLL Run-Time Library and VFP8T.DLL Run-Time Library.

To run an application .exe file using the development version of Visual FoxPro, you must force the application to use the Visual FoxPro Vfp8.exe file instead.

To run an executable application in Visual FoxPro

  • From the Project menu, choose Do. In the Do dialog box, select the name of your application's .exe file.

An application consisting only of modeless forms will not function properly in a run-time environment unless you provide a READ EVENTS command. You can make sure the application runs properly by adding a calling program or setting the WindowType property.

You can also type DO followed by the name of your application's .exe file in the Command window or use the -E command-line switch in the command line that starts Visual FoxPro. For example, if your application is called MYAPP, you can run it with the following command line:

MYAPP.EXE -E

This command-line switch forces the application to use the executable file, Vfp8.exe. For this switch to work correctly, Vfp8.exe must be in the search path.

To run a form in a run-time environment

  • Run the form from a program containing a READ EVENTS command.

    -or-

  • Set the form's WindowType property to Modal.

Some Visual FoxPro applications rely heavily on Visual FoxPro system menus. At run time, some menus and commands are unavailable, and without a provision for a READ EVENTS command, a menu-driven application ends as quickly as it starts. Use the following section to review any menus you include in your application.

For more information on structuring an application with the READ EVENTS command, see Controlling the Event Loop and examples of how to structure an application in Compiling an Application.

Default Menu Options

If you use the Visual FoxPro system menu, your application file includes only the following default menus and menu commands.

Menu | Menu items
File | Close, Save, Save As, Exit
Edit | Undo, Redo, Cut, Copy, Paste, Paste Special, Select All, Find, Replace
Window | Arrange All, Hide, Hide All, Show All, Clear, Cycle, all open windows
Help | Contents, Search for Help on, Product Support, About Visual FoxPro

You can disable or remove any of the default menus and menu commands, or add your own menus and menu commands to run-time applications.

Tip If your menu system works in the development environment but closes prematurely in your application, make sure you have a READ EVENTS command active while your menu system is running. Also be sure to include a CLEAR EVENTS command when you exit the menu system.

For more information about customizing menus, see Designing Menus and Toolbars.

See Also

Distributing Applications | Application Distribution Process | Resource Files in Applications | Distributable and Restricted Visual FoxPro Features and Files | Including Files with Applications for Distribution


Resource Files in Applications

Visual FoxPro provides several resource files that extend the basic functionality of your applications, including FoxUser resource files, API libraries, and ActiveX controls. If you use these files, you must include them in your project or distribution tree.

The following table lists some of the files you can include in your application by adding them to your project. For more information about including files in your application for distribution, see Including Files with Applications for Distribution.

If you are | Add these files to your project
Applying a custom configuration to your application | Config.fpw
Applying custom settings to your application | FoxUser.dbf and FoxUser.fpt

For details about how to include files in your setup program, see the help associated with the setup creation program you are using. The setup creation program you use must create MSI setup packages using Windows Installer technology.

FoxUser.* Resource Files

Visual FoxPro resource files store useful information for your application, including window positions, Browse window configurations, and label definitions. If your application relies on specific settings for any of these resource items, you must also distribute the FoxUser database and memo files or the resource files you create specifically for your application. These resource files consist of a Visual FoxPro table with an associated memo file, usually named FoxUser.dbf and FoxUser.fpt.

Note The FoxUser.dbf resource file is not the same as the locale-specific resource file that contains dialog boxes and error messages. The FoxUser.dbf resource file stores application information such as macros you have defined; the locale-specific resource file stores system text strings.

External Library Files

If your application includes external library files such as ActiveX controls (.ocx files) or Visual FoxPro API libraries (.fll files), make sure they are placed in the appropriate directory in your setup package. You can distribute the Visual FoxPro file FoxTools.fll with your applications. For more information on creating external libraries to access the Visual FoxPro API, see Accessing APIs.

ActiveX Controls and COM Components

If you include ActiveX controls or have created an Automation server (a COM component) as part of your application, include any .ocx and .dll files in your project and ensure the necessary support files are installed to the proper location on the user's machine.

Note The Windows 2000 Logo guidelines do not recommend installing components to the Windows System directory. You can only distribute ActiveX controls for which you are licensed. For Automation servers, you must also include registration files, such as type libraries (.tlb files) and registry files (.vbr files), with your application.

If you use your setup creation program to create the distribution disks, you can include these files automatically. When you do this, the setup creation program ensures that COM components are registered properly on the user's computer when the application is installed. For more information on including files in your setup creation program, see the help associated with the program.

All users can run forms containing ActiveX controls; however, your application cannot accomplish certain tasks if it is running under the run-time version of Visual FoxPro. Remember the following guidelines:

  • Your application must be running under a full version of Visual FoxPro to change forms, classes, or subclasses that include ActiveX controls.
  • Your application must be running under a full version of Visual FoxPro to add ActiveX controls to forms at run time. For example, the full version of Visual FoxPro is required to add the Outline control to a form by running the following code:
    PUBLIC frmOleNewForm
frmOleNewForm = CREATEOBJECT("form")
frmOleNewForm.Show
frmOleNewForm.ScaleMode = 3
frmOleNewForm.Addobject("NewOutline","OLEControl",;
   "MSOutl.Outline")
    Note When a form is closed, controls added at run time are not saved.
  • Your application can be running under either the run-time or full version of Visual FoxPro to add subclassed ActiveX controls to a form at run time. For example, you can define the RedOutline subclass from the Outline class, and distribute the subclass in Olelib.vcx; all users can then add the RedOutline control to a form by running the following code:
    PUBLIC frmOleNewForm
frmOleNewForm = CREATEOBJECT("form")
frmOleNewForm.Show
frmOleNewForm.ScaleMode = 3
SET CLASSLIB TO CURR() + OLELIB.VCX
frmOleNewForm.Addobject("NewOutline","RedOutline")

Configuration Files

You can use the configuration file, Config.fpw, to establish many default Visual FoxPro settings. For instance, you can change the Visual FoxPro title, the background color, and the way a user navigates with the keyboard.

If you want the configuration file to be read-only, place it in your project and mark it as included. If you want the configuration to be modifiable, place the file in your project and mark it as excluded. Distribute the configuration file with your application or executable file, as a separate file. By default, Visual FoxPro looks for a configuration file named Config.fpw. However, you can specify a different configuration file name using the -C command-line switch when starting Visual FoxPro.

For more information about options that you can set in the configuration file, see "Using a Configuration File" in Customizing the Visual FoxPro Environment.

Locale-Specific Resource Files

If you are distributing your application along with the run-time version of Visual FoxPro, you might need to include a locale-specific resource file. This file contains the dialog boxes and other user interface elements that Visual FoxPro uses to interact with the user. A different run-time resource file exists for each language in which Visual FoxPro is available.

For more information about using locale-specific run-time files, see "Distributing Locale-Specific Run-Time Files" in Developing International Applications.

Note The locale-specific resource file is not the same as the FoxUser.dbf resource file, which stores application information such as macros you have defined. The locale-specific resource file stores system text strings.

If you are creating an application for Middle Eastern platforms, be sure to add VBAME.DLL file to your distribution set and have it installed in the Windows System directory.

Help Files

If you create graphical Help for your application, include the .chm or .hlp file in your application distribution set so that your setup creation program can include it on your distribution disks. For details about creating help, see Creating Help.

Note You cannot distribute Winhelp.exe or the Help files shipped with Visual FoxPro.

See Also

Distributing Applications | Preparation for Distributing Applications | Distributable and Restricted Visual FoxPro Features and Files | Including Files with Applications for Distribution | Menu Options


Distributable and Restricted Visual FoxPro Features and Files

Visual FoxPro and its development environment contain many files and features that are licensed only for your use in designing, developing, and testing your applications. If your application contains any of these restricted features or files as well as files other than those authored by you or in Redist.txt, you must remove them. Under the terms of the Microsoft License Agreement you received with this product, you cannot ship these files in your application or on your disks.

You can distribute any Visual FoxPro file that is not restricted. For a list of redistributable files, see Redist.txt, which is located in your Visual FoxPro directory (C:\Program Files\Microsoft Visual FoxPro 8), and the guidelines for including redistributable files in this topic.

Restricted Visual FoxPro Features

You cannot include the following restricted Visual FoxPro menus and their menu commands in a distributed executable (.exe) file:

  • Database
  • Form
  • Menu
  • Program
  • Project
  • Query
  • Table

The following table lists commands for which your application returns the error "Feature not available" if included. Although you cannot include commands that create or modify menus, forms, or queries, you can run compiled menu, form, or query programs in your application.

Unavailable commands |
APPEND PROCEDURES | MODIFY DATABASE
BUILD APP | MODIFY FORM
BUILD EXE | MODIFY MENU
BUILD PROJECT | MODIFY PROCEDURE
CREATE FORM | MODIFY PROJECT
CREATE MENU | MODIFY QUERY
CREATE QUERY | MODIFY SCREEN
CREATE SCREEN | MODIFY VIEW
CREATE VIEW | MODIFY CONNECTION
SET STEP |

The following table lists commands that are ignored when used in a distributed application.

Ignored commands |
ASSERT | DEBUGOUT
SET DEBUG | SET DOHISTORY
SET DEVELOPMENT | SET ECHO

Restricted Visual FoxPro Files

Visual FoxPro installs files on your computer that are restricted and cannot be reproduced or distributed, including:

  • Some wizard files
  • TrueType fonts
  • Visual FoxPro Help files

Distributable Visual FoxPro Files

Pursuant to the Microsoft License Agreement you received with this product, you must distribute files in conjunction with a corresponding application. The following guidelines apply to distributable files.

Samples

Visual FoxPro provides files in the ...\Samples\ directory for you to learn from and build on. Although you cannot distribute unmodified Visual FoxPro samples, you can refer to portions of sample application code as examples for building your own application.

If you use any files in these directories, including all .bmp, .ico, and .cur files, you must include them in your project and application build. They must not appear by name on the distributable disks and cannot be distributed independently of your applications.

Class Libraries

You can use any .vcx file, including those in the \Ffc and \Gallery directories, the wizard class library, Wizstyle.vcx, and the sample class libraries without modification in your applications. You must include the libraries in your project and in your application build.

ODBC Files

Please refer to the Microsoft License Agreement you received with this product for specific restrictions with respect to your redistribution of ODBC files.

ActiveX Controls

Visual FoxPro includes a set of ActiveX controls (.ocx files) you can add to and distribute with your applications.

See Also

Distributing Applications | Preparation for Distributing Applications | Resource Files in Applications | Including Files with Applications for Distribution | ActiveX Controls Overview


Including Files with Applications for Distribution

You can freely reproduce and distribute some Visual FoxPro files, graphics, and programs with the applications you create; however, you must remove restricted files from your application. For more information, see Distributable and Restricted Visual FoxPro Features and Files.

Before you build your application, make sure that your project includes the necessary files for your application as well as any additional resource files, such as graphics files or templates.

To add files to your application

  • Include the files in your project.

    If you do not want to change these files in the distributed application, place the files in your project and mark them as included. The files are then read-only and cannot be modified.

    -or-

  • Add the files to your application directory to make them easily accessible to your setup creation program.

    If you want to modify them, place the files in your project and mark them as excluded. Then distribute them with your application as separate files.

For more information about creating a project, and including or excluding files in a project, see Compiling an Application.

See Also

Distributing Applications | Preparation for Distributing Applications | Resource Files in Applications | Menu Options


Programming in Visual FoxPro

Microsoft Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.

In This Section

Creating Programs
Explains the two ways to create a Visual FoxPro program, which is a text file containing a series of commands.
Object-Oriented Programming
Discusses how you can create self-contained application components that respond to user actions and to the system and which can be easily maintained and reused.
Optimizing Applications
Discusses ways to optimize performance by making your application smaller and faster.
Accessing APIs
Discusses how you can extend an application by taking advantage of external libraries such as Microsoft ActiveX controls or dynamic-link libraries (DLLs).

Related Sections

Using Visual FoxPro
Provides information on Visual FoxPro programming features that are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Walkthroughs
Provides common scenarios and step-by-step guides on how to create different types of applications and components.
Overview of Visual FoxPro Features
Discusses how Visual FoxPro gives you more of everything you have come to expect in a database management system (DBMS) — speed, power, and flexibility.
Customizing the Visual FoxPro Environment
Describes how you can customize your development environment after installing Visual FoxPro. Environment settings include the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Development Productivity Tools
Discusses the developer tools for application development within the Visual FoxPro application and the Visual FoxPro language.


Working with Programs

You can write code that executes a series of commands and save it in a program file instead of running it immediately. You can format code blocks and entire program files, search for and replace code references, and view code definitions.

In This Section

Creating Programs
Describes how to create a Visual FoxPro program.
Formatting Code in Programs
Describes how you can set formatting preferences for code in programs.
Running Code Manually
Describes when you might use the Command window to run code.
Searching and Replacing Code References
Describes how to search for and replace code references and text in programs and text files.
Viewing Code Definitions
Describes how to view the definition of a code element found in a code reference search in the current program file

Related Sections

Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Developing Visual FoxPro Applications
Explains concepts about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Language Reference
Contains descriptions of language elements in Visual FoxPro.
Development Productivity Tools
Describes Visual FoxPro developer tools that you can use for application development within the FoxPro application and the FoxPro language.


Creating Programs

You can write code that executes commands and save it in a program file in Visual FoxPro. Although you can run code in the Command window, running a program has some advantages such as the following:

  • You can modify and run programs multiple times.
  • You can run programs from menus, forms, and toolbars.
  • You can use programs to run other programs.

To create a program

  1. From the File menu, choose New.
  2. In the New dialog box, select Program, and click New File.
  3. In the editing window, type the code for the program.

You can also create a program in the following ways by using MODIFY COMMAND in the Command window or selecting Programs under the Code node in the Project Manager and choosing New. For more information, see MODIFY COMMAND Command and Project Manager Window.

Note Make sure you save the program after creating it.

To save a program

  • From the File menu, choose Save.

Programs are saved with the .prg extension.

If you try to close an unsaved program, a dialog box opens, prompting you to either save or discard the changes you made to it.

If you save a program that was created in the Project Manager, the program is added to the project.

If you save a program that does not have a name, the Save As dialog box opens so you can specify a name for the program. After you save your program, you can run or modify it.

Modifying Programs

To makes changes to a program, open the program.

To open a program

  1. From the File menu, choose Open.
  2. In the Open dialog box, choose Program in the Files of type list to show only program files.
  3. Select the program you want to modify and choose OK.

If the program is part of a project, you can select the program in the Project Manager and choose Modify. You can also type the MODIFY COMMAND command with the name of the program in the Command window as follows:

MODIFY COMMAND MyProgram

-or-

MODIFY COMMAND ?

From the list of files, select the program you want to modify and choose Open.

After you open the program, you can make changes. When you finish making your changes, be sure to save the program.

Running Programs

After you create and save a program, you can run it.

To run a program

  1. From the Program menu, choose Do.
  2. From the list of programs, select the program and choose Do.

If the program is part of a project, you can select the program in the Project Manager and choose Run. You can also type the DO command with the name of the program in the Command window as follows:

DO MyProgram

See Also

Programming in Visual FoxPro | Running Code Manually | Searching and Replacing Code References | Viewing Code Definitions | Project Manager Window | Operating the Command Window


Formatting Code in Programs

You can format entire program files or specific blocks of code according to the preferences you set in the Beautify Options dialog box.

For more information about the formatting preferences you can set, see Beautify Options Dialog Box.

To set formatting preferences

  1. Open the program file.
  2. To format a specific block of code, select the code you want to format. To format the entire program, do not select any code.
  3. From the Tools menu, select Beautify.
  4. In the Beautify Options dialog box, select the formatting preferences that you want.

You can also right-click the editing window and select Beautify from the shortcut menu.

The formatting process uses the top line in the block selected for determining the base indentation level.

To run formatting on the code

  • In the Beautify Options dialog box, click Run.

After formatting the code using the Beautify tool, you can make any additional changes in the formatting of the code.

See Also

Working with Programs | Creating Programs | _BEAUTIFY System Variable


Running Code Manually

Generally, you can do anything in the Command window that you can do in a program. You can run code in the Command window that you might usually execute in a program file. However, certain advantages exist when running code from a program. For more information, see Creating Programs.

The following example describes steps for viewing customer information in a table using the Visual FoxPro interface. Take note that some of the steps are echoed in the Command window.

To locate a record in a table

  1. From the File menu, choose Open.
  2. From the Files of type box, choose Table.
  3. In the list of files, double-click the customer.dbf file to open the Customer table.
  4. From the View menu, choose Browse to browse the table.

You can scroll through the table and look in the Company field for the customer, "Ernst Handel." However, you can perform the same task in the Command window.

To find a single order in a table programmatically

  • Type the following commands in the Command window:
    USE Customer
LOCATE FOR Company = "Ernst Handel"
BROWSE

For more information about the Command Window, see Command Window and Operating the Command window.

After you locate the order for this company, you might want to increase the maximum order amount by three percent.

To increase the maximum order amount

  1. Press the TAB key to move to the field named max_ord_amt.
  2. Multiply the value in the field by 1.03 and type the new value in the field.

To increase the maximum order amount programmatically

  • Type the following Visual FoxPro command in the Command window:
    REPLACE max_ord_amt WITH max_ord_amt * 1.03

It might be relatively simple to change the maximum order amount for a single customer, either using the interface or by typing code in the Command window.

However, suppose you wanted to increase the maximum order amount of every customer by three percent. Performing this task using the interface might be laborious and prone to mistakes. If you provide the appropriate commands in a program file, Visual FoxPro can perform this task quickly and easily without error.

The following example shows a block of code can be used in a program to open the Customer.dbf table, uses SCAN and ENDSCAN to perform the enclosed operations for every record in the table, and increases the maximum order amount for all customers in the table by three percent:

USE customer
SCAN
REPLACE max_ord_amt WITH ;
  max_ord_amt * 1.03
ENDSCAN

The semicolon (;) indicates that the command continues on the next line. For more information, see SCAN ... ENDSCAN Command and REPLACE Command.

See Also

Working with Programs | Creating Programs


Searching and Replacing Code References

You can search for and replace code references and text in your projects and folders in Visual FoxPro.

Searching Projects and Folders for Code References

You can use the Code References tool to locate specific code or text that appears in your projects or folders.

To search for a code reference in a project

  1. To search one or more projects, open the project or projects that you want to search.
  2. From the Tools menu, select Code References.

    If you did not perform a previous search in the project, the Look Up Reference dialog box appears. Otherwise, the Code References window appears and displays the previous search results.

  3. Type the code or text you want to search for in the Look for box.
  4. Make sure Scope is set to Entire project and the name of the project you want to search. To select a different open project, click the Scope arrow to display a list of open projects.
    • To change the scope of your search from a project to a folder, click the Scope arrow and select Folder. You need to specify the folder you want to search in the Look in box.
    • To restrict your search to the project home directory and subfolders, select the Limit search to project home directory and subfolders check box.
    • To specify file types other than the default types in your search, click the File Types arrow to display a list of file types.
    • To specify additional options for your search, select settings from the Options group or click the Options button to open the Options dialog box.
  5. Click Search to begin the search.

The Code References window displays the search string as a code reference node in the search pane and any results from your search in the results pane if successful.

You can view all the results by selecting the code reference node in the search pane, or you can filter your results for each file by selecting a file name in the search pane. You can open the file and go to a code reference directly by double-clicking a result in the results pane.

For more information about the Look Up Reference dialog box and its options, see Look Up Reference Dialog Box and Look Up Reference Dialog Box, Options Dialog Box.

To search for a code reference in a folder

  1. From the Tools menu, select Code References.

    If you did not perform a previous search in the folder, the Look Up Reference dialog box appears. Otherwise, the Code References window appears and displays the previous search results.

  2. Type the code or text you want to search for in the Look for box.
  3. Make sure the Scope box is set to Folder and that the Look in box is set to the folder you want to search.
    • To expand your search to the folder's subfolders, select the Search subfolders check box.
    • To specify file types other than the default types in your search, click the File Types arrow to display a list of file types.
    • To specify additional options for your search, select settings from the Options group or click the Options button to open the Options dialog box.
  4. Click Search to begin the search.

The Code References window displays the search string in the search pane and any results from your search in the results pane if successful.

You can view all the results by selecting the code reference node in the search pane, or you can filter your results for each file by selecting a file name in the search pane. You can open the file and go to a code reference directly by double-clicking a result in the results pane.

For more information about the Look Up Reference dialog box and its options, see Look Up Reference Dialog Box and Look Up Reference Dialog Box, Options Dialog Box.

Replacing Code References

You can use the Code References tool to search for and replace code or text that appears in your projects or folders.

To replace a code reference in a project or folder

  1. Perform a code reference search by using Code References tool to locate the code or text you want to replace.

    If your search is successful, the Code References tool displays the search results in the results pane of the Code References window.

  2. Identify all the lines of code in which you want to replace the code reference or text.
  3. Do one of the following:
    • To specify particular lines of code in which you want replace the code reference or text, select the check box for each line of code you want that appears in the results pane.
    • To specify all lines of code for replacement, right-click in the results pane to display a shortcut menu and choose Select All.
  4. Click Replace on the toolbar in the Code References window to open the Replace dialog box.

    If you select lines of code for replacement in which data files might be affected or where changes to data structures, property values, or property and method names in forms (.scx) or Visual Class libraries (.vcx) might occur, Visual FoxPro prompts you to confirm or decline the replacement operation.

    If you confirm replacement, Visual FoxPro performs only those replacements that do not affect data files and provides code in the search string node under the Replacement Logs node for you to manually perform the desired changes.

    If you decline replacement, no changes are made.

  5. Type the replacement code or text in the Replace with box. Select any additional desired options from the Options group.
  6. Click Replace to begin replacement.

If you selected Confirm replacements from the Options group, you must confirm the replacement operation for each line of code you selected.

After the Code References tool finishes replacing the code or text, you must confirm whether you want to refresh the results in the Code References window.

The Code References window displays a record of the replacement operation as a log node below the Replacement Logs node in the search pane and the results of the replacement in the results pane.

See Also

Creating Programs | Look Up Reference Dialog Box | Code References Window


Viewing Code Definitions

You can locate the definition of a code element found in a code reference search in the current program file, if the definition exists, using the View Definition command that appears on the shortcut menu in the Editing window.

To view the definition of a code element

  1. Open the program file to the location of the code element.
  2. Double-click the text of the code element to select it.
  3. Right-click to display the shortcut menu, and select View Definition.

You can also call View Definition using the DO (_FOXREF) WITH... command. For more information, see _FOXREF System Variable.

If the code element is user-defined, and the definition is found, Visual FoxPro opens the Editing window to the location of the definition. If the item you select is a native Visual FoxPro command or function, the Visual FoxPro Help opens the Help topic for that item. If the item you select is a file name, such as for a #INCLUDE statement or SET PROCEDURE command, Visual FoxPro opens the file.

If multiple definitions exist, Visual FoxPro opens the Go To Definition window for you to select the correct definition. View Definition first searches for other external file references that are in the source file, followed by files in the active project.

If the definition cannot be found in a file for the active project, View Definition searches other open projects or folders. If the definition is found in one of these locations, the Go To Definition window opens for you to select the correct location.

See Also

Creating Programs | Look Up Reference Dialog Box | Code References Window | Go To Definition Window


Object-Oriented Programming

While Visual FoxPro still supports standard procedural programming, new extensions to the language give you the power and flexibility of object-oriented programming. Object-oriented design and object-oriented programming represent a change in focus from standard procedural programming. Instead of thinking about program flow from the first line of code to the last line of code, you need to think about creating objects: self-contained components of an application that have private functionality as well as functionality that you can expose to the user.

In This Section

Basic Programming Concepts
Provides an overview of programming fundamentals necessary to work in Visual FoxPro, including data storage, data types, containers, operators, functions, commands, and controlling program flow.
Classes and Objects: The Building Blocks of Applications
Explains the differences between classes and objects and highlights the properties, methods, and events of objects.
Classes in Visual FoxPro
Introduces the types of classes in Visual FoxPro and describes their important characteristics.
Container Hierarchy Object Referencing
Describes how objects are referenced in the container hierarchy and explains the importance of identifying objects in relation to the container hierarchy.
Setting Properties
Describes how to set the properties of an object at run time or design time.
Calling Methods
Describes how to call the methods of an object from anywhere in an application once it has been created.
Access and Assign Methods
Discusses the support for Access and Assign methods that you can use to execute code when the value of a property is queried or when you attempt to change the property's value.
Procedures and User-Defined Functions
Discusses procedures and functions, which allow you to keep commonly used code in a single place and call it throughout your application whenever you need it.
Understanding the Event Model
Provides links to information on events, event tracking, and helpful hints on how to place code based on the sequence of events.

Related Sections

Creating Programs
Explains the two ways to create a Visual FoxPro program.
Optimizing Applications
Describes ways to optimize your stable application's performance by making it smaller and faster.
Accessing APIs
Describes how to extend Visual FoxPro if your application has requirements that cannot be met by the built in features by taking advantage of external libraries such as Microsoft ActiveX controls or dynamic-link libraries (DLLs).
Preparation for Class Creation
Contains information on how to plan the design of classes and how to select their functionality.
Creating Classes
Provides three ways to create a new class.
Modifying a Class Definition
Describes the steps required to modify a class in the Project Manager.
Subclassing a Class Definition
Contains directions on how to create a subclass of a user-defined class.


Basic Programming Concepts

When you program, you store data and manipulate it with a series of instructions. The data and data storage containers are the raw materials of programming. The tools you use to manipulate this raw material are commands, functions, and operators.

Storing Data

The data you work with probably includes amounts of time, money, and countable items, as well as dates, names, descriptions, and so on. Each piece of data is a certain type: it belongs to a category of data that you manipulate in similar ways. You could work directly with this data without storing it, but you would lose most of the flexibility and power of Visual FoxPro. Visual FoxPro provides numerous storage containers to extend your ability to easily manipulate data.

Data types determine how data is stored and how it can be used. You can multiply two numbers together, but you can't multiply characters. You can print characters in uppercase, but you can't print numbers in uppercase. Some of the primary data types in Visual FoxPro are listed in the following table:

Data Types

Type | Examples
Numeric | 123 3.1415 – 7
Character | "Test String" "123" "01/01/98"
Logical | .T. .F.
Date DateTime | {^1998-01-01} {^1998-01-01 12:30:00 p}

Data Containers

Data containers allow you to perform the same operations on multiple pieces of data. For example, you add the hours an employee has worked, multiply them by the hourly wage, and then deduct the taxes to determine the amount of pay the employee has earned. You'll have to perform these operations for every employee and every pay period. If you store this information in containers, and perform the operations on the containers, you can just replace the old data with new data and run the same program again. This table lists some of the main containers for data in Visual FoxPro:

Type | Description
Variables | Single elements of data stored in your computer's RAM (Random Access Memory).
Table Records | Multiple rows of predetermined fields, each of which can contain a predefined piece of data. Tables are saved to disk.
Arrays | Multiple elements of data stored in RAM.

Manipulating Data

Containers and data types give you the building blocks you need to manipulate data. The final pieces are operators, functions, and commands.

Using Operators

Operators tie data together. Here are the most common operators in Visual FoxPro.

Operator Valid Data Types Example Result
= All
? n = 7
 Prints .T. if the value stored in the variable n is 7, .F. otherwise
+ Numeric, Character, Date, DateTime
? "Fox" + "Pro"
 Prints "FoxPro"
! or NOT Logical
? !.T.
 Prints .F.
*, / Numeric
? 5 * 5
? 25 / 5
 Prints 25
Prints 5
Note A question mark (?) in front of an expression causes a new line character and the results of the expression to be printed in the active output window, which is usually the main Visual FoxPro window.

Remember that you must use the same type of data with any one operator. The following statements store two numeric pieces of data to two variables. The variables have been given names that start with n so we can tell at a glance that they contain numeric data, but you could name them with any combination of alphanumeric characters and underscores.

nFirst = 123
nSecond = 45

The following statements store two pieces of character data to two variables. The variables have been given names that start with c to indicate that they contain character data.

cFirst = "123"
cSecond = "45"

The following two operations, addition and concatenation, yield different results because the type of data in the variables is different.

? nFirst + nSecond
? cFirst + cSecond

Output

168
12345

Because cFirst is character data and nSecond is numeric data, you get a data type mismatch error if you try the following command:

? cFirst + nSecond

You can avoid this problem by using conversion functions. For example, STR( ) returns the character equivalent of a numeric value and VAL( ) returns the numeric equivalent of a character string of numbers. These functions and LTRIM( ), which removes leading spaces, enable you to perform the following operations:

? cFirst + LTRIM(STR(nSecond))
? VAL(cFirst) + nSecond

Output

12345
168

Using Functions

Functions return a specific type of data. For example, the functions STR( ) and VAL( ), used in the previous section, return character and numeric values, respectively. As with all functions, these return types are documented along with the functions.

There are five ways to call a Visual FoxPro function:

  • Assign the return value of the function to a variable. The following line of code stores the current system date to a variable named dToday:
    dToday = DATE( )
  • Include the function call in a Visual FoxPro command. The following command sets the default directory to the value returned from the GETDIR( ) function:
    CD GETDIR( )
  • Print the return value in the active output window. The following line of code prints the current system time in the active output window:
    ? TIME( )
  • Call the function without storing the return value anywhere. The following function call turns the cursor off:
    SYS(2002)
  • Embed the function in another function. The following line of code prints the day of the week:
    ? DOW(DATE( ))

Some other examples of functions are:

Function | Description
ISDIGIT( ) | Returns true (.T.) if the leftmost character in a string is a number; otherwise, returns false (.F.).
FIELD( ) | Returns the name of a field.
LEN( ) | Returns the number of characters in a character expression.
RECCOUNT( ) | Returns the number of records in the currently active table.
SUBSTR( ) | Returns the specified number of characters from a character string, starting at a specified location in the string.

Using Commands

A command causes a certain action to be performed. Each command has a specific syntax, which indicates what must be included in order for the command to work. There are also optional clauses associated with commands that allow you to specify in more detail what you want.

For example, the USE command allows you to open and close tables:

USE Syntax Description
USE
 Closes the table in the current work area.
USE customer
 Opens the CUSTOMER table in the current work area, closing any table that was already open in the work area.
USE customer IN 0
 Opens the CUSTOMER table in the next available work area.
USE customer IN 0 ;

  ALIAS mycust
Opens the CUSTOMER table in the next available work area and assigns the work area an alias of mycust.

Some examples of commands are:

Command | Description
DELETE | Marks specified records in a table for deletion.
REPLACE | Replaces the value stored in record field with a new value.
Go | Positions the record pointer to a specific location in the table.

Controlling Program Flow

Visual FoxPro includes a special category of commands that "wrap around" other commands and functions, determining when and how often the other commands and functions are executed. These commands allow conditional branching and looping, two very powerful programming tools. The following program illustrates conditional branches and loops. These concepts are described in more detail after the example.

Suppose that you had 10,000 employees and wanted to give everybody making $30,000 or more a 3 percent raise, and everybody making under $30,000 a 6 percent raise. The following sample program accomplishes this task.

This program assumes that a table with a numeric field named salary is open in the current work area. For information about work areas, see "Using Multiple Tables" in Working with Tables.

Sample Program to Increase Employee Salaries

Code Comments
SCAN
 The code between SCAN and ENDSCAN is executed as many times as there are records in the table. Each time the code is executed, the record pointer moves to the next record in the table.
   IF salary >= 30000.00
      REPLACE salary WITH ;
         salary * 1.03
 For each record, if the salary is greater than or equal to 30,000, replace this value with a new salary that is 3% higher.

The semicolon (;) after WITH indicates that the command is continued on the next line.

   ELSE
      REPLACE salary WITH ;
         salary * 1.06
 For each record, if the salary is not greater than or equal to 30,000, replace this value with a new salary that is 6% higher.
   ENDIF

ENDSCAN
End of the conditional IF statement.

End of the code that is executed for each record in the table.

This example uses both conditional branching and looping commands to control the flow of the program.

Conditional Branching

Conditional branching allows you to test conditions and then, depending on the results of that test, perform different operations. There are two commands in Visual FoxPro that allow conditional branching:

  • IF ... ELSE ... ENDIF
  • DO CASE ... ENDCASE

The code between the initial statement and the ENDIF or ENDCASE statement is executed only if a logical condition evaluates to true (.T.). In the example program, the IF command is used to distinguish between two states: either the salary is $30,000 or more, or it isn't. Different actions are taken depending on the state.

In the following example, if the value stored in the variable nWaterTemp is less than 100, no action is taken:

* set a logical variable to true if a condition is met.
IF nWaterTemp >= 100
   lBoiling = .T.
ENDIF
Note An asterisk at the beginning of a line in a program indicates that the line is a comment. Comments help the programmer remember what each segment of code is designed to do, but are ignored by Visual FoxPro.

If there are several possible conditions to check for, a DO CASE ... ENDCASE block can be more efficient and easier to keep track of than multiple IF statements.

Looping

Looping allows you to execute one or more lines of code as many times as you need to. There are three commands in Visual FoxPro that allow looping:

  • DO WHILE ... ENDDO
  • FOR ... ENDFOR
  • FOR EACH ... ENDFOR
  • SCAN ... ENDSCAN

Use SCAN when you are performing a series of actions for each record in a table, as in the example program just described. The SCAN loop enables you to write the code once and have it executed for each record as the record pointer moves through the table.

Use FOR when you know how many times the section of code needs to be executed. For example, you know there are a specific number of fields in a table. Because the Visual FoxPro function FCOUNT( ) returns this number, you can use a FOR loop to print the names of all the fields in the table:

FOR nCnt = 1 TO FCOUNT( )
   ? FIELD(nCnt)
ENDFOR

Use DO WHILE when you want to execute a section of code as long as a certain condition is met. You might not know how many times the code will have to execute, but you know when it should stop executing. For example, let's assume you have a table with people's names and initials, and you want to use the initials to look people up. You would have a problem the first time you tried to add a person who had the same initials as someone else already in your table.

To solve the problem, you could add a number to the initials. For example, Michael Suyama's identification code could be MS. The next person with the same initials, Margaret Sun, would be MS1. If you then added Michelle Smith to the table, her identification code would be MS2. A DO WHILE loop enables you to find the right number to append to the initials.

Sample Program with DO WHILE to Generate a Unique ID

Code Comments
nHere = RECNO()
 Save the location of the record.
cInitials = LEFT(firstname,1) + ;
   LEFT(lastname,1)

nSuffix = 0
Get the person's initials from the first letters of the firstname and lastname fields.

Establish a variable to hold the number to be added to the end of a person's initials if necessary.

LOCATE FOR person_id = cInitials
 See if there is another person in the table with the same initials.
DO WHILE FOUND( )
 If another record in the table has a person_id value that is the same as cInitials, the FOUND( ) function returns true (.T.) and the code in the DO WHILE loop executes.
If no match is found, the next line of code to be executed is the line following ENDDO.
   nSuffix = nSuffix + 1
   cInitials = ;
      LEFT(cInitials,2);
      + ALLTRIM(STR(nSuffix))
 Prepare a fresh suffix and append it to the end of the initials.
   CONTINUE
 CONTINUE causes the last LOCATE command to be evaluated again. The program checks to see if the new value in cInitials already exists in the person_id field of another record. If so, FOUND( ) will still return .T. and the code in the DO WHILE loop will execute again. If the new value in cInitials is indeed unique, FOUND( ) will return .F. and program execution continues with the line of code following ENDDO.
ENDDO
 End of the DO WHILE loop.
GOTO nHere
REPLACE person_id WITH cInitials
 Return to the record and store the unique identification code in the person_id field.

Because you don't know beforehand how many times you'll find matching identification codes already in use, you use the DO WHILE loop.

See Also

Working with Tables | SCAN ... ENDSCAN | FOR ... ENDFOR | DO WHILE ... ENDDO | IF ... ELSE ... ENDIF | DO CASE ... ENDCASE | GETDIR( ) | USE


Classes and Objects: The Building Blocks of Applications

Classes and objects are closely related, but they are not the same. A class contains information about how an object should look and behave. A class is the blueprint or schematic of an object. The electrical schematic and design layout of a telephone, for example, would approximate a class. The object, or an instance of the class, would be a telephone.

Objects Have Properties

An object has certain properties, or attributes. For example, a phone is a certain color and size. When you put a phone in your office, it has a certain position on your desk. The receiver can be on or off the hook.

Objects you create in Visual FoxPro also have properties that are determined by the class the object is based on. These properties can be set at design time or at run time.

For example, some of the properties that a check box can have are listed in the following table:

Property | Description
Caption | The descriptive text beside the check box.
Enabled | Specifies whether a user can choose the check box.
ForeColor | The color of the caption text.
Left | The position of the left side of the check box.
MousePointer | How the mouse pointer looks when over the check box.
Top | The position of the top of the check box.
Visible | Specifies whether the check box is visible.

Objects Have Associated Events and Methods

Each object recognizes and can respond to certain actions called events. An event is a specific and predetermined activity, initiated by either a user or the system. Events, in most cases, are generated by user interaction. For example, with a phone, an event is triggered when a user takes the receiver off the hook. Events are also triggered when the user presses the buttons to make a call.

In Visual FoxPro, user actions that trigger events include clicks, mouse moves, and key presses. Initializing an object and encountering a line of code that causes an error are system-initiated events.

Methods are procedures that are associated with an object. Methods are different from normal Visual FoxPro procedures: methods are inextricably bound with an object and are called differently than normal Visual FoxPro procedures are called.

Events can have methods associated with them. For example, if you write method code for the Click event, that code is executed when the Click event occurs. Methods can also exist independently of any events. These methods must be explicitly called in code.

The event set, while extensive, is fixed. You can't create new events. The method set, however, is infinitely extendible.

The following table lists some of the events associated with a check box:

Event | Description
Click | User clicks the check box.
GotFocus | User selects the check box by clicking it or tabbing to it.
LostFocus | User selects another control.

The following table lists some of the methods associated with a check box:

Method | Description
Refresh | The value of the check box is updated to reflect any changes that may have occurred to the underlying data source.
SetFocus | The focus is set to the check box just as though the user had pressed the TAB key until the check box was selected.

See Also

Object-Oriented Programming | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Classes in Visual FoxPro

All of the properties, events, and methods for an object are specified in the class definition. In addition, classes have the following characteristics that make them especially useful for creating reusable, easily maintained code:

  • Encapsulation
  • Subclasses
  • Inheritance

Hiding Unnecessary Complexity

When you include a phone in your office, you probably don't care how the phone internally receives a call, initiates or terminates connections to electronic switchboards, or translates key presses into electronic signals. All you need to know is that you can lift the receiver, dial the appropriate numbers, and talk to the person you want to talk to. The complexity of making that connection is hidden. The benefit of being able to ignore the inner details of an object so you can focus on the aspects of the object you need to use is called abstraction.

Encapsulation, which involves packaging method and property code together in an object, contributes to abstraction. For example, the properties that determine the items in a list box and the code that executes when you choose an item in the list can be encapsulated in a single control that you add to a form.

Leveraging the Power of Existing Classes

A subclass can have all the functionality of an existing class, plus any additional controls or functionality you want to give it. If your class is a basic telephone, you can have subclasses that have all the functionality of the original telephone and any specialized features you want to give them.

Subclassing is one way to decrease the amount of code you have to write. Start with the definition of an object that is close to what you want, and customize it.

Streamlining Code Maintenance

With inheritance, if you make a change to a class, that change is reflected in all subclasses based on the class. This automatic update saves you time and effort. For example, if a phone manufacturer wanted to change from dial to push-button style phones, it would save a lot of work to be able to make the change to the master schematic and have all previously manufactured phones based on that master schematic automatically inherit this new feature, rather than having to add the new feature to all the existing phones individually.

Inheritance doesn't work with hardware, but you do have this capability in software. If you discover a bug in your class, instead of having to go to each subclass and change the code, you fix it once in the class and the change propagates throughout all subclasses of the class.

Containers and Non-Containers

The two primary types of Visual FoxPro classes, and by extension Visual FoxPro objects, are container classes and control classes.

Container Classes

Containers can contain other objects and allow access to the objects contained within them. For example, if you create a container class that consists of two list boxes and two command buttons, and then add an object based on this class to a form, each individual object can be manipulated at run time and design time. You can easily change the positions of the list boxes or the captions of the command buttons. You can also add objects to the control at design time; for example, you can add labels to identify the list boxes.

The following table lists what each container class can contain:

Container | Can contain
Command button groups | Command buttons
Container | Any controls
Control | Any controls
Custom | Any controls, data environment, page frame, container, custom
DataEnvironment | Cursor, Relation, and CursorAdapter objects
Form sets | Forms, toolbars
Forms | Page frames, data environment, any controls, containers, custom
Grid columns | Headers and any objects except form sets, forms, toolbars, timers, and other columns
Grids | Grid columns
Option button groups | Option buttons
Page frames | Pages
Pages | Any controls, containers, custom
Project | Files, servers
Toolbars | Any controls, page frame, container

Control Classes

Control classes are more completely encapsulated than container classes are, but can be less flexible for that reason. Control classes do not have an AddObject method.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Preparation for Class Creation

You want to be able to use classes in many different contexts. Smart planning will enable you to most effectively decide what classes to design and what functionality to include in the class.

Deciding When to Create Classes

You could create a class for every control and every form you might ever use, but this isn't the most effective way to design your applications. You'll likely end up with multiple classes that do much the same thing but must be maintained separately.

Encapsulate Generic Functionality

You can create a control class for generic functionality. For example, command buttons that allow a user to move the record pointer in a table, a button to close a form, and a help button, can all be saved as classes and added to forms any time you want the forms to have this functionality.

You can expose properties and methods on a class so that the user can integrate them into the particular data environment of a form or form set.

Provide a Consistent Application Look and Feel

You can create form set, form, and control classes with a distinctive appearance so that all the components of your application have the same look. For example, you could add graphics and specific color patterns to a form class and use that as a template for all forms you create. You could create a text box class with a distinctive appearance, such as a shadowed effect, and use this class throughout your application any time you want to add a text box.

Deciding What Type of Class to Create

Visual FoxPro allows you to create several different kinds of classes, each with its own characteristics. You specify the type of class you want to create in the New Class dialog box or in the AS clause in the CREATE CLASS Command.

The Visual FoxPro Base Classes

You can create subclasses of most of the Visual FoxPro base classes in the Class Designer.

Visual FoxPro Base Classes

CheckBox | EditBox | Line | ProjectHook
Column* | Form | ListBox | Separator
CommandButton | FormSet | OLEBoundControl | Shape
CommandGroup | Grid | OLEContainerControl | Spinner
ComboBox | Header* | OptionButton* | TextBox
Container | Hyperlink Object | OptionGroup | Timer
Control | Image | Page* | ToolBar
Custom | Label | PageFrame |

* These classes are an integral part of a parent container and cannot be subclassed in the Class Designer.

All Visual FoxPro base classes recognize the following minimum set of events:

Event | Description
Init | Occurs when the object is created.
Destroy | Occurs when the object is released from memory.
Error | Occurs whenever an error occurs in event or method procedures of the class.

All Visual FoxPro base classes have the following minimum set of properties:

Property | Description
Class | What type of class it is.
BaseClass | The base class it was derived from, such as Form, Commandbutton, Custom, and so on.
ClassLibrary | The class library the class is stored in.
ParentClass | The class that the current class was derived from. If the class was derived directly from a Visual FoxPro base class, the ParentClass property is the same as the BaseClass property.

Extending the Visual FoxPro Base Classes

You can subclass these classes to set your own default control properties. For example, if you want the default names of controls you add to forms in your applications to automatically reflect your naming conventions, you can create classes based on the Visual FoxPro base classes to do this. You can create form classes with a customized look or behavior to serve as templates for all the forms you create.

You could also subclass the Visual FoxPro base classes to create controls with encapsulated functionality. If you want a button to release forms when the button is clicked, you can create a class based on the Visual FoxPro command button class, set the caption property to "Quit" and include the following command in the Click event:

THISFORM.Release

You can add this new button to any form in your application.

Creating Controls with Multiple Components

Your subclasses aren't limited to single base classes. You can add multiple controls into a single container class definition. Many of the classes in the Visual FoxPro sample class library fall into this category.

Creating Non-Visual Classes

A class based on the Visual FoxPro custom class doesn't have a run-time visual element. You can create methods and properties for your custom class using the Class Designer environment. For example, you could create a custom class named StrMethods and include a number of methods to manipulate character strings. You could add this class to a form with an edit box and call the methods as needed. If you had a method called WordCount, you could call it when needed:

THISFORM.txtCount.Value = ;
  THISFORM.StrMethods.WordCount(THISFORM.edtText.Value)

Non-visual classes (like the custom control and the timer control) have a visual representation only at design time in the Form Designer. Set the picture property of the custom class to the .bmp file you want displayed in the Form Designer when the custom class is added to a form.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Operating the Class Designer

When you specify what class your new class is based on and the library to store the class in, the Class Designer opens.

The Class Designer provides the same interface that the Form Designer does, allowing you to see and edit the properties of your class in the Properties window. Code editing windows allow you to write code to be executed when events occur or methods are called.

Adding Objects to a Control or Container Class

If you base the new class on the control or container class, you can add controls to it the same way you add controls in the Form Designer: choose the control button on the Form Controls toolbar and drag to size in the Class Designer.

No matter what type of class you base the new class on, you can set properties and write method code. You can also create new properties and methods for the class.

IF you press and hold the CTRL key while dragging objects from the toolbar to a form class, you disengage the default snap-to-grid behavior.

Adding Properties and Methods to a Class

You can add as many new properties and methods to the new class as you want. Properties hold values; methods hold procedural code to be run when you call the method.

Creating New Properties and Methods

When you create new properties and methods for classes, the properties and methods are scoped to the class, not to individual components in the class.

To add a new property to a class

  1. From the Class menu, choose New Property.
  2. In the New Property dialog box, type the name of the property.
  3. Specify the visibility: Public, Protected, or Hidden.

    A Public property can be accessed anywhere in your application. Protected and Hidden properties and methods are discussed in Protecting and Hiding Class Members.

  4. Choose Add.

    You can also include a description of the property that will be displayed at the bottom of the Properties window in the Class Designer and in the Form Designer when the control is added to a form.

    Caution When you add a property to a class that can be set by a user of the class, the user could enter an invalid setting for your property that could cause run-time errors. You need to explicitly document the valid settings for the property. If your property can be set to 0, 1, or 2, for example, say so in the Description box of the New Property dialog box. You might also want to verify the value of the property in code that references it.

To create an array property

  • In the Name box of the New Property dialog box, specify the name, size, and dimensions of the array.

    For example, to create an array property named myarray with ten rows and two columns, type the following in the Name box:

    myarray[10,2]

The array property is read-only at design time and is displayed in the Properties window in italics. The array property can be managed and redimensioned at run time. For an example of using an array property, see Managing Multiple Instances of a Form, Creating Forms.

To add a new method to a class

  1. From the Class menu, choose New Method.
  2. In the New Method dialog box, type the name of the method.
  3. Specify the visibility: Public, Protected, or Hidden.
  4. Select the Access check box to create an Access method, select the Assign check box to create an Assign method, or select both check boxes to create Access and Assign methods.

Access and Assign methods let you execute code when the value of a property is queried or when you attempt to change the property's value.

The code in an Access method is executed when the value of a property is queried, typically by using the property in an object reference, storing the value of the property to a variable, or displaying the value of property with a question mark (?).

The code in an Assign method is executed when you attempt to change the value of a property, typically by using the STORE or = command to assign a new value to the property.

You can also include a description of the method.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Creating Classes

You can create new classes in the Class Designer and you can see how each object will appear to the user as you design it.

To create a new class

  • In the Project Manager, select the Classes tab and choose New.

    -or-

  • From the File menu, choose New, select Class, and choose New File.

    -or-

  • Use the CREATE CLASS command.

The New Class dialog box lets you specify what to call the new class, the class to base the new class on, and the library to store it in.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Modifying a Class Definition

Once you have created a class, you can modify it. Changes made to a class affect all the subclasses and all the objects based on this class. You can add an enhancement to a class or fix a bug in the class, and all the subclasses and objects based on the class will inherit the change.

To modify a class in the Project Manager

  1. Select the class you want to modify.
  2. Choose Modify.

    The Class Designer opens.

You can also modify a visual class definition with the MODIFY CLASS command.

Caution Don't change the Name property of a class if the class is already being used in any other application components. Otherwise, Visual FoxPro will not be able to locate the class when needed.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Subclassing a Class Definition

You can create a subclass of a user-defined class in one of two ways.

To create a subclass of a user-defined class

  1. In the Project Manager New Class dialog box, click the dialog button to the right of the Based On box.
  2. In the Open dialog box, choose the class you want to base the new class on.

    -or-

  • Use the CREATE CLASS Command.

    For example, to base a new class, x, on parentclass in Mylibrary.vcx, use this code:

    CREATE CLASS x OF y AS parentclass ;
  FROM mylibrary

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Class Member Protection and Hiding

Properties and methods in a class definition are Public by default: code in other classes or procedures can set the properties or call the methods. Properties and methods that you designate as Protected can be accessed only by other methods in the class definition or in subclasses of the class. Properties and methods designated as Hidden can be accessed only by other members in the class definition. Subclasses of the class cannot "see" or reference hidden members.

To ensure correct functioning in some classes, you need to prevent users from programmatically changing the properties or calling the method from outside the class.

The following example illustrates using protected properties and methods in a class.

The stopwatch class included in Samples.vcx, in the Visual FoxPro ...\Samples\Classes directory, includes a timer and five labels to display the elapsed time:

The Stopwatch class contains labels and a timer.

Property Settings for the Stopwatch Class

Control | Property | Setting
lblSeconds | Caption | 00
lblColon1 | Caption | :
lblMinutes | Caption | 00
lblColon2 | Caption | :
lblHours | Caption | 00
tmrSWatch | Interval | 1000

This class also has three protected properties, nSec, nMin, and nHour, and one protected method, UpdateDisplay. The other three custom methods in the class, Start, Stop, and Reset, are not protected.

Tip Choose Class Info on the Class menu to see the visibility of all properties and methods of a class.

The protected properties are used in internal calculations in the UpdateDisplay method and the Timer event. The UpdateDisplay method sets the captions of the labels to reflect the elapsed time.

The UpdateDisplay Method

Code Comments
cSecDisplay = ALLTRIM(STR(THIS.nSec))
cMinDisplay = ALLTRIM(STR(THIS.nMin))
cHourDisplay = ALLTRIM(STR(THIS.nHour))
 Convert the numeric properties to Character type for display in the label captions.
THIS.lblSeconds.Caption = ;

 IIF(THIS.nSec < 10, ;
   "0" ,"") + cSecDisplay
THIS.lblMinutes.Caption = ;
  IIF(THIS.nMin < 10, ;
   "0", "") + cMinDisplay
THIS.lblHours.Caption = ;
  IIF(THIS.nHour < 10, ;
   "0", "") + cHourDisplay
Set the label captions, retaining the leading 0 if the value of the numeric property is less than 10.

The following table lists the code in the tmrSWatch.Timer event:

The Timer Event

Code Comments
THIS.Parent.nSec = THIS.Parent.nSec + 1

IF THIS.Parent.nSec = 60
  THIS.Parent.nSec = 0
  THIS.Parent.nMin = ;
  THIS.Parent.nMin + 1
ENDIF
Increment the nSec property every time the timer event fires: every second.
If nSec has reached 60, reset it to 0 and increment the nMin property.
IF THIS.Parent.nMin = 60

  THIS.Parent.nMin = 0
  THIS.Parent.nHour = ;
  THIS.Parent.nHour + 1
ENDIF
THIS.Parent.UpdateDisplay
If nMin has reached 60, reset it to 0 and increment the nHour property.

Call the UpdateDisplay method when the new property values are set.

The stopwatch class has three methods that are not protected: Start, Stop, and Reset. A user can call these methods directly to control the stopwatch.

The Start method contains the following line of code:

THIS.tmrSWatch.Enabled = .T.

The Stop method contains the following line of code:

THIS.tmrSWatch.Enabled = .F.

The Reset method sets the protected properties to zero and calls the protected method:

THIS.nSec = 0
THIS.nMin = 0
THIS.nHour = 0
THIS.UpdateDisplay

The user cannot directly set these properties or call this method, but code in the Reset method can.

Specifying the Default Value for a Property

When you create a new property, the default setting is false (.F.). To specify a different default setting for a property, use the Properties window. In the Other tab, click on your property and set it to the desired value. This will be the initial property setting when the class is added to a form or form set.

You can also set any of the base class properties in the Class Designer. When an object based on the class is added to the form, the object reflects your property settings rather than the Visual FoxPro base class property settings.

Tip If you want to make the default setting of a property an empty string, select the setting in the Property Editing box and press the BACKSPACE key.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Specifying Design-Time Appearance for a Class

You can specify the toolbar icon and the container icon for your class in the Class Info dialog box.

To set a toolbar icon for a class

  1. In the Class Designer, choose Class Info from the Class menu.
  2. In the Class Info dialog box, type the name and path of the .bmp file in the Toolbar icon box.
    Tip The bitmap (.bmp file) for the toolbar icon is 15 by 16 pixels. If the picture is larger or smaller, it is sized to 15 by 16 pixels and might not look the way you want it to.

The toolbar icon you specify is displayed in the Form Controls toolbar when you populate the toolbar with the classes in your class library.

You can also specify the icon to be displayed for the class in the Project Manager and Class Browser by setting the container icon.

To set a container icon for a class

  1. In the Class Designer, choose Class Info from the Class menu.
  2. In the Container icon box, type the name and path of the .bmp file to be displayed on the button in the Form Controls toolbar.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Creating, Copying, and Removing Class Library Files

Every visually designed class is stored in a class library with a .vcx file extension.

Creating a Class Library

You can create a class library in one of three ways.

To create a class library

  • When you create a class, specify a new class library file in the Store In box of the New Class dialog box.

    -or-

  • Use the CREATE CLASS command, specifying the name of the new class library.

    For example, the following statement creates a new class named myclass and a new class library named new_lib:

    CREATE CLASS myclass OF new_lib AS CUSTOM

    -or-

  • Use the CREATE CLASSLIB command.

    For example, type the following command in the Command window to create a class library named new_lib:

    CREATE CLASSLIB new_lib

Copying and Removing Class Library Classes

Once you add a class library to a project, you can easily copy classes from one library to another or simply remove classes from libraries.

To copy a class from one library to another

  1. Make sure both libraries are in a project (not necessarily the same project).
  2. In the Project Manager, select the Classes tab.
  3. Click the plus sign (+) to the left of the class library that the class is now in.
  4. Drag the class from the original library and drop it in the new library.
    Tip For convenience and speed, you might want to keep a class and all the subclasses based on it in one class library. If you have a class that contains elements from many different class libraries, these libraries must all be open, so it will take a little longer to initially load your class at run time and at design time.

To remove a class from a library

  • Select the class in the Project Manager and choose Remove.

    -or-

  • Use the REMOVE CLASS command.

To change the name of a class in a class library, use the RENAME CLASS command. Remember, however, that when you change the name of a class, forms that contain the class and subclasses in other .vcx files continue to reference the old name and will no longer function correctly.

Visual FoxPro includes a Class Browser to facilitate using and managing classes and class libraries. For more information, see Class Browser.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Adding Classes to Forms

You can drag a class from the Project Manager to the Form Designer or to the Class Designer. You can also register your classes so that they can be displayed directly on the Form Controls toolbar in the Class Designer or Form Designer and added to containers the same way the standard controls are added.

To register a class library

  1. From the Tools menu, choose Options.
  2. In the Options dialog box choose the Controls tab.
  3. Select Visual Class Libraries and choose Add.
  4. In the Open dialog box, choose a class library to add to the registry and choose Open.
  5. Choose Set as Default if you want the class library to be available in the Form Controls toolbar in future sessions of Visual FoxPro.

You can also add your class library to the Form Controls toolbar by choosing Add in the submenu of the View Classes button. To make these classes available in the Form Controls toolbar in future sessions of Visual FoxPro, you still need to set the default in the Options dialog box.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Default Property Setting Override

When you add objects based on a user-defined class to a form, you can change the settings of all the properties of the class that are not protected, overriding the default settings. If you change the class properties in the Class Designer later, the settings in the object on the form are not affected. If you have not changed a property setting in the form and you change the property setting in the class, the change will take effect in the object as well.

For example, a user could add an object based on your class to a form and change the BackColor property from white to red. If you change the BackColor property of the class to green, the object on the user's form will still have a background color of red. If, on the other hand, the user did not change the BackColor property of the object and you changed the background color of the class to green, the BackColor property of the object on the form would inherit the change and also be green.

Calling Parent Class Method Code

An object or class based on another class automatically inherits the functionality of the original. However, you can easily override the inherited method code. For example, you can write new code for the Click event of a class after you subclass it or after you add an object based on the class to a container. In both cases, the new code is executed at run time; the original code is not executed.

More frequently, however, you want to add functionality to the new class or object while keeping the original functionality. In fact, one of the key decisions you have to make in object-oriented programming is what functionality to include at the class level, at the subclass level, and at the object level. You can optimize your class design by using the DODEFAULT( ) function or scope resolution operator (::) to add code at different levels in the class or container hierarchy.

Adding Functionality to Subclasses

You can call the parent class code from a subclass by using the DODEFAULT( ) function.

For example, cmdOK is a command button class stored in Buttons.vcx, located in the Visual FoxPro ...\Samples\Classes directory. The code associated with the Click event of cmdOk releases the form the button is on. CmdCancel is a subclass of cmdOk in the same class library. To add functionality to cmdCancel to discard changes, for example, you could add the following code to the Click event:

IF USED( ) AND CURSORGETPROP("Buffering") != 1
   TABLEREVERT(.T.)
ENDIF
DODEFAULT( )

Because changes are written to a buffered table by default when the table is closed, you don't need to add TABLEUPDATE( ) code to cmdOk. The additional code in cmdCancel reverts changes to the table before calling the code in cmdOk, the ParentClass, to release the form.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Container Hierarchy Object Referencing | Setting Properties | Calling Methods | Event Response


Writing Class Definitions Programmatically

You can define classes visually in the Class Designer and the Form Designer or programmatically in .PRG files. This section describes how to write class definitions. For more information about forms, see Creating Forms.

In This Section

Programmatic Class Definitions
Displays the syntax of the basic shell for class creation.
Protection and Hiding of Class Members
Through example, illustrates how to protect or hide properties and methods in a class definition with keywords of the DEFINE CLASS command.
Creation of Objects from Classes
Describes how to create an object based on a saved visual class.
Addition of Objects to a Container Class
Details how to add objects to a container through use of the ADD OBJECT clause in the DEFINE CLASS command or the AddObject method.
Method and Event Code Guidelines
Lays out the rules for authoring event code and methods.
Creating a Set of Table Navigation Buttons
Provides an explanation of how to design and build table navigation buttons through code.
Definition of a Grid Control
Outlines how to define grid control programmatically.
Object Reference Creation
Explains how to make a reference to an object, and describes the benefits of creating references over making copies of objects.
Arrays of Members and Objects
Tells how to define members of classes as arrays and how to build arrays of objects.
Data Storage with Objects
Describes when and how to store data in objects.
Object and Data Integration
Contains information on why integrating objects and data is important.

Related Sections

Programming in Visual FoxPro
Microsoft® Visual FoxPro® is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Object-Oriented Programming
With object-oriented programming, you can create self-contained application components that respond to user actions and to the system and which can be easily maintained and reused.
Understanding the Event Model
The event model defines when and how user and system interactions occur.


Programmatic Class Definitions

In a program file, you can have program code prior to the class definitions, but not after the class definitions, in the same way that program code cannot come after procedures in a program. The basic shell for class creation has this syntax:

DEFINE CLASS ClassName1 AS ParentClass [OLEPUBLIC]
   [[PROTECTED | HIDDEN PropertyName1, PropertyName2 ...]
      [Object.]PropertyName = eExpression ...]
   [ADD OBJECT [PROTECTED] ObjectName AS ClassName2 [NOINIT]
      [WITH cPropertylist]]...
   [[PROTECTED | HIDDEN] FUNCTION | PROCEDURE Name[_ACCESS | _ASSIGN]
      [NODEFAULT]
      cStatements
   [ENDFUNC | ENDPROC]]...
ENDDEFINE

See Also

Writing Class Definitions Programmatically | Event Response | Protection and Hiding of Class Members | Calling Methods | Setting Properties | Object-Oriented Programming


Protection and Hiding of Class Members

You can protect or hide properties and methods in a class definition with the PROTECTED and HIDDEN keywords of the DEFINE CLASS command. PROTECTED and HIDDEN properties can be declared together in a comma-separated list. Protected methods must be declared individually.

For example, if you create a class to hold employee information, and you don't want users to be able to change the hire date, you can protect the HireDate property. If users need to find out when an employee was hired, you can include a method to return the hire date.

DEFINE CLASS employee AS CUSTOM
PROTECTED HireDate
  First_Name = ""
  Last_Name = ""
  Address = ""
  HireDate = { - - }

PROCEDURE GetHireDate
  RETURN This.HireDate
ENDPROC
ENDDEFINE

See Also

Writing Class Definitions Programmatically | Programmatic Class Definitions | Creation of Objects from Classes | Event Response | Object-Oriented Programming


Creation of Objects from Classes

When you have saved a visual class, you can create an object based on it with the CREATEOBJECT( ) function. The following example demonstrates running a form saved as a class definition in the class library file Forms.vcx:

Creating and Showing a Form Object Whose Class Was Designed in the Form Designer

Code Comments
SET CLASSLIB TO Forms ADDITIVE
 Set the class library to the .vcx file that the form definition was saved in. The ADDITIVE keyword prevents this command from closing any other class libraries that happen to be open.
frmTest = CREATEOBJECT("TestForm")
 This code assumes that the name of the form class saved in the class library is TestForm.
frmTest.Show
 Display the form.

See Also

Writing Class Definitions Programmatically | Protection and Hiding of Class Members | Addition of Objects to a Container Class | Programmatic Class Definitions | Object-Oriented Programming


Addition of Objects to a Container Class

You can use the ADD OBJECT clause in the DEFINE CLASS command or the AddObject method to add objects to a container.

For example, the following class definition is based on a form. The ADD OBJECT command adds two command buttons to the form:

DEFINE CLASS myform AS FORM
  ADD OBJECT cmdOK AS COMMANDBUTTON
  ADD OBJECT PROTECTED cmdCancel AS COMMANDBUTTON
ENDDEFINE

Use the AddObject method to add objects to a container after the container object has been created. For example, the following lines of code create a form object and add two command buttons to it:

frmMessage = CREATEOBJECT("FORM")
frmMessage.AddObject("txt1", "TEXTBOX")
frmMessage.AddObject("txt2", "TEXTBOX")

You can also use the AddObject method in the method code of a class. For example, the following class definition uses AddObject in the code associated with the Init event to add a control to a grid column.

DEFINE CLASS mygrid AS GRID
ColumnCount = 3
PROCEDURE Init
  THIS.Column2.AddObject("cboClient", "COMBOBOX")
  THIS.Column2.CurrentControl = "cboClient"
ENDPROC
ENDDEFINE

Adding and Creating Classes in Method Code

You can programmatically add objects to a container with the AddObject method. You can also create objects with the CREATEOBJECT( ) function in the Load, Init, or any other method of the class.

When you add an object with the AddObject method, the object becomes a member of the container. The Parent property of the added object refers to the container. When an object based on the container or control class is released from memory, the added object is also released.

When you create an object with the CREATEOBJECT( ) function, the object is scoped to a property of the class or a variable in the method that calls this function. The parent property of the object is undefined.

See Also

Writing Class Definitions Programmatically | Creation of Objects from Classes | Method and Event Code Guidelines | Protection and Hiding of Class Members | Object-Oriented Programming | Parent Object Reference


Method and Event Code Guidelines

In addition to writing code for the methods and events of an object, you can extend the set of methods in subclasses of Visual FoxPro base classes. Here are the rules for writing event code and methods:

  • The event set for the Visual FoxPro base classes is fixed and cannot be extended.
  • Every class recognizes a set of fixed default events, the minimum set of which includes Init, Destroy, and Error events.
  • When you create a method in a class definition with the same name as an event that the class can recognize, the code in the method is executed when the event occurs.
  • You can add methods to your classes by creating a procedure or function within the class definition.
  • You can create Access and Assign Methods for your classes by creating a procedure or function with the same name as a class property and _ACCESS or _ASSIGN appended to the procedure or function name.

Calling Event Code up the Class Hierarchy

When you create a class, the class automatically inherits all the properties, methods, and events of the parent class. If code is written for an event in the parent class, that code is executed when the event occurs with respect to an object based on the subclass. You can, however, overwrite the parent class code by writing code for the event in the subclass.

To explicitly call the event code in a parent class when the subclass has code written for the same event, use the DODEFAULT( ) function.

For example, you could have a class named cmdBottom based on the command button base class that has the following code in the Click event:

GO BOTTOM
THISFORM.Refresh

When you add an object based on this class to a form, named, for example, cmdBottom1, you might decide that you also want to display a message for the user so that he or she knows that the record pointer is at the bottom of the table. You could add the following code to the Click event of the object to display the message:

WAIT WINDOW "At the Bottom of the Table" TIMEOUT 1

When you run the form, however, the message is displayed, but the record pointer doesn't move because the code in the Click event of the parent class is never executed. To make sure the code in the Click event of the parent class is also executed, include the following lines of code in the Click event procedure of the object:

DODEFAULT( )
WAIT WINDOW "At the Bottom of the Table" TIMEOUT 1
Note You can use the ACLASS( ) function to determine all the classes in an object's class hierarchy.

Preventing Base Class Code from Executing

Sometimes you'll want to prevent the base class default behavior from taking place in an event or method. You can do this by including the NODEFAULT keyword in the method code you write. For example, the following program uses the NODEFAULT keyword in the KeyPress event of a text box to prevent the typed characters from being displayed in the text box:

frmKeyExample = CREATEOBJECT("test")
frmKeyExample.Show
READ EVENTS
DEFINE CLASS test AS FORM
  ADD OBJECT text1 AS TEXTBOX
  PROCEDURE text1.KeyPress
   PARAMETERS nKeyCode, nShiftAltCtrl
   NODEFAULT
   IF BETWEEN(nKeyCode, 65, 122) && between 'A' and 'z'
    This.Value = ALLTRIM(This.Value) + "*"
    ACTIVATE SCREEN      && send output to main Visual FoxPro window
    ?? CHR(nKeyCode)
   ENDIF
  ENDPROC
  PROCEDURE Destroy
   CLEAR EVENTS
  ENDPROC
ENDDEFINE

See Also

Writing Class Definitions Programmatically | Addition of Objects to a Container Class | Creating a Set of Table Navigation Buttons | Init | Destroy | Error | Access and Assign Methods | Object-Oriented Programming | NODEFAULT Command


Creating a Set of Table Navigation Buttons

A common feature of many applications is a series of navigation buttons that allow users to move through a table. These typically include buttons to move the record pointer to the next or prior record in the table, as well as to the top or bottom record in the table.

Designing the Navigation Buttons

Each of the buttons will have some characteristics and functionality in common, so it is a good idea to create a navigation button class. Then the individual buttons can easily derive this common appearance and functionality. This parent class is the Navbutton class defined later in this section.

Once the parent class is defined, the following subclasses define the functionality and appearance specific to each of the four navigation buttons: navTop, navPrior, navNext, navBottom.

Finally, a container class, vcr, is created and each of the navigation buttons is added to the container class. The container can be added to a form or a toolbar to provide table navigation functionality.

NAVBUTTON Class Definition

To create Navbutton, save the following six class definitions (Navbutton, navTop, navBottom, navPrior, navNext, and vcr) to a program file such as Navclass.prg.

Definition of the Generic Navigation Commandbutton Class

Code Comments
DEFINE CLASS Navbutton AS
COMMANDBUTTON

  Height = 25
  Width = 25

  TableAlias = ""
Define the parent class of the navigation buttons.

Give the class some dimensions.

Include a custom property, TableAlias, to hold the name of the alias to navigate through.

PROCEDURE Click
  IF NOT EMPTY(This.TableAlias)
   SELECT (This.TableAlias)
  ENDIF
ENDPROC
 If TableAlias has been set, this parent class procedure selects the alias before the actual navigation code in the subclasses is executed. Otherwise, assume that the user wants to navigate through the table in the currently selected work area.
PROCEDURE RefreshForm
  _SCREEN.ActiveForm.Refresh
ENDPROC
 Using _SCREEN.ActiveForm.Refresh instead of THISFORM.Refresh allows you to add the class to a form or a toolbar and have it function equally well.
ENDDEFINE
 End the class definition.

The specific navigation buttons are all based on the Navbutton class. The following code defines the Top button for the set of navigation buttons. The remaining three navigation buttons are defined in the following table. The four class definitions are similar, so only the first one has extensive comments.

Definition of the Top Navigation Button Class

Code Comments
DEFINE CLASS navTop AS Navbutton
  Caption = "|<"
 Define the Top navigation button class and set the Caption property.
PROCEDURE Click
 Create method code to be executed when the Click event for the control occurs.
  DODEFAULT( )

  GO TOP

  THIS.RefreshForm
 Call the Click event code in the parent class, Navbutton, so that the appropriate alias can be selected if the TableAlias property has been set.

Include the code to set the record pointer to the first record in the table: GO TOP.

Call the RefreshForm method in the parent class. It is not necessary to use the scope resolution operator (::) in this case because there is no method in the subclass with the same name as the method in the parent class. On the other hand, both the parent and the subclass have method code for the Click event.
ENDPROC
 End the Click procedure.
ENDDEFINE
 End the class definition.

The other navigation buttons have similar class definitions.

Definition of the Other Navigation Button Classes

Code Comments
DEFINE CLASS navNext AS Navbutton
  Caption = ">"
 Define the Next navigation button class and set the Caption property.
PROCEDURE Click
  DODEFAULT( )
  SKIP 1
  IF EOF( )
   GO BOTTOM
  ENDIF
  THIS.RefreshForm
ENDPROC
ENDDEFINE

Include the code to set the record pointer to the next record in the table.

End the class definition.
DEFINE CLASS navPrior AS Navbutton
  Caption = "<"
 Define the Prior navigation button class and set the Caption property.
PROCEDURE Click
  DODEFAULT( )
  SKIP –1
  IF BOF( )
   GO TOP
  ENDIF
  THIS.RefreshForm
ENDPROC
ENDDEFINE

Include the code to set the record pointer to the previous record in the table.

End the class definition.
DEFINE CLASS navBottom AS
Navbutton
  Caption = ">|"
 Define the Bottom navigation button class and set the Caption property.
PROCEDURE Click
  DODEFAULT( )
  GO BOTTOM
  THIS.RefreshForm
ENDPROC
ENDDEFINE

Include the code to set the record pointer to the bottom record in the table.

End the class definition.

The following class definition contains all four navigation buttons so that they can be added as a unit to a form. The class also includes a method to set the TableAlias property of the buttons.

Definition of a Table Navigation Control Class

Code Comments
DEFINE CLASS vcr AS CONTAINER
   Height = 25
   Width = 100
   Left = 3
   Top = 3
 Begin the class definition. The Height property is set to the same height as the command buttons it will contain.
   ADD OBJECT cmdTop AS navTop ;
      WITH Left = 0
   ADD OBJECT cmdPrior AS navPrior ;
      WITH Left = 25
   ADD OBJECT cmdNext AS navNext ;
      WITH Left = 50
   ADD OBJECT cmdBot AS navBottom ;
      WITH Left = 75
 Add the navigation buttons.
PROCEDURE SetTable(cTableAlias)
   IF TYPE("cTableAlias") = 'C'
      THIS.cmdTop.TableAlias = ;
         cTableAlias
      THIS.cmdPrior.TableAlias = ;
         cTableAlias
      THIS.cmdNext.TableAlias = ;
         cTableAlias
      THIS.cmdBot.TableAlias = ;
         cTableAlias
   ENDIF
ENDPROC
 This method is used to set the TableAlias property of the buttons. TableAlias is defined in the parent class Navbutton.

You could also use the SetAll method to set this property:
IF TYPE ("cTableAlias") = 'C'
This.SetAll("TableAlias", "cTableAlias")
ENDIF
However, this would cause an error if an object were ever added to the class that did not have a TableAlias property.
ENDDEFINE
 End class definition.

Once you have defined the class, you can subclass it or add it to a form.

Creating a Subclass Based on the New Class

You can also create subclasses based on vcr that have additional buttons such as Search, Edit, Save, and Quit. For example, vcr2 includes a Quit button:

Definition of a Table Navigation Control Subclass

Code Comments
DEFINE CLASS vcr2 AS vcr

ADD OBJECT cmdQuit AS
COMMANDBUTTON WITH ;
   Caption = "Quit",;
   Height = 25, ;
   Width = 50
Width = THIS.Width + THIS.cmdQuit.Width
cmdQuit.Left = THIS.Width - ;
   THIS.cmdQuit.Width
Define a class based on vcr and add a command button to it.
PROCEDURE cmdQuit.CLICK

   RELEASE THISFORM
ENDPROC
When the user clicks cmdQuit, this code releases the form.
ENDDEFINE
 End class definition.

Vcr2 has everything that vcr does, plus the new command button, and you don't have to rewrite any of the existing code.

Changes to VCR Reflected in the Subclass

Because of inheritance, changes to the parent class are reflected in all subclasses based on the parent. For example, you could let the user know that the bottom of the table has been reached by changing the IF EOF( ) statement in navNext.Click to the following:

IF EOF( )
   GO BOTTOM
   SET MESSAGE TO "Bottom of the table"
ELSE
   SET MESSAGE TO
ENDIF

You could let the user know that the top of the table has been reached by changing the IF BOF( ) statement in navPrior.Click to the following:

IF BOF()
   GO TOP
   SET MESSAGE TO "Top of the table"
ELSE
   SET MESSAGE TO
ENDIF

If these changes are made to the navNext and navPrior classes, they will also apply automatically to the appropriate buttons in vcr and vcr2.

Adding VCR to a Form Class

Once vcr is defined as a control, the control can be added in the definition of a container. For example, the following code added to Navclass.prg defines a form with added navigation buttons:

DEFINE CLASS NavForm AS Form
   ADD OBJECT oVCR AS vcr
ENDDEFINE

Running the Form Containing VCR

Once the form subclass is defined, you can display it easily with the appropriate commands.

To display the form

  1. Load the class definition:
    SET PROCEDURE TO navclass ADDITIVE
  2. Create an object based on the navform class:
    frmTest = CREATEOBJECT("navform")
  3. Invoke the Show method of the form:
    frmTest.Show

If you don't call the SetTable method of oVCR (the VCR object in NavForm) when the user clicks the navigation buttons, the record pointer moves in the table in the currently selected work area. You can call the SetTable method to specify what table to move through.

frmTest.oVCR.SetTable("customer")
Note When the user closes the form, frmTest is set to a null value (.NULL.). To release the object variable from memory, use the RELEASE command. Object variables created in program files are released from memory when the program is completed.

See Also

Writing Class Definitions Programmatically | Method and Event Code Guidelines | Definition of a Grid Control | Caption property | Height property | SetAll method | Object-Oriented Programming


Definition of a Grid Control

A grid contains columns, which in turn can contain headers and any other control. The default control contained in a column is a text box, so that the default functionality of the grid approximates a Browse window. However, the underlying architecture of the grid opens it up to endless extensibility.

The following example creates a form that contains a Grid object with two columns. The second column contains a check box to display the values in a logical field in a table.

Grid control with a check box in one column

Definition of a Grid Class with a Check Box in a Grid Column

Code Comments
DEFINE CLASS grdProducts AS Grid
   Left = 24
   Top = 10
   Width = 295
   Height = 210
   Visible = .T.
   RowHeight = 28
   ColumnCount = 2
 Start the class definition and set properties that determine the grid appearance.

When you set the ColumnCount property to 2, you add two columns to the grid. Each column contains a header with the name Header1. In addition, each column has an independent group of properties that determines its appearance and behavior.
Column1.ControlSource ="prod_name"
Column2.ControlSource ="discontinu"
 When you set the ControlSource of a column, the column displays that field's values for all the records in the table.
Discontinu is a logical field.
Column2.Sparse = .F.
 Column2 will contain the check box. Set the column's Sparse property to .F. so that the check box will be visible in all rows, not just in the selected cell.
Procedure Init
   THIS.Column1.Width = 175
   THIS.Column2.Width = 68
   THIS.Column1.Header1.Caption = ;
      "Product Name"
   THIS.Column2.Header1.Caption = ;
      "Discontinued"

   THIS.Column2.AddObject("chk1", ;
      "checkbox")
   THIS.Column2.CurrentControl = ;
      "chk1"
   THIS.Column2.chk1.Visible = .T.
   THIS.Column2.chk1.Caption = ""
ENDPROC
 Set column widths and header captions.

The AddObject method allows you to add an object to a container — in this case, a check box named chk1.
Set the CurrentControl of the column to the check box so that the check box will be displayed.
Make sure that the check box is visible.
Set the caption to an empty string so that the default caption "chk1" won't be displayed.
ENDDEFINE
 End of the class definition.

The following class definition is the form that contains the grid. Both class definitions can be included in the same program file.

Definition of a Form Class that Contains the Grid Class

Code Comments
DEFINE CLASS GridForm AS FORM
   Width = 330
   Height = 250
   Caption = "Grid Example"
   ADD OBJECT grid1 AS grdProducts
 Create a form class and add an object, based on the grid class, to it.
PROCEDURE Destroy
   CLEAR EVENTS
ENDPROC

ENDDEFINE
 The program that creates an object based on this class will use READ EVENTS. Including CLEAR EVENTS in the Destroy event of the form allows the program to finish running when the user closes the form.
End of the class definition.

The following program opens the table with the fields to be displayed in the grid columns, creates an object based on the GridForm class, and issues the READ EVENTS command:

CLOSE DATABASE
OPEN DATABASE (HOME(2) + "data\testdata.dbc")
USE products
frmTest= CREATEOBJECT("GridForm")
frmTest.Show
READ EVENTS

This program can be included in the same file with the class definitions if it comes at the beginning of the file. You could also use the SET PROCEDURE TO command to specify the program with the class definitions and include this code in a separate program.

See Also

Writing Class Definitions Programmatically | Creating a Set of Table Navigation Buttons | Object Reference Creation | Browse | Sparse property | AddObject method | CurrentControl | Object-Oriented Programming


Object Reference Creation

Instead of making a copy of an object, you can create a reference to the object. A reference takes less memory than an additional object, can easily be passed between procedures, and can aid in writing generic code.

Returning a Reference to an Object

Sometimes, you might want to manipulate an object by means of one or more references to the object. For example, the following program defines a class, creates an object based on the class, and returns a reference to the object:

*--NEWINV.PRG
*--Returns a reference to a new invoice form.
frmInv = CREATEOBJECT("InvoiceForm")
RETURN frmInv

DEFINE CLASS InvoiceForm AS FORM
   ADD OBJECT txtCompany AS TEXTBOX
   * code to set properties, add other objects, and so on
ENDDEFINE

The following program establishes a reference to the object created in Newinv.prg. The reference variable can be manipulated in exactly the same way as the object variable can:

frmInvoice = NewInv() && store the object reference to a variable
frmInvoice.SHOW

You can also create a reference to an object on a form, as in the following example:

txtCustName = frmInvoice.txtCompany
txtCustName.Value = "Fox User"
Tip Once you've created an object, you can use the DISPLAY OBJECTS command to display the object's class hierarchy, property settings, contained objects, and available methods and events. You can fill an array with the properties (not the property settings), events, methods, and contained objects of an object with the AMEMBERS( ) function.

Releasing Objects and References from Memory

If a reference to an object exists, releasing the object does not clear the object from memory. For example, the following command releases frmInvoice, the original object:

RELEASE frmInvoice

However, because a reference to an object belonging to frmInvoice still exists, the object is not released from memory until txtCustName is released with the following command:

RELEASE txtCustName

Checking to See if an Object Exists

You can use the TYPE( ), ISNULL( ), and VARTYPE( ) functions to determine if an object exists. For example, the following lines of code check to see whether an object named oConnection exists:

IF TYPE("oConnection") = "O" AND NOT ISNULL(oConnection)
   * Object exists
ELSE
   * Object does not exist
ENDIF
Note ISNULL( ) is necessary because .NULL. is stored to the form object variable when a user closes a form, but the type of the variable remains "O".

See Also

Writing Class Definitions Programmatically | Definition of a Grid Control | Arrays of Members and Objects | DISPLAY OBJECTS | AMEMBERS( ) | Object-Oriented Programming


Arrays of Members and Objects

You can define members of classes as arrays. In the following example, choices is an array of controls:

DEFINE CLASS MoverListBox AS CONTAINER
DIMENSION choices[3]
ADD OBJECT lstFromListBox AS LISTBOX
ADD OBJECT lstToListBox AS LISTBOX
ADD OBJECT choices[1] AS COMMANDBUTTON
ADD OBJECT choices[2] AS COMMANDBUTTON
ADD OBJECT choices[3] AS CHECKBOX
PROCEDURE choices.CLICK
   PARAMETER nIndex
   DO CASE
      CASE nIndex = 1
         * code
      CASE nIndex = 2
         * code
      CASE nIndex = 3
         * code
   ENDCASE
ENDPROC
ENDDEFINE

When the user clicks a control in an array of controls, Visual FoxPro passes the index number of the control to the Click event procedure. In this procedure, you can use a CASE statement to execute different code depending on which button was clicked.

Creating Arrays of Objects

You can also create arrays of objects. For example, MyArray holds five command buttons:

DIMENSION MyArray[5]
FOR x = 1 TO 5
   MyArray[x] = CREATEOBJECT("COMMANDBUTTON")
ENDFOR

There are some considerations to keep in mind with arrays of objects:

  • You can't assign an object to an entire array with one command. You need to assign the object to each member of the array individually.
  • You can't assign a value to a property of an entire array. The following command would result in an error:
    MyArray.Enabled = .F.
  • When you redimension an object array so that it is larger than the original array, the new elements are initialized to false (.F.), as is the case with all arrays in Visual FoxPro. When you redimension an object array so that it is smaller than the original array, the objects with a subscript greater than the largest new subscript are released.

See Also

Writing Class Definitions Programmatically | Object Reference Creation | Data Storage with Objects | Object and Data Integration | Object-Oriented Programming


Data Storage with Objects

In object-oriented languages, a class offers a useful and convenient vehicle for storing data and procedures related to an entity. For example, you could define a customer class to hold information about a customer as well as a method to calculate the customer's age:

DEFINE CLASS customer AS CUSTOM
   LastName = ""
   FirstName = ""
   Birthday = { - - }
   PROCEDURE Age
      IF !EMPTY(THIS.Birthday)
         RETURN YEAR(DATE()) - YEAR(THIS.Birthday)
      ELSE
         RETURN 0
      ENDIF
   ENDPROC
ENDDEFINE

However, data stored in objects based on the customer class are stored only in memory. If this data were in a table, the table would be stored on disk. If you had more than one customer to keep track of, the table would give you access to all of the Visual FoxPro database management commands and functions. As a result, you could quickly locate information, sort it, group it, perform calculations on it, create reports and queries based on it, and so on.

Storing and manipulating data in databases and tables is what Visual FoxPro does best. There are times, however, when you'll want to store data in objects. Usually, the data will be significant only while your application is running and it will pertain to a single entity.

For example, in an application that includes a security system, you would typically have a table of users who have access to the application. The table would include user identification, password, and access level. Once a user has logged on, you won't need all the information in the table. All you need is information about the current user, and this information can be easily stored and manipulated in an object. The following class definition, for example, initiates a logon when an object based on the class is created:

DEFINE CLASS NewUser AS CUSTOM
   PROTECTED LogonTime, AccessLevel
   UserId = ""
   PassWord = ""
   LogonTime = { - - : : }
   AccessLevel = 0
   PROCEDURE Init
      DO FORM LOGON WITH ; && assuming you have created this form
         This.UserId, ;
         This.PassWord, ;
         This.AccessLevel
      This.LogonTime = DATETIME( )
   ENDPROC
* Create methods to return protected property values.
   PROCEDURE GetLogonTime
      RETURN This.LogonTime
   ENDPROC
   PROCEDURE GetAccessLevel
      RETURN This.AccessLevel
   ENDPROC

ENDDEFINE

In the main program of your application, you could create an object based on the NewUserclass:

oUser = CREATEOBJECT('NewUser')
oUser.Logon

Throughout your application, when you need information about the current user, you can get it from the oUser object. For example:

IF oUser.GetAccessLevel( ) >= 4
   DO ADMIN.MPR
ENDIF

See Also

Writing Class Definitions Programmatically | Arrays of Members and Objects | Object and Data Integration | Object Reference Creation | Object-Oriented Programming


Object and Data Integration

In most applications, you can best utilize the power of Visual FoxPro by integrating objects and data. Most Visual FoxPro classes have properties and methods that allow you to integrate the power of a relational database manager and a full object-oriented system.

Properties for Integrating Visual FoxPro Classes and Database Data

Class | Data properties
Grid | RecordSource, ChildOrder, LinkMaster
All other controls | ControlSource
List box and combo box | ControlSource, RowSource
Form and form set | DataSession

Because these data properties can be changed at design or run time, you can create generic controls with encapsulated functionality that operate on diverse data.

For more information about integrating data and objects, see Creating Forms, and Using Controls

See Also

Writing Class Definitions Programmatically | Data Storage with Objects | Arrays of Members and Objects | Object Reference Creation | Object-Oriented Programming


Browsing Classes with the Class Browser

You can browse, track, and modify classes using the Visual FoxPro Class Browser.

To | See
Run the Class Browser | Running the Class Browser
Look at a class hierarchy | Viewing Class Hierarchies
View specific classes | Filtering the Class Browser Class List
View the code for a class | Viewing Class Definition Code
View typelib and object library information | Viewing Type Library Information
Create, remove, redefine, or copy classes | Managing Classes with the Class Browser
Add an instance of a class to a form | Adding Controls to Forms with the Class Browser
Modify classes | Modifying Class Icons and Descriptions
Modify the Class Browser | Customizing the Class Browser

See Also

Adding Controls to Forms with the Class Browser | Class Browser Buttons | Class Browser Window | Customizing the Class Browser | Filtering the Class Browser Class List | Managing Classes with the Class Browser | Modifying Class Icons and Descriptions | Running the Class Browser | Viewing Class Definition Code | Viewing Class Hierarchies


Running the Class Browser

You can run the Class Browser from the Visual FoxPro menu or from the Command window.

To run the Class Browser

  1. From the Tools menu, choose Class Browser.

    -or-

    Use the DO command and the _BROWSER system variable:

    DO (_BROWSER)

The program stored by default to the _BROWSER system memory is Browser.app. Browser.app accepts five optional arguments:

DO (_BROWSER) [WITH [tcFileName][, tcDefaultClass[.member]][, tlListBox][, tcClassType][, tnWindowState]]

Argument | Description
cFileName | The name of the .vcx, .scx, .olb, .tlb, .pjx, or .exe file to open in the Class Browser.
cDefaultClass[.member] | The class in the .vcx to be selected by default. If no default class is specified, the class library is selected. If a member is specified, that member is selected in the Members list.
lListBox | Specifies whether to display the classes and members in list boxes rather than treeview controls. Include true (.T.) for this parameter to display the list boxes. The default is false (.F.)
cClassType | Specifies the initial Type filter for the classes displayed in the Class Browser. You can change the filter in the Class Browser by choosing another value from the Type list. The default is no filter.
nWindowState | 0 - Normal (the default) 1 - Minimized 2 – Maximized
lGallery | Default: .F. Specifies whether to open in the Component Gallery instead of the Class Browser. Use true (.T.) to open in the Component Gallery.

For example, the following command opens the Class Browser maximized with the print_report class in Samples.vcx selected, the cmdOK object selected in the Members list, and the forms and members in Samples.vcx displayed in list boxes:

DO (_BROWSER) WITH "samples.vcx", "print_report.cmdOK", .T., "form", 2

To specify a default class and member name to open with the Class Browser

  1. Open the file in the Class Browser
  2. Highlight the file in the Class list of the Class Browser
  3. In the Command window, type the following code:
    DO (_BROWSER) WITH "mylib","myclass.cMessage"

You can also use the Class Browser to specify the default file to open when you start the Class Browser from the Tools menu or the Command window.

To specify a default library to open with the Class Browser

  1. Open the file in the Class Browser
  2. Highlight the file in the Class list of the Class Browser
  3. In the Command window, type the following code:
    _oBrowser.SetDefaultFile

This resets any previously specified default libraries.

You can add files to the default library opened by Class Browser.

To specify additional libraries to open with the Class Browser

  1. Open the additional file in the Class Browser
  2. Highlight the file in the Class list of the Class Browser
  3. In the Command window, type the following code:
    _oBrowser.SetDefaultFile(.T.)

To remove libraries from the Class Browser list

  1. Highlight the file in the Class list of the Class Browser
  2. In the Command window, type the following code:
    _oBrowser.ResetDefaultFile

To remove all libraries from the Class Browser list

  1. In the Command window, type the following code:
    _oBrowser.ResetDefaultFile(.T.)

See Also

Adding Controls to Forms with the Class Browser | _BROWSER System Variable | Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Properties | Class Browser Window | Customizing the Class Browser | Filtering the Class Browser Class List | Managing Classes with the Class Browser | Modifying Class Icons and Descriptions | Running the Class Browser | Viewing Class Definition Code


Viewing Class Hierarchies

With the Class Browser, you can see the hierarchy for a class library. You can also view user-defined members for a class and track the inheritance of members between related classes.

To view class members and hierarchies

  1. Run the Class Browser.
  2. Open a class library.
  3. From the Class list, select a class. The Class Browser displays the icon for the class in the Class list and beside the Type drop-down. The user-defined class members are displayed in the Members list.

If Hierarchical mode is selected on the shortcut menu, subclasses are displayed indented beneath parent classes.

When a class is selected, you can easily view its parent.

To view the parent class

  • Right-click the class and then choose Select ParentClass from the shortcut menu. The Class Browser selects the parent class.

If the class has a chevron (<<) next to it, its parent class is located in a class library (.vcx) that is not displayed in the class list. When you choose Select ParentClass from the class shortcut menu, the class library containing the parent class is added to the class list, and the parent class is selected.

You can view multiple class libraries or form files by opening another file in the current Class Browser window or by opening another Class Browser window. You can also open the same file in several Class Browser windows.

See Also

Adding Controls to Forms with the Class Browser | _BROWSER System Variable | Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Properties | Class Browser Window | Customizing the Class Browser | Filtering the Class Browser Class List | Managing Classes with the Class Browser | Modifying Class Icons and Descriptions | Running the Class Browser | Viewing Class Definition Code


Filtering the Class Browser Class List

You can use filters such as a Visual FoxPro base class type or a class name to display a specific set of classes in the Class list.

To filter the list of classes

  1. Open a file in the Class Browser.
  2. In the Type box, type a class name or select one from the list.

    -or-

    In the Type box, type a single filter, or several filters separated by a comma. The comma acts as a logical OR: a class needs to match only one filter to be included in the class list.

    The classes matching the filters appear in the class list and the filter you entered is added to the drop-down list. The drop-down list keeps a history of the types and filters you have selected to view in the current instance of the Class Browser window. The list is not saved after the instance is closed.

    Note When you choose Alphabetical, Visual FoxPro evaluates all of the classes. When you choose Hierarchical, the default choice, Visual FoxPro evaluates the parent classes. If a parent class matches the filter, its child classes are evaluated. If the parent class does not match the filter, its child classes are not evaluated and do not appear in the list — even if the child matches the filter.

You can create a filter that combines characters in a class name with wildcards as described in the following table.

search template | description
+cTargetName | Name must start with cTarget.
%cTargetName% | Name contains cTarget. For example, to view all classes containing the string "mover," type %MOVER%.
-cTarget - has precedence over other search filters. | Name does NOT contain cTarget.
~cTarget | Name contains something similar to cTarget.
cTarget* An asterisk (*) replaces an unlimited number of characters. | Name contains anything following cTarget. For example, to view all classes beginning with "VCR," type VCR*.
"cTarget" | Name IS cTarget. If cTarget is not a Base Class, search reports results of class name search.
cTarget | If cTarget is a Base Class search will report all members of that Base Class no matter what the name.
[?…]cTarget[?…] A question mark replaces a single character. You can use them any place in any quantity. | Name contains cTarget plus the specified unknown characters in the specified relative positions. For example, to view all classes starting with MsgBox and some number, such as MsgBox1, type MsgBox?.

You can use combinations of search parameters separated by spaces which indicate an OR operator as in the following examples:

If you want this | Use an expression like this
The target is a string that must start with "test" but is NOT a "form" class. | -%form% +test*
The target is any string that does NOT contain "debug" and starts with "c" OR contains "test". | c* %test% -%debug%
The target is any string that does NOT start with "debug" and is similar to "test" OR is the string "myform" | ~test -debug* "myForm"

You can also expand your search for classes to include a specific character string in its name or description.

To search by class name and description text

  1. Open a file in the Class Browser, and then choose the Find button.
  2. In the Find Class dialog box, type a string of text you want found.
  3. A list of classes with the string in its name or description appears in the class list. If the list is hierarchical, only the matching parent classes and their associated matching subclasses are in the list. If you want to view any class that has the string of text, choose the alphabetical option.

See Also

Adding Controls to Forms with the Class Browser | Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Window | Customizing the Class Browser | Managing Classes with the Class Browser | Modifying Class Icons and Descriptions | Running the Class Browser | Viewing Class Definition Code | Viewing Class Hierarchies


Viewing Class Definition Code

If you want to see specific parameters or understand the logic behind a class, you can use the Class Browser to view the code for the class in one of three ways. You can even view the parent class code for a user-defined method.

To view class definition code

  1. In the Class Browser, select the class you want to view.
  2. Choose the View Class Code button.
  3. Visual FoxPro displays the definition code for the class you selected in a read-only window. You can use some of the editing commands from the Edit menu, such as Find, Copy, and Select All.

The class definition displayed in the read-only window includes all property settings and method and event code.

Note The code displayed is for information. In many cases, you can save it to a program and run it directly, but code with nested containers will generate errors. To view type library information, use Object Browser.

To modify a class that is displayed in the Class Browser

  • Double-click the class in the Class list or press the spacebar on a selected class.

To edit method code of a method in the Members list

  • Double-click the method in the Members list.

When you modify a class or form while the Class Browser window is open, you can easily view the ParentClass code for a method or event.

To view ParentClass code for a method

  1. Double-click a class or member.
  2. If no code window is open in the Form Designer or Class Designer, choose Code from the View menu.
  3. Choose the Edit ParentClass Method toolbar button.
    Note You can also view code or modify a class by selecting the class in the Members list and pressing the SPACEBAR.

To save class definition code to a file

  1. Choose Export from the shortcut menu

    -or-

  2. Right-click the View Code button
  3. Specify the file name in the Open dialog box.

See Also

Adding Controls to Forms with the Class Browser | Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Window | Customizing the Class Browser | Filtering the Class Browser Class List | Managing Classes with the Class Browser | Modifying Class Icons and Descriptions | Running the Class Browser | Trace Window | Viewing Class Hierarchies | Viewing Type Library Information | Object Browser


Viewing Type Library Information

Type libraries are COM Component definition files that include information about types and objects exposed by an OLE application. A type library can be a stand-alone binary file (.tlb), compiled in an application file (.exe), embedded in an ActiveX control (.ocx), or included in a .dll. Dlls with one or more type libraries are often compiled as object libraries (.olb).

To view type library information

  1. In the Object Browser, choose Open Type Library.
  2. In the Open dialog box select the tab that will give you access to the library you want.

    Recent History tab lists the most recently opened libraries.

    COM libraries tab lists the available libraries and provide a Browse button so you can find the library you want.

    Current Selection lists any open libraries.

    In the Files of type drop-down list in the Open dialog box, choose Application, *.dll, *.ocx, *.olb, or *.tlb.

  3. Select a library and click OK.

The type library information for the selected file is displayed in the Classes & Members list.

See Also

_OBJECTBROWSER System Variable | Using Object Browser


Managing Classes with the Class Browser

You can create subclasses, copy classes from one class library to another, remove classes and library files, rename a class, or redefine the relationship of a class.

Caution If you remove, rename, or redefine a class, the forms that are not currently displayed in a Class Browser window and that rely on the class might not run properly.

To add a subclass

  1. In the Class Browser, open a class library.
  2. Select the class you want to subclass, and then choose the New Class button.
  3. In the New Class dialog box, enter the name for the new subclass.
  4. In the Class Designer, define and save the subclass.
  5. The Class Browser displays the new subclass.

To copy a class from one class library to another

  1. In the Class Browser, open the source class library.
  2. From the Tools menu, open a second instance of the Class Browser and select the destination library file.
  3. In the source class library, select the class you want to copy, and then while pressing the Ctrl key, drag the Class Move icon picture located above the class list to the class icon picture in the destination library. The cursor appears with a plus sign when you are over the destination class icon.

To copy multiple classes from one class library file to another

  1. Open the source class library in the Class Browser.
  2. If you want to filter the class list, type a filter in the Type box to limit the classes you want to copy from the file.
  3. From the Tools menu, open a second instance of the Class Browser and select the destination library file.
  4. In the source class library, select the class library file you want to copy, and then while pressing the Ctrl key, drag the class icon picture located above the class list to the class icon picture in the destination library. The cursor appears with a plus sign when you are over the destination class icon picture.

To remove a class, class library, or form

  1. Open the class library or form in the Class Browser.
  2. In the Class list, select the class, class library, or form you want to remove or delete, and then choose the Remove button. For classes, the record in the library is marked for deletion the next time you choose Clean Up Library. For class libraries and forms, the file is deleted from the disk.

To rename a class in a class library

  1. Open the class library in the Class Browser.
  2. In the Class list, select the class you want to rename, and then choose the Rename button.
    Caution If you rename a class that has associated subclasses that are not currently contained in an open Class Browser window, the subclasses will not be able to reference properties that are inherited from the renamed class.
  3. In the Rename Class dialog box, type the new name, and then choose Rename.
  4. The Class Browser displays the new name and the new name is automatically referenced in all the affected forms and classes currently displayed in Class Browser windows.

To change the parent class of a class

  1. Open the class library in the Class Browser.
  2. In the Class list, select the class you want to redefine, and then choose the Redefine button.
  3. In the As box of the Redefine dialog box, select the name of the new parent class using the drop down list. You can redefine some base classes

You can also use drag and drop functionality to manage classes in the Class Browser. Managing files in the Class Browser is the recommended way to update project files as well as class libraries and forms. Changes made in the Class Browser are cascaded through every open .vcx and .scx file. Common Drag and drop moves an object from one location to another. Modifier keys with drag and drop provide the following behaviors:

Drag and drop with… | To…
CTRL | Copy a class between Class Browser windows
Right-click | Instantiates object in a container: to Command window – generates instantiation code to desktop – instantiates in Class Browser to form – instantiates object and can open a builder.
SHIFT | Creates instance of the class but doesn't display it. Drag to Command window functions as a simple drag and drop.

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Properties | Class Browser Window | Customizing the Class Browser | Filtering the Class Browser Class List | Modifying Class Icons and Descriptions | Running the Class Browser | Viewing Class Hierarchies | Viewing Type Library Information


Creating Instances of Classes with the Class Browser

You can easily create instances of classes displayed in the Class Browser.

To create an instance of a class

  1. Open the class library or form in the Class Browser.
  2. In the Class list, select the class or form you want to create an instance of.
  3. Drag the Class Move icon from beside the Type list and drop it on the main Visual FoxPro window.

If you drop a form or form class on the main Visual FoxPro window, the form is created and displayed. If you drop a control on the main Visual FoxPro window, the control is added to the _SCREEN object. If you hold the SHIFT key down during the drag operation, the object is created but not made visible. To suppress error messages generated when you create instances, hold the CTRL key down during the drag operation.

You can also drop the Class Move icon in the Command window so you can execute the appropriate NEWOBJECT or CREATEOBJECT code to instantiate the class.

Note When you create an instance of a class, the code in the Init event, and possibly other events, runs. You need to know what code is associated with your classes before creating an instance. If the class requires a particular environment that has not been set up, Visual FoxPro will generate errors. The Class Browser does not provide error handling for user-defined classes.

To remove an object from the _SCREEN object

  • Use the RemoveObject method of _SCREEN.

For example, if you drag the VCR class from ...\Samples\classes\buttons.vcx and drop it on the form, the following line of code in the Command window removes it:

_SCREEN.RemoveObject("VCR1")

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Window | Customizing the Class Browser | SaveAs Method | SaveAsClass Method | Viewing Class Hierarchies | Viewing Type Library Information


Adding Controls to Forms with the Class Browser

You can add controls from the Class Browser while designing or running a form.

To add controls to a form or container

  1. In the Form Designer, open the form.
  2. In the Class Browser, open the class library file containing the class of the object you want to add to the form.
  3. From the Class list, select the class name, and then drag the class icon on the form. The class icon is located above the Class list.

To view the class for a control on a form or in a container

  1. In the Form Designer, select the control.
  2. From the Tools menu, choose Class Browser. The Class Browser opens and displays the class of the control you selected on the form.

You can design your forms so that you can add objects of a class from the Class Browser on the form while it is running. You might want to design a form class that has this feature as one of its properties.

To add objects on a running form or a container on a form

  1. Run the form.
  2. Open the Class Browser and view the class list containing the class of object you want to add to the form.
  3. Select the class you want and drag the class icon from the Class Browser to the form.
  4. A new object appears on the form based on the class you selected from the Class Browser.
    Tip You can also add an instance of the selected class to any container by positioning the mouse pointer over the container and entering the following line of code in the Command window: _oBrowser.FormAddObject(SYS(1270))

To view the class for a control on a running form

  1. Set the focus to the control.
  2. From the Tools menu, choose Class Browser. The Class Browser evaluates _SCREEN.ActiveForm.ActiveControl and displays the class of the control you selected on the form.

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Window | Customizing the Class Browser | SaveAs Method | SaveAsClass Method | Viewing Class Hierarchies | Viewing Type Library Information


Modifying Class Icons and Descriptions

Using the Class Browser, you can modify the container icon, class description, and member descriptions for a class. You can also modify a class through the Class Designer from the Class Browser.

When you select a class in the Class Browser, the icon for the class appears above the class list. You can assign a different bitmap or icon to the class. By default, the class container icon and toolbar icon are the same as the parent's.

To change the class icon

  1. In the Class Browser, select the class with the icon you want to change.
  2. Right click the mouse to choose the Class Icon picture located above the class list.
  3. In the Open dialog box, select the new bitmap or icon, then choose OK.
  4. The new icon replaces the old one in the Class Browser. If the old class icon for the container and toolbar were the same, both change to the new icon. If they were different, only the container icon changes.
  5. You might see a prompt asking if you wish to reset the class library icon to the default, which is the icon Visual FoxPro uses for its base classes. If you want to change the icon to match its base class, choose Yes.

To change class and member descriptions without opening each class in the Class Designer, you can use the description boxes in the Class Browser.

To change the description for a class, method, or property

  1. In the Class Browser, select the class you want to change.
  2. In the edit box in the bottom-left corner of the window, type the new text for the class description.
  3. In the Members list, select a method or property.
  4. In the edit box in the bottom-right corner of the window, type the new text for the property description.

If no member is selected in the Members list, the edit box in the bottom-right corner of the window displays the class and timestamp information for the class selected in the Classes list.

Note You can change the descriptions for methods and properties. The descriptions for classes, object members, and instances are read-only.

If you want to modify more than the icon and descriptions for a class, you can open the Class Designer by selecting a class or file name in the Class Browser.

To modify a class in the Class Designer

  • In the Class list, double-click the name of a class to open the Class Designer.

    -or-

  • In the Class list, double-click the name of a file, and then choose a class in the Open dialog box.

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Window | Class Designer | Customizing the Class Browser | Filtering the Class Browser Class List | Managing Classes with the Class Browser | MODIFY CLASS Command | Viewing Class Definition Code | Viewing Class Hierarchies | Viewing Type Library Information


Customizing the Class Browser

You can change the properties, events, and methods of the Class Browser.

To programmatically manipulate the Class Browser

  1. Open the Class Browser to automatically create the public variable _oBrowser. You can use this variable to reference or manipulate the Class Browser form as you can any form object.
  2. Set the properties of the Class Browser you want to change.

    For example, before or after opening the Class Browser, you can set the Caption property of the Class Browser to "Hello" and the Left property to 10 with the following lines of code:

    _OBROWSER.Caption = "Hello"
_OBROWSER.Left = 10

See Also

Browsing Classes with the Class Browser | _BROWSER System Variable | Class Browser Buttons | Class Browser Methods | Class Browser Object Members | Class Browser Properties | Class Browser Window | Initial Values of Class Browser Properties


Container Hierarchy Object Referencing

The class hierarchy and the container are two separate entities. Visual FoxPro looks for event code up through the class hierarchy, whereas objects are referenced in the container hierarchy. To manipulate an object, you need to identify it in relation to the container hierarchy. For example, to manipulate a control on a form in a form set, you need to reference the form set, the form, and then the control. For an explanation of class hierarchies, see Calling Event Code up the Class Hierarchy.

You can compare the referencing of an object within its container hierarchy to giving Visual FoxPro an address to your object. When you describe the location of a house to someone outside your immediate frame of reference, you need to indicate the country, the state or region, the city, the street, or just the street number of the house, depending on how far they are from you. Otherwise, there could be some confusion.

The following illustration shows a possible container-nesting situation.

Nested containers

To disable the control in the grid column, you need to provide the following address:

Formset.Form.PageFrame.Page.;
 Grid.Column.Control.Enabled = .F.

The ActiveForm property of the application object (_VFP) allows you to manipulate the active form even if you don't know the name of the form. For example, the following line of code changes the background color of the active form, no matter what form set it belongs to:

_VFP.ActiveForm.BackColor = RGB(255,255,255)

Similarly, the ActiveControl property allows you to manipulate the active control on the active form. For example, the following expression entered in the Watch window displays the name of the active control on a form as you interactively choose the various controls:

_VFP.ActiveForm.ActiveControl.Name

Relative Referencing

When you are referencing objects from within the container hierarchy (for example, in the Click event of a command button on a form in a form set), you can use some shortcuts to identify the object you want to manipulate. The following table lists properties or keywords that make it easier to reference an object from within the object hierarchy:

Property or keyword | Reference
Parent | The immediate container of the object.
THIS | The object.
THISFORM | The form that contains the object.
THISFORMSET | The form set that contains the object.
Note You can use THIS, THISFORM, and THISFORMSET only in method or event code.

The following table provides examples of using THISFORMSET, THISFORM, THIS, and Parent to set object properties:

Command Where to include the command
THISFORMSET.frm1.cmd1.Caption = "OK"
 In the event or method code of any controls on any form in the form set.
THISFORM.cmd1.Caption = "OK"
 In the event or method code of any control on the same form that cmd1 is on.
THIS.Caption = "OK"
 In the event or method code of the control whose caption you want to change.
THIS.Parent.BackColor = RGB(192,0,0)
 In the event or method code of a control on a form. The command changes the background color of the form to dark red.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Setting Properties | Calling Methods | Event Response


Setting Properties

You can set the properties of an object at run time or design time.

To set a property

  • Use this syntax:

    Container.Object.Property = Value

    For example, the following statements set various properties of a text box named txtDate on a form named frmPhoneLog:

    frmPhoneLog.txtDate.Value = DATE( ) && Display the current date
frmPhoneLog.txtDate.Enabled = .T. && The control is enabled
frmPhoneLog.txtDate.ForeColor = RGB(0,0,0)    && black text
frmPhoneLog.txtDate.BackColor = RGB(192,192,192)  && gray background

For the property settings in the preceding examples, frmPhoneLog is the highest-level container object. If frmPhoneLog were contained in a form set, you would also need to include the form set in the parent path:

frsContacts.frmPhoneLog.txtDate.Value = DATE( )

Setting Multiple Properties

The WITH ... ENDWITH structure simplifies setting multiple properties. For example, to set multiple properties of a column in a grid in a form in a form set, you could use the following syntax:

WITH THISFORMSET.frmForm1.grdGrid1.grcColumn1
 .Width = 5
 .Resizable = .F.
 .ForeColor = RGB(0,0,0)
 .BackColor = RGB(255,255,255)
 .SelectOnEntry = .T.
ENDWITH

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Calling Methods | Event Response


Calling Methods

Once an object has been created, you can call the methods of that object from anywhere in your application.

To call a method

  • Use this syntax:

    Parent.Object.Method

The following statements call methods to display a form and set the focus to a text box:

frsFormSet.frmForm1.Show
frsFormSet.frmForm1.txtGetText1.SetFocus

Methods that return values and are used in expressions must end in open and closed parentheses. For example, the following statement sets the caption of a form to the value returned from the user-defined method GetNewCaption:

Form1.Caption = Form1.GetNewCaption( )
Note Parameters passed to methods must be included in parentheses after the method name; for example, Form1.Show(nStyle). passes nStyle to Form1's Show method code.

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Event Response


Access and Assign Methods

Microsoft Visual FoxPro supports Access and Assign methods. These user-defined methods make it possible for you to execute code when querying the value of a property, or when you attempt to change the property's value.

Visual FoxPro executes the code in an Access method when querying the value of a property, typically by using the property in an object reference, storing the value of the property to a variable, or displaying the value of property with a question mark (?).

Visual FoxPro executes the code in an Assign method when you attempt to change the value of a property, typically by using the STORE or = command to assign a new value to the property.

Visual FoxPro executes Access and Assign methods when querying or changing property values only at run time, not design time.

Note When attempting to assign a value to a property at run time, you must include a PARAMETERS or LPARAMETERS statement in the Assign method to accept the value because Visual FoxPro passes the value to the Assign method.

You can create Access and Assign methods independently of each other, that is, you can create an Access method without an Assign method, or an Assign method without an Access method. You can create Access and Assign methods for properties that are created programmatically within a DEFINE CLASS statement or interactively for a form or class with the Form and Class designers.

Note You can create Access and Assign methods for all native Visual FoxPro properties. For example, you can create an Access method for the Left property of a form, making it possible for you to execute code whenever the form's Left property is queried. You can create an Assign method for a native Visual FoxPro property that is read-only, for example, the ParentClass property. However, the method is never executed.

Visual FoxPro treats Access and Assign methods as Protected at run time, so they cannot be accessed outside of the class definition. However, Visual FoxPro treats these methods in a special way in the Class Designer. Usually, Visual FoxPro marks the Protected method of an object dropped onto a container, for example, a command button dropped onto a form, as read-only and not editable in the designer. However, you can edit the Access and Assign methods of objects in the designer.

Note The Assign method is not supported for the Value property of a control.

Benefits of Access and Assign Methods

Access and Assign methods provide the following benefits:

  • You can create a public interface for a class or object that separates the interface from the implementation.
  • You can easily implement property validation.
  • You can easily protect properties in subclassed ActiveX controls.

THIS_ACCESS Method

The code in a THIS_ACCESS method is executed whenever you attempt to change the value of a member of an object or a member of an object is queried.

A THIS_ACCESS method is created in code within a DEFINE CLASS command, or in the New Method or Edit Properties dialog boxes for .vcx visual class libraries. A THIS_ACCESS method must return an object reference always; otherwise, an error is generated. Typically, the THIS object reference is returned. A THIS_ACCESS method must also include a parameter to accept the name of the member of the object that is changed or queried.

The following simple example demonstrates how to create a THIS_ACCESS method in code within a DEFINE CLASS command. When this example is run as a program, 'Caption' is displayed twice, first when the Caption property is assigned a value, and again when the Caption property value is queried. The value of the Caption property ('abc') is then displayed.

CLEAR
oTempObj = CREATEOBJECT('MyForm')  && Instantiate the Form
oTempObj.Caption = 'abc'  && Assign a value, triggers THIS_ACCESS
? oTempObj.Caption  && Query a value, triggers THIS_ACCESS

DEFINE CLASS MyForm AS Form
   PROCEDURE THIS_ACCESS
      LPARAMETER cMemberName  && Object member name

      IF cMemberName = 'caption'
         ? cMemberName  && Display the object member name
      ENDIF
      RETURN THIS
   ENDPROC
ENDDEFINE

Note that THIS_ACCESS is not intended to be a global replacement for Access and Assign methods - it only provides information about which object member is accessed or queried. Unlike an Access or Assign method, THIS_ACCESS does not provide control over values returned to specific object members.

See Also

Object-Oriented Programming | Classes in Visual FoxPro | Calling Methods | Creating Access and Assign Methods


Creating Access and Assign Methods

Enhancements to the DEFINE CLASS command and the Form and Class designers make it possible for you to create Access and Assign methods both programmatically and interactively. See DEFINE CLASS for details on the access and assign methods additions.

The Form and Class Designers

You can create access and assign methods for new properties by using the New Property item of the Form menu in the Form Designer.

To create an Access or Assign method in the Form Designer

  1. Choose New Property from the Form menu.

    The New Property dialog box is displayed.

  2. Enter the name of the property to create in the Name text box, and then select the Access Method check box or Assign Method check box (or both).
  3. Choose Add to create a property for the form, and to create Access or Assign methods for the property.

You can create access and assign methods for intrinsic properties by using the New Method item of the Form menu in the Form Designer.

To create an Access or Assign method for an intrinsic Visual FoxPro property in the Form Designer

  1. Choose New Method from the Form menu.

    The New Method dialog box is displayed.

  2. Enter the name of the intrinsic property followed with _Access or _Assign in the Name text box. For example, to create an Access method for the Left property, enter Left_Access in the Name text box.
  3. Choose Add to create an Access or Assign methods for the intrinsic property.
    Note In the Form Designer, you can create properties with Access and Assign methods only for a form or formset. To create properties with Access and Assign methods for a control or object, use the Class Designer to create the control or object class. In the Class Designer, add properties with Access and Assign methods to the control or object, and then add the control or object class to the Form in the Form Designer.

You can create an access or assign method for a class by using the New Property item in the Class menu of the Class Designer.

To create an Access or Assign method for a class in the Class designer

  1. Choose New Property from the Class menu.

    The New Property dialog box is displayed.

  2. Enter the name of the property to create in the Name textbox, then select the Access Method check box or Assign Method check box (or both).
  3. Choose Add to create a property for the class, and to create Access or Assign methods for the property.

For more information about creating Access or Assign methods, see the New Property Dialog Box topic.

See Also

Access and Assign Methods | Calling Methods


Procedures and User-Defined Functions

Procedures and functions allow you to keep commonly used code in a single place and call it throughout your application whenever you need it. This makes your code easier to read and easier to maintain because a change can be made once in the procedure rather than multiple times in your programs.

In Visual FoxPro, procedures look like this:

PROCEDURE myproc
  * This is a comment, but it could be executable code
ENDPROC

Traditionally, procedures contain code that you write to perform an operation, and functions do some operations and return a value. In Visual FoxPro, functions are similar to procedures:

FUNCTION myfunc
  * This is a comment, but it could be executable code
ENDFUNC

You can include procedures and functions in a separate program file or at the end of a program file that contains normal program code. You cannot have normal executable program code included in a program file following procedures and functions.

If you include your procedures and functions in a separate program file, you can make these procedures and functions accessible in your program by using the SET PROCEDURE TO command. For example, for a file called FUNPROC.PRG, use this command in the Command window:

SET PROCEDURE TO funproc.prg

Calling a Procedure or Function

There are two ways to call a procedure or function in your programs:

  • Use the DO command. For example:
    DO myproc

    -or-

  • Include a set of parentheses after the function name. For example:
    myfunc( )

Each of these methods can be expanded by sending or receiving values from the procedure or function.

Sending Values to a Procedure or Function

To send values to procedures or functions, you include parameters. The following procedure, for example, accepts a single parameter:

PROCEDURE myproc( cString )
   * The following line displays a message
   MESSAGEBOX ("myproc" + cString)
ENDPROC
Note Including the parameters inside parentheses in a procedure or function definition line, for example, PROCEDURE myproc(cString), indicates that the parameter is scoped locally to the procedure or function. You can also allow a function or procedure to accept locally scoped parameters with LPARAMETERS.

Parameters work identically in a function. To send a value as a parameter to this procedure or to a function, you can use a string or a variable that contains a string, as shown in the following table.

Passing Parameters

Code Comments
DO myproc WITH cTestString
DO myproc WITH "test string"
 Calls a procedure and passes a literal string or character variable.
myfunc("test string")
myfunc( cTestString )
 Calls a function and passes a copy of a character variable or literal string.
Note If you call a procedure or function without using the DO command, the UDFPARMS setting controls how parameters are passed. By default, UDFPARMS is set to VALUE, so copies of the parameters are passed. When you use DO, the actual parameter is used (the parameter is passed by reference), and any changes within the procedure or function are reflected in the original data, regardless of the setting of UDFPARMS.

You can send multiple values to a procedure or function by separating them with commas. For example, the following procedure expects three parameters: a date, a character string, and a number.

PROCEDURE myproc( dDate, cString, nTimesToPrint )
   FOR nCnt = 1 to nTimesToPrint
      ? DTOC(dDate) + " " + cString + " " + STR(nCnt)
   ENDFOR
ENDPROC

You could call this procedure with this line of code:

DO myproc WITH DATE(), "Hello World", 10

Receiving Values from a Function

The default return value is true (.T.), but you can use the RETURN command to return any value. For example, the following function returns a date that is two weeks later than date passed to it as a parameter.

FUNCTION plus2weeks
PARAMETERS dDate
   RETURN dDate + 14
ENDFUNC

The following line of code stores the value returned from this function to a variable:

dDeadLine = plus2weeks(DATE())

The following table lists the ways you can store or display values returned from a function:

Manipulating Return Values

Code Comments
var = myfunc( )
 Stores the value returned by the function to a variable.
? myfunc( )
 Prints the value returned by the function in the active output window.

Verifying Parameters in a Procedure or Function

It's a good idea to verify that the parameters sent to your procedure or function are what you expect to receive. You can use the TYPE( ) and PARAMETERS( ) functions to verify the type and number of parameters sent to your procedure or function.

The example in the previous section, for instance, needs to receive a Date type parameter. You can use the TYPE( ) function to make sure the value your function receives is the right type.

FUNCTION plus2weeks( dDate )
   IF TYPE("dDate") = "D"
      RETURN dDate + 14
   ELSE
      MESSAGEBOX( "You must pass a date!" )
      RETURN { - - }      && Return an empty date
   ENDIF
ENDFUNC

If a procedure expects fewer parameters than it receives, Visual FoxPro generates an error message. For example, if you listed two parameters, but you call the procedure with three parameters, you'll get an error message. But if a procedure expects more parameters than it receives, the additional parameters are simply initialized to false (.F.). Because there is no way to tell whether the last parameter was set to false (.F.) or omitted, the following procedure checks to make sure the appropriate number of parameters was sent:

PROCEDURE SaveValue( cStoreTo, cNewVal, lIsInTable )
   IF PARAMETERS( ) < 3
      MESSAGEBOX( "Too few parameters passed." )
      RETURN .F.
   ENDIF
   IF lIsInTable
      REPLACE (cStoreTo) WITH (cNewVal)
   ELSE
      &cStoreTo = cNewVal
   ENDIF
   RETURN .T.
ENDPROC

Sample Procedure to Return Numeric Characters from a String

Code Comments
FUNCTION NumbersOnly( cMixedVal )
 Start of the function, which accepts a character string.
  cNumOnly = ""
  FOR nCnt = 1 TO LEN(cMixedVal)
   cCharacter = ;
  SUBSTR(cMixedVal, nCnt, 1)
    IF ISDIGIT(cCharacter)
       cNumOnly = ;
   cNumOnly + cCharacter
    ENDIF
   ENDFOR
 Create a string that has only the numeric characters from the original string.
RETURN cNumOnly
 Return the string that has only numeric characters.
ENDFUNC
 End of the function.

In addition to allowing you to use this code in multiple situations, this function makes the program easier to read:

SCAN
   REPLACE FieldName WITH NumbersOnly(FieldName)
ENDSCAN

Or, even more simply:

REPLACE ALL FieldName WITH NumbersOnly(FieldName)

See Also

Character Functions | Basic Programming Concepts | Running Code Manually | Creating Programs | TYPE( ) | PARAMETERS( ) | RETURN


Understanding the Event Model

Microsoft Visual FoxPro provides true modeless operation, so you can coordinate multiple forms automatically and run multiple instances of a form simultaneously. Visual FoxPro also manages event processing for you, so you can give users a much richer interactive environment.

In This Section

Events in Visual FoxPro
Describes what events are in Microsoft Visual FoxPro and provides a table containing the core set of Visual FoxPro events.
Tracking Event Sequences
Explains how to turn on event tracking and provides an example form to illustrate how event order is dependent on user interaction.
Assigning Code to Events
Provides helpful hints on how to place code based on the sequence of events.

Related Sections

Programming in Visual FoxPro
Microsoft Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Object-Oriented Programming
With object-oriented programming, you can create self-contained application components that respond to user actions and to the system and which can be easily maintained and reused.
Writing Class Definitions Programmatically
You can define classes visually in the Class Designer and the Form Designer or programmatically in .PRG files.


Event Response

The code you include in an event procedure is executed when the event takes place. For example, the code you include in the Click event procedure of a command button is executed when the user clicks the command button.

You can programmatically cause Click Event, DblClick Event, MouseMove Event, and DragDrop Event events with the MOUSE Event command, or use the ERROR command to generate Error events and the KEYBOARD command to generate KeyPress events. You cannot programmatically cause any other events to occur, but you can call the procedure associated with the event. For example, the following statement causes the code in the Activate event of frmPhoneLog to be executed, but it doesn't activate the form:

frmPhoneLog.Activate

If you do want to activate the form, use the Show method of the form. Calling the Show method causes the form to be displayed and activated, at which point the code in the Activate event is also executed:

frmPhoneLog.Show

See Also

Object-Oriented Programming | Classes and Objects: The Building Blocks of Applications | Classes in Visual FoxPro | Preparation for Class Creation | Creating Classes | Modifying a Class Definition | Subclassing a Class Definition | Operating the Class Designer | Class Member Protection and Hiding | Specifying Design-Time Appearance for a Class | Creating, Copying, and Removing Class Library Files | Adding Classes to Forms | Default Property Setting Override | Container Hierarchy Object Referencing | Setting Properties | Calling Methods


Events in Visual FoxPro

Event code is triggered automatically by the system in response to some user action. For example, code written for the Click event is automatically processed by the system when the user clicks on a control. Event code can also be triggered by system events, as in the case of the Timer event in a timer control.

The Core Events

The following table contains a list of the core set of Visual FoxPro events, which apply to most controls.

Core Event Set

Event | When the event is triggered
Init | An object is created.
Destroy | An object is released from memory.
Click | The user clicks the object using the primary mouse button.
DblClick | The user double-clicks the object using the primary mouse button.
RightClick | The user clicks the object using the secondary mouse button.
GotFocus | The object receives the focus, either by user action such as tabbing or clicking, or by changing the focus in code using the SetFocus method.
LostFocus | The object loses the focus, either by user action such as tabbing to or clicking another object, or by changing the focus in code using the SetFocus method.
KeyPress | The user presses and releases a key.
MouseDown | The user presses the mouse button while the mouse pointer is over the object.
MouseMove | The user moves the mouse over the object.
MouseUp | The user releases the mouse button while the mouse pointer is over the object.

Containers and Object Events

There are two basic rules to keep in mind when you are writing event code for controls:

  • Containers do not process events associated with the controls they contain.
  • If no event code is associated with a control, Visual FoxPro checks to see if there is code associated with the event higher up the class hierarchy for the control.

When a user interacts with an object in any way — by tabbing to it, clicking it, moving the mouse pointer over it, and so on — object events take place. Each object receives its events independently. For example, even though a command button is on a form, the form's Click event is not triggered when a user clicks the command button; only the command button's Click event is triggered.

If there is no Click event code associated with the command button, nothing happens when the user clicks the button, even though there is Click event code associated with the form.

This rule is also true of grid controls. The grid contains columns, which in turn contain headers and controls. When events occur, only the innermost object involved in the event recognizes the event. The higher-level containers do not recognize the event.

There is an exception to this rule, however. If you have written event code for an option button group or a command button group but there is no code for the event in a particular button in the group, the group event code is executed when the button event occurs.

Note When a sequence of events, such as MouseDown then MouseUp, is initiated for a control, the whole sequence of events belongs to the control. For example, if you click the left mouse button on a command button and drag the mouse pointer away from the command button, the command button's MouseMove events continue to occur, even though the mouse pointer is moving over the form. If you release the left mouse button over the form instead of over the command button, the MouseUp event that occurs is associated with the command button rather than the form.

Classes and Control Events

If a control on a form is based on a user-defined class (which, in turn, could be based on another user-defined class), Visual FoxPro checks in the immediate control for event code when an event occurs. If there is code in that event procedure, Visual FoxPro executes it. If no code exists in the event procedure, Visual FoxPro checks the next level up in the class hierarchy. If at any point in the class hierarchy Visual FoxPro finds code for the event, that code is executed. Any code further up the hierarchy is not executed.

You can, however, include code in an event procedure and explicitly call the code in classes that the control is based on by using the DODEFAULT( ) function.

See Also

Understanding the Event Model | Tracking Event Sequences | Assigning Code to Events | SetFocus method


Tracking Event Sequences

The Visual FoxPro event model is extensive, allowing you a great deal of control over the components of your application in response to a wide variety of user actions. Some of the event sequences are fixed, as for example, when a form is created or destroyed. Some events occur independently, but most occur in conjunction with several other events based on user interaction.

Setting Event Tracking On

The best way to see the Visual FoxPro event sequences is to set event tracking on in the debugger. Event tracking allows you to see when each event associated with your own forms and controls occurs in relation to other events, so that you can determine the most efficient place to include your code.

To set event tracking on

  1. From the Tools menu in the Debugger window, choose Event Tracking.
  2. In the Event Tracking dialog box, select Turn event tracking on.

The events in the Events to track list are written to the Debugger Output window or a file as they occur.

Note In this example, the MouseMove and Paint events have been removed from the Events to track list because these events occur so frequently that they make it more difficult to see the sequences of the other events.

Watching Events Occur

Sometimes a single event is triggered by a user action, such as the user moving the mouse pointer over a control. Often, however, a user action triggers multiple events.

This section describes the order in which events occur in response to user interaction, using the following form as an example.

A sample form to illustrate event sequences

In this example scenario, the user performs the following actions on the form:

  1. Runs the form.
  2. Types text in Text1.
  3. Selects the field, and copies it to the clipboard.
  4. Moves to Text2.
  5. Pastes the text into Text2.
  6. Closes the form by clicking Command2.

These actions trigger one or more system events for each object. The following tables detail the events triggered in response to each user action.

Action 1

The user runs the form by typing the following command in the Command window:

DO FORM form1 NAME frmObject

Visual FoxPro loads the form, initializes each object, then initializes the form; the form is activated and then the first field receives input focus.

Object | Event
DataEnvironment | BeforeOpenTables
Form1 | Load
DataEnvironment | Init
Text1 | Init
Text2 | Init
Command1 | Init
Command2 | Init
Form1 | Init
Form1 | Activate
Form1 | GotFocus
Text1 | When
Text1 | GotFocus

Action 2

The user types Test in Text1. Each keystroke generates two events. The KeyPress event receives 2 parameters: the pressed key and the state of the SHIFT, ALT, and CTRL keys.

Object | Event
Text1 | KeyPress(84, 1) "T"
Text1 | InteractiveChange
Text1 | KeyPress(101, 0) "e"
Text1 | InteractiveChange
Text1 | KeyPress(115,0) "s"
Text1 | InteractiveChange
Text1 | KeyPress(116,0) "t"
Text1 | InteractiveChange

Action 3

The user double-clicks Text1 to select the text, then presses CTRL+C to copy the text to the Clipboard. Mouse events and a Click event accompany the DblClick event. The MouseMove and MouseDown events receive four parameters: a number indicating which button was pressed, the Shift state, and X and Y locations. The X and Y locations are relative to the form and reflect the scale mode (for example, pixels) of the form. Only one MouseMove event is listed for each control. In actuality, this event would probably fire half a dozen times or more.

Object | Event
Form1 | MouseMove(0, 0, 100, 35)
Text1 | MouseMove(0,0,44,22)
Text1 | MouseDown(1, 0, 44, 22)
Text1 | MouseUp(1, 0, 44, 22)
Text1 | Click
Text1 | MouseDown(1, 0, 44, 22)
Text1 | MouseUp(1, 0, 44, 22)
Text1 | DblClick

Action 4

The user presses TAB to move to Text2.

Object | Event
Text1 | KeyPress(9, 0)
Text1 | Valid
Text1 | LostFocus
Text2 | When
Text2 | GotFocus

Action 5

The user pastes the copied text into Text2 by pressing CTRL+V.

Object | Event
Text2 | InteractiveChange

Action 6

The user clicks Command2, which closes the form.

Object | Event
Form1 | MouseMove
Command2 | MouseMove
Text2 | Valid
Command2 | When
Text2 | LostFocus
Command2 | GotFocus
Command2 | MouseDown(1, 0, 143, 128)
Command2 | MouseUp(1, 0, 143, 128)
Command2 | Click
Command2 | Valid
Command2 | When

As the form closes and the object is released, these additional events take place, in opposite order to the events in Action 1.

Object | Event
Form1 | Destroy
Command2 | Destroy
Command1 | Destroy
Text2 | Destroy
Text1 | Destroy
Form1 | Unload
DataEnvironment | AfterCloseTables
DataEnvironment | Destroy

The Visual FoxPro Event Sequence

The following table shows the general firing sequence of Visual FoxPro events. The data environment's AutoOpenTables property is assumed to be set to true (.T.). Other events can occur based on user interaction and system response.

Object | Events
Data environment | BeforeOpenTables
Form set | Load
Form | Load
Data environment cursor(s) | Init
Data environment | Init
Objects 1 | Init
Form | Init
Form set | Init
Form set | Activate
Form | Activate
Object1 2 | When
Form | GotFocus
Object1 | GotFocus
Object1 | Message
Object1 | Valid 3
Object1 | LostFocus
Object2 3 | When
Object2 | GotFocus
Object2 | Message
Object2 | Valid 4
Object2 | LostFocus
Form | QueryUnload
Form | Destroy
Object 5 | Destroy
Form | Unload
Form set | Unload
Data environment | AfterCloseTables
Data environment | Destroy
Data environment cursor(s) | Destroy

1. For each object, from innermost object to outermost container
2. First object in the tab order
3. Next object to get focus
4. As the object loses focus
5. For each object, from outermost container to innermost object

See Also

Events in Visual FoxPro | Assigning Code to Events | Debugger | Command | KeyPress event | Click event | DblClick event | MouseMove | MouseDown | AutoOpenTables property | Understanding the Event Model


Assigning Code to Events

Unless you associate code with an event, nothing happens when that event occurs. You'll almost never write code for all of the events associated with any Visual FoxPro object, but you'll want to incorporate functionality in response to certain key events in your applications. To add code to be executed when an event occurs, use the Properties window in the Form Designer.

The sequence of events affects where you should put code. Keep in mind the following tips:

  • The Init events of all the controls on a form execute before the Init event of the form, so you can include code in the Init event of the form to manipulate any of the controls on the form before the form is displayed.
  • If you want some code to be processed whenever the value of a list box, combo box, or check box changes, associate it with the InteractiveChange event. The Click event might not occur or might be called even if the value hasn't changed.
  • When you are dragging a control, the other mouse events are suspended. For example, the MouseUp and MouseMove events do not occur during a drag-and-drop operation.
  • The Valid and When events return a value. True (.T.) is the default. If you return false (.F.) or 0 from the When event, the control cannot get the focus. If you return false (.F.) or 0 from the Valid event, the focus cannot leave the control.

For more information about using the Form Designer, see Creating Forms. For information on coding classes and adding event code, see Object-Oriented Programming.

See Also

Tracking Event Sequences | Events in Visual FoxPro | Assigning Code to Events | Understanding the Event Model


Event Binding for Objects

You can use event binding when you want to attach a Visual FoxPro object to an event, method, or property from another Visual FoxPro object or an event from a Component Object Model (COM) object, both of which can act as event sources. However, the approach for binding events from native and COM objects differs.

In This Section

Event Binding for Visual FoxPro Objects
Discusses binding events, methods, and properties from other native Visual FoxPro objects to Visual FoxPro objects.
Event Binding for COM Objects
Discusses binding events from COM objects to Visual FoxPro objects.

Related Sections

What's New in Visual FoxPro 8.0
Describes new features and enhancements for this version of Visual FoxPro.
General Reference
Includes technical Visual FoxPro information such as file types, file structures, and other reference information about Visual FoxPro elements.


Event Binding for Visual FoxPro Objects

You can use event binding to trigger events, properties, or methods of native Visual FoxPro objects from other Visual FoxPro objects using the following functions:

  • BINDEVENT( )

    Associates an event from a native Visual FoxPro object with the method or event of another Visual FoxPro object.

  • UNBINDEVENTS( )

    Detaches events previously bound to Visual FoxPro objects.

  • RAISEEVENT( )

    Raises, or triggers, events for user-defined custom methods. You can also use RAISEEVENT( ) for native events and methods.

  • AEVENTS( )

    Retrieves information about the number of existing event bindings.

To bind events from Component Object Model (COM) objects, see Event Binding for COM Objects and EVENTHANDLER( ) Function.

Binding an Event

You can use the BINDEVENT( ) function to attach, or bind, an event, method, or property from one Visual FoxPro object, or event source, to the method or event of another Visual FoxPro object, or the event handler. The method that handles the event acts as a "delegate" for the event handler.

You can bind to any valid Visual FoxPro object method or event, including the Access and Assign methods. However, both the event source and event handler must be valid Visual FoxPro objects. You cannot use COM objects or bind to methods of objects in collections referenced by the _VFP system variable because these collections also pass through COM.

Note When you specify objects for event binding, make sure they are fully instantiated. Do not bind events, methods, or properties to an object in its Load or Init event because the object might not yet be fully instantiated and can cause the binding operation to fail.

You can use the same object as both the event source and event handler. The following example shows how Form1 acts as both source and handler:

BINDEVENT( Form1, "Resize", Form1, "myresize1" )

You can use different objects from the same class as the event source and handler. However, the event of an object that is used as both the event source and handler cannot be the same as the delegate method.

You can bind multiple event handlers to the same event source and event in an act referred to as "multi-casting." If multiple handlers exist for the same event, events occur in first in, first out (FIFO) order.

You can bind multiple delegate methods from an event handler to a particular event source and event. For example:

BINDEVENT( Form1, "Resize", oHandler, "myresize1" )
BINDEVENT( Form1, "Resize", oHandler, "myresize2" )

You cannot bind to an event with parameters that are passed by reference. Though calling BINDEVENT( ) succeeds, raising the event, for example, using RAISEEVENT( ), fails.

Visual FoxPro does not support event binding in designers such as the form and class designers, even though you can obtain object references using the ASELOBJ( ) or SYS(1270) functions.

For more information, see BINDEVENT( ) Function, ASELOBJ( ) Function, and SYS(1270) - Object Location.

Unbinding an Event

You can use the UNBINDEVENTS( ) function to detach events, methods, and properties that were bound using the BINDEVENT( ) function from native Visual FoxPro objects. UNBINDEVENTS( ) returns the number of events that it unbinds if it succeeds. You can specify a Visual FoxPro object event source or an object reference, which can be used as the event source or event handler.

For more information, see UNBINDEVENTS( ) Function.

Raising an Event

You can use the RAISEEVENT( ) function to raise, or trigger, events for custom and native methods. Directly calling methods does not make events occur, unless you set the appropriate flags when using BINDEVENT( ) to attach events to other objects. Therefore, you need RAISEEVENT( ) to trigger these events.

For more information, see RAISEEVENT( ) Function.

Retrieving Event Binding Information

You can use the AEVENTS( ) function to retrieve the number of Visual FoxPro events that are currently bound to Visual FoxPro objects. Visual FoxPro stores the information in an array. Depending on the parameters you pass, AEVENTS( ) returns either a single-element array containing an object reference to the event source or an array which represents each existing event binding as a row and contains information about the binding across five columns.

For more information, see AEVENTS( ) Function.

See Also

Event Binding for Objects


Event Binding for COM Objects

You can bind events from Component Object Model (COM) objects to a Visual FoxPro object by using the EVENTHANDLER( ) function. For example, by binding an event from an ActiveX Data Object (ADO) recordset, you can run Visual FoxPro code when the record pointer moves around in the recordset. The EVENTHANDLER( ) function specifically handles binding events raised by COM objects and by the IConnectionPoint interface, which is part of COM.

However, Visual FoxPro does not support the raising events through the IConnectionPoint interface directly. In order to bind a COM event to a Visual FoxPro object, the object must implement the event interface of the COM object, an action referred to as tightly-coupled event handling, where both the event source and event sink objects are live when the event occurs. Event sinks are clients that bind to a connectable object because they receive events triggered by the connectable object.

Instead, COM+ Events, part of COM+ Services, provides the preferred strategy for handling events between COM components. COM+ Events sends and delivers event notifications between applications. Applications can send and receive notifications of events, such as the hiring of a new employee, a change in a stock price, or a drop in inventory level that requires restocking.

In the COM+ Events model, applications that send out event notifications act as event sources and are called publishers. Applications that receive event notifications are called subscribers. COM+ Events are often called loosely coupled events because publishers and subscribers do not possess any knowledge about each other and allow event subscribers to remain inactive until events occur. Instead, you define a set of events inside the scope of an event class, and this event class is installed in a COM+ application.

To use COM+ Events, you author an event class that implements one or more interfaces. Each interface defines a group of methods, which represents a set of events. You write subscriber components that implement these interfaces and respond to events when they occur. Finally, you write a publisher application to create objects from the event class and call various methods when the application is ready to fire events. The event service handles processing the method and delivering the events to every subscriber.

See Also

Event Binding for Objects | Event Binding for Visual FoxPro Objects | EVENTHANDLER( ) Function


Optimizing Applications

When you use Visual FoxPro to design and run applications, you want to get the best performance from your operating system, from Visual FoxPro, and from your application.

In This Section

Optimization of Tables and Indexes
Describes how you can speed access to data in tables by using indexes and by using buffering efficiently. In addition, you can use Rushmore Query Optimization technology to optimize your queries.
Using Rushmore Query Optimization to Speed Data Access
Explains that Visual FoxPro includes Rushmore data access technology to help you optimize the performance of your applications.
Optimizing Forms and Controls
Describes how you can make significant improvements in the forms and controls in your application.
Optimization of Programs
Discusses how you can write the fastest possible programs by writing your code carefully.
Optimization of ActiveX Controls
Explains that if you use Automation or Microsoft ActiveX controls in your application, you can fine-tune the application to get the best performance out of both ActiveX controls and automation.
Optimizing Applications in Multiuser Environments
Discusses the importance of performance when you are writing applications for a multiuser environment in which inefficiencies would be multiplied.
Optimizing Access to Remote Data
Describes the expense of data retrieval from any remote database.
Optimization of International Applications
Explains that if you are developing international applications, you might want to manage the collating sequence of your data for optimal performance.

Related Sections

Programming in Visual FoxPro
Describes how you can access the full power of Visual FoxPro by using object-oriented programming techniques and the event-driven model when creating applications.
Creating Programs
Explains the two ways to create a Visual FoxPro program.
Object-Oriented Programming
Describes how you can use object-oriented programming to create self-contained application components that respond to user actions and to the system and which can be easily maintained and reused.
Accessing APIs
Describes how to extend Visual FoxPro if your application has requirements that cannot be met by built in Visual FoxPro features by taking advantage of external libraries such as Microsoft® ActiveX® controls or dynamic-link libraries (DLLs).


Optimization of Tables and Indexes

You can speed access to data in tables by using indexes and by using buffering efficiently. In addition, you can use Rushmore Query Optimization technology to optimize your queries.

Using Indexes

To speed up access to data in a table, use an index. Adding an index to a table speeds up searches, especially if you're able to use Rushmore technology to optimize your search. Indexing also allows you to work with data in a particular order, such as viewing a customer table in order by last name.

If the records in a table have unique keys, create a primary or candidate index on the field. These types of indexes allow Visual FoxPro to validate the key at a low level, resulting in best performance.

In addition to indexing fields used for searching and sorting, you should also index any fields involved in a join. If you join two tables on fields that are not indexed, the join operation can take as much as hundreds of times longer.

An important feature of Visual FoxPro is that you can create an index on any expression. (In some database products, you can index only on fields.) This capability allows you to use indexes to optimize searching, sorting, or joining on combinations of fields, or on expressions derived from fields. For example, you can index a name field based on an expression that uses the SOUNDEX( ) function. That way, your application can provide extremely quick access to names that sound alike.

When adding indexes to your tables, you must balance the benefit you get in retrieval times against a performance loss when updating the table. As you add more indexes to your table, updates and inserts to the table are slower because Visual FoxPro needs to update each index.

Finally, avoid using indexes on fields that contain only a few discrete values, such as a logical field. In these cases, the index contains only a small number of entries, and the overhead of maintaining the index probably outweighs the benefit it provides when searching.

For details about how to index effectively when using Rushmore technology, see Using Rushmore Query Optimization to Speed Data Access.

Optimizing Joins

When you create joins using SELECT - SQL, the following situations can degrade performance and produce unexpected results:

  • Joining tables on data that is not a primary or unique key in one of the tables.
  • Joining tables containing empty fields.

To avoid these situations, create joins based on the relationship between primary keys in one table and foreign keys in the other. If you create a join based on data that is not unique, the end result can be the product of two tables. For example, the following SELECT - SQL statement creates a join, which can produce a very large result:

SELECT *;
 FROM  tastrade!customer INNER JOIN tastrade!orders ;
 ON  Customer.postal_code = Orders.postal_code

In the example, postal code uniquely identifies a location within a city, but has little value if your intent is to match customer rows and their order rows. The postal code doesn't necessarily uniquely identify a customer or an order. Instead, create a join using a statement such as the following:

SELECT *;
 FROM  tastrade!customer INNER JOIN tastrade!orders ;
 ON  Customer.customer_id = Orders.customer_id

In this example, the field customer_id uniquely identifies a specific customer and the orders belonging to that customer, and therefore creates a result set that combines the customer row with each order row.

In addition, use caution when joining tables with empty fields because Visual FoxPro will match empty fields. However, Visual FoxPro doesn't match fields containing null. When creating a join, qualify the field expressions in the join condition by testing for an empty string.

For example, if you think that the customer id field in the Orders table might be empty, use a statement such as the following to filter out order records with no customer number:

SELECT *;
 FROM  tastrade!customer INNER JOIN tastrade!orders ;
 ON  Customer.customer_id = Orders.customer_id;
 WHERE tastrade!orders <> ""
Tip You can also test for an empty string using the EMPTY( ) function, but including a function call within the filter expression is not as fast as comparing to a constant value.

Using the Project Manager

When you use the Project Manager, you can combine an unlimited number of programs and procedures into a single .app or .exe file. This can greatly increase program execution speed for a couple of reasons.

First, Visual FoxPro opens a program file and leaves it open. Later, when you issue a DO command on a program contained in the file, Visual FoxPro doesn't need to open an additional file.

Second, an application of only one or two files reduces the number of files necessary in the working directory. The speed of all file operations increases as the operating system has fewer directory entries to examine when opening, renaming, or deleting files.

For information on using the Project Manager to create applications, see Compiling an Application.

General Table and Index Optimization Hints

To create the fastest possible tables and indexes, follow the recommendations listed below.

  • If record or table buffering is not enabled, use INSERT - SQL instead of APPEND BLANK followed by REPLACE, particularly with an indexed table in a multiuser environment, because indexes only need to be updated once.
  • If you need to append a large number of records to an indexed table, it might be faster to remove the index, append the records, and then re-create the index.
  • In SQL statements, avoid function calls if possible, especially in statements that will return more than one record, because the statement must be reevaluated (and the functions called again) for each record. If you are creating a SQL statement with variable data, use name expressions or macro substitution in favor of the EVALUATE( ) function. A better strategy yet is to construct the entire statement dynamically, not just individual clauses. For more information, see Using Macros and Creating Name Expressions.
  • If you usually use a certain index order, you can improve performance by periodically sorting the table in this order.
  • Use .cdx instead of .idx files in multiuser environments because you can update one .cdx file faster than you can update multiple .idx files.

See Also

Optimizing Applications | Optimizing Your System | Using Rushmore Query Optimization to Speed Data Access | Optimizing Forms and Controls | Optimization of Programs


Using Rushmore Query Optimization to Speed Data Access

To help you optimize the performance of your applications, Visual FoxPro includes Rushmore Query Optimization data access technology. Using Rushmore technology, you can run certain complex table operations hundreds or even thousands of times faster than without it.

Understanding Rushmore Query Optimization Technology

Rushmore Query Optimization technology is a data access technique that uses standard Visual FoxPro indexes to optimize access to data. You can use Rushmore with any Visual FoxPro index, including FoxPro 1.x (.idx) indexes, compact (.idx) indexes, and compound (.cdx) indexes.

Both .cdx and compact .idx indexes use a compression technique that produces indexes as small as one-sixth the size of uncompressed old-format indexes. Visual FoxPro can process a compressed index faster because it requires less disk access, and because more of the index can be buffered in memory. Although Rushmore Query Optimization, like other file access techniques, benefits from the smaller size of compact indexes, it also functions very well with indexes in older formats.

When Visual FoxPro processes very large tables on computers with only the minimum amount of RAM, Rushmore might not find sufficient memory to operate. In that case, Visual FoxPro might display a warning message ("Not enough memory for optimization"). Although your program will function correctly and without losing any data, the query will not benefit from Rushmore optimization.

In its simplest form, Rushmore speeds the performance of single-table commands using FOR clauses that specify sets of records in terms of existing indexes. Also, Rushmore can speed the operation of certain commands such as LOCATE and INDEX. For a complete list of optimizable commands, see the next section, "Using Rushmore Query Optimization with Tables."

Visual FoxPro SQL commands use Rushmore as a basic tool in multi-table query optimization, using existing indexes and even creating new ad-hoc indexes to speed queries.

Using Rushmore Query Optimization with Tables

Use Rushmore to optimize data access according to the number of tables involved. When you access single tables, you can take advantage of Rushmore anywhere that a FOR clause appears. When you access multiple tables, SELECT - SQL queries supersede all Rushmore optimizations. In an SQL command, Visual FoxPro decides what is needed to optimize a query and does the work for you. You don't need to open tables or indexes. If SQL decides it needs indexes, it creates temporary indexes for its own use.

To use Rushmore Query Optimization

Choose one of the following options:

  • To access data from a single table, use a FOR clause in a command such as AVERAGE, BROWSE, or LOCATE, or use SQL commands to update tables. For a complete list of commands that use the FOR clause, refer to the table below.

    -or-

  • To access data from more than one table, use the SELECT - SQL DELETE - SQL, and UPDATE - SQL commands.

The following table lists commands that use FOR clauses. Rushmore is designed so that its speed is proportional to the number of records retrieved.

Potentially Optimizable Commands with FOR Clauses

AVERAGE | BLANK
BROWSE | CALCULATE
CHANGE | COPY TO
COPY TO ARRAY | COUNT
DELETE | DISPLAY
EDIT | EXPORT TO
INDEX | JOIN WITH
LABEL | LIST
LOCATE | RECALL
REPLACE | REPLACE FROM ARRAY
REPORT | SCAN
SET DELETED | SET FILTER
SORT TO | SUM
TOTAL TO |

If you use a scope clause in addition to an optimizable FOR clause expression, the scope must be set to ALL or REST to take advantage of Rushmore. The NEXT or RECORD scope clauses disable Rushmore. Because the default scope is ALL for most commands, Rushmore works when you omit the scope clause.

Rushmore can use any open indexes except for filtered and UNIQUE indexes.

Note For optimal performance, don't set the order of the table.

Creating index or tags automatically sets the order. If you want to take maximum advantage of Rushmore with a large data set that must be in a specific order, issue SET ORDER TO to turn off index control, then use the SORT command.

Indexing Effectively for Rushmore Query Optimization

Rushmore cannot take advantage of all indexes. If you use a FOR clause in the INDEX command, Rushmore cannot use the index for optimization. For example, because it contains a FOR clause, the following statement cannot be optimized:

INDEX ON ORDNUM FOR DISCOUNT > 10 TAG ORDDISC

Similarly, Rushmore cannot use an index created with a NOT condition. For example, the following expression can be optimized:

INDEX ON DELETED() TAG DEL

But this one cannot:

INDEX ON NOT DELETED() TAG NOTDEL
  • In the special case that you want to exclude delete records from a query, using an index, as in the first example earlier, will speed up operations when you've set SET DELETED to ON.

Operating Without Rushmore Query Optimization

Data retrieval operations proceed without Rushmore optimization in the following situations:

  • When Rushmore cannot optimize the FOR clause expressions in a potentially optimizable command.
  • When a command that might benefit from Rushmore contains a WHILE clause.
  • When memory is low. Data retrieval continues, but is not optimized.

Disabling Rushmore Query Optimization

Though you rarely want to, you can disable Rushmore. When you issue a command that uses Rushmore, Visual FoxPro immediately determines which records match the FOR clause expression. These records are then manipulated by the command.

If a potentially optimizable command modifies the index key in the FOR clause, the recordset on which Rushmore is operating can become outdated. In this case, you can disable Rushmore to ensure that you have the most current information from the table.

To disable Rushmore for an individual command

  • Use the NOOPTIMIZE clause.

    For example, this LOCATE command is not optimized:

    LOCATE FOR DueDate < {^1998-01-01} NOOPTIMIZE

You can globally disable or enable Rushmore for all commands that benefit from Rushmore, with the SET OPTIMIZE command.

To disable Rushmore globally

  • Use the following code:
    SET OPTIMIZE OFF

To enable Rushmore globally

  • Use the following code:
    SET OPTIMIZE ON

The default setting of Rushmore optimization is ON.

Optimizing Rushmore Expressions

Rushmore technology depends on the presence of a basic optimizable expression in a FOR clause or in an SQL WHERE clause. A basic optimizable expression can form an entire expression or can appear as part of an expression. You can also combine basic expressions to form a complex optimizable expression.

Creating Basic Optimizable Expressions

A basic optimizable expression takes one of the two following forms:

eIndex relOp eExp

-or-

eExpr relOp eIndex

A basic optimizable expression has the following characteristics:

  • eIndex exactly matches the expression on which an index is constructed.
  • eExpr is any expression and can include variables and fields from other unrelated tables.
  • relOp is one of the following relational operators: <, >, =, <=, >=, <>, #, ==, or !=. You can also use the ISNULL( ), BETWEEN( ), or INLIST( ) functions (or their SQL equivalents such as IS NULL, and so on).

You can use BETWEEN( ) or INLIST( ) in the following two forms:

BETWEEN(eIndex, eExpr, eExpr)

-or-

INLIST(eIndex, eExpr [, eExpr, eExpr, ...])
Note ISBLANK( ) and EMPTY( ) are not optimizable by Rushmore.

If you create the indexes firstname, custno, UPPER(lastname), and hiredate, each of the following expressions is optimizable:

firstname = "Fred"
custno >= 1000
UPPER(lastname) = "SMITH"
hiredate < {^1997-12-30}

An optimizable expression can contain variables and functions that evaluate to a specific value. For example, using the index addr, if you issue the command STORE "WASHINGTON AVENUE" TO cVar, then the following statements are also basic optimizable expressions:

ADDR = cVar
ADDR = SUBSTR(cVar,8,3)

Understanding When Queries Are Optimized

It is important to understand when queries will be optimized and when they will not. Visual FoxPro optimizes search conditions by looking for an exact match between the left side of a filter expression and an index key expression. Therefore, Rushmore can optimize an expression only if you search against the exact expression used in an index.

For example, imagine that you've just created a table and are adding the first index using a command such as the following:

USE CUSTOMERS
INDEX ON UPPER(cu_name) TAG name

The following command is not optimizable, because the search condition is based on the field cu_name only, not on an expression that is indexed:

SELECT * FROM customers WHERE cu_name ="ACME"

Instead, you should create an optimizable expression using a command such as the following, in which the expression for which you are searching exactly matches an indexed expression:

SELECT * FROM customers WHERE UPPER(cu_name) = "ACME"
Tip To determine the level of Rushmore optimization being used, call SYS(3054).

Combining Basic Optimizable Expressions

You can combine simple or complex expressions based on the FOR clause or WHERE clause to increase data retrieval speed, if the FOR expressions have the characteristics of basic optimizable expressions.

Basic expressions might be optimizable. You can combine basic expressions using the AND, OR, and NOT logical operators to form a complex FOR clause expression that might also be optimizable. An expression created with a combination of optimizable basic expressions is fully optimizable. If one or more of the basic expressions are not optimizable, the complex expression might be partially optimizable or not optimizable at all.

A set of rules determines if an expression composed of basic optimizable or non-optimizable expressions is fully optimizable, partially optimizable, or not optimizable. The following table summarizes Rushmore query optimization rules.

Combining Basic Expressions

Basic Expression | Operator | Basic Expression | Query Result
Optimizable | AND | Optimizable | Fully Optimizable
Optimizable | OR | Optimizable | Fully Optimizable
Optimizable | AND | Not Optimizable | Partially Optimizable
Optimizable | OR | Not Optimizable | Not Optimizable
Not Optimizable | AND | Not Optimizable | Not Optimizable
Not Optimizable | OR | Not Optimizable | Not Optimizable
— | NOT | Optimizable | Fully Optimizable
— | NOT | Not Optimizable | Not Optimizable

You can use the AND operator to combine two optimizable expressions into one fully optimizable expression:

FIRSTNAME = "FRED" AND HIREDATE < {^1997-12-30}      && Optimizable

In this example, the OR operator combines a basic optimizable expression with an expression that is not optimizable to create an expression that is not optimizable:

FIRSTNAME = "FRED" OR "S" $ LASTNAME      && Not optimizable

Using the NOT operator on an optimizable expression creates a fully optimizable expression:

NOT FIRSTNAME = "FRED"      && Fully optimizable

You can also use parentheses to group combinations of basic expressions.

Combining Complex Expressions

Just as you can combine basic expressions, you can combine complex expressions to create a more complex expression that is fully optimizable, partially optimizable, or not optimizable. You can then combine these more complex expressions to create expressions that again might be fully or partially optimizable, or not optimizable at all. The following table describes the results of combining these complex expressions. These rules also apply to expressions grouped with parentheses.

Combining Complex Expressions

Expression | Operator | Expression | Result
Fully Optimizable | AND | Fully Optimizable | Fully Optimizable
Fully Optimizable | OR | Fully Optimizable | Fully Optimizable
Fully Optimizable | AND | Partially Optimizable | Partially Optimizable
Fully Optimizable | OR | Partially Optimizable | Partially Optimizable
Fully Optimizable | AND | Not Optimizable | Partially Optimizable
Fully Optimizable | OR | Not Optimizable | Not Optimizable
— | NOT | Fully Optimizable | Fully Optimizable
Partially Optimizable | AND | Partially Optimizable | Partially Optimizable
Partially Optimizable | OR | Partially Optimizable | Partially Optimizable
Partially Optimizable | AND | Not Optimizable | Partially Optimizable
Partially Optimizable | OR | Not Optimizable | Not Optimizable
— | NOT | Partially Optimizable | Not Optimizable
Not Optimizable | AND | Not Optimizable | Not Optimizable
Not Optimizable | OR | Not Optimizable | Not Optimizable
— | NOT | Not Optimizable | Not Optimizable

You can combine fully optimizable expressions with the OR operator to create one expression that is also fully optimizable:

* Fully-optimizable expression
(FIRSTNAME = "FRED" AND HIREDATE < {^1997-12-30}) ;
   OR (LASTNAME = "" AND HIREDATE > {^1996-12-30})

To create partially optimizable expressions, combine a fully optimizable expression with an expression that is not optimizable. In the following example, the AND operator is used to combine the expressions:

* Partially-optimizable expression
(FIRSTNAME = "FRED" AND HIREDATE < {^1997-12-30}) ;
   AND "S" $ LASTNAME

Partially optimizable expressions can be combined to create one expression that is also partially optimizable:

* Partially-optimizable expression
(FIRSTNAME = "FRED" AND "S" $ LASTNAME) ;
   OR (FIRSTNAME = "DAVE" AND "T" $ LASTNAME)

Combining expressions that are not optimizable creates an expression that is also not optimizable:

* Expression that is not optimizable
("FRED" $ FIRSTNAME OR "S" $ LASTNAME) ;
   OR ("MAIN" $ STREET OR "AVE" $ STREET)

See Also

Optimization of Tables and Indexes | Optimizing Forms and Controls | Optimizing Applications | Optimizing Your System | LOCATE | INDEX


Optimizing Forms and Controls

You can also make significant improvements in the forms and controls in your application.

Using the Data Environment

If you use the data environment of the Form Designer or Report Designer, table open performance is much faster than executing USE, SET ORDER, and SET RELATION commands in the form Load event. When you use the data environment, Visual FoxPro uses low-level engine calls to open the tables and set up the indexes and relations.

Limiting the Number of Forms in a Form Set

Use form sets only when it is necessary to have a group of forms share a private data session. When you use a form set, Visual FoxPro creates instances of all forms and all controls on all forms in the form set, even though the first form in the form set is the only one being displayed. This can be time consuming, and is unnecessary if the forms don't have to share a private data session. Instead, you should execute DO FORM for other forms when they're needed.

However, if you do use a form set, you will gain some performance back when you access the forms in the form set, because the forms will already be loaded but not visible.

Dynamically Loading Page Controls on a Page Frame

Page frames, like form sets, load all the controls for each page when the page frame is loaded, which can cause a noticeable delay when the page frame is loaded. Instead, you can dynamically load page controls, as needed, by creating a class out of the controls on each page, then loading them as the page is activated.

To dynamically load page controls

  1. Design your form as you normally would, including all controls on all pages.
  2. When your design is complete, go to the second page of your page frame, and save the controls you find there as a class.
  3. Open the class you created, and ensure the controls are still properly laid out.
  4. Repeat Steps 2 and 3 for the third and subsequent pages of the page frame.
  5. In the Activate event of the second and subsequent pages of the page frame, add objects and make them visible.

    For example, if your controls class is named cnrpage1, you would add the following code:

    IF THIS.ControlCount = 0
   THIS.AddObject("cnrpage1","cnrpage1")
   THIS.cnrpage1.Visible = .T.
ENDIF

Dynamically Binding Controls to Data

You can speed the load time for a form that contains many data-bound controls if you delay the binding of those controls until they're needed.

To dynamically bind controls to data

  1. Put the tables and views for your form in the data environment so that they're opened when the form is loaded.
  2. For each bound control, add code to its GotFocus event code that binds the control to the data value. For example, the following code binds a ComboBox control to the customer.company field:
    * Check to see if the control has been bound yet.
IF THIS.RecordSource = ""
   * Set the record source to the right value
   * and set the record source type to "fields"
   THIS.RecordSource = "customer.company"
   THIS.RecordSourceType = 6
   THIS.Refresh
ENDIF

Delaying Screen Refresh

If you must make several changes to the screen — for example, change the values of several controls at once — you can reduce the overall time required to update the screen by delaying screen refresh until all changes are done. For example, if you make controls visible or invisible, change control colors, or move records in bound controls, it is much more efficient to delay the painting of those controls until after the changes have all been completed:

To delay screen refresh

  1. Set the form's LockScreen property to true.
  2. Update the controls as required.
  3. Call the form's Refresh method.
  4. Set the form's LockScreen property to false.

For example, the following example changes the display properties of several properties at once, moves to a new record, and only then refreshes the screen with new information. If LockScreen were not set to true, each of these operations would repaint the affected controls individually and the overall update performance would seem sluggish.

THISFORM.LockScreen = .T.
THISFORM.MyButton.Caption = "Save"
THISFORM.MyGrid.BackColor = RGB (255, 0, 0) && Red
SKIP IN customers
SKIP IN orders
THISFORM.Refresh
THISFORM.LockScreen = .F.
Tip This technique doesn't provide any benefit if you're updating only a single control.

Reducing Code in Frequently-Used Methods

Because the Refresh method and Paint event are called frequently, you can improve performance in forms by reducing the amount of code in these methods. Similarly, to speed the load time for a form, you could move code from the Init event to a less frequently used event such as Activate, Click, and GotFocus. Then, you use a property on the control (such as Tag or a custom property) to keep track of whether the control has already run code that only needs to be run once.

See Also

Using Rushmore Query Optimization to Speed Data Access | Optimization of Programs | Optimizing Applications | Optimizing Your System


Optimization of Programs

By writing your code carefully, you can write the fastest possible programs. There are several ways to improve program performance in Visual FoxPro:

  • Following the general programming performance hints provided below.
  • Using name expressions instead of macro substitution.
  • Referencing object properties efficiently.

General Programming Performance Hints

To write the fastest programs possible, follow the recommendations listed below.

  • Choose the correct data type for your data. In particular, use the Integer data type for numeric information whenever possible, as it is processed most efficiently. Wherever possible, use Integer data types for primary and foreign key values, which will result in smaller data files, smaller (and therefore faster) indexes, and faster joins.
    Note For an example showing how to create a smaller (and therefore faster) index, run Solution.app, located in the Visual FoxPro ...\Samples\Solution directory. Choose View Samples by Filtered List, select Indexes from the drop-down list, and then choose Create Small Indexes Using BINTOC( ) from the list that appears.
  • Avoid reopening files, which slows performance. Instead, assign files to work areas as you open them, then use the SELECT command to choose a specific work area as needed.
  • Use FOR ... ENDFOR loops rather than DO WHILE ... ENDDO loops when possible, because they're faster.
  • When you copy data from multiple fields, SCATTER TO ARRAY is faster than SCATTER MEMVAR.
  • To use memory most efficiently, avoid creating objects before you need them, and clear objects when you finish with them to free memory.
    Tip You can test how much memory each object consumes by calling the SYS(1016) function.
  • Send output to the topmost window whenever possible; updating windows behind the top window is substantially slower. Causing output to scroll behind a window is nearly a worst-case event.
  • Disable status display with the SET TALK OFF command, which eliminates the overhead of screen update.
  • Set the SET DOHISTORY command to OFF to avoid updating the command window each time a program runs.

Using Name Expressions Instead of Macro Substitution

If you use name expressions instead of macro substitution, program performance will greatly improve. For example, if you assign a value to the variable cFile, a name expression created with cFile is faster than macro substitution.

cFile = "CUST"
use &cFile      && Macro substitution, slow
use (cFile)      && Name expression: faster, preferred

Referencing Object Properties Efficiently

By understanding how Visual FoxPro works with properties and objects, you can make your applications run more efficiently.

Optimizing Repeated References to a Property

When you reference an object property with the object.property syntax, Visual FoxPro must search for the object before it can access the property. If you must access the property repeatedly, this search strategy can slow performance.

To avoid referencing the same procedure repeatedly (such as in a loop), read the property value into a variable, make changes, and then set the property when you're through. For example, the following code fills a property array by first creating an array in memory, filling it, and then setting the property only once at the end:

* Copy string to a local variable
lcChar = THISFORM.cCharString
LOCAL laCharArray[256]   && Create local array
FOR nCounter = 1 to 256
   laCharArray[x] = SUBSTR(laChar,x,1)
ENDFOR
* Copy the local array to the property array
ACOPY(laCharArray,THISFORM.aCharArray)

Referencing Multiple Properties Efficiently

If you update more than one property for the object, Visual FoxPro must search for the object multiple times, which can affect performance. In the following example, the code causes Visual FoxPro to search through four objects (such as THISFORM, pgfCstInfo, pgCstName, and txtName) to find the property to be set. Because the code sets two properties, the fourfold search is done twice:

THISFORM.pgfCstInfo.pgCstName.txtName.Value = ;
 "Fred Smith"
THISFORM.pgfCstInfo.pgCstName.txtName.BackColor = ;
 RGB (0,0,0)  & Dark red

To avoid this overhead, use the WITH ... ENDWITH command. This method causes Visual FoxPro to find the object once. For example, the following example accomplishes the same task as the previous one, but faster:

WITH THISFORM.pgfCstInfo.pgCstName.txtName
   .Value = "Fred Smith"
   .BackColor = RGB (0,0,0)  & Dark red
ENDWITH

You can also store an object reference in a variable, then include the variable in place of the object reference:

oControl = THISFORM.pgfCstInfo.pgCstName.txtName
oControl.Value = "Fred Smith"
oControl.BackColor = RGB (0,0,0)  & Dark red

See Also

Optimizing Forms and Controls | Optimization of ActiveX Controls | Optimizing Applications | Optimizing Your System | SELECT | FOR ... ENDFOR | SCATTER


Optimization of ActiveX Controls

If you use Automation or ActiveX controls in your application, you can fine-tune the application to get the best performance out of both ActiveX controls and Automation.

Using ActiveX Controls Efficiently

For best performance when using ActiveX controls in your forms, use the following suggestions:

  • Start Automation servers in advance. Controls bound to general fields will generally perform better when the servers for those data types (like Microsoft Excel or Word) are already running on the client's machine.
  • Insert objects "As Icon." When you insert an ActiveX control into a field, insert it as an icon or placeholder rather than as an entire object. This reduces the amount of storage space required because Visual FoxPro stores a presentation image with the object, which can consume a lot of storage space. Inserting an object as an icon also increases performance for drawing the object.
  • Use image controls. If you want to display a bitmap (such as a company logo), image controls are much faster than OLEBound controls.
  • Use manual links whenever possible. Manual links to objects are faster because they avoid the notification time required for automatic links, and because the server doesn't need to be started to draw the object. If you don't need to update an object frequently, use manual links.

Optimizing Automation Performance

If your application interacts with other applications, you can get the best performance using the following techniques.

Avoiding Multiple Instances of the Server

In some cases, Automation servers (such as Microsoft Excel) will always start a new instance, even if one is already running. To remedy this and improve performance, use the GetObject( ) function instead of CreateObject( ). For example, the following call will always use an existing instance, if it exists:

x = GetObject(,"excel.Application")

In contrast, the following call creates a new instance:

x = CreateObject("excel.Application")

If you call GetObject( ) but the server isn't already running, you will get error 1426. In that case, you can trap for the error and call CreateObject( ):

ON ERROR DO oleErr WITH ERROR()
x = GetObject(,"excel.application")
ON ERROR  && restore system error handler

PROCEDURE oleErr
PARAMETER mError
IF mError = 1426 then
 x = CreateObject("excel.application")
ENDIF

Referencing Objects Efficiently

Executing expressions that use objects within the Automation server can be expensive, particularly when evaluated multiple times. It is much faster to store objects' references to variables for reference.

See Also

Optimization of Programs | Optimizing Applications in Multiuser Environments | Optimizing Access to Remote Data | Optimizing Applications | Optimizing Your System


Optimizing Applications in Multiuser Environments

If you're writing applications for a multiuser environment, performance is particularly important, because inefficiencies are multiplied. In addition, if multiple users are accessing data, your application must handle issues of concurrency and network access.

To handle these issues, you can:

  • Adjust lock retry interval.
  • Use transaction processing efficiently.

You might also benefit from the suggestions for working with data stored on remote servers. For details, see Optimizing Access to Remote Data.

Adjusting Lock Retry Interval

If your application attempts to lock a record or table and is unsuccessful, you can have Visual FoxPro automatically retry the lock after a small interval. However, each lock attempt results in more network traffic. If network traffic is already heavy, sending repeated lock requests adds a burden to the network, and results in overall slowdown for all users.

To address this situation, you can adjust the interval between lock attempts. By using a larger interval (which results in fewer retries per second), you reduce network traffic and gain performance.

To adjust the lock retry interval

  • Call the SYS(3051) function, passing it the number of milliseconds to wait between each lock attempt.

Using Transaction Processing Efficiently

When using transaction processing, you must design transactions to minimize the impact that they have on other users. While a transaction is open, any locks set during the transaction remain locked until the transaction is committed or rolled back. Even if you issue an explicit UNLOCK command, locks are held until the END TRANSACTION or ROLLBACK command.

Furthermore, appending records to a table requires Visual FoxPro to lock the table header. The header remains locked for the duration of the transaction, preventing other users from also appending records.

To minimize the impact of transactions, design them so that they begin and end as close to the actual data update as possible; the ideal transaction contains only data update statements.

If you are adding transaction processing to data updates made in a form, don't open a transaction, run the form, and then commit the transaction when the form is closed. Instead, put the transaction processing statements in the event code for the Save button (for example):

* Save method from the cmdSave command button
BEGIN TRANSACTION
UPDATE PRODUCTS SET reorder_amt = 0 WHERE discontinued = .T.
END TRANSACTION

See Also

Optimization of ActiveX Controls | Optimizing Access to Remote Data | Optimizing Applications | Optimizing Your System | Optimization of International Applications


Optimizing Access to Remote Data

Data retrieval from any remote database is expensive. In order to get data from a server database, the following steps must occur:

  1. The client issues the query to the remote database.
  2. The server parses and compiles the query.
  3. The server generates a result set.
  4. The server notifies the client that the result is complete.
  5. The client fetches the data over the network from the server. This step can happen all at once, or the client can request that results be sent in pieces as requested.

You can use a number of techniques to speed up the retrieval (or update) of data, such as:

  • Retrieving only the data you need
  • Updating remote tables efficiently
  • Sending statements in a batch
  • Setting packet size
  • Delaying retrieval of memo and binary data
  • Storing lookup data locally
  • Creating local rules

Retrieving Only the Data You Need

In most applications that use remote data, forms and reports don't need to access all the data from a table at once. Therefore, you can speed performance by creating remote views that fetch or update only the fields and records you want, which minimizes the amount of data that needs to be transmitted across the network.

To create queries that minimize the overhead of data retrieval from remote sources, follow these suggestions:

  • Specify only the fields you need. Don't use the statement SELECT * FROM customers unless you need all the fields from the table.
  • Include a WHERE clause to limit the number of records downloaded. The more specific your WHERE clause, the fewer records are transmitted to your computer, and the faster the query will finish.
  • If you cannot predict at design time what values to use in a WHERE clause, you can use parameters in the clause. When the query is executed, Visual FoxPro uses the value of a parameter variable or prompts the user for the search value. For example, this query allows the application or user to fill in the region at run time:
    SELECT cust_id, company, contact, address ;
   FROM customers ;
   WHERE region = ?pcRegion
  • Set the NoDataOnLoad property of the corresponding Data Environment Cursor object. This technique is commonly used with parameterized views in which the data for the parameter comes from the value of a control on a form.

Updating Remote Tables Efficiently

When you use a view to update a table on a remote data source, Visual FoxPro must check whether the record or records you are updating have been changed. To do so, Visual FoxPro must examine the data on the server and compare it to the data being held on your computer. In some instances, this can be a time-consuming operation.

To optimize the process of updating data on remote data sources, you can specify how Visual FoxPro should check for changed records. To do this, you indicate the WHERE clause that Visual FoxPro should generate in order to perform the update.

For example, imagine that you are using a view based on a customer table on a remote data source. You created the view using a SELECT - SQL statement such as this one:

SELECT cust_id, company, address, contact ;
   FROM customers ;
   WHERE region = ?vpRegion

You want to be able to update all four fields that you have specified in the view except the key field (cust_id). The following table illustrates the WHERE clause that Visual FoxPro will generate for each of the options available under the SQL WHERE clause.

Note The OLDVAL( ) function returns the pre-update version of fields you modified, and the CURVAL( ) function returns the current value stored on the remote data source. By comparing them, Visual FoxPro can determine whether the record has changed on the remote data source since you downloaded it to your computer.
Setting Resulting WHERE clause
Key fields only
WHERE OLDVAL(cust_id) = CURVAL(cust_id)
Key and updatable fields
(default)
WHERE OLDVAL(cust_id) = CURVAL(cust_id) AND

   OLDVAL(<mod_fld1>) = CURVAL(<mod_fld2>) AND
   OLDVAL(<mod_fld2>) = CURVAL(<mod_fld2>) AND
   ...
Key and modified fields
WHERE OLDVAL(cust_id) = CURVAL(cust_id) AND

   OLDVAL(company) = CURVAL(company) AND
   OLDVAL(contact) = CURVAL(contact) AND
   OLDVAL(address) = CURVAL(address)
Key and timestamp
WHERE OLDVAL(cust_id) = CURVAL(cust_id) AND

   OLDVAL(timestamp) = CURVAL(timestamp)

In general, you should choose an option for the SQL WHERE clause in this order of preference:

  1. Key and timestamp, if the remote database supports timestamped fields, which is the fastest way to tell if a record has changed.
  2. Key and modified fields, because the fields you update to the server are almost always a subset of the total number of fields that you could update.
  3. Key and updatable fields.
  4. Key fields only. Using these settings implies that the remote server will insert an entirely new record using the changed key, and will delete the old record.

Sending Statements in a Batch

Some servers (such as Microsoft SQL Server) allow you to send a batch of SQL statements in a single packet. This speeds performance because you reduce network traffic, and because the server can compile multiple statements at once.

For example, if you specify a batch size of four, then update 10 records in a database, Visual FoxPro sends four statements such as the following to the server database in one batch:

UPDATE customer SET contact = "John Jones" ;
   WHERE cust_id = 1;
UPDATE customer SET contact = "Sally Park" ;
   WHERE cust_id = 2;
UPDATE customer SET company = "John Jones" ;
   WHERE cust_id = 3;
UPDATE customer SET contact = "John Jones" ;
   WHERE cust_id = 4

To send statements in a batch

  • In the Options dialog box, choose the Remote Data tab, and then under Records to batch update, specify the number of records to include in a batch.

    -or-

  • Call the DBSETPROP( ) or CURSORSETPROP( ) functions to set these properties:
    • Set Transaction to 2.
    • Set BatchUpdateCount to the number of statements to send in a batch.

      -or-

  1. In the View Designer, choose Advanced Options from the Query menu to display the Advanced Options dialog box.
  2. In the Performance area, next to Number of records to batch update, specify the number of statements to send in a batch.
    Note You should experiment with different values for this property and the PacketSize property to optimize your updates.

Setting Packet Size

You can optimize access to remote servers by fine-tuning the size of the network packet that is sent to and retrieved from the remote database. For example, if your network supports large packet sizes (greater than 4,096 bytes), you can increase the packet size in Visual FoxPro in order to send more data each time you read or write to the network.

To set packet size

  • Call the DBSETPROP( ) or CURSORSETPROP( ) functions and set the PacketSize property to a positive integer value. The default value is 4,096.
    Note Different network providers will handle this property differently, so you should consult your network service documentation. Novell NetWare, for example, has a maximum packet size of 512 bytes so setting the PacketSize property to a value greater than this will have no additional benefit.

Delaying Retrieval of Memo and Binary Data

If you're storing Memo or binary data on a remote server, you can improve performance by delaying the download of this data until your application actually requires it.

To delay retrieval of memo and binary data

  • In the Options dialog box, choose the Remote Data tab, and then under Remote view defaults, set Fetch memo.

    -or-

  • Call the DBSETPROP( ) or CURSORSETPROP( ) functions to set the FetchMemo property.

Storing Lookup Data Locally

Many applications include static lookup data such as state abbreviations, postal codes, and employee titles. If your application contains this type of data, and if the table is not too large, you might be able to speed up your application by keeping copies of this information on each user's computer, because lookups do not generate network traffic.

This technique is primarily useful for data that never changes or changes very rarely. If the data does change on occasion, you must devise a strategy for downloading a new copy of the lookup table to each user's computer.

Creating Local Rules

You can gain efficiency in your application by creating local field-level and record-level rules within Visual FoxPro, rather than relying on rules defined on the server. These rules can prevent data that doesn't conform to data or business rules from getting into the database.

By defining rules in Visual FoxPro, you trap the invalid data before it's sent across the network, which is faster, and which gives you better control for handling error conditions. However, using local rules also means that you must coordinate them with rules on the remote server. For example, if there are changes to the rules on the server, you might have to change your local rules to match.

For details about creating local rules, see Updating Data in a View in Creating Views.

See Also

Optimizing Applications in Multiuser Environments | Optimization of International Applications | Optimizing Applications | Optimizing Your System | NoDataOnLoad | SELECT - SQL


Optimization of International Applications

If you are developing international applications, you might need to manage the collating sequence of your data for optimal performance. This section discusses:

  • Using collating sequence efficiently.
  • Using SELECT - SQL with multiple collating sequences.

Using Collating Sequence Efficiently

If your data does not include diacritical marks, such as accents (á) or umlauts (ü), you can improve performance by using the machine collating sequence because:

  • Non-machine index keys are twice as large because they contain the diacritical information.
  • Non-machine collation uses many special rules for indexing characters to return proper results.

Because the machine collate sequence is faster, it is usually preferred for joins and searching, while other collate sequences are perfect for ordering records.

When you create an index, Visual FoxPro uses the current collating sequence set by using the SET COLLATE, CREATE TABLE - SQL, ALTER TABLE - SQL, or INDEX commands. For example, if you want to create two indexes with two collating sequences, you can use SET COLLATE and a sequence of commands such as the following:

SET COLLATE TO "MACHINE"
INDEX ON lastname TAG _lastname     && Join or seek index.
SET COLLATE TO "GENERAL"
INDEX ON lastname TAG lastname  && Sort index.

When you want to seek, select, or join on the field lastname, issue the command SET COLLATE TO "MACHINE" before performing the operation. Rushmore Query Optimization uses the index created in the machine collate sequence, and the search operation runs very quickly.

Using SQL SELECT with Multiple Collating Sequences

When you issue a SELECT - SQL command, Visual FoxPro uses the current collating sequence for searching and for the ORDER BY and GROUP BY clauses. If you want to search and sort using different collating sequences, you can split your SQL commands into two steps as follows:

* Select records using one collating sequence.
SET COLLATE TO "MACHINE"
SELECT * FROM table INTO CURSOR temp1 ;
  WHERE lname = "Müller"
* Order records using a different collating sequence.
SET COLLATE TO "GENERAL"
SELECT * FROM temp1 INTO TABLE output ORDER BY lastname

See Also

Optimizing Access to Remote Data | Optimizing Applications | Optimizing Your System | Optimizing Applications in Multiuser Environments | Optimization of ActiveX Controls


Accessing APIs

If your application has requirements that cannot be met by the features already built into Visual FoxPro, you can extend the program by taking advantage of external libraries such as Microsoft ActiveX controls or dynamic-link libraries (DLLs). Using external libraries, you can add all kinds of objects to your application, from enhanced text boxes to calendars and other full-featured applications, and you can take advantage of the functionality offered by other programs (including Microsoft Windows) through their application programming interfaces (APIs).

In This Section

Extending Visual FoxPro with External Libraries
Explains that you can add Microsoft ActiveX controls (.ocx files) to your application easily, which provides you with new objects to use in forms, to subclass, and to manage the way you work with native Visual FoxPro controls. In addition, you can link to an external library, such as a DLL, and call the library's functions to use in your own programs.
Accessing the Visual FoxPro API
If an external library is not available to suit your needs, you can write your own Microsoft ActiveX control or Visual FoxPro-specific dynamic-link library (.fll file). By calling the functions available in the Visual FoxPro API, you can create controls or libraries that are tightly integrated with and optimized for use in Visual FoxPro.

Related Sections

Programming in Visual FoxPro
Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Creating Programs
Explains the two ways to create a Visual FoxPro program, which is a text file containing a series of commands.
Object-Oriented Programming
With object-oriented programming, you can create self-contained application components that respond to user actions and to the system and which can be easily maintained and reused.
Optimizing Applications
Describes ways to optimize the performance of your stable, running application by making your application smaller and faster.


Extending Visual FoxPro with External Libraries

You can extend the native capabilities of Microsoft® Visual FoxPro® by taking advantage of the facilities of Microsoft® ActiveX® controls (.ocx files), ActiveX objects, and dynamic-link libraries (DLLs). External libraries make it possible for you to access not only the capabilities of other programs but also those of Microsoft® Windows®. For example, you can use an ActiveX control to read and update the Windows registry directly, or it can call system-level functions by linking to one of the DLLs in Windows.

In This Section

Access to External Libraries
In most cases, Visual FoxPro provides all the tools you must have to complete your application. However, occasionally you might find that an application requires additional functionality not available in Visual FoxPro already.
Accessing ActiveX Controls and Objects
You can use any Microsoft® ActiveX® control that is available on your computer. To use an ActiveX control, you add it to a form and then set its properties, write handlers for its events, or call its methods.
Accessing Dynamic-Link Libraries
If the functionality you require is available in a DLL, you can link to the library and call its functions.
Accessing a Visual FoxPro Library
Like a DLL, a Visual FoxPro library (.fll file) contains functions you can call as you would any other function.

Related Sections

Accessing APIs
If your application has requirements that cannot be met by the features already built into Visual FoxPro, you can extend the program by taking advantage of external libraries — Microsoft® ActiveX® controls or dynamic-link libraries (DLLs).
Accessing the Visual FoxPro API
If an external library is not available to suit your needs, you can write your own Microsoft® ActiveX® control or Visual FoxPro -specific dynamic-link library (.fll file). By calling the functions available in the API available in Visual FoxPro, you can create controls or libraries that are tightly integrated with and optimized for use in Visual FoxPro.


Access to External Libraries

In most cases, Visual FoxPro provides all the tools you need to complete your application. However, occasionally you might find that an application requires additional functionality not already available in Visual FoxPro. In those cases, you can reach outside Visual FoxPro and take advantage of the capabilities of external libraries.

Visual FoxPro makes it possible for you to access these kinds of external libraries:

  • ActiveX controls (.ocx files) and Objects. ActiveX controls and objects are programs that include objects designed to accomplish specific tasks. Most ActiveX controls and objects add new objects to Visual FoxPro — everything from a new type of text box to a calendar, calculator, or other complex object. Some ActiveX controls and objects also incorporate additional facilities, such as access to your e-mail system or to the communications ports on your computer. As a rule, after incorporating an ActiveX control or object into Visual FoxPro, you can use the objects in them as you would any Visual FoxPro base class.
  • Dynamic-link libraries (.dll files). A .dll file is a library of functions that you can call from Visual FoxPro programs as you would any user-defined function in Visual FoxPro. Many Windows programs — and Windows itself — make their functionality available using .dll files. For example, you can access the system color settings for Windows by linking to a system .dll file and calling functions in it.
  • Visual FoxPro external libraries (.fll files). An .fll file is like a .dll file, but uses special protocol for sharing data with Visual FoxPro, and often contains calls to internal Visual FoxPro functions. As a consequence, .fll files are specific to Visual FoxPro, unlike .dll files, which can be called from any Windows program. You can call the functions in an .fll as you would any user-defined function in Visual FoxPro.

Before you use any library, you must be familiar with the conventions used to access its controls or functions. For example, if you want to include an ActiveX control on a form, you must know what properties, events, and methods you can use to manage the control. For an ActiveX control, you can use a Visual FoxPro Class Browser to determine the properties, events, and methods you can use. Similarly, if you want to call a function in a .dll file, you must know the function name, the number and data types of the parameter it requires, and the data type of its return value. In general, you can obtain this type of information from the documentation that accompanies a library, whether in a book or a Help system. For information about system .dll files for Windows, you can refer to the Software Development Kit (SDK) appropriate to your version of Windows.

See Also

Extending Visual FoxPro with External Libraries | Accessing ActiveX Controls and Objects | Accessing Dynamic-Link Libraries | Accessing a Visual FoxPro Library | Accessing the Visual FoxPro API


Accessing ActiveX Controls and Objects

You can use any ActiveX control that is available on your computer. To use an ActiveX control, you add it to a form, then set its properties, write handlers for its events, or call its methods. You can add an ActiveX control to a form using the Form Controls toolbar or the OLE Container control, or by using code. For details about adding an ActiveX control in the Form Designer, see Adding OLE.

You can create an ActiveX control in code in much the same way you would create any Visual FoxPro control. However, before creating the control you must determine the name of the control's class library, which is stored in the Windows registry. If you have no other way to determine the class library name, use the Form Designer to create the control (as described in the previous section), and then get the control's OLEClass property.

ActiveX objects can be created directly with CREATEOBJECT( ), and don't require an instance of a form.

To create an ActiveX control in code

  1. Call CREATEOBJECT( ) to create a form.
  2. Call the new form's AddObject method to add the control, specifying olecontrol as the class. You must pass the control's class library name as the third parameter of the AddObject method.

For example, the following program creates a new form and adds an outline control to it:

oMyForm = CREATEOBJECT("form")
oMyForm.AddObject("oleOutline","olecontrol", ;
   "MSOutl.Outline")

After you've created the form and control, you can display the form by calling its Show method, and display the control by setting its Visible property to true:

oMyForm.oleOutline.Visible = .T.
oMyForm.Show

Some ActiveX controls aren't designed primarily to be used interactively by a user. For example, a timer control doesn't support methods for user interaction. Even then, you can still create the control on a form because the control will usually make available a default visible component, such as an icon. Frequently you will not be able to change or resize the icon.

If you don't want your application to display the icon for non-interactive controls, you can hide the control by setting the Visible property of its OLE container control to false, or set its Left property to a negative value (such as –100) that moves it off the visible portion of the screen. Alternatively, you can place the control on a form that's never made visible (that is, for which the Show method is never called). In all cases, you can still call the control's methods as if the control were visible.

See Also

Access to External Libraries | Accessing Dynamic-Link Libraries | Accessing a Visual FoxPro Library | Extending Visual FoxPro with External Libraries | Accessing the Visual FoxPro API | Adding OLE | CREATEOBJECT( )


Accessing Dynamic-Link Libraries

If the functionality you require is available in a DLL, you can link to the library and call its functions. Before calling a DLL function, you must determine its calling protocol, including the name of the function, the number and data types of its parameters, and the data type of its return value.

In Visual FoxPro, you can only use DLLs that have been written for a 32-bit environment. However, if you require access to a 16-bit DLL, you can call it using functions available in Foxtools.fll. For details, see Help for Foxtools (Foxtools.chm).

To call a DLL function

  1. Register the DLL function using the DECLARE - DLL command. Function names are case-sensitive.
    Note If you specify WIN32API for the library name, Visual FoxPro searches for the 32-bit Windows DLL function in Kernel32.dll, Gdi32.dll, User32.dll, Mpr.dll, and Advapi32.dll.
  2. Call the function as you would any Visual FoxPro function.

For example, the following program registers the GetActiveWindow( ) function from the Windows USER system DLL, which displays the handle of the Visual FoxPro main window. The GetActiveWindow( ) takes no parameters, but returns a single integer:

DECLARE INTEGER GetActiveWindow IN win32api
MESSAGEBOX(STR( GetActiveWindow() ) )

The DLL containing the function you're registering must be available in the default directory, in the Windows or System directories, or along the DOS path.

If the function you want to call has the same name as another function already available in Visual FoxPro (either a native function or a DLL function previously declared), you can assign an alias to the function with the duplicate name, then call it using the alias.

DECLARE INTEGER GetActiveWindow IN win32api AS GetWinHndl
MESSAGEBOX(STR( GetWinHndl() ) )

Linked DLL functions remain available until you quit Visual FoxPro, so you only need to declare them once per session. If you don't intend to call the functions in a DLL again, you can issue the CLEAR DLLS command to remove it from memory and free resources.

Note Issuing CLEAR DLLS clears all declared DLL functions from memory.

Passing Parameters to a DLL

When you register a DLL function, you must specify the number and data types of its parameters. By default, data is passed by value. You can force a parameter to be passed by reference by including an at sign (@) in front of the parameter.

In general, DLL functions follow the data type conventions used for C, which differ from those used in Visual FoxPro. For example, DLL functions do not support a data type for a date or for currency. If the data you're passing to a DLL function is in a data type not supported by the function, you must convert it to an appropriate type before passing it. For example, you can convert a date to a numeric Julian format using commands such as the following:

cDate = sys(11, date())
nDate = val( cDate )

Some DLL functions require more complex parameters, such as structures or arrays. If the function requires a pointer to a structure, you must determine the layout of the structure, then emulate it as a string in Visual FoxPro before passing it or receiving it from the DLL function. For example, the Windows system function GetSystemTime( ) expects a pointer to a structure consisting of eight words or unsigned 16-bit integers indicating the year, month, day, and so on. The structure is defined this way:

typedef struct _SYSTEMTIME {
   WORD wYear ;
   WORD wMonth ;
   WORD wDayOfWeek ;
   WORD wDay ;
   WORD wHour ;
   WORD wMinute ;
   WORD wSecond ;
   WORD wMilliseconds ;
} SYSTEMTIME

To pass data between Visual FoxPro and the GetSystemTime( ) function, you must create a 40-byte string buffer (consisting initially of spaces) and then pass the address of this string to the function for it to fill in. When the string is returned, you must parse it in 2-byte increments to extract the individual fields of the structure. The following fragment illustrates how you could extract three of the fields from the structure:

DECLARE INTEGER GetSystemTime IN win32api STRING @
cBuff=SPACE(40)
=GetSystemTime(@cBuff)

tYear = ALLTRIM(STR(ASC(SUBSTR(cBuff,2)) *  ;
   256 + ASC(SUBSTR(cBuff,1))))
tMonth = ALLTRIM(STR(ASC(SUBSTR(cBuff,4)) * ;
   256 + ASC(SUBSTR(cBuff,3))))
tDOW = ALLTRIM(STR(ASC(SUBSTR(cBuff,6)) * ;
   256 + ASC(SUBSTR(cBuff,5))))

For more information, you can examine the sample form Systime.scx in the Visual FoxPro …\Samples\Solution\Winapi directory. For other examples of how to pass parameters to DLL functions, see the program Registry.prg in the Visual FoxPro …\Samples\Classes directory.

If the data you're working with in Visual FoxPro is in an array, you must loop through the array and concatenate it into a single string representing a C-style array before passing it to the DLL function. If the Windows function expects 16-bit or 32-bit values, you must convert the values to their hex equivalents before concatenating them into string. When you pass the string containing the array data, Visual FoxPro passes the address of the string variable to the DLL, which can then manipulate it as an array. For an example of this, see the sample form Syscolor.scx in the Visual FoxPro …\Samples\Solution\Winapi directory.

See Also

Accessing ActiveX Controls and Objects | Accessing a Visual FoxPro Library | Extending Visual FoxPro with External Libraries | Accessing the Visual FoxPro API | DECLARE - DLL | CLEAR DLLS


Accessing a Visual FoxPro Library

Like a DLL, a Visual FoxPro library (.fll file) contains functions you can call as you would any other function. Because .fll files are created specifically to be called from Visual FoxPro, it's generally easier to pass parameters to and from .fll functions.

To use a Visual FoxPro library, you specify the name of the .fll file, and then call the function normally. Unlike registering DLL functions, you don't need to register individual functions within the .fll file, nor do you need to specify information about the parameters or data types used by the function.

Note If you want to use an .fll library from an earlier version of Visual FoxPro, the library must be recompiled to work with Visual FoxPro version 5.0.

To call an .fll function

  1. Register the .fll function by issuing a SET LIBRARY command.
  2. Call any of the functions in the library as you would any function.

For example, the following program calls a function from the Foxtools.fll library to determine what type of drive the C: drive is:

SET LIBRARY TO "C:\Program Files\Microsoft ;
Visual FoxPro 8.0\Foxtools.fll"
? DriveType("C:")

If you need to register more than one .fll file, include the ADDITIVE keyword in the SET LIBRARY command. If you don't, the previously registered .fll file is cleared and replaced by the one most recently registered.

If a function name conflicts with that of another function already available in Visual FoxPro, the last function defined takes precedence. If the function name in a linked library has the same name as that of an intrinsic Visual FoxPro function, the Visual FoxPro function takes precedence.

The functions in an .fll file remain available until you quit Visual FoxPro, so you only need to register them once per session. If you don't intend to call the functions in a .fll file again, issue RELEASE LIBRARY, RELEASE ALL, or SET LIBRARY to remove it from memory and free resources.

See Also

Accessing Dynamic-Link Libraries | Accessing ActiveX Controls and Objects | Access to External Libraries | Extending Visual FoxPro with External Libraries | Accessing the Visual FoxPro API


Accessing the Visual FoxPro API

If Visual FoxPro does not include the features you require for your application already, you can extend its capabilities by creating a Microsoft ActiveX control (.ocx file) or library (.fll file) specific to Visual FoxPro.

In This Section

Library or ActiveX Object Creation
You can extend the capabilities of Visual FoxPro by creating programs that accomplish tasks required by your application.
Adding Visual FoxPro API Calls
To integrate your program with Visual FoxPro, you can call Visual FoxPro API routines.
Passing and Reception of Parameters
When your program is called from Visual FoxPro, it can receive parameters.
Return of a Value to Visual FoxPro
The method you use to return a value from your program to Visual FoxPro depends on whether you are creating a Microsoft ActiveX control or an FLL library.
Passing of Parameters to Visual FoxPro API Functions
Often the Visual FoxPro API routines will require parameters of a particular Visual FoxPro data structure.
Access to Visual FoxPro Variables and Fields
You can access Visual FoxPro variables or field values in your ActiveX control or FLL function, either to read them or to set them.
Managing Memory
The Visual FoxPro API provides direct access to the Visual FoxPro dynamic memory manager.
Building and Debugging Libraries and ActiveX Controls
After creating a project, you are ready to build and debug it.

Related Sections

Accessing APIs
If your application has requirements that cannot be met by the features already built into Visual FoxPro, you can extend the program by taking advantage of external libraries — Microsoft ActiveX controls or dynamic-link libraries (DLLs).
Extending Visual FoxPro with External Libraries
You can add ActiveX controls (.ocx files) to your application easily, which provides you with new objects to use in forms, to subclass, and to manage the way you work with native Visual FoxPro controls. In addition, you can link to an external library, such as a DLL, and call the library's functions to use in your own programs.
API Library Construction
Reference material covering API Library routines, system events, and key codes.


Library or ActiveX Object Creation

You can extend the capabilities of Visual FoxPro by creating programs in C or C++ that accomplish tasks required by your application. For example, if your application requires direct access to Windows facilities, you can write a C or C++ program that makes calls to the Windows API, and then returns information to Visual FoxPro.

You can create three types of programs to access the Visual FoxPro API:

  • An ActiveX control (.ocx file).
  • A COM object.
  • A DLL specific to Visual FoxPro. Because the DLL can be called only from Visual FoxPro, it is customary to name it with the extension .fll.

Each type of program has advantages. An ActiveX control:

  • Can be accessed using standard object-oriented techniques, such as setting its properties and invoking its methods.
  • Can be subclassed, and its methods overridden.
  • Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user states.
  • Features simpler parameter passing.
  • Can also be called from other Windows programs, if you program it with this in mind.

The advantages of COM objects:

  • Can be accessed using standard object-oriented techniques, such as setting its properties and invoking its methods.
  • Its methods can be overridden.
  • Is encapsulated, and can be called (instantiated) multiple times without complex environment management to preserve user states.
  • Features simpler parameter passing.
  • Can also be called from other Windows programs, if you program it with this in mind.

On the other hand, an .fll library:

  • Might be familiar to you if you've used previous versions of Visual FoxPro.

See Also

Accessing the Visual FoxPro API | API Library Construction | Creating a Basic ActiveX Object | Creating a Basic FLL Library | Extending Visual FoxPro with External Libraries | Adding Visual FoxPro API Calls


Creating a Basic ActiveX Object

You can create COM objects with the ActiveX Template Library provided with Microsoft® Visual C++.

You create Microsoft ActiveX controls specific to Visual FoxPro as you would any similar control. Most C++ compilers allow you to create skeletons of the control, and they can be created with the Microsoft Visual Basic Control Creation Edition.

The follow sections describe the steps for creating an ActiveX control with Microsoft Visual C++ for use in Visual FoxPro.

To create a project for the ActiveX control

  1. Start Microsoft Visual C++.
  2. From the File menu, choose New.
  3. In the New dialog box, choose Project Workspace.
  4. In the New Project Workspace dialog box, specify a project name.
  5. In the Type list, choose OLE ControlWizard.
  6. Choose Create, and then follow the steps in the wizard.

When the wizard is finished, you can build the ActiveX control immediately. However, you'll also need to define properties and methods for the control.

To add properties and methods to the ActiveX control

  1. From the View menu, choose ClassWizard.
  2. Choose the OLEAutomation tab.
  3. Choose Add Method or Add Property.
  4. Fill in the name, parameter, and other information required by the element you are creating, and then choose OK.
  5. Choose Edit Code to display the editor, and then enter the code that defines the property or method you're creating.

For example, to create a Version property that returns the .ocx file version as an integer (such as 101), you create the property with a return type of long, and add code similar to the following:

#define VERSION 101

long CPyCtrl::GetVersion()
{
   // set the version number here
   return VERSION;
}

Because the version number is ordinarily read-only, you wouldn't create a SetVersion( ) function.

See Also

Library or ActiveX Object Creation | Creating a Basic FLL Library | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Adding Visual FoxPro API Calls


Creating a Basic FLL Library

Because an FLL library is essentially a DLL with calls to the Visual FoxPro API, you create an FLL library by following the steps in your development environment for creating a DLL.

To create a project for the FLL library

  1. Start Microsoft Visual C/C++.
  2. From the File menu, choose New.
  3. In the New dialog box, choose Project Workspace.
  4. In the New Project Workspace dialog box, specify a project name.
  5. In the Type list, choose Dynamic-Link Library.

After creating the basic DLL structure, you add the functions you want to be able to call from Visual FoxPro. The following sections provide skeletons for creating functions in both C and C++.

Setting Up a Library Template

Each function library that you create has the same basic structure. By using a template for the structure, all you have to do is fill in the blanks that apply to your specific library routine.

There are five elements in a Visual FoxPro library template:

  1. #include statement
  2. Function definition
  3. Function code
  4. FoxInfo structure
  5. FoxTable structure

A Sample C Template

You can use the following template to create libraries written in C:

#include <Pro_ext.h>

void Internal_Name(ParamBlk *parm)
{
// function code goes here.
}

FoxInfo myFoxInfo[] = {
   {"FUNC_NAME", (FPFI) Internal_Name, 0, ""},
};

FoxTable _FoxTable = {
   (FoxTable *)0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

A Sample C++ Template

For C++ routines, you can use the following template. This template differs from the C template because it declares the FoxTable structure as external:

#include <Pro_ext.h>

void Internal_Name(ParamBlk  *parm)
{
// function code goes here.
}

   FoxInfo myFoxInfo[] = {
      {"FUNC_NAME", (FPFI) Internal_Name, 0, ""},
   };

extern "C" {
   FoxTable _FoxTable = {
      (FoxTable *)0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
   };
}

Using the Template

To use the header file and create a compiled library, you need:

  • The header file Pro_ext.h. You can print this file to see the function declarations, typedefs, and structs used in the Visual FoxPro API.
  • The file Winapims.lib.

Both of these files are installed in the API subdirectory when you install Visual FoxPro.

The function definition returns void and expects the following parameter: ParamBlk *parm. The ParamBlk structure is discussed under Passing and Reception of Parameters.

Other than the files listed above, the only other required elements of a Visual FoxPro library are the FoxInfo and FoxTable structures.

Using FoxInfo and FoxTable Structures

Your library functions communicate with Visual FoxPro through the FoxInfo structure. From this structure, Visual FoxPro determines the function name and the number and type of parameters. The FoxTable structure is a linked list that keeps track of the FoxInfo structures. See Pro_ext.h in the Visual FoxPro API directory for the FoxInfo and FoxTable struct definitions.

FoxInfo Structure

The FoxInfo structure is the vehicle used to communicate function names and parameter descriptions between Visual FoxPro and your library. A generic FoxInfo structure looks like this:

FoxInfo arrayname[ ] = {
   {funcName1, FPFI function1, parmCount1, parmTypes1}
   {funcName2, FPFI function2, parmCount2, parmTypes2}
      . . .
   {funcNameN, FPFI functionN, parmCountN, parmTypesN}
};

The placeholders are defined as follows:

arrayname
A variable of type FoxInfo. Note that you can include several FoxInfo structure lines in this array.
funcName
Contains the name that the Visual FoxPro user calls to invoke your function.
function
The address of your C language routine. This is the exact (case-sensitive) name you use to define your function.
parmCount
Specifies the number of parameters described in the parmTypes string or one of the following flag values.
Value | Description
INTERNAL | Specifies that the function cannot be called directly from Visual FoxPro.
CALLONLOAD | Specifies that the routine is to be called when the library is loaded. CALLONLOAD can't call any routine that returns results to Visual FoxPro.
CALLONUNLOAD | Specifies that the routine is to be called when the library is unloaded or when the Visual FoxPro QUIT command is issued. CALLONUNLOAD cannot call any routine that returns results to Visual FoxPro.
parmTypes
Describes the data type of each parameter. The following table lists the valid values for parmTypes.
Value Description
""
 No parameter
"?"
 Any type can be passed. In the body of the function, you'll need to check the type of the passed parameter.
"C"
 Character type parameter
"D"
 Date type parameter
"I"
 Integer type parameter
"L"
 Logical type parameter
"N"
 Numeric type parameter
"R"
 Reference
"T"
 DateTime type parameter
"Y"
 Currency type parameter
"O"
 Object type parameter

Include a type value for each parameter passed to the library. For example, if you create a function that accepts a character and a numeric parameter, substitute "CN" for parmType.

Note To indicate that a parameter is optional, precede it with a period. Only trailing parameters can be omitted.

The following FoxInfo structure defines a library with one function — internally called dates and externally accessed as DATES — that accepts one Character type parameter:

FoxInfo myFoxInfo[] = {
   { "DATES", (FPFI) dates, 1, "C" }
};

When you've compiled the library with this FoxInfo structure and loaded it in Visual FoxPro with the SET LIBRARY TO command, you can call this function in Visual FoxPro with the following line of code:

=DATES("01/01/95")

FoxTable Structure

The FoxTable structure is a linked list that keeps track of all the FoxInfo structures you have for a given library:

FoxTable _FoxTable = {nextLibrary, infoCount,infoPtr};

where the placeholders are defined as follows:

nextLibrary
A pointer used internally by Visual FoxPro; should be initialized to 0.
infoCount
The number of Visual FoxPro external routines defined in this library.
infoPtr
The address of the first element of an array of FoxInfo structures. This name must match the array name listed in the FoxInfo statement.

The following is an example of a FoxTable statement. If your FoxInfo array name is myFoxInfo, you'll never need to change this statement:

FoxTable _FoxTable = {
   (FoxTable  *) 0,
   sizeof( myFoxInfo) / sizeof( FoxInfo ),
   myFoxInfo
};

Visual FoxPro captures General Protection Faults (GPFs) in ActiveX controls placed on a form, or COM objects instantiated from within Visual FoxPro. A GPF in an ActiveX control or COM object is now treated as a trappable Visual FoxPro error (Error 1440 - OLE object might be corrupt).

See Also

Creating a Basic ActiveX Object | API Library Construction | Adding Visual FoxPro API Calls | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Passing and Reception of Parameters | SET LIBRARY TO


Adding Visual FoxPro API Calls

To integrate your program with Visual FoxPro, you can call Visual FoxPro API routines. These API routines are functions you can call from any C or C++ program, including an .ocx or .fll file, that give you access to variables, manage database operations, and accomplish many other Visual FoxPro-specific tasks.

The following table lists the general categories of API calls available in Visual FoxPro. For details about individual API functions, see API Library Routines A-Z or API Library Routines by Category.

To use the Visual FoxPro API routines, you must include the file Pro_ext.h, available in the Visual FoxPro API directory. This file includes the prototypes for the functions and structures that allow you to share information with Visual FoxPro.

If you're writing an ActiveX control, you must also add calls to initialize and clear the API.

To add Visual FoxPro API routines to your ActiveX object

  1. Use #INCLUDE to include the Pro_ext.h file along with any other required header files.
  2. In the Constructor (Init method) of the control, call _OCXAPI( ) to initialize the interface to Visual FoxPro using this code:
    _OCXAPI(AfxGetInstanceHandle(),DLL_PROCESS_ATTACH);
  3. Include calls to the Visual FoxPro API as required in your object.
  4. In the Destructor (Destroy method) for the object, call _OCXAPI( ) again to release the process created in the Constructor, using this code:
    _OCXAPI(AfxGetInstanceHandle(),DLL_PROCESS_DETACH);

For an example of an .fll library that includes calls to the Visual FoxPro API, see the sample programs in \Api\Samples directory that have the extension C: EVENT.C, HELLO.C, and so on.

If you use Visual FoxPro API calls in your ActiveX control, COM object, or .fll library, the code containing the calls is incompatible with other applications. You might therefore want to build one or more tests into the program to determine whether the object is being called from Visual FoxPro.

For example, if you're creating an ActiveX control using the Microsoft Foundation Classes, you can change the control's constructor code to include a test and then alert the user if the control has been called from a program other than Visual FoxPro:

if (!_OCXAPI(AfxGetInstanceHandle(),DLL_PROCESS_ATTACH))
{
   ::MessageBox(0,"This OCX can only be hosted by Visual Foxpro","",0);
      //Here you can do whatever you want when the host isn't VFP:
      // you might want to reject loading or you
      // might want to set a property
      // saying that the host isn't VFP and the control will use other
      // means to achieve it's purpose.
}

If you're creating an ActiveX control using the Microsoft ActiveX Template Library, use the following code:

if (!_OCXAPI(_Module.GetModuleInstance(),DLL_PROCESS_ATTACH))
{
   ::MessageBox(0,"This OCX can only be hosted by Visual Foxpro","",0);
      //Here you can do whatever you want when the host isn't VFP:
      // you might want to reject loading or you
      // might want to set a property
      // saying that the host isn't VFP and the control will use other
      // means to achieve it's purpose.
}

In this example, the control doesn't exit, and will continue running after the user has acknowledged the message. The strategy you choose depends on how you anticipate the control will be used. For example, if you detect that the control is being used outside of Visual FoxPro, you can set a flag that you test at each point in the control where you call the Visual FoxPro API. If the flag indicates that the control is outside Visual FoxPro, you can branch around the API call to an alternative means of accomplishing the same task.

See Also

Creating a Basic FLL Library | Accessing the Visual FoxPro API | Passing and Reception of Parameters | Return of a Value to Visual FoxPro | Extending Visual FoxPro with External Libraries | API Library Construction


Passing and Reception of Parameters

When your program is called from Visual FoxPro, it can receive parameters. For example, an ActiveX control might receive parameters when one of its methods is invoked. Similarly, a Visual FoxPro program might call a function in your FLL library and pass parameters to it.

Visual FoxPro can pass parameters to your program by value or by reference. By default, parameters respect the setting made with SET UDFPARMS. Other variables (such as arrays or fields) and expressions are passed by value.

To force a parameter to be passed by reference, precede the variable reference with the @ operator. To force a parameter to be passed by value, enclose it in parentheses.

Note In Visual FoxPro, individual array elements are always passed by value. When SET UDFPARMS is set to VALUE and no array element is specified, the array name by itself refers to the first element of the array (unless it is prefixed with @).

Because ActiveX controls and COM objects are Windows-standard programs, no special mechanism is required to pass parameters from Visual FoxPro and your program. You can write the program as if it were receiving parameters from any C or C++ program.

In contrast, functions in an FLL library use the FoxInfo structure to receive data from Visual FoxPro. The FoxInfo structure lists your library functions and the number and type of parameters they expect. For example, the following FoxInfo structure belongs to a library with one function, internally called dates, that accepts one Character parameter:

FoxInfo myFoxInfo[] = {
   { "DATES", (FPFI) dates, 1, "C" }
};

Functions you define in your libraries actually receive only one parameter, a pointer to the parameter block. This parameter block, defined in the ParamBlk structure, holds all the information about the parameters that were passed from the Visual FoxPro function call. Your function declaration follows this format:

void function_name(ParamBlk *parm)

For example, the function definition for dates is:

void dates(ParamBlk *parm)

The ParamBlk structure consists of an integer that represents the number of parameters, immediately followed by an array of parameter unions. The structure definition is included in Pro_ext.h:

/* A parameter list to a library function.      */
typedef struct {
   short int pCount;      /* number of parameters passed */
   Parameter p[1];         /* pCount parameters */
} ParamBlk;

The Parameter typedef included in the ParamBlk structure is a union of a Value structure and a Locator structure. Call by value is handled by a Value structure; call by reference is handled by a Locator structure. You use these structures to access the parameters passed to your function when the function is called in Visual FoxPro.

The following information is extracted from the file Pro_ext.h and shows the definition of the Parameter type:

/* A parameter to a library function.         */
typedef union {
   Value val;
   Locator loc;
} Parameter;

Value Structure Definition

If a parameter is passed to your function by value, use the Value structure to access it. The following Value structure definition is extracted from the Pro_ext.h file:

// An expression's value.
Typedef struct {
   char         ev_type;
   char         ev_padding;
   short         ev_width;
   unsigned      ev_length;
   long         ev_long;
   double         ev_real;
   CCY         ev_currency;
   MHANDLE      ev_handle;
   ULONG         ev_object;
} Value;

Value Structure Fields

The following table is a guide to the values you can pass and receive in the Value structure for different types of data. Only the structure fields listed for a data type are used for that data type.

Contents of Value structure for different data types

Data type Structure field Value
Character
ev_type
 'C'
ev_length
 string length
ev_handle
 MHANDLE to string
Numeric
ev_type
 'N'
ev_width
 Display width
ev_length
 Decimal places
ev_real
 Double precision
Integer
ev_type
 'I'
ev_width
 Display width
ev_long
 Long integer
Date
ev_type
 'D'
ev_real
 Date1
Date Time
ev_type
 'T'
ev_real
 Date + (seconds/86400.0)
Currency
ev_type
 'Y'
ev_width
 Display width
ev_currency
 Currency value2
Logical
ev_type
 'L'
ev_length
 0 or 1
Memo
ev_type
 'M'
ev_wdith
 FCHAN
ev_long
 Length of memo field
ev_real
 Offset of memo field
General
ev_type
 'G'
ev_wdith
 FCHAN
ev_long
 Length of general field
ev_real
 Offset of general field
Object
ev_type
 'O'
ev_object
 Object identifier
Null
ev_type
 '0' (zero)
ev_long
 Data type

1. The date is represented as a double-precision floating-point Julian day number calculated using Algorithm 199 from Collected Algorithms of the ACM.
2. The currency value is a long integer, with an implied decimal point in front of the last four digits.

Note ev_length is the only true indicator of a string's length. The string can't have a null terminator because the string can contain embedded null characters.

Locator Structure Definition

Use the Locator structure to manipulate parameters passed by reference. The following Locator structure definition is extracted from the Pro_ext.h file:

typedef struct {
  char  l_type;
  short l_where, /* Database number or -1 for memory */
  l_NTI,      /* Variable name table offset*/
  l_offset,  /* Index into database*/
  l_subs,  /* # subscripts specified 0 <= x <= 2 */
  l_sub1, l_sub2; /* subscript integral values */
} Locator;

Locator Structure Fields

The following table is a guide to the fields in the Locator structure.

Locator field Field use
l_type
 'R'
l_where
 The number of the table containing this field, or – 1 for a variable.
l_NTI
 Name Table Index. Visual FoxPro internal use.
l_offset
 Field number within table. Visual FoxPro internal use.
l_subs
 For variables only, the number of subscripts (0 – 2).
l_sub1
 For variables only, the first subscript if l_subs is not 0.
l_sub2
 For variables only, the second subscript if l_subs is 2.
Note It's good programming practice to check for the parameter type in ev_type to help determine which fields to access from the Value structure.

An Example of Accessing Parameters in an FLL Library

The following example uses _StrCpy( ) to return a Character type to Visual FoxPro that's the concatenation of its two Character parameters. Notice that although the handle of each parameter's Value structure is used as working memory to perform the concatenation, changes to this memory allocation don't affect the Visual FoxPro argument that was passed by value.

#include <Pro_ext.h>

Example(ParamBlk *parm)
{
// make the paramBlk structure easier
// to manage by using #define shortcuts
#define p0 (parm->p[0].val)
#define p1 (parm->p[1].val)

// make sure there is enough memory
if (!_SetHandSize(p0.ev_handle, p0.ev_length + p1.ev_length))
   _Error(182); // "Insufficient memory"

// lock the handles
_HLock(p0.ev_handle);
_HLock(p1.ev_handle);

// convert handles to pointers and make sure the
// strings are null-terminated
((char *)_HandToPtr(p0.ev_handle))[p0.ev_length] = '\0';
((char *)_HandToPtr(p1.ev_handle))[p1.ev_length] = '\0';

// concatenate strings using the API function _StrCpy
_StrCpy((char *)_HandToPtr(p0.ev_handle) + p0.ev_length,
_HandToPtr(p1.ev_handle));

// return the concatenated string to Visual FoxPro
_RetChar(_HandToPtr(p0.ev_handle));

// unlock the handles
_HUnLock(p0.ev_handle);
_HUnLock(p1.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"STRCAT", Example, 2, "CC"},
};

FoxTable _FoxTable = {
   (FoxTable *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Adding Visual FoxPro API Calls | Return of a Value to Visual FoxPro | Accessing the Visual FoxPro API | Passing of Parameters to Visual FoxPro API Functions | Extending Visual FoxPro with External Libraries | API Library Construction


Return of a Value to Visual FoxPro

The method you use to return a value from your program to Visual FoxPro depends on whether you're creating an ActiveX control or an FLL library.

Returning a Value from an ActiveX Control

To return a value from the ActiveX control to Visual FoxPro, use the RETURN statement in the control, passing a single value, as in the following example:

#define VERSION 101

// other code here

long CPyCtrl::GetVersion()
{
   // set the version number here in variable fVersion
   return VERSION;
}

Returning a Value from an FLL Library

To return values from an FLL library, use API functions, not native C or C++ commands. The following functions allow you to return values to Visual FoxPro.

Note Don't use the following API function to return a value from an .ocx file; use the RETURN statement. The API return functions should only be used in FLL libraries.
Function | Description
_RetChar(char *string) | Sets the function return value to a null-terminated string.
_RetCurrency(CCY cval, int width) | Sets the function return value to a currency value.
_RetDateStr(char *string) | Sets the function return value to a date. The date is specified in mm/dd/yy[yy] format.
_RetDateTimeStr(char *string) | Sets the function return value to a date and time specified in mm/dd/yy[yy] hh:mm:ss format.
_RetFloat(double flt, int width, int dec) | Sets the function return value to a float value.
_RetInt(long ival, int width) | Sets the function return value to a numeric value.
_RetLogical(int flag) | Sets the function return value to a logical value. Zero is considered FALSE. Any non-zero value is considered TRUE.
_RetVal(Value *val) | Passes a complete Visual FoxPro Value structure; any Visual FoxPro data type except for memo can be returned. You must call _RetVal( ) to return a string that contains embedded null characters or to return a .NULL. value.
Note To return the value of an object data type, use the _RetVal() function, filling in the ev_object field in the Value structure.

The following example, Sum, accepts a reference to a numeric field in a table and uses _RetFloat to return the sum of the values in the field:

#include <Pro_ext.h>

Sum(ParamBlk *parm)
{
// declare variables
double tot = 0, rec_cnt;
int i = 0, workarea = -1; // -1 is current workarea
Value val;

// GO TOP
_DBRewind(workarea);

// Get RECCOUNT( )
rec_cnt = _DBRecCount(workarea);

// Loop through table
for(i = 0; i < rec_cnt; i++)
{
   //Place value of the field into the Value structure
   _Load(&parm->p[0].loc, &val);

   // add the value to the cumulative total
   tot += val.ev_real;

   // SKIP 1 in the workarea
   _DBSkip(workarea, 1);
}

// Return the sum value to Visual FoxPro
_RetFloat(tot, 10, 4);
}
// The Sum function receives one Reference parameter
FoxInfo myFoxInfo[] = {
   {"SUM", Sum, 1,"R"}
};
FoxTable _FoxTable = {
   (FoxTable *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

Assuming there's a numeric field named amount in the currently open table, the following line of code in a Visual FoxPro program calls the function:

? SUM(@amount)

See Also

Passing and Reception of Parameters | Passing of Parameters to Visual FoxPro API Functions | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Access to Visual FoxPro Variables and Fields | API Library Construction


Passing of Parameters to Visual FoxPro API Functions

Often the Visual FoxPro API routines will require parameters of a particular Visual FoxPro data structure. The following sections provide a list of Visual FoxPro data types and additional data structures. For the actual type definitions and structure definitions, refer to the Pro_ext.h file.

Visual FoxPro API Data Types

The following data types are used in Visual FoxPro API routines.

Data type Description
EDLINE
 The number of a line in an open file in an editing window. The first line is 1.
EDPOS
 The offset position of a character in an open file in an editing window. The offset position of the first character in the file or memo field is 0.
FCHAN
 File channel. Every file opened by Visual FoxPro, or through the API by using _FCreate( ) and _FOpen( ), is assigned an FCHAN.
FPFI
 A 32-bit pointer to a function returning an integer.
ITEMID
 A unique identifier assigned to a single command on a menu.
MENUID
 A unique identifier assigned to a menu.
MHANDLE
 A unique identifier given to every block of memory allocated by Visual FoxPro, or allocated through the API using _AllocHand( ). It can be de-referenced to its pointer using _HandToPtr( ).
NTI
 Name table index. Every variable and table field's name has an entry in this table.
WHANDLE
 Window handle. A unique identifier assigned to every window opened by Visual FoxPro, or opened through the API using _WOpen( ).
Note Because FAR pointers are not appropriate for 32-bit compilers, #define statements in Pro_ext.h redefine FAR, _far, and __far as null values.

Visual FoxPro API Data Structures

The primary data structures used in the Visual FoxPro API library are listed in the following table.

Structure Description
EventRec
 A structure used to describe what the system is doing at a given time.
FoxInfo
 Used in FLL libraries for communicating between Visual FoxPro and your program; not used in .ocx files.
FoxTable
 Used in FLL libraries for communicating between Visual FoxPro and your program; not used in .ocx files.
Locator
 A structure used to access parameter values (FLL) or Visual FoxPro variables or fields (FLL and ocx).
ParamBlk
 Used in FLL libraries for communicating between Visual FoxPro and your program; not used in .ocx files.
Parameter
 Used in FLL libraries for communicating between Visual FoxPro and your program; not used in .ocx files.
Point
 A structure that defines the horizontal and vertical coordinates of a single point on the screen. Coordinates are specified in rows and columns.
Rect
 A structure that defines the coordinates of a rectangle on the screen. The upper-left corner of the rectangle is defined by (top,left) and the lower-right corner is defined by (bottom-1,right-1). Coordinates are specified in rows and columns.
Value
 A structure used to access parameter values (FLL) or Visual FoxPro variables or fields (FLL and OCX).

See Also

Return of a Value to Visual FoxPro | Access to Visual FoxPro Variables and Fields | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Managing Memory | API Library Construction


Access to Visual FoxPro Variables and Fields

You can access Visual FoxPro variables or field values in your ActiveX control or FLL function, either to read them or to set them. In addition, you can create new variables that can be accessed from within Visual FoxPro.

Variables and fields are made available in Visual FoxPro in a name table, which is an array containing the names of all currently-defined variables and fields. You can access an individual element in the array using a name table index (NTI). A special API function, _NameTableIndex( ), returns the index of an existing variable or field based on a name that you provide. After you've determined the NTI for a given variable, you can read it using the _Load( ) API function or set it using the _Store( ) API function. To create a new variable, you can call the API function _NewVar( ).

To access Visual FoxPro variables or fields, you use the Value and Locator structures defined in Pro_ext.h. If you're creating an FLL library, you can use the same technique you used to access parameters passed to your functions. For details about the Value and Locator structures, see Passing and Receiving Parameters.

The following example, drawn from the Foxtlibctl.cpp program in the \Api\Samples\Foxtlib directory, illustrates how you can use the Value and Locator structures in an ActiveX control to access Visual FoxPro variables:

long CFoxtlibCtrl::TLGetTypeAttr(long pTypeInfo, LPCTSTR szArrName)
{
  int nResult = 1;
  TYPEATTR *lpTypeAttr;
  Locator loc;
  Value val;
  OLECHAR szGuid[128];
  char *szBuff;
__try {
   if (_FindVar(_NameTableIndex(( char *)szArrName),-1,&loc)) {
      ((ITypeInfo *)pTypeInfo)->GetTypeAttr(&lpTypeAttr);
      if (_ALen(loc.l_NTI, AL_ELEMENTS) < 16) {
         _Error(631); //Array argument not of proper size.
      }

      //1 = Guid
      StringFromGUID2(lpTypeAttr->guid, (LPOLESTR )&szGuid,sizeof(szGuid));
      OLEOleToAnsiString(szGuid,&szBuff);
      val.ev_type = 'C';
      val.ev_length = strlen(szBuff);
      val.ev_handle = _AllocHand(val.ev_length);
      _HLock(val.ev_handle);
      _MemMove((char *) _HandToPtr( val.ev_handle ), szBuff, val.ev_length);
      OLEFreeString((void **)&szBuff);
      _HUnLock(val.ev_handle);
      loc.l_sub1 = 1;
      _Store(&loc,&val);
      _FreeHand(val.ev_handle);

      //2 = LCID
      loc.l_sub1 = 2;
      val.ev_type = 'I';
      val.ev_long = lpTypeAttr->lcid;
      _Store(&loc,&val);

      // code for values 3 - 16 here
      ((ITypeInfo *)pTypeInfo) -> ReleaseTypeAttr(lpTypeAttr);
      }
   } __except  (EXCEPTION_EXECUTE_HANDLER) {
      nResult = 0;
   }
return nResult;

See Also

Passing of Parameters to Visual FoxPro API Functions | Managing Memory | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Building and Debugging Libraries and ActiveX Controls | _NameTableIndex( )


Managing Memory

The Visual FoxPro API provides direct access to the Visual FoxPro dynamic memory manager. For API routines that request memory allocations, a memory identifier – or handle, is returned. The Visual FoxPro segment-loading architecture uses handles instead of pointers so it can manage memory more efficiently.

Note The techniques described in this section for managing memory using the Visual FoxPro API apply to both ActiveX controls and FLL libraries.

Using Handles

A handle refers to a memory handle, which is essentially an index into an array of pointers. The pointers point to blocks of memory that Visual FoxPro knows about. Nearly all references to memory in the API are made through handles instead of the more traditional C pointers.

To allocate and use memory in your library

  1. Allocate a handle with _AllocHand( ).
  2. Lock the handle with _HLock( ).
  3. Convert the handle into a pointer with _HandToPtr( ).
  4. Reference the memory by using the pointer.
  5. Unlock the handle with _HUnLock( ).
    Note To avoid memo file corruption, don't write to a memo file before calling _AllocMemo( ).

In order to address the allocated memory, your API routines must convert the handle to a pointer by calling the _HandToPtr( ) routine. Even if the Visual FoxPro memory manager needs to reorganize memory to obtain more contiguous memory for subsequent memory requests, the handle remains the same. Routines that grow, shrink, free, and lock memory allocations are also provided.

When you're creating external routines, try to minimize memory use. If you create an external routine that dynamically allocates memory, try to use the least amount of memory possible. Be especially careful about locking large memory allocations for long periods of time. Remember to unlock memory handles with _HUnLock( ) when they no longer need to be locked, because the performance of Visual FoxPro can be adversely affected by locked memory handles.

Caution Excessive use of dynamic memory deprives Visual FoxPro of memory for buffers, windows, menus, and so on, and degrades performance, because the memory given to fill API requests is managed by the Visual FoxPro memory manager. Allocating large handles and retaining them could cause Visual FoxPro to run out of memory and terminate abnormally. The Visual FoxPro environment has no memory protection. The external API routine cannot provide all the validation that's inherent in a standard Visual FoxPro program. If you corrupt memory, you receive messages such as "Transgressed handle," "Internal consistency error," and "Transgressed node during compaction."

The following function from an FLL library illustrates memory allocation. The example uses _RetDateStr( ) to return a Visual FoxPro Date type (assuming that the Character parameter is a proper date):

#include <Pro_ext.h>

void dates(ParamBlk  *parm)
{
   MHANDLE mh;
   char *instring;

   if ((mh = _AllocHand(parm->p[0].val.ev_length + 1)) == 0) {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   instring = _HandToPtr(parm->p[0].val.ev_handle);
   instring[parm->p[0].val.ev_length] = '\0';
   _RetDateStr(instring);
   _HUnLock(parm->p[0].val.ev_handle);
}
FoxInfo myFoxInfo[] = {
   {"DATES", (FPFI) dates, 1, "C"}
};
FoxTable _FoxTable = {
   (FoxTable *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

Understanding Stacks

The control or library you create doesn't have a stack of its own. Instead, it uses the stack of its calling program, in this case the Visual FoxPro stack. You cannot control the size of the Visual FoxPro stack or affect the amount of stack space available to an ActiveX control or .fll file.

Under normal circumstances, this distinction isn't important. The Visual FoxPro stack is generally large enough to hold the automatic variables you might need to allocate in a control or library. If you run out of stack space, you can always allocate additional memory on the heap dynamically.

Following Handle Rules

The following rules apply to ownership of handles and the responsibility for freeing them:

  • Users must free all handles they allocate, including handles allocated by functions such as _Load().
  • _Load() only creates a handle when the variable you're loading is a character string (that is, ev_type = 'C'). All the other data types store their values in the Value structure itself, while loading a character string puts an MHANDLE in the ev_handle of the Value structure.
  • In an FLL library, Visual FoxPro assumes responsibility for freeing all handles returned with _RetVal( ). Users must not free these handles, even if they allocate them.
  • Users must not free handles passed to them in their ParamBlk.
    Caution When you write an external routine that calls functions, be careful to follow all rules and check the return results. A stray pointer or handle reference could damage the Visual FoxPro internal data structures, causing an immediate abnormal termination or delayed problems, which could result in data loss.

See Also

Access to Visual FoxPro Variables and Fields | Building and Debugging Libraries and ActiveX Controls | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | _AllocHand( ) | API Library Construction


Building and Debugging Libraries and ActiveX Controls

After creating a project, you're ready to build and debug it.

Building the Project

Before building, you need to establish the project settings. Some of the settings you make depend on whether you want to create a debug or release version of the control or library. As a rule, you create debug versions of the program until you're satisfied that it's working correctly, and then you create a release version.

To specify a debug or release version

  1. From the Build menu, choose Set Default Configuration.
  2. Choose whether you're creating a debug or release version of the control.
  3. Choose OK.

To establish project settings

  1. From the Build menu, choose Settings.
  2. Under Settings For, choose whether you're creating a debug or release version of the program.
  3. Click the C/C++ tab and then make these settings:
    • In the Category list, choose Code Generation.
    • In the Calling Convention list, choose _fastcall.
    • In the Use run-time library list, choose Multithreaded DLL.
  4. Choose the Link tab and then in the Object/Library Modules text box, add one of the following libraries:
    • If you're building an .ocx, add OCXAPI.LIB from the Visual FoxPro API directory.
    • If you're building an .fll, add WINAPIMS.LIB from the Visual FoxPro API directory.
  5. Unmark Ignore all default libraries.
  6. Choose OK.

To make sure the compiler can find the necessary files

  1. From the Tools menu, choose Options.
  2. Click the Directories tab.
  3. In the Show directories for list, choose Include files.
  4. In the Directories toolbar, click the Add button.
  5. Add the directory with Pro_ext.h.
  6. In the Show directories for list, choose Library files.
  7. In the Directories toolbar, click the Add button.
  8. Add the directory with Ocxapi.lib from the Visual FoxPro API directory (when creating a control) or add the Winapims.lib from the Visual FoxPro API directory (when creating an FLL)
  9. In the Options dialog box, choose OK.

After you've specified the settings, you can compile and link your program.

To compile and link an .ocx file

  • From the Build menu, choose Build projname.ocx.

When you compile and link the .ocx file, Visual C++ automatically registers the control on the computer on which it was built. If for any reason you must register the control manually, you can do so using the following procedure.

To register the ActiveX control

  • From the Tools menu in the Microsoft Development Environment, choose Register Control.

    -or-

  • Declare and call DLLRegisterServer( ) from your program.

Debugging an ActiveX Control or FLL Library

Debugging the control or library in the context of a full Visual FoxPro application is more difficult than debugging it separately from the application. It's a good idea to create a simple test program to test the operation of your control or library.

Debugging with the Microsoft Development Environment

Microsoft Visual C++ version 4.0 and higher offers an integrated debugging environment that makes it easy to set break points and to step through your code. You can even run Visual FoxPro from Visual C++.

To start debugging with Microsoft Visual C++

  1. From the Build menu, choose Settings.
  2. In the Project Settings dialog box, click the Debug tab.
  3. In the Executable for debug session text box, type the path followed by Vfp8.exe.

    For example, type: C:\Program Files\Microsoft Visual FoxPro 8.0\Vfp8.exe.

  4. Choose OK.
  5. Set a break point in your library.
  6. From the Build menu, choose Debug. Then, from the submenu choose Go.
  7. When Visual Studio displays a message that says, " Vfp8.exe doesn't contain debugging information," choose Yes to continue.

For more information about debugging in Visual C++, see the Visual C++ documentation set.

Debugging with Other Debuggers

You should be able to debug a control or library with any debugger that correctly handles an INT 3 (_BreakPoint( )) embedded in your program. You can use any debugger for symbolic debugging as long as it can do all of the following:

  • Make a symbol table from a map file.
  • Load the symbol table independent of the program.
  • Relocate the symbols to a new address.

To debug a library

  1. Add a _BreakPoint( ) call to the routine at the point where debugging will begin.
  2. Build the control or library.
  3. Invoke your debugger.
  4. If your debugger supports symbols, load the symbol table for your library.
  5. Start Visual FoxPro.
  6. Call your library routine from Visual FoxPro.
  7. When the breakpoint is reached, make adjustments to the symbol base to align your symbols with the actual location where the library was loaded.
  8. Increment the instruction pointer (IP) register by 1 to skip over the INT 3 instruction.
  9. Continue debugging as with a normal program.
    Note Always remove any breakpoints specified in your debugger before you release your product.

See Also

Managing Memory | Access to Visual FoxPro Variables and Fields | Accessing the Visual FoxPro API | Extending Visual FoxPro with External Libraries | Return of a Value to Visual FoxPro


Development Productivity Tools

Visual FoxPro continues to provide developer tools for application development within the FoxPro application and the FoxPro language. Visual FoxPro has added and enhanced object-oriented language and behaviors. This version of Visual FoxPro includes Web-oriented language and tools designed to help rapid application development in multi-tier environments and to streamline your maintenance tasks.

In This Section

IntelliSense Overview
Describes how IntelliSense in Visual FoxPro displays information in pop-up windows and drop-down lists that assists you with statement and function completion syntax and displays the available variables, objects, properties, methods, and events of objects.
Using the Component Gallery
Describes the Component Gallery, a container for catalogs of software objects, such as class libraries, forms, buttons, and so on.
Coverage Profiler Application
Describes a coverage application, which writes information about which lines of code in a file were run whereas a profiler application provides information about which lines actually run, how many times a line is run, duration, and so on.
Productivity Tools
Discusses the different tools available to help make creating Visual FoxPro applications easier and faster.

Related Sections

Using Visual FoxPro
Describes how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Walkthroughs
Provides common scenarios and step-by-step instructions for how to create different types of applications and components.
Overview of Visual FoxPro Features
Discusses how Visual FoxPro gives you more of everything you have come to expect in a database management system (DBMS) — speed, power, and flexibility.
Customizing the Visual FoxPro Environment
Describes how to customize your development environment after installing Visual FoxPro. Environment settings include the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Project Manager Hooks
Explains that in Visual FoxPro, you can access a project programmatically, making it possible to manipulate a project as an object.


IntelliSense Overview

IntelliSense in Visual FoxPro displays information in pop-up windows and drop-down lists that assists you with statement and function completion syntax and displays the available variables, objects, properties, methods, and events of objects. IntelliSense provides automatic statement completion in the Command window and the enhanced Visual FoxPro Editor, as well as through List Members, Quick Info, and List Values. You can also use the _vfp.EditorOptions property to programmatically change the status of List Members to Auto, Manual or Disabled. For more information, see EditorOptions Property.

In Visual FoxPro, although IntelliSense is always available for native commands and functions, strong typing allows full IntelliSense support in editor windows for all user-defined code elements. Strong typing also is used in OLEPUBLIC type libraries.

In This Section

IntelliSense Support in Visual FoxPro
IntelliSense List Members is supported for _VFP and _Screen system variables, instantiated objects, visual objects, ActiveX controls, COM servers, native Visual FoxPro classes, and user-defined members. IntelliSense Quick Info is supported for object methods and events. IntelliSense List Values is supported and can be displayed for property assignments that have a fixed set of values.
Using IntelliSense in Visual FoxPro
IntelliSense functionality is activated as you type in the Visual FoxPro Editor, in code editor windows for methods, and in the Command window.
Customizing IntelliSense Using FoxCode
You can modify or add to the functionality of IntelliSense in Visual FoxPro by modifying the contents of FoxCode.dbf. By default, the FoxCode.dbf table is installed in your Windows user application folder or HOME( ) location.
Auto Table/Field/Variable Names
When you type a table-related keyword in the Visual FoxPro Editor or in the Command window, the Auto Table/Field drop-down list displays the valid members in the current context.
Auto MRU (Most Recently Used) Files
When you type one of the listed commands in the Command window, Visual FoxPro displays a drop-down list of the appropriate most-recently used (MRU) files.

Related Sections

Development Productivity Tools
Visual FoxPro provides developer tools for application development within the FoxPro application and the FoxPro language.
Starting with the Component Gallery
The Component Gallery is a container for catalogs of software objects, such as class libraries, forms, buttons, and so on.
Coverage Profiler Application
A coverage application writes information about which lines of code in a file were run. A profiler application provides information about which lines actually run, how many times a line is run, duration, and so on.
Project Manager Hooks
In Visual FoxPro, you can access a project programmatically, making it possible for you to manipulate a project as an object.
Automating Keystroke Tasks with Macros
If you find yourself using the same keystrokes repeatedly, or if you want to automate some keystroke tasks for your users, you can record and save these keystrokes in macros by using the Macros dialog box.
Productivity Tools
Learn about the different tools available to help make creating Visual FoxPro applications easier and faster.


IntelliSense Support in Visual FoxPro

IntelliSense List Members is supported for _VFP and _Screen system variables, instantiated objects, visual objects, Microsoft ActiveX controls, COM servers, native Visual FoxPro classes, and user-defined members. IntelliSense List Members from objects and native functions are supported in the Watch window.

IntelliSense Quick Info is supported for object methods and events.

IntelliSense List Values is supported and can be displayed for property assignments that have a fixed set of values.

Note Certain native commands and functions (for example, SET) also display an IntelliSense-like list. These are defined in FoxCode.dbf.

You can access IntelliSense functionality automatically for containers and controls in Visual FoxPro visual designers such as the Form designer. To use IntelliSense functionality for class references, ActiveX Controls, and COM Servers in programs, you must declare these objects as strongly typed before you reference them. For more information, see Strong Typing in Class, Objects, and Variable code.

IntelliSense is supported in the Visual FoxPro Editor for programs, in other code editor windows for methods, and in the Command window according to the following scheme:

Visual FoxPro feature | Visual FoxPro Editor | Code editor window | Command window
_SCREEN | A | A | A
_VFP/Application | A | A | A
Instantiated Objects |  |  | A
Visual Objects | S | A |
Class References | S | S |
ActiveX Controls | S | A |
COM Servers | S | S |
THIS, THISFORM, THISFORMSET | S | A |
Table and Field Names |  |  | A
User-Defined | A | A | A

A = all appropriate members S = only strongly typed members

IntelliSense Default Settings

When Visual FoxPro starts, List Values, List Members, and Quick Info are enabled. You can disable or enable default IntelliSense functionality in the IntelliSense Manager option of the Tools menu. Even when Auto IntelliSense is disabled, you can enable IntelliSense functionality by using keyboard shortcuts (CTRL+I for Quick Info and CTRL +J for List Members and List Values).

In addition, you can enable or disable IntelliSense functionality programmatically by setting the _VFP.EditorOptions property value. For more information, see EditorOptions Property.

You can add or modify some Visual FoxPro IntelliSense functionality by adding or modifying records in FoxCode.dbf or by making selections in the IntelliSense Manager.

See Also

IntelliSense Overview | Auto Table/Field/Variable Names | Auto MRU (Most Recently Used) Files | Using IntelliSense in Visual FoxPro | Customizing IntelliSense Using FoxCode | List Members | Quick Info | List Values | FoxCode Object


List Members

Valid members (properties, methods, events, and objects) are listed for a specific object reference. When you enter the name of an object, property, or valid Visual FoxPro command or function, an activator key displays a drop-down list of valid values for the current member.

For objects, the activator key is usually a period (.). For commands and functions, the activator key can be a space bar or the left (open) parenthesis.

As you type or navigate through the list, List Members displays a tip describing the type or the range of the selected item.

The List Members drop-down list remains open until you do one of the following:

  • Enter all required parameters, followed by a space
  • Type a terminator key (ESC, END, HOME, or invalid character key)
  • Change the active window

The status of List Members can be changed to Auto, Manual or Disabled within the General tab of the IntelliSense Manager. For more information, see Visual FoxPro IntelliSense Manager Window. You can also use the _vfp.EditorOptions property to programmatically change the status of List Members to Auto, Manual or Disabled. For more information, see EditorOptions Property.

When set to Automatic, List Members appears when an Activator key is pressed. With List Members set to Manual, you can activate List Members with the Edit menu, shortcut menu or using CTRL+J if the cursor is positioned at a location with available properties, methods, or events.

List Members is available wherever you can type Visual FoxPro code, including the Visual FoxPro Editor, the Command window, and all code window editors.

See Also

IntelliSense Overview | IntelliSense Support in Visual FoxPro | Quick Info | List Values | EditorOptions Property


Quick Info

Quick Info is a list of syntax information on commands, functions, variables and properties, methods, and events of instantiated objects.

Quick Info is usually activated by the left (open) parenthesis for functions and with a space (" ") for commands.

When you enter the name of a valid Visual FoxPro statement or function, the syntax, with the first parameter in bold font, displays immediately below the current line. After you enter an argument value, the next argument appears in bold font.

The status of Quick Info can be changed to Auto, Manual or Disabled within the General tab of the IntelliSense Manager. For more information, see Visual FoxPro IntelliSense Manager Window. You can also use the _vfp.EditorOptions property to programmatically change the status of Quick Info to Auto, Manual or Disabled. For more information, see EditorOptions Property.

When set to Automatic, Quick Info appears when an Activator key is pressed. With Quick Info set to Manual, you can activate Quick Info with the Edit menu or shortcut menu or using CTRL+I if the cursor is positioned at a location with available Quick Info.

Quick Info is available wherever you can type Visual FoxPro code, including the Visual FoxPro Editor, the Command window, and all code window editors.

See Also

IntelliSense Overview | IntelliSense Support in Visual FoxPro | List Members | List Values | EditorOptions Property


List Values

List Values is a list of valid property settings. For example, if the property is Logical type, the display list contains True and False. For properties in type libraries, list values supports enumerations. List Values is enabled along with List Members from the IntelliSense Manager or using CTRL+J. You can also use the _vfp.EditorOptions property to programmatically enable or disable Quick Info.

List Values is usually activated by the equals (=) key.

Note List Members, Quick Info, and List Values, once enabled through the IntelliSense Manager, are activated whenever you type an activator key.

See Also

IntelliSense Overview | IntelliSense Support in Visual FoxPro | List Members | Quick Info | EditorOptions Property


Using IntelliSense in Visual FoxPro

IntelliSense functionality is activated as you type in the Visual FoxPro Editor, in code editor windows for methods, in the Command window, and in the Watch window when debugging code.

To display IntelliSense drop-down lists and dialog boxes

  • Enter Visual FoxPro or user-defined keywords in an editor.

    Keywords in this case are syntax elements in Visual FoxPro commands, functions, and class definitions; ActiveX control methods and events; COM servers; and user-defined keywords. When you use the AS clause in code, IntelliSense displays a drop-down list of available types, including types from the following sources:

    • Visual FoxPro object base classes
    • Visual FoxPro data types

    The following items will be listed if you add them in the IntelliSense Manager:

    • Registered type libraries
    • User-defined types and enumerated values and custom classes

    To implement IntelliSense for Visual FoxPro and COM classes in code (.prg) files, you must employ strong typing. Internally, for objects created at run time by commands such as CREATEOBJECT( ), CREATEOBJECTEX( ), NEWOBJECT( ), and GETOBJECT( ), Visual FoxPro creates an instance of a temporary memory object to provide the Properties, Methods and Events list. IntelliSense creates a drop-down list from those available in the class definition or type library, which it seeks in the following locations:

    • Visual FoxPro object base classes
    • Class definitions in memory, in the order in which they were loaded
    • Class definitions in the current program
    • Class definition in the class library (.vcx) file opened by the SET CLASS command
    • Class definitions in the procedure files opened by the SET PROCEDURE command
    • Class definitions in the Visual FoxPro program execution chain (for more information, see DO Command)
    • The system registration database (the Registry)
    • Keyboard shortcuts for Quick Info and List Members
  • Type an activator key in a code statement.

    Activator keys (which are determined by the type of the item in the FoxCode.dbf) are " " (space), "." (period), "(" (left or open parenthesis), and "=" (equals sign). In addition to the activator keys, IntelliSense responds to navigator and termination keys. Alphanumeric keys sequentially select from the available list, and arrow and page keys respectively pan and scroll through available list members.

Keyboard Shortcuts

You can use the Shortcut menu options, or, in the appropriate position in an editor window, you can use the following shortcut keys to engage IntelliSense features:

Shortcut keys | IntelliSense feature
CTRL+I | Quick Info
CTRL+J | List Member, List Values

IntelliSense Options

You can modify or restore the default IntelliSense Auto List and Auto Quick Info settings in the Visual FoxPro IntelliSense Manager Window. The contents of the Auto List Values drop-down list are determined by the type library of the referenced object.

The most detailed way of affecting the functionality of IntelliSense for native commands and functions is to change the contents of the FoxCode.dbf table. Object properties, methods, and events are not affected by the FoxCode.dbf table.

You can enable or disable IntelliSense functionality programmatically by setting the _VFP.EditorOptions property value. For more information, see EditorOptions Property.

You can set the font and color scheme for the drop-down list in the Windows Display Control panel. You can set the maximum number of items displayed in the drop-down list through the List display count check box in the Editor tab of the Tools menu Options dialog box.

You can access the references stored in the FoxCode.dbf at design time from the IntelliSense Manager and using the _FOXCODE system variable as in the following example:

USE (_FOXCODE) SHARED

See Also

IntelliSense Overview | IntelliSense Activator, Navigation, and Terminator Keys | Auto Table/Field/Variable Names | Auto MRU (Most Recently Used) Files | IntelliSense Support in Visual FoxPro | Customizing IntelliSense Using FoxCode | FoxCode Object | EditorOptions Property | _FOXCODE System Variable


IntelliSense Activator, Navigation, and Terminator Keys

To engage IntelliSense functionality, type a keyword followed by one of the activator, navigation, or terminator keys listed in the following table:

Activator Keys

Key | Description
 | Space. Activator key for command item types. Opens drop-down list for Visual FoxPro and user-defined keywords or displays tip window.
. | Period. Activator key for function item types. Opens drop-down list for Object properties, methods, or events (List Members) or activates tooltips or valuetips.
( | Left (open) parenthesis. Activator key. Opens drop-down list for Visual FoxPro functions or activates tooltips or valuetips.
= | Equals sign. Activator key for properties. Verifies white space between the property and the "=" character. Opens drop-down list of available values or an appropriate value editor, such as for fonts or colors, or activates tooltips or valuetips.

Navigation Keys

Key | Description
aA - zZ, 0 - 9 | Alphanumerics. Move the cursor through available matching items in the drop-down list until there are no more matches.
<— | Left arrow key. Moves the cursor left one character. Can terminate the drop-down list if the cursor moves out of context (for example, before a period).
—> | Right arrow key. Moves the cursor right one character. Can terminate the drop-down list if the cursor moves out of context (for example, beyond what is already typed).
PAGE UP | Navigator key. Moves the cursor up one page in the drop-down list.
PAGE DOWN | Navigator key. Moves the cursor down one page in the drop-down list.
TAB | Navigator key. Selects the highlighted member in the drop-down list and places the cursor immediately after the word added to the editor.

Terminator Keys

Key | Description
ESC | Terminator key. Terminates the IntelliSense drop-down list.
HOME | Terminator key. Terminates the IntelliSense drop-down list and moves the cursor to the beginning of the current line.
END | Terminator key. Terminates the IntelliSense drop-down list and moves the cursor to the end of the current line.
Return, Space, and other non-alphanumeric characters | Terminator keys. Terminate the IntelliSense drop-down list and move the cursor to the end of the current line.

See Also

IntelliSense Overview | Using IntelliSense in Visual FoxPro


Customizing IntelliSense Using FoxCode

You can modify or add to the functionality of IntelliSense in Visual FoxPro by modifying the contents of FoxCode.dbf. By default, the FoxCode.dbf table is installed in your Windows user application folder.

Note When you launch Visual FoxPro for the first time, a duplicate of FoxCode.dbf is copied to your personal Windows application data location. This can be reset in the File Locations tab of the Options dialog box.

To customize IntelliSense

  • Modify the contents of FoxCode.dbf described in the following table directly or through the Visual FoxPro IntelliSense Manager Window.

Limited IntelliSense support exists in the Watch window via the FoxCode.dbf table, depending on whether an expression is valid for the Watch window. IntelliSense is supported for the following:

  • Instantiated object List Members drop-down lists
  • Instantiated object Quick Info tips
  • _FOXCODE functions
  • m.memory variable expansion

IntelliSense is not supported for the following:

  • Instantiated object List Values drop-down lists
  • _FOXCODE commands
  • _FOXCODE default script handlers
  • _FOXCODE property value editors
  • _FOXCODE user commands
  • Most recently used (MRU) files

FoxCode.dbf Structure

Field name | Type (size) | Description
Type | C (1) | Specifies the type of reference contained in this record.
Abbrev | C (24) | Represents the minimum set of keystrokes that trigger IntelliSense for this item.
Expanded | C (26) | Specifies what is inserted at cursor.
Cmd | C (15) | Specifies the command script to execute for this item.
Tip | M | Specifies the contents of the Quick Tip info (parameters).
Data | M | Specifies all List values or any Visual FoxPro code specific to this item and can, optionally, contain other script text.
Case C (1) Specifies how the text is replaced.
U = UPPER
L = lower
M or <empty> = Mixed
P = Proper
X = Unchanged

Any value you specify in this field of the version record sets a global default for individual records that do not have a Case setting.
Save | L | Specifies whether the record is saved when the field is updated.
TimeStamp | T | Represents the Unique timestamp for this item.
Source | M | Specifies the source of record content. Core contents shipped with this version of Visual FoxPro are specified as RESERVED here. This field can contain path and file name of user-supplied records.
UniqueID | C (10) | Specifies a unique identifier for this record.
User | M | Specifies user information.

Valid FoxCode.dbf Type Column Values

Value | Type | Description
C | Command | Specifies Visual FoxPro command and auto-completion items.
F | Function | Specifies Visual FoxPro functions used in Quick Info tips.
O | COM Component | Specifies the COM Typelib reference for use with AS drop-down list.
P | Property | Specifies Visual FoxPro properties.
S | Script | Specifies that the data field contains Visual FoxPro script to be run.
T | Typing | Specifies items that appear in the AS drop-down list or when referenced as an object.
U | User | Specifies user-defined auto-expansion items. These items, unlike Command item types, do not have to be absolute pattern matches.
V | Version | Specifies the special record for version information (reserved).

COM Component Item Type

COM Component item type is a FoxCode.dbf record whose contents will appear in an AS clause drop-down list, such as a Typing item type record. The COM Typing item type record represents the name of the COM type library that contains a collection of classes (ProgIDs), instances of which can be created by Visual FoxPro using the CreateObject( ) function.

The Data field of this type record contains the GUID and version for the type library rather than code, as in the following table:

Field Name | Example
Type | O
Abbrev | Excel
CMD | {}
Tip | Microsoft Excel 9.0 Object Library
Data | {00020813-0000-0000-C000-000000000046}#1.3

Command Item Type

Command item type is a FoxCode.dbf record whose contents represent Visual FoxPro command completion or substitution statements as in the following table:

Field Name | Example
Type | C
Abbrev | MC
Expanded | MODIFY COMMAND

You trigger the content of these records in IntelliSense by typing either the Abbrev field or the expanded value contents followed by a space in an editor.

Function Item Type

Function item type is a FoxCode.dbf record whose contents represent Visual FoxPro functions, procedures, and user-defined functions as in the following table:

Field Name | Example
Type | F
Abbrev | FCOU
Expanded | FCOUNT
Tip | [nWorkArea | cTableAlias]

You display the Tip field content of these records in a Tip window by typing the Abbrev value or the expanded value followed by a left parenthesis.

Property Item Type

Property item type is a FoxCode.dbf record whose contents specify a property. Use this type to add a custom Value Editor when assigning values to the specified property.

The following is an example of specifying value editors for properties (P type entries in table):

Field Name | Example
Type | P
Abbrev | .Picture
Cmd | {picture}

The Cmd field contains a reference, "{picture}", to a FoxCode script record whose ABBREV field contains the value "picture" (see the Script item type for more information). By typing ".picture=" you run the code contained in the script record related to this property record.

Except in Type = "T" or "O" records, if the Cmd field contains only beginning and ending braces ("{}") with no script reference, the record contains its own script in the Data field as in the following table:

Field Name | Example
Type | C
Abbrev | NOW
Cmd | {}
Data | LPARAMETER oFoxCode RETURN TRANSFORM(DATE( ))

Script Item Type

Script item type is a FoxCode.dbf record that can contain text as code in its data field. Another record executes this code by referencing it in the Cmd field. This type of record can contain the following:

  • FoxCode in Data field to be evaluated to text.
  • An ID in the Cmd field that references another record that contains the code. By placing code in a separate Script item type as in the following table, you enable multiple items to reference the same code:
    {picture}…
    Field Name | Example
    Type | S
    Abbrev | Picture
    Data (In the Memo field)
    LPARAMETER oFoxcode
LOCAL lcPicture
oFoxcode.valuetype="V"
lcPicture = getpict()
IF LEN(lcPicture) > 0
   lcPicture = ['] + lcPicture+ [']
ENDIF
RETURN lcPicture

In this example, a Property item type record with "picture" in the ABBREV field references this Script item type record and runs the code in the Data field, displaying the Open Picture dialog box.

The script in Script records must contain a PARAMETERS or LPARAMETERS statement to accommodate the object reference.

The Return value replaces the typed text. If the return value evaluates to an empty string (""), Visual FoxPro leaves the typed text unchanged.

Each script called by IntelliSense must contain a parameter that is passed to the FoxCode parameter object. This object contains metadata detailing how the script was called, including the source record in the FoxCode table. For details, see FoxCode Object Reference.

Typing Item Type

Typing item type is a FoxCode.dbf record that represents the contents of an item displayed in the drop-down list of an AS clause. Optionally, the Data field of this record can contain code whose return value is inserted at the screen cursor location. If you include text in the Data field, end it with a RETURN statement.

Field Name | Example
Type | T
Abbrev | CommandButton

User Item Type

User item type is a FoxCode.dbf record used to specify abbreviations for user-defined content as in the following table. Unlike the Command item type, the User item type abbreviation does not have to be the same as the initial characters of the expansion content.

Field Name | Example
Type | U
Abbrev | MYADDRESS
Expanded | 101 Main Street

Version Item Type

Version item type is the FoxCode.dbf record used for default settings and to track version information. This is reserved for internal use.

Field Name | Example
Type | V
Expanded | <Identifies latest version of FoxCode> For internal use.

See Also

IntelliSense Overview | Using Scripting in FoxCode.dbf | Visual FoxPro IntelliSense Manager Window | Auto Table/Field/Variable Names | Auto MRU (Most Recently Used) Files | IntelliSense Support in Visual FoxPro | Using IntelliSense in Visual FoxPro | FoxCode Object


Using Scripting in FoxCode.dbf

You can enhance significantly the design time functionality of Visual FoxPro by modifying the FoxCode.dbf. You can add your own procedures by changing field values or by adding Visual FoxPro code to the Data field of Script item types. You can create script items that provide code for any other item, or you can include code within an item that is specific to that record.

To enable scripting for any item

  1. Place a reference to the triggering keystrokes (from the Abbrev field) in the Cmd field of an item. A reference consists of the triggering keystrokes delimited by right and left braces as in this example:

    {picture}

  2. Copy the triggering keystrokes to the Abbrev field of the referenced Script item.

    To apply an existing script to this item, reference the Abbrev field contents of the Script item type record that contains the code you want to use in its Data field.

  3. Add appropriate Visual FoxPro code to the Data field of the script item as in the following example from the Data field of the Script item type referenced by the earlier Cmd field example:
    LPARAMETER oFoxcode
LOCAL lcPicture
oFoxcode.valuetype="V"
lcPicture = getpict()
IF LEN(lcPicture) > 0
   lcPicture = ['] + lcPicture+ [']
ENDIF
RETURN lcPicture

    You can access Script item types from any other item type by using this procedure, allowing one Script item to serve many other items.

In the following example, each item requires two records to enable its functionality – the calling item, which contains the reference information, and the Script item type, which contains the code to be run.

To enable scripting within an item type

  • Provide appropriate Visual FoxPro code in the Data field of the item record.

    This example uses the code in the previous Script item type in the Data field.

    LPARAMETER oFoxcode
LOCAL lcPicture
oFoxcode.valuetype="V"
lcPicture = getpict()
IF LEN(lcPicture) > 0
   lcPicture = ['] + lcPicture+ [']
ENDIF
RETURN lcPicture

Data Fields and the FoxCode Object

The Data field generally contains script code to be executed by user-defined IntelliSense scripts. However, it can also be used just to store data used by scripts. This type of metadata is automatically passed to a script by the FoxCode parameter object.

For details about the FoxCode object, see FoxCode Object.

See Also

IntelliSense Overview | Customizing IntelliSense Using FoxCode | Visual FoxPro IntelliSense Manager Window | FoxCode Object


Auto Table/Field/Variable Names

The Auto Table/Auto Field/Variable Names functionalities of IntelliSense's list of field names in the open table is referenced by typing USE or USE + the alias in the Command window. The information in this drop-down list consists of table names or field names, depending on the reference.

When you type a table-related keyword in the Visual FoxPro Editor or in the Command window, the Auto Table/Field drop-down list displays the valid members in the current context. As you type or tab through the list of fields, a Tip window displays the type and width of the field in focus.

The following table lists the Auto Table/Field keywords:

Keyword | Function
USE | Shows tables from the active database and MRU tables.
REPLACE | Shows fields from the table, cursor, or view in the currently selected work area.
MODIFY MEMO | Shows memo fields from the table, cursor, or view in the currently selected work area.
MODIFY GENERAL | Shows general fields from the table, cursor, or view in the currently selected work area.

In addition, you can type "m." in the Command window to view a list of all declared variables in a drop-down window. When you select a variable, its value is displayed in a menu tip.

See Also

IntelliSense Overview | Auto MRU (Most Recently Used) Files | IntelliSense Support in Visual FoxPro | Using IntelliSense in Visual FoxPro | Customizing IntelliSense Using FoxCode


Auto MRU (Most Recently Used) Files

Auto Most Recently Used (MRU) functionality of IntelliSense is a list of available, most recently used files of the types associated with specific commands. When you type one of the listed commands in the Command window, Visual FoxPro displays a drop-down list of the appropriate MRU files. Auto MRU Files is activated by the spacebar key.

Specific Visual FoxPro commands seek and open files of a default set of file extension as described in the following list:

Command | File extensions and types
CD | path
DO | .prg, .mpr, .qpr, .fxp, .app, .exe
DO FORM | .scx
LABEL FORM | .frx, .lbx
MODIFY CLASS | .vcx
MODIFY COMMAND | .prg, .mpr, .qpr
MODIFY DATABASE | .dbc
MODIFY FILE | any file type and extension
MODIFY FORM | .scx
MODIFY LABEL | .lbx
MODIFY MENU | .mnx
MODIFY PROJECT | .pjx
MODIFY QUERY | .qpr
MODIFY REPORT | .frx
MODIFY VIEW | local and remote views
OPEN DATABASE | .dbc
REPORT FORM | .frx, .lbx
SET DATABASE | .dbc
USE | .dbf, view

You can control MRU functionality through the Tools, Options Dialog Box and default IntelliSense functionality through the Visual FoxPro IntelliSense Manager Window.

See Also

IntelliSense Overview | Strong Typing in Class, Objects, and Variable code | Auto Table/Field/Variable Names | IntelliSense Support in Visual FoxPro | Using IntelliSense in Visual FoxPro | Customizing IntelliSense Using FoxCode


Strong Typing in Class, Objects, and Variable code

Visual FoxPro is not a strongly typed language in which you must declare variables as a specific data type. However, strong typing provides control that makes coding easier and less error-prone, and supports IntelliSense for these items in the editor.

Note Strong typing is not enforced at design time or at run time. In Visual FoxPro, strong typing allows IntelliSense objects in the editor. Strong typing also is used in OLEPUBLIC type libraries.

To implement strong typing, use the AS clause in LPARAMETERS Command, PARAMETERS Command, LOCAL Command, and PUBLIC Command parameter and variable declarations, as well as FUNCTION Command and PROCEDURE Command statements as in the following examples:

LOCAL oExcel AS "excel.application"
oExcel = CreateObject("excel.application")
oExcel.   &&displays dropdown

PUBLIC ARRAY MyArray[2] AS _form OF ffc\_base

LPARAMETERS MyParam1 AS string OF _base.vcx

PARAMETERS MyParam1 AS custom OF Mybase.vcx

FUNCTION MyFunction AS custom

You can also use the AS clause in the DEFINE CLASS Command command to apply strong typing to objects, method parameters, and values.

DEFINE CLASS MyClass1 AS custom OLEPUBLIC
   FUNCTION MyMethod (MyParam1 AS integer, MyParam2 AS string) AS integer
      RETURN MyParam1
   ENDFUNCTION
ENDDEFINE

See Also

IntelliSense Overview | Auto MRU (Most Recently Used) Files


Using the Component Gallery

The Component Gallery is a container for catalogs of software objects such as class libraries, forms, buttons, and so on. The Component Gallery also contains Visual FoxPro classes. You can use the Component Gallery to organize components into object, project, application, or other groupings. These visual groupings are dynamically customizable so that you can use, duplicate, or rearrange components among several classifications within the Component Gallery. You can access a specific component from any of the places in the Component Gallery in which you place a reference to that component. You can have several references in different catalogs or folders to a single object. For instance, a button might appear in one or more Component Gallery project categories (represented as folders), but might also be visible in a "Tools" category that holds references to all the buttons you use.

You can use the Component Gallery for all the functions provided by the separate Project Manager, Class Browser, and Form Controls toolbar. Each of the other Visual FoxPro components provides very specific focus to the projects or classes from within the special environment of either Project file or Class library. The Component Gallery allows you to manage the relationships between components and many of the behaviors of those components from an abstract design level as well as from a more intimate development perspective.

You can drag and drop components within the Component Gallery and from the Component Gallery to projects or forms. You can also change properties of objects or classes from within the Component Gallery.

The Component Gallery can contain any Visual FoxPro element, including local and remote documents, files, or folders, Automation servers like Microsoft Excel and Word, and HTML locations and files. You can also include .prg files containing code snippets, classes, wizards, builders, or art.

In This Section

Managing Projects with the Component Gallery
Explains how to use the Component Gallery to use the templates, builders, and wizards in the Component Gallery to create the project or applications.
Component Gallery Catalogs
Describes how to use the Visual FoxPro Component Gallery catalogs and the default catalog, which includes items grouped into several categories, including forms, controls, and others.
Customizing the Component Gallery
Describes how you can change the default behavior of the Visual FoxPro Component Gallery catalog, folders, and gallery items by customizing the Component Gallery.
Component Gallery Object Members
Provides a list of classes and items that reference the class, which comprise the Visual FoxPro Component Gallery interface.
Component Gallery Class Library (Vpfgallery.vcx)
Explains how the Visual FoxPro Component Gallery class library, Vpfgallery.vcx, provides the item types as classes.
Component Gallery Table Structure
Describes the table structure of the Visual FoxPro Component Gallery.

Related Sections

Development Productivity Tools
Provides information on developer tools provided for application development within the Visual FoxPro application and the language.
IntelliSense Overview
Provides information on IntelliSense, which displays information in popup windows and drop-down lists that assist you with statement and function completion syntax.
Coverage Profiler Application
Discusses a coverage application, which writes information about which lines of code in a file were run, and a profiler application, which provides information about which lines actually run, how many times a line is run, duration, and so on.
Project Manager Hooks
Describes how you can access a project programmatically, making it possible for you to manipulate a project as an object.
Automating Keystroke Tasks with Macros
Describes how you can record and save keystrokes in macros by using the Macros dialog box.
Productivity Tools
Describes the different tools available to help make creating Visual FoxPro applications easier and faster.


Managing Projects with the Component Gallery

You can use the Component Gallery to create Projects and Applications and to manage their development. Use the Component Gallery to arrange components within the Component Gallery or use the templates, builders, and wizards in the Component Gallery to create the project or application you want.

To create a project or an application from the Component Gallery

  • Use the Application Wizard or New Application template in the Applications folder of the Visual FoxPro catalog.

For catalogs and folders, select tabs and options for the change you want to make. For details, see Component Gallery Options dialog box in Help.

Moving and Viewing Items in the Component Gallery

You can move items in the right, Object, pane of the Component Gallery window to the desktop or to an open project or form. The Project Manager recognizes the item referenced by the Component Gallery item and places it in the proper location in the Project Manager. Component Gallery items placed on the desktop are nonfunctional. There is no desktop representation for the Database, Folder, and gallery items representing nonvisual files.

To move items from the Component Gallery

  1. In the right pane, click the item you want to move.

    The Move icon, located in the upper-left corner of the Component Gallery window, changes according to what item you select.

  2. Drag and drop the Move icon to the desktop or to an open project or form.

When the Component Gallery cannot find the original item represented by the gallery item, a Find dialog box opens so that you can locate the item.

The following table identifies the gallery items included in Visual FoxPro and their default behaviors.

Component Gallery Item Type | Project | Form | Screen | Controls
Class (_ClassItem) |  |  | 6 |
File (_FileItem) |  |  |  |
URL (_UrlItem) |  | 1 |  |
Form (_FormItem) |  | 9 | 11 |
Report (_ReportItem) |  | 9 | 11 |
Program (_ProgramItem) |  |  | 11 |
Menu (_MenuItem) |  | 10 | 11 |
Image (_ImageItem) |  | 2 | 7 | 2
Sound (_SoundItem) |  | 3 |  |
Video (_VideoItem) |  | 3 |  |
ActiveX (_ActiveXItem) |  |  |  |
Data (_DataItem) |  | 4 |  |
Template (_TemplateItem) | 5 |  |  |
Catalog (_CatalogItem) |  |  | 8 |
Sample (_SampleItem) |  |  |  |
Project (_ProjectItem) |  |  | 11 |

1 – Add hyperlink class
2 – Add an image class or set a Picture property
3 – Add a multimedia class
4 – Add a grid class
5 – Depending on the type (for example, form) creates a new file and adds it to the project
6 – Creates an instance in Screen
7 – Sets the Visual FoxPro wallpaper
8 – Launches a new Gallery window with that catalog
9 – Add a Button class to launch a form/report
10 – Add a shortcut menu to a form
11 – Opens in a designer (modifies)

Using Shortcut Menus in the Component Gallery

You can right-click on a selected item in the right, Object, pane to display an Item Shortcut menu containing all the action options for that item, including Add to Project or Add to Form options. Use the shortcut menu to modify or, in some cases, run the gallery item. The shortcut menus are characteristic for each type of gallery item. You can change some properties of the selected item by clicking Properties on the shortcut menu to open the Item Properties dialog box.

Organizing Visual FoxPro or Windows Components into User-Defined Groups

The Component Gallery folders represent an arbitrary grouping of gallery items. You can reassemble the gallery items using drag and drop or you can duplicate items into other folders. You can copy and rename a catalog or folder and reassemble the items it contains. There are few, if any, limits on how you can use, modify, or create catalogs or folders.

Reviewing and Modifying Classes

Because Component Gallery items represent real items that can be objects or classes, you can review or modify these classes by accessing the original object through the Component Gallery.

To review a class

  1. In the Component Gallery, right-click a class.
  2. On the shortcut menu, click View in Browser.

    This opens the Class Browser, so you can view the properties and methods of the selected class.

To modify a class

  1. In the Component Gallery, right-click a class.
  2. On the shortcut menu, click Modify.

    This opens the class in the Class Designer.

Creating and Modifying Forms

You can use the Component Gallery to duplicate or modify forms and to add forms and other gallery items to a project.

To create a form from the Component Gallery

  • Double-click any template or select New Form from the shortcut menu of any template in the Forms folder of the Component Gallery.

    -or-

    Double-click the Form Wizard in the Forms folder of the Component Gallery.

    -or-

    Select Create Form from the shortcut menu of Component Gallery items in the Forms folder of the Component Gallery.

Advanced Editing Features in the Component Gallery

The default settings for catalogs and folders enable you to perform basic review and management with gallery items. If you want to modify characteristics of catalogs or folders, or if you want greater access to gallery properties, select Advanced editing enabled in the Component Gallery Options dialog box.

See Also

Using the Component Gallery | Component Gallery Catalogs | Development Productivity Tools | Customizing the Component Gallery | Component Gallery Object Members


Component Gallery Catalogs

When you open the Component Gallery, the left, Catalog, pane displays the default catalog shipped with the Component Gallery. A catalog is a visual representation of items that belong to a Visual FoxPro or user-defined group of items. Within a catalog you can create folders to further organize subgroups of items. Items can be forms, queries, programs, templates, art files, sound files, or other objects. The Visual FoxPro Component Gallery default catalog includes items grouped into several categories, including forms, controls, and others. The default catalog also includes an empty folder named Favorites that you can use to create or copy gallery items into. You can also copy and rename the default catalog, or create your own catalogs.

Component Gallery catalog options are set for catalog content and opening behavior. Global catalogs can contain any Component Gallery item type. Default catalogs open automatically when you start the Component Gallery. For details, see the Catalogs tab of the Component Gallery Options dialog box in Help.

The Component Gallery includes the following catalogs.

Catalog | Description
VFPGLRY | Contains components used by other catalogs in the gallery. Contains all the catalogs shipped with Visual FoxPro. Default and Global catalog.
Visual FoxPro | Contains the Visual FoxPro Foundation classes. Default catalog.
Favorites | An empty folder. Global catalog
My Base Classes | Contains subclassed Visual FoxPro base classes. Default catalog
ActiveX | A dynamic catalog containing either a list of all registered ActiveX Controls or a list of all Visual FoxPro ActiveX Controls. Default catalog.
World Wide Web | A collection of Web site URLs
Multimedia | A variety of images, sounds, and video items you can use in your applications
Samples | References to the Solutions, ActiveX Servers and Client/Server samples

When you click a catalog in the list view, the right, Object, pane, displays the contents of that catalog. You can open other catalogs by double-clicking the catalog in either panel. Several Catalogs are included in the Gallery folder.

See Also

Managing Projects with the Component Gallery | Customizing the Component Gallery | Component Gallery Object Members | Component Gallery Class Library (Vpfgallery.vcx) | Development Productivity Tools | Using the Component Gallery


Customizing the Component Gallery

You can customize the Component Gallery by changing the default behavior of catalog, folder, and gallery items through the appropriate Properties dialogs.

To create a Component Gallery catalog

  1. Select the Options button on the Component Gallery toolbar.
  2. Click the Catalogs tab in the Component Gallery Options dialog box.
  3. Click New and name the new catalog in the Open dialog.
  4. Click OK.
  5. The Component Gallery adds the catalog to the treeview so you can begin using it as you would any existing catalog.

To change a catalog or folder configuration

  1. Right-click the catalog or folder.
  2. From the shortcut menu, click Properties.
  3. In the Catalog Properties dialog box or Folder Properties dialog box, select the tab containing the options you want to configure.

    Gallery catalogs and folders, as displayed in the Component Gallery window Catalog pane, can represent URLs, folders, or files on your hard disk. You can view a Gallery folder as Web view or as an Explorer-level view, depending on the way you specify the name in the General tab of the Folder properties dialog.

Web Views

You can specify URLs or files as Gallery catalogs or as Gallery items. When you configure an item as a Gallery folder, the item automatically opens as a Web view in the Object (right) pane when you select it in the Catalog pane.

To configure a Gallery catalog or folder as a Web view

  1. In the Folder Properties Dialog_Box, select the Node tab.
  2. In the Dynamic folder field, specify the Web page or file name as in the following examples:

    http:\\www.microsoft.com\

    file:\\c:\my documents\testpage.htm

    file:\\c:\my documents\Wordfile.doc

When you highlight the Web view icon in the Catalog pane, the toolbar changes to include Web navigation buttons. The Web view will reflect the settings of your Windows Explorer.

Explorer-level Views

You can specify a directory as a Gallery folder or catalog that has characteristics of Windows Explorer.

To configure a Gallery catalog or folder as an Explorer-level view

  1. In the Folder Properties Dialog_Box, select the Node tab.
  2. In the Dynamic folder field, specify a folder or file name and backslash (\) as the value as in the following examples:

    C:\My Documents\

    Note This specification creates a view of actual files, unlike other Component Gallery views. In this view you can delete files from your disk. To create an Explorer-level view that maintains protection of displayed files, specify the target using a wildcard designation as in the following example:

    C:\My Documents\*.*

Avoid using wildcards to create dynamic folders when you can expect to find more than 512 items, unless you have a fast machine with a large amount of RAM.

See Also

Component Gallery Catalogs | Component Gallery Object Members | Development Productivity Tools | Using the Component Gallery | Component Gallery Class Library (Vpfgallery.vcx)


Component Gallery Object Members

The Component Gallery is comprised of an interface, whose classes are contained in Vfpglry.vcx, and items that reference the following Visual FoxPro Foundation Classes.

Object | Description | Class library
About Dialog | Provides a simple About dialog box for custom applications. | _dialogs.vcx
ActiveX Calendar | A calendar control that can be tied to a date field. | _datetime.vcx
Array Handler | Provides methods for handling array operations not performed by native product array functions. | _utility.vcx
Cancel Button | Releases a form and discards any outstanding buffered data. | _miscbtns.vcx
Clock | A simple clock control for a form or container. | _datetime.vcx
Conflict Catcher | A dialog box for resolution of row conflicts encountered while editing under optimistic buffering. | _dataquery.vcx
Cookies Class | A simple Web class for handling cookies between Web pages. | _internet.vcx
Cross Tab | Generates a cross tab. | _utility.vcx
Data Edit Buttons | A complete set of edit buttons (as used by Form Wizards). | Wizbtns.vcx
Data Navigation Buttons | A Top, Next, Prev, Bottom navigation button group and the DataChecker class to check for conflicts when moving records. | _datanav.vcx
Data Navigation Object | A nonvisual navigation object that other classes can use. | _table.vcx
Data Session Manager | Manages data sessions and handles data updates. | _app.vcx
Data Validation | Traps for data conflicts on buffered data. | _datanav.vcx
DBF -> HTML | Converts a Visual FoxPro cursor (.dbf) to HTML. | _internet.vcx
Distinct Values Combo | Performs a lookup of unique values from the controlsource field to populate a combo box. | _dataquery.vcx
Error Object | A generic error handler that works for both object and procedural code. | _app.vcx
Field Mover | A supermover list box that automatically loads fields from current data source. | _movers.vcx
File Registry | Provides a set of registry functions that return application-specific information. | Registry.vcx
File Version | Retrieves information from the version resource of a file. | _utility.vcx
Filter Button | Displays dialog to specify a data filter on a particular field. | _table2.vcx
Filter Dialog | A dialog that enables you to specify filter conditions on data. | _table.vcx
Filter Expression Dialog | Creates an advanced filter expression dialog. | _table.vcx
Find (Findnext) Buttons | A generic find/findnext buttonset. | _table.vcx
Find Button | Locates a record based on specific criteria. | _table.vcx
Find Dialog | A find dialog with simple options such as Field choice. | _table.vcx
Find Files/Text | Uses the Filer.DLL COM object to search for files. | _utility.vcx
Find Object | Creates a generic object that locates a record based on specified critereria. | _table.vcx
Font Combobox | A combo box that lists available fonts. It is also used by tbrEditing and rtfControls classes. | _format.vcx
Fontsize Combobox | A combo box that lists available font sizes. It is also used by tbrEditing and rtfControls classes. | _format.vcx
Format Toolbar | Provides a toolbar for applying font formatting to text of the active control. | _format.vcx
FRX -> HTML | Converts a Visual FoxPro reporting output (.frx) to HTML. | _internet.vcx
GetFile and Directory | Retrieves both a file and a folder name. | _controls.vcx
Goto Dialog Button | Creates a button that displays the Goto dialog box. | _table2.vcx
Goto Dialog | Creates a Goto record dialog box. | _table.vcx
Graph By Record Object | A navigation button group that allows you to refresh a new graph per record on the fly. | _utility.vcx
Graph Object | Generates a Graph using the core Graph Wizard engine. | Autgraph.vcx
Help Button | Displays the Help file as it starts searching for the specified HelpContextID. | _miscbtns.vcx
Hyperlink Button | Launches a Web browser from a button. | _hyperlink.vcx
Hyperlink Image | Launches a Web browser from an image. | _hyperlink.vcx
Hyperlink Label | Launches a Web browser from a label. | _hyperlink.vcx
INI Access | A set of registry functions that access old INI-style file settings. | Registry.vcx
Item Locator | This button brings up a dialog to locate a record. | _dialogs.vcx
Keywords Dialog | Creates a dialog like the Component Gallery keywords dialog. | _dialogs.vcx
Launch Button | Launches an application with an optional document. | _miscbtns.vcx
Locate Button | Displays a dialog to locate a record. | _table2.vcx
Lookup Combobox | Performs a lookup of values in a field to populate a combo box. | _dataquery.vcx
Mail Merge Object | Generates a Word Mail Merge using the core Mail Merge Wizard engine. | Mailmerge.vcx
Messagebox Handler | A simple wrapper around the MessageBox function. | _dialogs.vcx
MouseOver Effects | Highlights a control as the mouse passes over it. | _ui.vcx
Mover | Provides a simple mover list box class with move/remove buttons. | _movers.vcx
Navigation Shortcut Menu | A shortcut menu that can be dropped onto a form. | _table2.vcx
Navigation Toolbar | A set of navigation buttons in a toolbar. | _table2.vcx
Object State | Determines the state of an object and saves/restores the object property settings. | _app.vcx
ODBC Registry | A set of registry functions that return ODBC-specific information. | Registry.vcx
Offline Switch | Provides a view of online data for use offline. | _dataquery.vcx
OK Button | Performs a simple form release. | _miscbtns.vcx
Output Control | Displays a complex dialog box that prompts the user for a reporting output option. | _reports.vcx
Output Dialog | Displays a dialog box that prompts the user for a reporting output option. | _reports.vcx
Output Object | Various reporting output options. | _reports.vcx
Password Dialog | A simple Password dialog for custom applications. | _dialogs.vcx
Pivot Table | Generates a Microsoft Excel Pivot Table using the core PivotTable Wizard engine. | Pivtable.vcx
Preview Report | A generic button to run a report. | _miscbtns.vcx
QBF | Provides a buttonset for Query-By-Form querying. | _dataquery.vcx
Registry Access | Provides access to information in the Windows Registry. | registry.vcx
Resize Object | Causes form objects to resize/move with the Form's resize event. | _controls.vcx
RTF Controls | Provides a set of buttons for applying font formatting to text of the active control. | _format.vcx
Run Form Button | A button that runs a form. | _miscbtns.vcx
SCX -> HTML | Converts an .scx form to HTML. | _internet.vcx
SendMail Buttons | Uses the MAPI ActiveX Control to send a mail message from a form. | _miscbtns.vcx
Shell Execute | Provides Windows Explorer double-click behavior. | _environ.vcx
Shortcut Menu Class | This wrapper class dynamically creates shortcut pop-up menus. | _menu.vcx
Simple Edit Buttons | Provides simple Add, Edit, Delete, Duplicate, Save, and Cancel buttons (as used by Form Wizards). | Wizbtns.vcx
Simple Navigation Buttons | Provides a set of Next and Previous navigation buttons. | _table.vcx
Simple Picture Navigation Buttons | This is a set of simple picture navigation buttons. | _table2.vcx
Sort Button | Displays a dialog that enables you to perform an ascending or descending data sort on a particular field. | _table2.vcx
Sort Dialog | Enables you to perform an ascending or descending data sort on a particular field. | _table2.vcx
Sort Mover | This subclass of the supermover list box class automatically handles sorting of data. | _movers.vcx
Sort Object | Performs a sort on a data source. | _table.vcx
Sort Selector | Performs an ascending or descending sort based on the current control. | _table2.vcx
Sound Player | This class loads and plays a sound file. | _multimedia.vcx
Splash Screen | Provides a simple Splash Screen for custom applications. | _dialogs.vcx
SQL Pass Through | Provides SQL Pass Thru and can allow you to execute stored procedures on your host database. | _dataquery.vcx
Stop Watch | Provides a stop watch control for a form or container. | _datetime.vcx
String Library | Performs various string conversions. | _utility.vcx
Super Mover | Provides Move, Remove, Moveall, and Removeall buttons. | _movers.vcx
System Toolbars | A manager class that handles and tracks Systoolbars. | _app.vcx
Table Mover | This subclass of the supermover list box class automatically loads tables and fields from the current data source. | _movers.vcx
Text Preview | Provides a viewer of output text. | _reports.vcx
Thermometer | Provides a standard thermometer class. | _controls.vcx
Trace Aware Timer | This is an application utility that determines whether the trace window is open. | _app.vcx
Type Library | The main routine ExportTypeLib creates a text file with Typelib output. | _utility.vcx
URL Combo | Creates a combo box for typing in a Web URL. It launches Microsoft Internet Explorer and navigates to the site. | _internet.vcx
URL Open Dialog | Provides a dialog that creates a drop-down list that stores URL history. | _internet.vcx
VCR Buttons | A Top, Next, Prev, and Bottom navigation button group. | _table.vcx
VCR Picture Navigation Buttons | A set of VCR picture navigation buttons. | _table2.vcx
Video Player | Loads and plays a video file using MCI commands. | _multimedia.vcx
Web Browser control | A subclass of the Internet Explorer 4.0 Browser control, which provides hooks for Visual FoxPro code. | _webview.vcx
Window Handler | Performs several common window operations typical of applications. | _ui.vcx

For details on these class libraries, see Visual FoxPro Foundation Classes A-Z. For information on how to use the foundation classes, see Guidelines for Using Visual FoxPro Foundation Classes.

See Also

Customizing the Component Gallery | Development Productivity Tools | Using the Component Gallery | Component Gallery Class Library (Vpfgallery.vcx) | Component Gallery Table Structure


Component Gallery Class Library (Vpfgallery.vcx)

The Component Gallery class library, Vpfgallery.vcx, provides the item types as classes.

Item type | Description
Class (_ClassItem) | The generic item type for any Visual FoxPro class. This can be either from .vcx or .prg files.
File (_FileItem) | This is any file. Visual FoxPro reads the Registry for shell functions and adds them to the menu. The gallery includes a look up routine that checks for specific extensions and redirects the item type. The gallery supports UNC naming conventions for team development (sharing of Catalogs across networks).
ActiveX (_ActiveXItem) | This is an ActiveX Control or Server such as an .ocx created by Visual Basic CCE or .exe/.dll created by Visual FoxPro.
Data (_DataItem) | This is a Visual FoxPro datasource (.dbc, .dbf, View, and so forth.).
Image (_ImageItem) | This is a File Item Type whose file has an image file extension such as .bmp, .jpg, .gif, .ico, .cur, .ani, and so on.
Sound (_SoundItem) | This is a File Item Type whose file has either a .wav or .rmi extension.
Video(_VideoItem) | This is a File Item Type whose file has a .avi extension.
URL (_UrlItem) | This is a Web Item Type and includes Web and local documents such as HTML files.
Sample (_SampleItem) | This is a File Item Type for files that run in Visual FoxPro and can be an executable Visual FoxPro file such as .app, .exe, .prg, .scx, or .frx files.
Template (_TemplateItem) | This is a Script Item Type that opens a builder for the Visual FoxPro element represented by the type of the highlighted item, including forms and reports.
Catalog (_CatalogItem) | This is a Component Gallery type that allows you to Add and Open Visual FoxPro catalogs.
Form(_FormItem) | This is a type for Visual FoxPro forms (.scx).
Report (_ReportItem) | This is a type for Visual FoxPro reports (.frx).
Menu (_MenuItem) | This is a type for Visual FoxPro menus (.mnx).
Program (_ProgramItem) | This is a type for Visual FoxPro programs (.prg).
Project (_ProjectItem) | This is a type for Visual FoxPro projects (.pjx).

You can use the Class Browser to examine the details of any of these classes.

For details on other classes used in the Component Gallery, see Visual FoxPro Foundation Classes A-Z or use the Class Browser to examine the libraries in the Ffc folder.

See Also

Component Gallery Object Members | Component Gallery Table Structure | Development Productivity Tools | Coverage Profiler Application | Using the Component Gallery


Component Gallery Table Structure

The Visual FoxPro Component Gallery is described in the following table structure.

Field | Field Name | Type | Width | Index
1 | TYPE | Character | 12 | No
2 | ID | Character | 12 | No
3 | PARENT | Memo | 4 | No
4 | LINK | Memo | 4 | No
5 | TEXT | Memo | 4 | No
6 | TYPEDESC | Memo | 4 | No
7 | DESC | Memo | 4 | No
8 | PROPERTIES | Memo | 4 | No
9 | FILENAME | Memo | 4 | No
10 | CLASS | Memo | 4 | No
11 | PICTURE | Memo | 4 | No
12 | FOLDERPICT | Memo | 4 | No
13 | SCRIPT | Memo | 4 | No
14 | CLASSLIB | Memo | 4 | No
15 | CLASSNAME | Memo | 4 | No
16 | ITEMCLASS | Memo | 4 | No
17 | ITEMTPDESC | Memo | 4 | No
18 | VIEWS | Memo | 4 | No
19 | KEYWORDS | Memo | 4 | No
20 | SRCALIAS | Memo | 4 | No
21 | SRCRECNO | Numeric | 6 | No
22 | UPDATED | DateTime | 8 | No
23 | COMMENT | Memo | 4 | No
24 | USER | Memo | 4 | No

See Also

Component Gallery Class Library (Vpfgallery.vcx) | Coverage Profiler Application | Development Productivity Tools | Using the Component Gallery | Component Gallery Object Members


Coverage Profiler Application

A coverage application writes information about which lines of code in a file were run. A profiler application provides information about which lines actually run, how many times a line is run, duration, and more. Coverage and profiling enable a developer to identify problem areas in an application, especially skipped code and performance bottlenecks.

Visual FoxPro Coverage Profiler is provided in two parts – a Coverage engine you can use or customize, and a multiwindow application you can use to analyze programs and projects. The Coverage Profiler source files are not installed by default. To use these files you must first expand the xsource.zip file in the \Tools\XSource folder of the Visual FoxPro home directory.

The Coverage Profiler application provides several ways to view the data provided by the Coverage Engine. Coverage.app is a subclass of the Coverage engine. You can automate coverage, or modify the User Interface to suit your needs, run Coverage Profiler in unattended mode and not display the application window, or use engine features without using the interface.

Upon startup the coverage application suspends coverage logging enabled with a SET COVERAGE TO command. When you release the coverage object, the application provides a choice to restore the SET COVERAGE setting.

In This Section

Coverage Profiler Log File
Describes how the Visual FoxPro Coverage Profiler uses a log file, which consists of records in comma-delimited lines.
Examining Application Coverage and Profile
Provides information about how the Coverage Profiler can provide accurate and useful information about your project or application.
Coverage Profiler Modification
Describes how to change the default setting of the Coverage Profiler application so that it can run inside the main Visual FoxPro window, instead of in a separate window.
Coverage Profiler Add-Ins
Describes how to write add-ins and enhance the Coverage Profiler application.
Logging Code Coverage
Explains how code coverage gives you information about which lines of code have been executed and how long it took to execute them. You can use this information to refine your code for performance and ensure that you've adequately tested the code.
Conserving Disk Space During Coverage Runs
Discusses how you can change the size of some of the engine work table fields to make these tables somewhat smaller to avoid "out of disk space" errors during coverage runs.

Related Sections

Development Productivity Tools
Provides information on developer tools provided for application development within the Visual FoxPro application and the language.
IntelliSense Overview
Provides information on IntelliSense, which displays information in popup windows and drop-down lists that assist you with statement and function completion syntax.
Coverage Profiler Application
Discusses a coverage application, which writes information about which lines of code in a file were run, and a profiler application, which provides information about which lines actually run, how many times a line is run, duration, and so on.
Project Manager Hooks
Describes how you can access a project programmatically, making it possible for you to manipulate a project as an object.
Automating Keystroke Tasks with Macros
Describes how you can record and save keystrokes in macros by using the Macros dialog box.
Productivity Tools
Describes the different tools available to help make creating Visual FoxPro applications easier and faster.


Coverage Profiler Log File

Coverage Profiler uses a log file generated by Visual FoxPro when you use the Coverage option in the Debugger Tools menu or use SET COVERAGE TO as in the following command:

SET COVERAGE TO cCoverage.log

When you use the command, the ADDITIVE clause allows you to avoid overwriting an existing log. This command starts data streaming and opens the file cCoverage.log, a text file that will gather the stream of details on the file or application you examine.

A coverage log file consists of records in comma-delimited lines. The following list describes the structure of each record.

Item | Description
1 | execution time
2 | class executing the code
3 | object, method, or procedure in which the code is found or called
4 | line number within the method or procedure
5 | fully defined file
6 | call stack level

After specifying the log file name, run the program or application you want to examine. When you end the program you can use the SET COVERAGE TO command to stop the data stream to the coverage log.

You can view the coverage log by starting Coverage Profiler from the Tools menu or by using DO as in the following command:

DO (_COVERAGE) [WITH cCoverage]

Visual FoxPro prompts you for the name if you do not specify a log file. The _COVERAGE System variable in Visual FoxPro defaults to the Coverage Profiler application, Coverage.app.

See Also

Component Gallery Table Structure | Examining Application Coverage and Profile | Development Productivity Tools | Using the Component Gallery | Coverage Profiler Modification


Examining Application Coverage and Profile

To use the Coverage Profiler effectively, prepare your application and your environment carefully. If you use the following guidelines, the Coverage Profiler can provide accurate and useful information about your project or application.

To use the Coverage Profiler to examine application coverage

  1. Use the Coverage Logging option of the Debugger Tools menu or the SET COVERAGE command to start the coverage data stream and to open the file to log that data.
  2. Run the program or application you want to examine for coverage.
  3. Run the coverage application from the Tools menu or use DO (_COVERAGE) in the command window.

    The Coverage Profiler application starts in Coverage Mode by default.

To use Coverage Profiler to examine application profile

  1. Use the SET COVERAGE command to start the coverage data stream and to open the file to log that data.
  2. Run the program or application you want to profile.
  3. Run the coverage application from the Tools menu or use DO (_COVERAGE) in the command window.
  4. Click the Profile Mode button in the Coverage Profiler dialog box.

    If you find that you are most often interested in profiling, you can change the default to Profile Mode in the Coverage Profiler Options dialog box.

To use the Coverage Profiler with a specific log file

  • Run the coverage application using the WITH option and the log file name as in the following example:
    DO (_COVERAGE) WITH "Mylog.LOG"

    This example uses the log file Mylog.log and opens the Coverage Profiler application window to display the results. If you specify no file name, the Coverage Profiler uses the log specified in a current SET COVERAGE TO command or displays the Open file dialog box when coverage logging is OFF.

To use the Coverage Profiler without the User Interface

  • Run the coverage application using the WITH option and specify true (.T.) for unattended mode running as in the following example:
    DO (_COVERAGE) WITH "Mylog.LOG",.T.

    In this example, the Coverage Profiler application uses the log file Mylog.log and runs without displaying the Coverage Profiler application window.

To use the Coverage Profiler with a specific Add-In file

  • Run the coverage application using the WITH option and the add-in file name as in the following example:
    DO (_COVERAGE) WITH "Mylog.LOG",, "add_ui.prg"

    This example uses the log file Mylog.log and opens the Coverage Profiler application window to display the results, and then the Add-In program ADD_UI.PRG runs. The second, unspecified, parameter is a logical value that specifies whether the coverage engine operates in unattended mode. In the default setting, false (.F.), the Coverage Profiler window displays.

Besides viewing the profiler information, you can insert comments or markers and you can save the information as a file to use later.

See Also

Coverage Profiler Application | Coverage Profiler Modification | Development Productivity Tools | Coverage Profiler Add-Ins | Project Manager Hooks


Coverage Profiler Modification

By default the Coverage Profiler application runs in a separate window. You can reconfigure it to run inside the main Visual FoxPro window by changing the Environment Option. In the Coverage Profiler Options dialog box, change the Environment selection from Coverage frame to FoxPro frame, and then restart the Coverage Profiler.

You can also use the Coverage Profiler Options dialog box to modify the following Coverage Profiler characteristics.

Characteristic | Description
Add-Ins | Specifies whether Add-Ins are registered in the Coverage Profiler as they are used. For more information, see the section, "."
Coverage Marks | Specifies whether the Coverage Profiler marks code that is run or code that is not run. Specifies the character(s) used to mark code. Specifies when code is marked.
Fonts | Specifies the fonts used in the Coverage Profiler as code and in displays.
Smart Pathing | Specifies whether Coverage Profiler automatically seeks files in previously specified locations.
Start Mode | Specifies whether Coverage Profiler opens in Coverage or Profile Mode.

Ensuring Relevance in the Coverage Profiler

To help ensure that the files processed by the Coverage Profiler are the correct files:

  • Set your project directory as the default before you start coverage logging so that the referenced files are relative.
  • Avoid renaming objects dynamically. The Coverage Profiler will not find objects if you rename them at run time.
  • Avoid using source files with exactly the same root name, even with different extensions. Internally, the Coverage Profiler cannot distinguish between them.
  • Make sure that your project contains only the correct versions of much-modified files.
  • Make sure your project does not contain multiple copies of a file in subdirectories.
  • Perform a compile for the coverage run:
    • Make sure Debug information is in your application.
    • Turn Encrypt OFF.
    • Use RECOMPILE or Build All to force a fresh compile of all source code.
    • Perform the compile immediately before the coverage run so that you know that the source code exactly matches the object code.

Some lines in code, such as comments, DEFINE CLASS and ELSE statements, and lines within TEXT ... ENDTEXT do not appear in coverage logs because they are not even potentially executable. Also, lines broken by continuation symbols (semicolons) are considered as a single line of code and marked only on the last line.

See Also

Examining Application Coverage and Profile | Coverage Profiler Add-Ins | Development Productivity Tools | Coverage Profiler Application | Project Manager Hooks


Coverage Profiler Add-Ins

Add-Ins are code files (usually .prg or .scx) that provide an easy way for you to adjust the Coverage Profiler. The cov_standard subclass of the coverage engine, which comprises the User Interface of Coverage.app, shows only a small part of what you can do with the engine. The engine analyzes the coverage log; cov_standard just displays the results in one of many ways you could want to see them.

You could create a different subclass of cov_engine with a very different display. For example, your subclass might display a dialog that runs queries against the coverage statistics gathered by the engine. The display options might provide a view of the marked code for a filtered set of log entries, or only a graph of the profiling results.

You might not want to subclass cov_engine to create a new interface from scratch because the cov_engine class provides an easier process. You can add functionality to cov_standard, or any cov_engine subclass, using Add-Ins. Cov_standard exposes this feature through a button in the main dialog of Coverage Profiler. When you run an Add-In on an instance of cov_standard such as Coverage Profiler, the Add-In can manipulate the capabilities of cov_engine, the coverage tables, as well as cov_standard. Add-Ins might also add new dialogs and features to the cov_standard visual interface.

Writing Add-Ins

You can write Add-Ins to enhance the standard interface or you can subclass cov_standard to create your own wholly new interface.

Enhancing the Standard Application

The following list includes features you might want to provide through Add-Ins:

  • Add a visible feature to the main dialog.
  • Add a dialog into the coverage engine formset (reference limitation below on how to make sure your dialog shows up in the right place).
  • Display a separate dialog that accesses a Coverage engine feature (reference limitation below on how to make sure your dialog shows up in the right place).
  • Provide a querying interface that uses the Source table and presents a list of all lines that meet your criteria, and filters or orders the results.
    Note You can use the Adjust... methods (AdjustCoverageFilenameCursor( ), AdjustSourceCursor( ), and AdjustTargetCursor( )) of the Engine to add fields to the Source and Target tables when the engine creates them, and use these fields in your Add-Ins.
  • Add file names to the IgnoredFiles cursor, to eliminate those files from analysis. This can save analysis time.
  • Use the special Init hook for Add-Ins.
  • Register Add-Ins for retrieval and easy access to a list of Add-Ins.

    The modal dialog class cov_AddInDialog in the standard coverage engine subclass, presents previously registered dialogs in a drop-down list. When you set the coverage engine lRegisterAdd-In option ON, the full path name of successfully run Add-Ins are added to the Windows Registry so you can easily run these Add-Ins again. The Standard UI class also allows you to set this property in the Coverage Profiler Options dialog box.

    The Coverage Engine object maintains a list of all registered Add-Ins in the aAddIns property.

  • Use the final coverage.log field information, callstack, to design your own interface or your own view of the coverage log.

When you write Add-Ins, consider the following information:

  • You can use any of the supported file types as Add-Ins. The supported file types are .qpr, .qpx, .mpr, .mpx, .app, .exe, .scx, fxp, .prg and .procedures (if the procedures are already available in an open procedure library).
  • The Coverage Engine formset has an "invisible" toolbar. If your Add-In is nonvisual you can use this toolbar to contain it. If your Add-In is a visual control, the standard subclass main dialog .Cov_tools member container is probably the most convenient place to put it. This allows the position and size of the toolbar to be automatically synchronized with the rest of the dialog when it is resized.
  • All the engine methods that use the Source and Target tables take optional arguments that allow you to point these methods at the appropriate aliases while you're working with them. You can also change the current cSourceAlias and cTargetAlias property contents to match the pair of cursors in which you are interested. This allows you to compare multiple Coverage log runs to each other within the same interface.
  • Limitations:
    • Add-Ins must accept one parameter (the Coverage engine passes a reference to itself).
    • An Add-In must be one of the permitted file types, listed above.
    • Procedures you use as Add-Ins should be available in a currently loaded procedure library (see SET PROCEDURE) in Help. The Engine does not use the IN FileName syntax, and it does not call procedures or .prg files as functions and RETURN their values. It does not use the NAME or LINK keywords on the DO FORM command; you can either manage the reference yourself, or allow the Engine to scope a form for you by making your form a member of the Engine formset.
    • If you run an Add-In at startup, you must use a reference because the public _oCoverage variable is not yet available. At other times, you can use the public variable reference within your own code, if you prefer.
    • When you write an Add-In as a form, if you create the form as ShowWindow = 1 and run Coverage in its own frame, your Add-In forms should display in the Coverage frame.
    • If you use .RunAddIn from the Command window, make sure the coverage frame is the active MDI frame before you instantiate your forms.

Subclass Cov_Standard Class

You can subclass either the coverage engine or its standard subclass. The following list describes the structure of the COVERAGE project source file set.

File | Description
Coverage.prg | A "wrapper" for the coverage object, which instantiates the object.
Coverage.vcx
Coverage.vct 		All classes for the engine and its standard subclass.
Cov_short.mnx
Cov_short.mnt 		Shortcut menu.
Cov_pjx.frx
Cov_pjx.frt 		Default mechanism to deliver project-level results.
Coverage.h Header file for all Coverage code, incorporating the following elements:

*— Coverage character constants for log and parsing:

   #INCLUDE COV_CHAR.H

*— Coverage localized strings (can use some log and parsing constants):

   #INCLUDE COV_LOCS.H

*— Coverage common dialog component constants:

   #INCLUDE COV_DLGS.H

*— Coverage specs & requirements:

   #INCLUDE COV_SPEC.H

*— Coverage registry object constants:

   #INCLUDE COV_REGS.H

*— Coverage tune-able options:

   #INCLUDE COV_TUNE.H

The COVERAGE project source file set also includes various .ico .bmp, and .msk files.

Use the file COV_TUNE.H (containing appropriate comments and explanations) to become familiar with options available to you without rewriting code.

Because Add-In use is governed by the coverage engine superclass, any other coverage subclass you create can use Add-Ins in the same manner as the standard subclass.

The coverage engine subclass instantiated by the default Coverage.app does not augment the coverage engine RunAddIn( ) method in any way. It does, however, invoke a modal dialog box to allow the user to pick an Add-In before it invokes the coverage engine RunAddIn( ) method. The modal dialog box receives a reference to the Coverage object and sets the coverage engine cAddIn property.

If you write your own coverage engine subclass, ensure that your subclass can use the same modal dialog class (cov_AddInDialog) to handle Add-Ins as the standard Coverage application; the dialog box does not rely on any features of the standard subclass.

You can call a different modal dialog box, set the cAddIn file name directly in the cAddIn property, or override the contents of the cAddIn property by passing the name of the Add-In file you wish to run to the RunAddIn( ) method.

However you access an Add-In to run in your subclass, you can investigate the list of Add-Ins registered to Coverage.app by checking the file names in the coverage engine aAddIns property.

For details on the Properties, Events, and Methods of the coverage engine, see Coverage Engine Object in Help.

See Also

Coverage Profiler Modification | Project Manager Hooks | Development Productivity Tools | Project Object Hierarchy | Coverage Profiler Application


Logging Code Coverage

Later in the development process, you might want to refine your code for performance and ensure that you've adequately tested the code by logging code coverage information.

Code coverage gives you information about which lines of code have been executed and how long it took to execute them. This information can help you identify areas of code that aren't being executed and therefore aren't being tested, as well as areas of the code that you might want to fine tune for performance.

You can toggle code coverage on and off by clicking the Code Coverage toolbar button in the Debugger window. If you toggle code coverage on, the Coverage dialog box opens so that you can specify a file to save the coverage information to.

You can also toggle coverage logging on and off programmatically by using the SET COVERAGE TO command. You could, for example, include the following command in your application just before a piece of code you want to investigate:

SET COVERAGE TO mylog.log

After the section of code you want to log coverage for, you could include the following command to set code coverage off:

SET COVERAGE TO

When you've specified a file for the coverage information, switch to the main Visual FoxPro window and run your program, form, or application. For every line of code that is executed, the following information is written to the log file:

  • How long in seconds the line took to execute.
  • The class, if any, that the code belongs to.
  • The method or procedure the line of code is in.
  • The number of the line of code.
  • The file that the code is in.
  • Call stack level in which the line of code executes.

The easiest way to extract information from the log file is to convert it into a table so that you can set filters, run queries and reports, execute commands, and manipulate the table in other ways.

The Coverage Profiler application creates a cursor from the data generated in coverage logging and uses this cursor in a window for easy analysis.

The following program converts the text file created by the coverage log into a table:

cFileName = GETFILE('DBF')
IF EMPTY(cFileName)
   RETURN
ENDIF

CREATE TABLE (cFileName) ;
   (duration n(7,3), ;
   class c(30), ;
   procedure c(60), ;
   line i, ;
   file c(100))

APPEND FROM GETFILE('log') TYPE DELIMITED

See Also

Output Display | The Handling of Run-Time Errors | Testing and Debugging Applications | Debugger | Coverage | SET COVERAGE TO


Conserving Disk Space During Coverage Runs

If you experience "out of disk space" errors during coverage runs, you can change the size of some of the engine work table fields to make these tables somewhat smaller.

The default values of these fields are 115, because it allows for long path names and long object and method names. Values longer than 115 are not recommended, because two of these fields might be used in concatenated keys in which the sum of any two field lengths must not exceed the maximum key length (240).

Do not decrease the Hostfile field unless you are sure the lengths of your fully-qualified source files will not be exceeded. Otherwise, the engine might generate errors when it tries to find the uncompiled versions of these files.

If you know that you nest pageframes and grids several container-layers deep or that you tend to use very long class names, specify values greater than the maximum string length that ObjClass or Executing fields are likely to contain, plus a margin for error. You might want to examine the source and target files first to see how the engine uses these fields.

When you have decreased the size of the ObjClass or Executing fields, beware of suddenly-incorrect coverage and profiling statistics. Although the Profiler generates no obvious errors when the analyzing the log, statistical errors will occur if object and method names are being truncated in the fields.

Ordinarily, you use the iLenHostfile, iLenObjClass, and iLenExecuting property values to change the size of these fields. You can even change them dynamically while Coverage is open, before you open a coverage log that is unusually large.

Note When you have opened a log, do not change these values until you are ready to evaluate a new log, or you might experience statistical errors when new target entries' code is marked.

However, if you have set COV_TOPSPEED true (.T.) in the COV_TUNE.H header file, to increase speed by forcing the engine to make in-line calls, the engine uses constants also defined in COV_TUNE.H, rather than property values, to determine the size of these fields. (These values are used repeatedly, to ensure exact comparisons, as the engine parses lines of code.) If you set COV_TOPSPEED true (.T.), you must set the values in COV_TUNE.H directly.

See Also

Coverage Profiler Application | Coverage Engine Object


Productivity Tools

Visual FoxPro has a number of tools that can be used to increase your productivity while creating applications.

In This Section

Using the Task List Manager
Describes how to use the Task List Manager to keep track of shortcut, user-defined, and custom tasks.
Using the Object Browser
Describes how to use the Object Browser to view information about components, such as objects, classes, properties, methods, and events.
Operating the Command Window
Describes the Command window, which can be used to run code. When you type a Visual FoxPro command in the window, the code is executed immediately.
Using the Accessibility Browser
Discusses the Accessibility Browser, which you can use to verify that your application is accessible to people with disabilities.
Using the Automated Test Harness
Provides information on the Automated Test Harness, which can be used to run scripts to help automate the testing of your application.
Utility Programs
Describes the tools, which are provided with Microsoft Visual FoxPro to help speed the process of application development.

Related Sections

Development Productivity Tools
Provides information on developer tools provided for application development within the Visual FoxPro application and the language.
IntelliSense Overview
Provides information on IntelliSense, which displays information in popup windows and drop-down lists that assist you with statement and function completion syntax.
Using the Component Gallery
Describes the Component Gallery, a container for catalogs of software objects, such as class libraries, forms, buttons, and so on.
Coverage Profiler Application
Discusses a coverage application, which writes information about which lines of code in a file were run, and a profiler application, which provides information about which lines actually run, how many times a line is run, duration, and so on.
Project Manager Hooks
Describes how you can access a project programmatically, making it possible for you to manipulate a project as an object.
Automating Keystroke Tasks with Macros
Describes how you can record and save keystrokes in macros by using the Macros dialog box.


Customizing the Toolbox

The Toolbox can be customized to contain the categories and items that you use the most. You can also order items in a way that you find most effective. This can be done by adding or deleting a category, changing the order of categories, and adding or deleting items in a category.

Before you can customize the Toolbox, you must have it open.

To open the Toolbox

  • On the Tools menu, click Toolbox.

To add a new category

  1. Right-click the Toolbox, and click Customize Toolbox on the shortcut menu.
  2. In the Customize Toolbox dialog box, click the Categories folder.
  3. At the top of the Customize Toolbox dialog box, click Add Category.
  4. In the Add Category dialog box, type a new category name in the Category name box.
  5. In the Category type list, select the type of category you are adding, and click OK.

To delete a category

  1. Right-click the Toolbox, and select Customize Toolbox on the shortcut menu.
  2. In the Customize Toolbox dialog box, click the category you want to delete.
  3. At the top of the Customize Toolbox dialog box, click Remove Category.
  4. When prompted to delete the category, click OK.

To add an item to a category

  1. Right-click the Toolbox, and select Customize Toolbox on the shortcut menu.
  2. In the Customize Toolbox dialog box, select the category that you want to add your class.
  3. Click Add Item on the Customize Toolbox dialog box.
  4. In the Add Item dialog box, select the type of item you want to add, and click OK.
  5. In the Add Class Library dialog box, select the category to add to your Class Library.
  6. Click the ellipsis (...) button next to the Class Library box, select a class to add from the Open box, and click OK
  7. In the Add Class Library dialog box, click OK.

To delete an item from a category

  1. Right-click the Toolbox, and select Customize Toolbox on the shortcut menu.
  2. In the Customize Toolbox dialog box, select the category that you want to delete an item from.
  3. In the Category Item list, select the item that you want to delete.
  4. Click Remove Item on the Customize Toolbox dialog box.
  5. When prompted to delete the item, click OK.

See Also

Productivity Tools | Toolbox


Using the Task List Manager

You can keep track of tasks using the Task List Manager, which stores tasks in the FoxTask.dbf table file. You can create the following types of tasks:

  • Shortcut References a specific line of code you might want to edit or view later.
  • User-defined Specifies a to-do or information item you might want to track. These are added manually.
  • Other A custom task. You must add this type of task programmatically in your application.
    Note Make sure to set the Type field of the custom task to "O" in FoxTask.dbf file, which is referenced by the _FOXTASK system variable. For more information, see _FOXTASK System Variable.

To open the Task List Manager

  • On the Tools menu, click Task List.

For more information, see Task List Manager Window.

Working with Tasks

You can perform many actions in the Task List Manager, such as add, edit, prioritize, set status for, and delete tasks.

Adding Tasks

You can add shortcut and user-defined tasks in the Task List Manager.

To add a shortcut task

  1. Open the program file in which you want to create the shortcut.
  2. In the code editing window, select the line of code that you want to create as a shortcut.
  3. On the Edit menu, point to Bookmarks and click Toggle Task List Shortcut.

You can also add a shortcut by doing one of the following after selecting the line of code:

  • Right-click the selected code and click Add Task List Shortcut.
  • Press ALT+F2 to add or remove the shortcut.
  • Press and hold the CTRL key, and then double-click the Editor's Selection Margin.

Shortcut tasks are indicated by an arrow icon in the task type column.

To add a user-defined task

  1. In the Tasks window, click Click here to add a new task in the Contents column.

    A cursor appears in the text box.

  2. Type information about the task you want to perform.
  3. When you are finished, press RETURN or click outside the text box.

    The task is added to the end of the list so you can enter additional information.

User-defined tasks are indicated by a person/task icon in the task type column.

Editing Tasks

You can edit a task directly in the Task List or using the Task Properties dialog box. The Task Properties dialog box contains the Task and Fields tabs, which displays information for all available fields, even if they are not shown in the Tasks window.

Note Double-clicking a shortcut task in the Tasks window opens the appropriate editing window and moves directly to that shortcut.

To edit a task in the Task Properties dialog box

  1. In the task type column (third column from the left), double-click the icon next to the task.
  2. In the Task Properties dialog box, click the Task tab.
  3. Edit the fields and settings you want.

You can also open the Task Properties dialog box by right-clicking the task, and clicking Open Task.

Prioritizing Tasks

You can set and organize priorities for tasks.

To set a priority for a task

  1. In the priority column, indicated by an exclamation mark (!), click the box for the task you want
  2. From the list, select a priority.

You can organize tasks by priority by clicking the priority column header. You can also enter a due date for a task.

Marking Tasks

You can mark tasks to indicate their status as read or complete in the Task List Manager.

Marking Tasks as Read

Tasks that are not yet read appear in bold. You can mark tasks as read when you are finished reading about the task.

To mark a task as read

  • Right-click the task, and click Mark as Read.

    When a task is read, it no longer appears in bold.

You can also mark a task as read by opening the Task Properties dialog box, clicking the Task tab, and selecting the Read check box.

Marking Tasks as Complete

You can mark tasks as complete when you are finished with the task.

To mark a task as complete

  • In the task list column, or second column from the left, select the check box for the task you want to complete.

    When a task is complete, it appears as strikethrough text.

You can also mark a task as complete by right-clicking the task, and clicking Mark as Complete or by opening the Task Properties dialog box, clicking the Task tab, and selecting the Complete check box.

Deleting Tasks

You can delete tasks in the Task List Manager.

Note Shortcut tasks are deleted automatically when you remove the shortcut in the editing window.

To delete a task

  • Right-click the task, and click Delete Task.

Adding Files to User-Defined Tasks

Shortcut tasks have a file automatically associated with them. You can add file associations to user-defined or other tasks, although it is not required.

To add a file association

  • In the File Name field for the task, type the full path and name of the file and any additional information required, such as line or method.

You can also add a file association by opening the Task Properties dialog box, and entering the file name in the File Name field.

Opening Files for Editing

You can open and edit files associated with tasks.

To open and edit a file associated with a task

  • Double-click the task in the Tasks window.

You can also right-click shortcut tasks or user-defined tasks that have file associations, and click Open File.

Editing Custom Fields

You can edit custom fields that exist in the Task List Manager.

To edit custom fields

  1. In the task type column (third column from the left), double-click the icon next to the task.
  2. In the Task Properties dialog box, click the Fields tab.

    A list of available custom fields appears.

Cleaning and Editing the Task List Table

You can clean the Task List table and edit the structure of the user-defined columns table.

To clean the Task List table

  1. Right-click the Tasks window, and click Options.
  2. In the Tasklist Options dialog box, click Clean Up FoxTask.

To edit the structure of the user-defined columns table

  1. Right-click the Tasks window, and click Options.
  2. In the Tasklist Options dialog box, click Edit Structure.

Customizing the Task List Manager

You can customize the view of your Task List Manager in several ways:

  • Sorting tasks You can sort the task list by clicking on the column header of the field by which you want to sort. Clicking a column repeatedly toggles that field between ascending/descending order.
  • Filtering task types You can filter the types of tasks you want to display in the Task List by selecting specific task types from the Show Tasks submenu of the Task List context menu. The submenu contains options to display shortcuts, user-defined and other Tasks.
  • Choose fields for viewing You can choose which fields you want to view in the Task List by selecting the Column Chooser menu item from the Task List context menu. A Columns picker dialog box appears so you can add new fields using drag-and-drop directly to the Task List. To remove a field, right-click the column header and select the Remove This Column menu item.
  • Adding custom fields You can add custom fields to your Task List. Custom fields are stored in a separate table from your main _FOXTASK (Foxtask.dbf) table. This custom fields table must have a UniqueID field, so it can be linked to the field in the Foxtask table. You can edit Custom fields from the Fields tab of the Task Properties dialog box.

    You can add a new or existing custom fields table in the Options dialog box. Access the Options dialog box from the Options menu item of the Task List context menu item. All custom fields appear in the Columns Chooser dialog box, so you can add them to or remove them from the Task List.

See Also

Task List Manager Window | _FoxTask System Variable | _TASKLIST System Variable | Creating Bookmarks and Task List Shortcuts


Using the Object Browser

The Object Browser makes it possible for you to browse, filter, and search for components that you might want to consume in your projects.

To open the Object Browser

  • On the Tools menu, click Object Browser.

You can also open the Object Browser by clicking the Object Browser button on the main Visual FoxPro toolbar, or, type the following line of code in the Command window:

DO (_OBJECTBROWSER)
Note After the Object Browser opens, you can open it programmatically by using the _OBJECTBROWSER system variable.

You can view any COM class type library that is registered on your system. The left pane shows a list of all loaded class type libraries. You can expand each category to display the classes in the library. Members associated with those classes appear in the right pane.

Working with Classes

Classes provide complete member information for a particular COM component or ActiveX control that you might want to consume in your application. Instances of these objects typically are created using one of the following Visual FoxPro functions:

CREATEOBJECT( ), CREATEOBJECTEX( ), NEWOBJECT( ), GETOBJECT( ), ADDOBJECT Method
Note ActiveX controls usually are dropped onto a form class directly and are instantiated with the form.

You can drill down into a class to view member detail by selecting the class from the Classes node in the Classes & Members pane. When selected, the properties, methods, and events for that class are displayed in the Members pane on the right. Protected members are shown with a lock icon.

When you click class members in the Members pane, detail information is shown in the Description pane. The contents of the Description pane give details of data types for member parameters and return values. Underlined items in the Description pane are links you can click to go directly to that item for more information. If available, a functional description of the member also will be displayed in the Description pane.

Working with Properties, Methods and Events

The best way to view properties, methods, and events is to use a particular class in the Members pane. Typically you work with a single class at a time. Sometimes you might wish to view all the properties, methods, and events in a library at one time, not filtered by class. To do this, click the appropriate node in the Classes & Members pane. Depending on the size of the type library, it might take several seconds or minutes to list all the members.

When you click a property, method, or event in the Classes & Members pane, you can view all the classes and interfaces that use it in the Members pane.

Working with Cached Classes

When you expand one of the Properties, Methods, or Events nodes in the Classes & Methods pane, it might take a while to display all the contents. Because of this, the Object Browser caches this information in the Objectbrowser.dbf. This saves time when you want to reload a library later. You can click the Refresh button to have properties, methods or events reloaded next time one of these nodes is expanded.

Working with Constants and Enums

Many type libraries contain constants. A constant is the equivalent of a numeric #DEFINE with which Visual FoxPro developers are familiar. Enums are collections of two or more constants.

Enums are special in that a member can denote a specific enum as the data type for a parameter or return value. For a parameter this means that the value passed for a parameter must be one of the Constants associated with the specified Enum.

You can view the value of a constant by clicking it and viewing the numeric value in the Description pane.

When specifying a constant for a method parameter, you must pass in the actual numeric value. Visual FoxPro does not recognize the actual constant name as a reference as with other languages, such as Visual Basic.

You can create a set of #DEFINE directives that represent all the constants by using drag and drop from the Constants node of a type library to an editor window.

Working with Interfaces

Advanced developers might want to work with specific interfaces in the COM library. Interfaces are particularly useful when you create COM Servers in Visual FoxPro that use the IMPLEMENTS clause of the DEFINE CLASS command. The IMPLEMENTS clause accepts an interface name as a parameter and can be used in association with a variety of COM+ Services as well as the EVENTHANDLER( ) Function.

You can create a class template by using drag and drop from an Interface node to an editor window. This template will contain any IMPLEMENTS statement and member details of the interface.

Searching within Libraries

You can perform searches for text in a library by clicking on the Find button. The Find button displays a unique Find view above the two main panes. The Simple Find view searches for a specified string within all opened libraries. The search is made within all elements of a library and for strings "contained within". The Advanced Find view supports greater refinement of the search.

Persistence of Object Browser Data

The Object Browser session is persisted between uses. Object Browser information is saved to an objectbrowser.dbf table stored in the same location as the Object Browser. This information includes the following:

  • A Recent History list of all previously opened libraries so you can retrieve one of these libraries quickly in the future.
  • Cached properties, methods, and events for a library so it can be loaded quickly next time accessed.
  • All previously loaded add-ins.
  • User preferences specified in the Options dialog box.
  • COM components and ActiveX controls displayed in the Open dialog box (stored in Foxrefs.dbf).

Working with Add-Ins

  • Object Browser add-ins can perform a variety of useful functions not native to the browser itself. These include adding additional user interface elements, new menu items, and drag-drop capabilities.

    Add-ins typically are created as VCX classes.

Existing Add-Ins Install Wizard

The first step of the Existing Add-Ins wizard specifies the following options:

  • Enter a user-friendly name for the add-in as you wish it to appear in the Add-Ins list of the Options dialog box.
  • Enter a description for the add-in as you want it to appear in the Add-Ins list of the Options dialog box.
  • Select an icon to display in the Add-Ins list of the Options dialog box (optional).

The second step specifies input for class information of the add-in.

  • Select the specific class and class library for the add-in class.

The third step is an optional step to provide support information:

  • You can specify a URL to a Web page that provides additional information for using the add-in. You also can provide specific HTML that appears in the add-in description.

The last step makes it possible for you to finish the add-in installation.

  • You can specify some advanced options. These include Properties and User Defined Settings.

See Also

Object Browser | Class Browser | _ObjectBrowser System Variable | DEFINE CLASS | EVENTHANDLER( ) | Viewing Type Library Information


Operating the Command Window

You can execute a Visual FoxPro command by typing it into the Command window and pressing ENTER. To re-execute the command, move the cursor to any place on the line containing the command and press ENTER again.

You can even run multiple lines of code from the Command window as though they were a self-contained program.

To run multiple lines of code in the Command window

  1. Select the lines of code.
  2. Press ENTER or choose Execute Selection from the shortcut menu.

Since the Command window is an editing window, you can edit commands using the editing tools available in Visual FoxPro. You can edit, insert, delete, cut, copy, or paste text in the Command window.

The advantage of entering code in the Command window is that the instructions are carried out immediately. There is no need to save a file and run it as a program.

In addition, choices you make from menus and dialog boxes are echoed in the Command window as commands. You can copy and paste these commands into a Visual FoxPro program, then run the program repeatedly, making it easy to execute thousands of commands repeatedly.

See Also

Running Code Manually | Creating Programs | Command Window


Using the Accessibility Browser

The Accessibility Browser is a simple explorer tool that provides a means to developing applications that are more accessible to people with disabilities. By following accessibility design practices and using Active Accessibility when needed, you can make applications more accessible. In addition, the Accessibility Browser can help you write automated test suites (or select and buy off-the-shelf Test software).

The Accessibility Browser makes it possible for you to examine the IAccessible properties of objects and how objects are related to each other. The Accessibility Browser is installed in the MSAA folder of the Tools subdirectory. Source code is included so you can enhance the functionality of this explorer-like tool.

To launch the Accessibility Browser

  1. From the Program menu, select Do.
  2. In the Do dialog box, select the ..\Tools\MSAA\accbrow.app file, and click the Do button.

See Also

Accessibility Browser Window | Development Productivity Tools | Accessibility for People with Disabilities | SYS(2800) - Accessibility Support


Using the Automated Test Harness

The Automated Test Harness tool is intended to help create scripts that you can run to automate the testing of your Visual FoxPro applications. The tool uses Microsoft Active Accessibility (MSAA) technology to record and play back mouse and keyboard events.

The tool files are installed in the Microsoft Visual FoxPro 8.0\Tools\Test\ folder.

For additional information about the tool, see the readme file (aatesthelp.htm) in the \Tools\Test folder.

To run the Automated Test Harness

  1. Run the Automated Test Harness from \Tools\Test\AATEST.APP or from the Visual FoxPro command prompt, enter:
    DO (HOME() + "tools\test\aatest")
  2. To record the script, click Record in the toolbar or from the Record menu. A list of available applications appears.
  3. Select a Visual FoxPro application, and, when prompted, enter a name for your text script.

    The selected Visual FoxPro application or window appears, and the tool is ready to record the events.

  4. Record the events. Run your application as you typically would using the keyboard and mouse. Make sure you have run through all of the user interface elements, including forms, menus, windows, and dialog boxes.
  5. When finished, click Stop in the toolbar. You also can pause and resume recording as needed.

To view the events log, which has been selected or currently recorded, click "Edit the script."

To play back scripts, select the script you want to run, and click Play. If the program detects an error, you see a prompt in the testing application.

To see the test log, select the Test Log tab.

Note Only one instance of the test tool can be run from one installation because the test tables are opened exclusively.

See Also

Testing and Debugging Applications | Accessibility Browser Window | Debugging and Error Handling


Utility Programs

These tools are provided with Microsoft Visual FoxPro to help speed the process of application development.

In This Section

Addlabel.app
Adds label sizes to the New Label dialog box in the Label designer.
Code Analyzer
Provides visual controls, a menu, and keyboard options to navigate through application file code by using output from the Documenting wizard.
Filer.dll
Supports the most popular features of the Filer, including support for searching files for text strings and opening multiple files for editing.
Gendbc.prg
Generates a program that can re-create a database.
Genhtml.prg
Generates a Web page based on data in a table.
Hexedit.app
Examines or changes address, byte, and ASCII values of data in a file.

Related Sections

Productivity Tools
Describes the different tools available to help make creating Visual FoxPro applications easier and faster.
Using the Task List Manager
Explains how the Task List Manager can help keep track of shortcut, user-defined, and custom tasks.
Using the Object Browser
Describes how the Object Browser enables you to view information about components, such as objects, classes, properties, methods and events.
Operating the Command Window
Explains that the Command window can be used to run code and that when you type a Visual FoxPro command in the window, the code is executed immediately.
Using the Accessibility Browser
Describes how you can use the Accessibility Browser to verify that your application is accessible to people with disabilities.
Using the Automated Test Harness
Explains that the Automated Test Harness can be used to run scripts to help automate the testing of your application.


Addlabel.app

Located in the Visual FoxPro Tools\Addlabel folder, Addlabel.app makes it possible for you to add custom label sizes to the new label dialog box in the label designer by adding new sizes to the Windows Registry.

DO Addlabel.app

Adding Label Sizes

If you don't see a label size that you need in the Label Designer, you can add label sizes to the New Label dialog box by adding new label definitions.

To add a label definition

  1. Run Addlabel.app.
  2. In the Custom Labels dialog box, choose New.
  3. In the Label Name box of the New Label Definition dialog box, enter a name for the new label definition. This name will be displayed in the New Label dialog box when you create a new label.
  4. In the text boxes that are displayed over the label illustration, type values for label height, width and margins. You also need to specify how many labels to print in a row in the Number Across spinner.
  5. Choose Add.

See Also

Analyzer.app | Cpzero.prg | Gendbc.prg | Genhtml.prg | Hexedit.app | Label Designer | Utility Programs


Code Analyzer

Located in the Visual FoxPro Tools\Analyzer folder, Analyzer.app provides a way to dynamically trace the structure and symbols in Visual FoxPro application files. Code Analyzer provides visual controls, a menu, and keyboard options to navigate through application file code by using output from the Documenting Wizard.

DO HOME( ) + 'tools\analyzer\analyzer' WITH 'DocWizTargetDirectory'

Parameters

DocWizTargetDirectory
Specifies the name of the Documenting Wizard target directory.

Code Analyzer Tabs

Symbols
Provides access to all the user symbols in the open code document.
Hierarchies
Provides display of either the calling tree hierarchy or the class hierarchy of your program.

See Also

Addlabel.app | Cpzero.prg | Gendbc.prg | Hexedit.app | Genhtml.prg | Documenting Wizard | Hierarchies Tab, Code Analyzer | Symbols Tab, Code Analyzer | Utility Programs


Symbols Tab, Code Analyzer

This tab displays the symbols available in your documented code and provides a way to navigate through the code and between symbols. The tab contains the following controls.

Tab Options

Goto
Opens a text window or moves the cursor to the first occurrence of the symbol selected in the Files grid.
Next
Moves the text window cursor to the next occurrence of the symbol selected in the Files grid.
Symbols
Displays all the symbols available in the documented file.
Files
Displays the procedures and files in which the selected symbol occurs.

See Also

Documenting Wizard | Hierarchies Tab, Code Analyzer | ANALYZER.app | Utility programs


Hierarchies Tab, Code Analyzer

This tab provides display of either the calling tree hierarchy or the class diagram of your program. The tab contains the following controls:

Tab options

Files
Displays either the calling tree hierarchy or the class diagram of your program.
Option
Selects the alternate displays of the Files outline control.

See Also

Documenting Wizard | Symbols Tab, Code Analyzer | ANALYZER.app | Utility programs


Cpzero.prg

Located in the Visual FoxPro Tools\Cpzero folder, Cpzero.prg removes the code page mark from any file that has a table file structure. After removing the mark, Cpzero applies another mark that you specify.

Typically, you use Cpzero with files from other platforms or earlier versions of FoxPro. If these files do not have code page marks when you open them, Visual FoxPro prompts you for a code page. If you specify the wrong code page, however, the data in the files won't display properly. To correct the code page, use Cpzero.

DO Cpzero [WITH "filename"[, codepage_number]]

Parameters

filename
Specifies the name of the file and must be delimited with single or double quotation marks. If filename is not included, a Locate File dialog box is displayed.
codepage_number
Specifies the desired code page number. If it is not included, the Code Page dialog box is displayed.
Note Before you run Cpzero on a table, make sure it is closed.

Example

* Remove the code page from MYFILE.DBF and specify 437
* as the new code page.
*
DO Cpzero WITH 'MYFILE.DBF',437

See Also

Addlabel.app |Code Analyzer | Gendbc.prg | Genhtml.prg | Hexedit.app | Code Pages Supported by Visual FoxPro | CPCONVERT( ) Function | CPCURRENT( ) Function | CPDBF( ) Function | GETCP( ) Function | Utility Programs | SET CPDIALOG Command | SET NOCPTRANS Command


Filer.dll

Filer.dll is a component version of the Filer desk accessory, available in previous versions of Microsoft Visual FoxPro (versions 3.0b and earlier). Filer.dll supports the most popular features of the Filer, including support for searching files for text strings and opening multiple files for editing.

Filer.dll is a COM object, and as such, supports Automation. Therefore, you can create an instance of Filer.dll in Visual FoxPro or other Automation servers such as Microsoft Visual Basic and Microsoft Excel.

Filer.dll is a base component that provides the file and text search engine, but doesn't include a user interface. For example, you can programmatically create an instance of the Filer and search for and manipulate files without any input from a user. However, a Visual FoxPro form, Filer.scx (and Filer.sct), is provided to demonstrate how you can create a user interface for Filer.dll.

The following command will create an instance of the non-visual Filer search engine in Visual FoxPro. The syntax for other Automation servers is similar.

oMyFiler = CREATEOBJECT('Filer.FileUtil')

Once the Filer object is instantiated, you can specify file search conditions with the Filer properties, and then execute the file search with the Find( ) method. The Find method creates a Files collection object with its own set of properties that make it possible for you to determine information about the files that match the search conditions. There are also methods for the Files collection object that make it possible for you to open or delete the matching files.

The following simple Visual FoxPro example demonstrates how you can search for and open text files from within Visual FoxPro.

*** Instantiate the Filer object
oMyFiler = CREATEOBJECT('Filer.FileUtil')

oMyFiler.SearchPath = HOME() && Home directory
oMyFiler.FileExpression = '*.TXT' && Text file search

oMyFiler.Find(0) && Search, discard last collection

FOR nFileCount = 1 TO oMyFiler.Files.Count
   oMyFiler.Files.Item(nFileCount).Edit && Open files
ENDFOR

Distribution

You can distribute Filer.dll and its companion files, filer.ico, filer.scx, and filer.sct, with your distributed Visual FoxPro runtime applications.

Note These files are unsupported – technical support is not available for problems you encounter when using these files.

Filer Object Properties

The following table describes the properties associated with the Filer object.

Property | Data Type | Description
SearchPath | C | The folder from which the search starts. Universal naming conventions (UNC) are supported. Read/write.
FileExpression | C | The file search mask that can include multiple masks separated by semicolons (;). For example, the file search mask *.scx; *.sct specifies to search for all files with the extensions .scx and .sct. The default file search mask is *.*. Read/write.
SubFolder | N | A numeric value that specifies if a recursive search is performed from the folder specified with the SearchPath property. If SubFolder is 0, the file search is performed only in the folder specified with the SearchPath property. If SubFolder is 1, the file search is performed in the folder specified with the SearchPath property and all its subfolders. Note that the Filer ignores System folders. The default value is 0. Read/write.
SearchText1 | C | A text string to search for in the files that match the file search mask specified by the FileExpression property. The default value is the empty string. Read/write.
SearchText2 | C | An additional text string to search for in the files that match the file search mask specified by the FileExpression property. Ignored if SearchText1 contains the empty string. The default value is the empty string. Read/write.
SearchText3 | C | An additional text string to search for in the files that match the file search mask specified by the FileExpression property. Ignored if SearchText1 and SearchText2 contain the empty string. The default value is the empty string. Read/write.
IgnoreCase | N | A numeric value specifying whether or not case is ignored for text in the text strings specified in SearchText1, SearchText2, and SearchText3. If IgnoreCase is 0, case isn't ignored (upper- and lower-case are significant). If IgnoreCase is 1, case is ignored. The default value is 1. Read/write.
WholeWords | N | A numeric value specifying whether or not the text in the text strings specified in SearchText1, SearchText2, and SearchText3 must match whole words for the search to be successful. If WholeWords is 0, the text in the text strings do not have to match whole words for the search to be successful. If WholeWords is 1, the text in the text strings must match whole words for the search to be successful. The default value is 0. Read/write.
SearchAnd | N | A numeric value specifying whether or not all the text in the text strings specified in SearchText1, SearchText2, and SearchText3 must match for the search to be successful. If SearchAnd is 0, the search is successful if any of the text in the text strings matches. If SearchAnd is 1, the search is successful only if all of the text in the text strings matches. The default value is 0. Read/write.
Editor | C | The editor in which files are opened with the Files collection Open method. Ignored if the IsHostedByFox property is 1. The default editor is Notepad. Read/write.
IsHostedByFox | N | A numeric value indicating the client that instantiated Filer.dll. If IsHostedByFox is 1, the client is Visual FoxPro, and the Visual FoxPro editor is used to open files. If IsHostedByFox is 0, the client is an application other than Visual FoxPro, and the editor used to open files is specified by the Editor property. The default value is 1 in Visual FoxPro. Read/write.
SortBy | N | A numeric value that specifies the order in which the Files collection is sorted. The following table lists the values for the SortBy property and the order in which the files are sorted. 0 No order 1 Path and file name 2 File name 3 File extension 4 File size 5 File last write date 6 File last access date 7 File creation date 8 File attributes The default value is 1. Read/write.
SortDirection | N | A numeric value that specifies if the Files collection is sorted in ascending or descending order. If SortDirection is 0, the Files collection is sorted in ascending order. If SortDirection is 1, the Files collection is sorted in descending order. The default value is 0. Read/write.

Filer Object Methods

The following table describes the methods associated with the Filer object.

Method | Description
Find(nValue) | A method that performs the file search and creates a Files collection. The Find method contains a numeric value indicating the number files in the Files collection. nValue is a numeric value that specifies if Files collections from previous searches are discarded. If nValue is 0, the Files collections from previous searches are discarded. If nValue is 1, the Files collection created by the current search is appended to the previous searches. Note that nValue is not optional.

Files Collection Objects

The following table describes the object references associated with the Files collection.

Object | Description
Item(nValue) | An object reference to a file in the Files collection. nValue is an index to a file in the Files collection. nValue begins at 1, and continues to the number of files in the Files collection. You can use the Count property, described below, to determine the number of files in the Files collection.

Files Collection Properties

The following table describes the properties associated with the Files collection.

Property | Data Type | Description
Count | N | Contains the number of files in the Files collection. Read-only.
Name | C | The name of the file, excluding the path. Read-only.
Size | N | The size of the file in bytes. Read-only.
SizeHigh | N | The high 4 bytes of the file size if the file size is greater than 4 gigabytes. Read-only.
Attr | N | The Windows file attributes for a file. The following is a list of numeric values for typical file attributes. 0 No attributes set 1 Read-Only 2 Hidden 4 System 32 Archived The value of Attr can be the sum of several file attributes. For example, if Attr is 7 (1+2+4), the file is a read-only, hidden system file. For more information about the other file attributes for which Attr returns values, see the GetFileAttributes function described in the Microsoft Developer's Network library. Read/write.
DateTime | N | The time stamp assigned by Windows to a file when it is created. The integer portion of the time stamp is the number of days since 12/30/1899, and the remainder is the fractional remainder of the day from which you can determine the time when the file was created. The Filer form, Filer.scx, contains a user-defined method called GetTime that demonstrates how you can determine the date and time a file was created from the DateTime property. Read-only.
LastAccessTime | N | The time stamp assigned by Windows to a file when it is was last accessed. Read-only.
LastWriteTime | N | The time stamp assigned by Windows to a file when it is was last written to. Read-only.
AlternateName | C | The short name of the file if the file name is longer than the MS-DOS® 8.3 character naming convention. Read-only.
Path | C | The full path to file. Read-only.

Files Collection Methods

The following table describes the methods associated with the Files collection.

Method | Description
Edit | Opens the specified file for editing. If the IsHostedByFox property is 1 (the default for Visual FoxPro), the file is opened in the Visual FoxPro editor. If the IsHostedByFox property is 0, the file is opened in the editor specified with the Editor property (NotePad by default).
Delete | Deletes the specified file from disk. The file isn't placed in the Recycling Bin.

Running Filer.scx

A sample form, Filer.scx, is included to demonstrate how you can create a user interface in Visual FoxPro for Filer.dll. To run the Filer form, use the DO FORM command as follows:

DO FORM (HOME(1) + 'Tools\Filer\Filer.scx')

When you run the Filer form, a Filer item is added to the Visual FoxPro Tools menu, and the item remains in the menu during the current Visual FoxPro session. Choose the Filer item from the Tools menu to run the Filer again.

Issue the following command to open the Filer form to view the code behind the interface or to modify the form:

MODIFY FORM (HOME(1) + 'Tools\Filer\Filer.scx')

See Also

VFP8R.DLL Run-Time Library | VFP8T.DLL Run-Time Library | COMPOBJ( ) Function | DO FORM Command


Gendbc.prg

Located in the Visual FoxPro Tools\Gendbc folder, this tool generates a program that can recreate a database. GenDBC.prg supports autoincrementing, collating sequences, and filtered primary keys. You can use this program to generate the following:

  • Code that you can analyze to learn how a database is created by using program code
  • Code that you can insert in your program code, eliminating the need to ship databases with your application
  • Code that you can insert in your program code to recreate the database if a customer's data is corrupt
DO GENDBC WITH filename

Parameters

filename
Specifies a character string containing the name of an output file. The filename can contain path information and a file extension. If no extension is supplied, the default extension, .prg, is used.
Note This program works only on the currently active database.

Example

The following example creates a program called MyData.prg, which contains code for recreating a database, MyDatabase. The program, Main.prg is created in the C:\VFP folder and contains code for recreating the database, Main.

OPEN DATABASE MyDatabase
DO gendbc WITH 'MyData.prg'
SET DATABASE TO Main
DO gendbc WITH 'c:\vfp\main'

See Also

Addlabel.app | Code Analyzer | Genhtml.prg | Hexedit.app | Cpzero.prg | Utility Programs


Genhtml.prg

Genhtml.prg is the default program called by the _GENHTML system variable.

You can use _GenHTML to easily collect static data or to convert forms, labels, reports, and menus for viewing or transmitting in email or posting as Web pages. You can use _GenHTML to share data with sites that don't have Visual FoxPro installed or to create templates for use in Web pages.

GenHTML.PRG is accessed from the File menu when you choose the Save As HTML option. This menu option is available when the Form Designer, Label Designer, Menu Designer, or Report Designer is active or when a table or cursor is open in a Browse window. GenHTML uses the specified data source as the basis for generating an HTML document using classes contained in the _HTML.VCX class library.

You can run GenHTML from the Command window with the following syntax:

DO (_GENHTML) WITH <cOutFile> <cSourceFile> [, <nShow>][,<vIELink>][,...
parameter | description
cOutFile | Default = "" Specifies the name of the output file. When specify no extension, .HTM is the default.
cSourceFile | Default: = "" Specifies the source file name, alias or object.
nShow | Default: = 0 Specifies whether GenHTML will create and open the output file. tnShow can take the following values: 0 = Generate output file1 = Generate and display output file in Visual FoxPro editor.2 = Generate and display output file in Internet Explorer.3 = Generate and display output file after using a Save As dialog box4 = Create PUBLIC _oHTML object and generate a file.5 = Create a PUBLIC _oHTML object without generating a file.
vIELink | Default: Specifies a link to an Internet Explorer object or Web browser control.
Object | Default: Specifies a reference to an Internet Explorer object.
cStyle | Default: Specifies a Style ID in GenHTML.DBF.
tcScope | Default: Specifies the scope of scan by setting the cScope property.
cHTMLClass | Default: Specifies the class, and optionally, the class library that is instantiated for HTML object.

See Also

Addlabel.app| Code Analyzer | Gendbc.prg | Hexedit.app | Cpzero.prg | Utility Programs


HexEdit

Located in the Visual FoxPro Tools\Hexedit folder, Hexedit.app provides a way to examine address values, or examine or change byte and ASCII values of data in a file. HexEdit is a visual equivalent of the MS-DOS Debug program DUMP Command.

Caution If you want to edit the file, make sure it is not in use or otherwise locked.
DO HEXEDIT.app

When you choose a file, HexEdit displays a dialog box with the following control options.

Note If you want to edit the file, make sure it is not in use or otherwise locked.

Dialog Options

Select File
Displays the Open dialog box so you can change the current file.
Address
Displays the file offset address of the first byte of data in a 16-byte block displayed in the next columns.
0...F
Displays sixteen 2-digit numbers, representing the hexadecimal byte value in that file location.
Text
Displays the ASCII representation of the byte value in the corresponding location in the byte value columns.
Save Edits
Saves changes to the open file.
Undo Edits
Discards all edits to the open file.
Find
Enables you to specify a character to seek in the file. You can also choose to search forward or backward from anywhere in the file.
Jump
Enables you to specify either a hexadecimal or decimal address to edit.
Close
Closes HexEdit and the open file.

See Also

Addlabel.app | Analyzer.app | Gendbc.prg | Cpzero.prg | Genhtml.prg | Utility programs | Visual FoxPro Key Codes


Samples and Walkthroughs

Microsoft Visual FoxPro includes numerous code samples, as well as step-by-step walkthroughs to help you learn and experiment with various program features.

In This Section

Samples
Provides class library, server, solutions, and foundation class code samples that you can use for experimenting and getting to know particular features in Visual FoxPro.
Walkthroughs
Provides a list of common scenarios in Visual FoxPro and gives step-by-step instructions for each, making it a good place to start learning about various Visual FoxPro features.

Related Sections

Getting Started with Visual FoxPro
Provides links to areas to help you get started with creating database management solutions, including information on installing, upgrading, and customizing Visual FoxPro.
Programming in Visual FoxPro
Provides links to basic information about creating applications in Visual FoxPro to maximize your programming productivity.


Samples

Visual FoxPro comes with numerous code samples that you can use for experimenting and becoming acquainted with features.

For additional samples, see the Microsoft Visual FoxPro 8.0 \Samples folder, which contains samples you can use to learn about using APIs, COM+ services, and data access.

In This Section

Sample Class Libraries
Lists sample class libraries that provide encapsulated functionality that you can add to your applications easily.
Server Samples
Lists server samples that focus on Automation Servers. An Automation server is a COM component application that exposes functionality that can be used and reused by other applications through Automation.
Solutions Samples
Contains many examples of useful things you can do using Microsoft Visual FoxPro.
Visual FoxPro Foundation Class Samples
Contains descriptions of samples in which you can use Visual FoxPro Foundation Classes along with the Component Gallery for rapid application development.

Related Sections

Getting Started with Visual FoxPro
Provides information about installing, upgrading, and configuring Visual FoxPro, as well as customizing the development environment.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
Walkthroughs
Provides step-by-step instructions for common scenarios, making them a good place to begin learning about the various features of Visual FoxPro.


Sample Class Libraries

The Visual FoxPro sample class library provides encapsulated functionality that you can easily add to your applications. The Solutions Samples illustrate using most of the sample classes. The sample classes are contained in the following files:

  • Buttons Class Library
  • Samples Class Library
  • Typelib Class Library
  • Utility Class Library
  • Registry Program

Buttons Class Library

Buttons.vcx contains the following classes.

Class | Description
CmdOK | A command button that releases the form it is added to. If the form is contained in a form set, cmdOK releases the form set.
CmdCancel | A subclass of cmdOK with the Caption property set to "Cancel."
CmdHelp | A command button that invokes Help with the HelpContextID of the form to which it is added.
MailBtn | A container with a command button, a Microsoft MAPI Message control, and a Microsoft MAPI Session control. Code in the Click event of the command button logs on to mail and composes a message containing the values in the current record of a table. For an example of using the MailBtn class, see SENDMAIL.SCX in the Visual FoxPro Samples\Solution\OLE folder.
VCR | A set of table navigation buttons that makes it possible for a user to move the record pointer to the next, prior, top, and bottom records of a table. Set the Skiptable property to the alias of the table you want to move the record pointer in. If Skiptable is empty, the record pointer is moved in the currently selected work area.

Samples Class Library

Samples.vcx contains the following classes.

Class | Description
CboFontName | A combo box that displays all the currently available fonts in the system.
CboFontSize A combo box that displays all the available point sizes for a particular font. Pass a font name to the FillList method to populate the combo box. The nLargestFont and nSmallestFont properties delimit the maximum and minimum font sizes displayed. You can use this control in conjuction with the cboFontName class. In the InteractiveChange event of the cboFontName object, call the FillList method of the cboFontSize object:

THISFORM.cboFontSize1.FillList(THIS.Value)

For an example of using this class, see the tbrEditing class in the same class library.
Clock A container that displays the current date and time.

The "Display a system clock" component in the Solutions sample also uses the Clock class.
Datachecker A custom class that manages resolving data conflicts. Code in the Error event of the VCR class in BUTTONS.vcx calls the CheckConflicts method of this class if an attempt to write buffered data to a table encounters changed values:

nConflictStatus = ; THIS.DataChecker1.CheckConflicts()

The "Run multiple instances of a form" component in the Solutions sample also uses this class to check for data conflicts.

For more information, open the class and read the comments in the code.
Distinct_values_combo | A combo box that is populated on initialization with the distinct values in the ControlSource alias. For example, if you add this class to a form and set the ControlSource to "customer.country", the combo box will be populated with the countries in the customer table without displaying the country names more than once.
FrmNoTitle A form with properties set so that no title is displayed. If you want to display information in a separate window, you can create an object based on this class and use form graphics methods.

The "Display line animation on a form" component in the Solutions sample also uses a form with no title to display the animation.
Lookup_combo A combo box that makes it easy to display values from one field, for example a company name, while binding a ControlSource to another field, for example a company id number. This class has four custom properties:

order_column: Column to sort the table by (optional).

lookup_table: Table to fill the combo box from.

display_column: Column in the table to display.

return_column: Column whose value is written to the ControlSource.
MoverLists A container with two list boxes and four command buttons. A user can move selected items from one list to the other list by clicking the command buttons or by dragging and dropping.

You need to make sure the RowSourceType of each list box is set to 0 and use the AddItem method to add items to the source list box.

MoverLists has three custom properties:

CanDropIcon: Cursor to be displayed over a valid target in a drag and drop operation.

NoDropIcon: Cursor to be displayed when dropping will not add the selected items to the list box.

DragThreshold: Number of pixels before the drag operation begins.

The "Move items between list boxes" component in the Solutions sample illustrates the use of this class.
Print_reports A modal form that makes it possible for a user to preview a report, print it, or direct it to a file. You can set the cReport property of the class to the name of the report or pass the report name in as a parameter:

o = CREATEOBJECT(print_reports, ; "myreport.frx")
QBF A container with three command buttons. Add this class and the VCR class to a form with data-bound controls. When the user chooses Enter QBF, the values in the controls are blanked out. Values that the user enters in the controls specify the filter to be set on the table when the user chooses Query.

The controls need to have a ControlSource set and the Parent of the controls needs to be the form, not another container.

The "Create a query by example form" component in the Solutions sample illustrates the use of this class.
Resizable A custom class that manages resizing and repositioning the controls on a form at run time, maintaining their relative sizes and positions. Add the class to a form and, in the Resize event of the form, call the AdjustControls method:

THIS.Resizable2.AdjustControls

Resizable has two custom properties you need to set:

RepositionList: A string containing all the classes for which objects are repositioned.

ResizeList: A string containing all the classes for which objects are resized.

The "Resize and reposition controls at run time" component in the Solutions sample illustrates the use of this class.
RTFcontrols A container class containing cboFontName, cboFontSize and command buttons for Bold, Italic, and ForeColor. The cboFontSize control is refreshed in the InteractiveChange event of cboFontName, but no additional functionality is coded with the Bold, Italic and ForeColor command buttons.

The "Use the RichText control" component in the Solutions sample illustrates the use of this class.
SoundPlayer | This class can be used to play a non-visual multimedia file such as a .WAV audio file. See the following section, Sample Multimedia Classes, for more information about this class.
StopWatch A container class with a timer and labels to display stop watch values.

StopWatch has three custom methods you'll want to use:

Start: Starts the stop watch

Stop: Stops the stop watch

Reset: Resets the displayed time to 0:00

The "Display a stop watch" component in the Solutions sample illustrates the use of this class.
TbrEditing tbrEditing has a custom property and a method you'll want to use:

nAppliesTo Property: This property can be set to 1, 2, or 3.

  1. User choices affect the current control on the active form.
  2. User choices affect all text boxes and edit boxes on the active form.
  3. User choices affect all controls on the active form.

Refresh: Accepts an object reference as a parameter and sets all the editing controls to the appropriate values of the object. Call the Refresh method in the GotFocus event of a control.

The "Change font attributes" component in the Solutions sample illustrates the use of this class.
VideoFrame | This class can be used to play a visual multimedia file, such as a video for Windows file. See the following section, Sample Multimedia Classes, for more information about this class.

Sample Multimedia Classes

Two of the classes (SoundPlayer and VideoFrame) in the Visual FoxPro Samples\Classes\Samples.vcx class library make it possible for you to use the MCI (Multimedia Command Interface) to play multimedia files.

To locate documentation for the MCI commands, search for "Multimedia Commands" in the MSDN Library (http://msdn.microsoft.com/library).

Sound Player Class

This class can be used to play a non-visual multimedia file, such as a .WAV audio file. It makes it possible for you to specify the file to be played, and then provides built-in methods to easily play the media file.

Property | Description
AutoOpen | Specifies whether the sound file should be automatically opened and displayed when the object is instantiated. The default value is True (.T.).
AutoPlay | Specifies whether the sound file should be automatically played when it is opened. The default value is True (.T.).
AutoRepeat | Specifies whether the sound file plays continuously. The default value is False (.F.).
ControlSource | Specifies the column that contains the sound file reference. If empty, the class expects a static file name to be in the SoundFile property.
MCIAlias | Specifies the alias to be used by MCI. If left empty, the alias defaults to the Name property of the class. Normally this can be left empty, but if the user wants to play the same sound file twice at the same time, a different alias would need to be specified for each.
SoundFile | Holds the name of a sound file to play, for example "C:\WINDOWS\CHIMES.WAV".
Method | Description
OpenSound | Opens the sound file.
PlaySound | Plays the sound file. The file must be opened with the OpenSound method before it can be played.
PauseSound | Pauses the playing of a sound file. Play can be continued by calling the PlaySound method.
SetPosition | Makes it possible for the user to specify the position of the media file. It can be executed at any time after the file has been opened. Valid values are "Start," "End," or a specific millisecond into the sound.
CloseSound | Closes the sound file and releases all resources associated with it.

VideoFrame Class

The VideoFrame class can be used to play a visual multimedia file such as a video for Windows file. This class makes it possible for you to position and size the video to be played, and then provides built-in methods to easily play the media file.

For an example of using this class, see Video.scx in the Visual FoxPro Samples\Solution\Forms folder.

Property | Description
AutoOpen | Specifies whether the video file should automatically be opened and displayed when the object is instantiated. The default value is True (.T.).
AutoPlay | Specifies whether the video file should automatically play when it is opened. The default value is True (.T.).
AutoRepeat | Specifies whether the video file will loop the video. Setting this to .T. will cause the video to play continuously. The default value is False (.F.).
ControlSource | Specifies a Field that contains the video file reference. If empty, the class expects a static file name to be in the VideoFile property.
MCIalias | Specifies the alias to be used by MCI. If left empty, the alias defaults to the Name property of the class. Normally this can be left empty, but if the user wants to play the same video file twice at the same time, a different alias would need to be specified for each.
VideoFile | Holds the name of a video file to play, for example: "C:\VFP\SAMPLES\SOLUTION\FORMS\FOX.AVI".
Method | Description
CloseVideo | Closes the video file and releases all resources associated with it.
DoMCI | Called by the other methods to execute MCI commands. It can also be called by a user to execute a specific MCI command.
OpenVideo | Opens the video file and shows the first frame.
PauseVideo | Pauses a playing video. The video can be restarted by using the PlayVideo method.
PlayVideo | Plays the video file. The video file must be opened in the OpenVideo method before it can be played.
SetPosition | Makes it possible for the user to specify the position of the media file. It can be executed at any time after the video file has been opened. Valid values are "Start", "End", or a specific millisecond into the video.

Typelib Class Library

Typelib.vcx contains the following class.

Class | Description
Typelib | A container class that contains a Visual FoxPro Foxtlib Control. The ExportTypeLib method of this class calls the methods of the Foxtlib control to read type library information from .OLB, .TLB, and .EXE files. The "View type library information" component in the Solutions sample illustrates the use of this class.

Utility Class Library

Utility.vcx contains the following classes.

Class | Description
Arraylib | A custom class with methods for inserting array elements, deleting array elements, and scanning array columns.
Execsp | A custom class with methods that facilitate SQL pass through and executing stored procedures on a remote database.
Filelib | A custom class with methods that perform common string tasks used when manipulating file names, for example, removing the extension, adding a backslash to a path, and so on.
Menulib | A container class with methods that create a shortcut menu from an array. The "Create dynamic shortcut menus" component in the Solutions sample illustrates the use of this class.

Registry Program

Registry.prg contains the following classes.

Class | Description
FileReg | A subclass of the Registry class that provides methods for reading the application associated with particular file extensions and the path to the application.
FoxReg | A subclass of the Registry class that provides methods for reading and writing Visual FoxPro settings in the Windows Registry.
ODBCReg | A subclass of the Registry class that provides methods for reading ODBC data source and driver information.
OldINIReg | A subclass of the Registry class that provides methods for reading and writing to an .INI file.
Registry | A custom class that provides methods for accessing Windows API functions for manipulating the Windows Registry.

For examples of using the registry classes, run SOLUTION.app in the ..\Samples\Solution folder.

See Also

Solutions Samples | Visual FoxPro Foundation Classes | Server Samples


Server Samples

Visual FoxPro includes several samples, which focus on Automation Servers. An Automation server is a COM component application that exposes functionality that can be used and reused by other applications through Automation. In addition, you can create one or more classes to handle enterprise-wide business rules. A client application that uses the business rule object would pass input parameters in a method call, and the Automation server might then do a great deal of work, retrieving or storing data from various sources and performing complex calculations, before returning the answer.

In This Section

FoxISAPI Automation Server Samples
Visual FoxPro includes an ISAPI extension called Foxisapi.dll that creates an instance of a Visual FoxPro automation server and then calls a method on that server that returns HTML. The FoxISAPI extension makes it possible for you to access Visual FoxPro custom Automation servers from any ISAPI supported Web server, such as Microsoft Internet Information Services (IIS) version 5.0 or later and Microsoft Personal Web Server.
COM+ Samples
Samples for using Queued Components, COM+ Events, and Compensation Resource Managers are located in the ...\Samples\COM+ folder.

Related Sections

Using Visual FoxPro
Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Visual FoxPro is a powerful interactive data management tool, but you also can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Sample Class Libraries
You can add functionality to your applications easily using the Visual FoxPro sample class libraries.
Visual FoxPro Foundation Class Samples
The Visual FoxPro Foundation Classes are provided with the Component Gallery as a way to provide rapid application development, with as little coding as possible, by providing common database development tools and structures; fast, extensible generic components; components that enhance Web page development; and effective wrappers for system API functions.


FoxISAPI Automation Server Samples

Visual FoxPro includes an ISAPI extension called Foxisapi.dll that makes it possible for you to access Visual FoxPro custom Automation servers from any ISAPI supported Web server such as Microsoft Internet Information Services (IIS) version 5.0 or later and Microsoft Personal Web Server. The FoxISAPI extension works by creating an instance of a Visual FoxPro automation server and then calling a method on that server that returns HTML. The HTML is passed from the Web server back to a Web browser such as Microsoft Internet Explorer.

Visual FoxPro includes two FoxISAPI automation server samples that demonstrate how you can use the power of Visual FoxPro to dynamically support a Web site. The first sample, FoxWeb, located in the Samples\Servers\FoxIsapi\FoxWeb folder, is a simple sample designed to demonstrate basic FoxISAPI concepts. This sample steps you through the process of setup and deployment of FoxISAPI servers, both local and remotely. In addition, the sample walks through steps needed to implement pooling of servers for improved scalability.

The second sample, FoxIs, located in the Samples\Servers\FoxIsapi\FoxIs folder, is a more complex sample that contains routines to map visual and functional content of a Visual FoxPro form to HTML. The concepts are the same as FoxWeb; FoxISAPI instantiates a server and invokes a method to return HTML. Because the FoxIs sample uses a visual form, it offers additional versatility by making it possible for you to run it as a stand-alone program, from OLE clients, and from a Web browser.

If you're not familiar with creating Visual FoxPro Automation servers, see Creating Automation Servers.

FoxISAPI Components

The following table lists the core FoxWeb Automation server sample files and a description of each.

File | Description
Foxisapi.dll | The main component of the FoxISAPI Automation server samples, FoxWeb and FoxIs. Foxisapi.dll is used with IIS or Microsoft Personal Web Server. Foxisapi.dll creates an instance of a Visual FoxPro Automation server and executes a method on that server. The method then returns the HTML displayed in the Web browser. Foxisapi.dll is used primarily with Visual FoxPro; however, it can be used with any Automation server.
Foxisapi.ini | An initialization file for Foxisapi.dll file that makes it possible for you to configure Foxisapi.dll.
Odebug.prg | A Visual FoxPro program used for debugging your Internet applications.

Configuring FoxISAPI Components

To install the core FoxISAPI components, follow these steps:

  1. Copy the Foxisapi.dll and Foxisapi.ini files to your Web server's script folder. For example, C:\InetPub\scripts\.
  2. Copy the Oldebug.prg program file to your Visual FoxPro root folder (the location returned by HOME( ) function). For example, C:\Program Files\Microsoft Visual FoxPro\.

See Also

FoxWeb, a Simplified Visual FoxPro Internet Automation Server | FoxIs, a Visual FoxPro Internet Server | Solutions Samples | Server Samples


FoxWeb, a Simplified Visual FoxPro Internet Automation Server

FoxWeb is a simplified ISAPI Automation server sample designed to quickly get a Web site up and running. FoxWeb provides a new version of Foxisapi.dll (also provided with the Visual FoxPro FoxIs server sample). Foxisapi.dll now can manage multiple instances of Visual FoxPro Automation servers, and provides additional debugging methods for Visual FoxPro applications designed for the Internet.

The FoxWeb Automation Server

The FoxWeb sample uses a simple Visual FoxPro server class intended to demonstrate the basic usage of a server run under FoxISAPI. All the code is stored in a file called FoxWeb.prg. This file contains a class called Server, which is marked as OLEPUBLIC so that it gets registered as an Automation server COM component when it is built. This class is instantiated by FoxISAPI and contains a number of methods that can be invoked (such as the Hello and Delay methods) as shown below. These methods illustrate the structures required by FoxISAPI in order to function properly.

The FoxWeb Sample Files

The files for the new Visual FoxPro FoxWeb Automation server sample are located in the Visual FoxPro ...\Samples\Servers\Foxisapi\FoxWeb directory.

Setting up the FoxWeb Automation Server

The following sections describe how to use Visual FoxPro to quickly get a Web site up and running with FoxWeb.

Registering the Visual FoxPro FoxWeb Automation Server

The Visual FoxPro Automation servers that return HTML must be registered. Registration is done automatically if your .exe or .dll was built with the Visual FoxPro Project Manager or with the BUILD EXE, BUILD DLL, or BUILD MTDLL commands. For example, if you open the FoxWeb project provided with the FoxWeb sample in the Project Manager, you can choose Build to create an Automation server as an in-process .dll or an out-of-process .exe file. Note that the registration occurs only on the machine on which the file was built.

A Visual FoxPro Automation server built as an out-of-process .exe can also be registered by specifying the Automation server name and including the /RegServer switch. For example, the following command registers the Visual FoxPro FoxWeb Automation server:

FoxWeb.exe /RegServer

A Visual FoxPro Automation server built as an in-process .dll can also be registered with Regsvr32.exe. For example, the following command registers the Visual FoxPro FoxWeb Automation server:

Regsvr32 FoxWeb.dll
Note If your Visual FoxPro ISAPI Automation server uses additional files such as .gif or .jpg files, be sure to place these files in directories that Microsoft Internet Information Services (IIS) or Microsoft Personal Web Server can access.

Using your Web Browser to access a Visual FoxPro ISAPI Automation Server

A Visual FoxPro ISAPI Automation server is accessed from your Web browser by providing the URL (Universal Resource Locator) of the Automation server. The Web browser makes an HTTP request that is passed to Microsoft IIS or the Microsoft Personal Web Server. The Automation server passes the request to Foxisapi.dll, which, in turn, passes the request to your Automation server.

For example, the URL below accesses the ISAPI Automation server named FoxWeb.Server:

HTTP://MyServer/Scripts/Foxisapi.dll/FoxWeb.server.Delay?30

The following table describes each of the elements of the URL example above.

URL Element | Description
Myserver | The virtual folder of IIS or the Personal Web Server.
Scripts/Foxisapi.dll | The IIS or Microsoft Personal Web Server Scripts folder and Foxisapi.dll.
FoxWeb.Server The registered name (ProgID) of the Visual FoxPro ISAPI Automation server to call.

In this example, FoxWeb is the name of the .exe or .dll file for the Visual FoxPro Automation server. Server is the class name specified in the OLEPUBLIC clause of the DEFINE CLASS command that creates the Automation server.

FoxWeb.Server is also the ProgID for the Automation server as it is stored in the Windows Registry. You can use RegEdit to view or modify the Automation server's ProgID.
Delay | The name of the method to execute on the Visual FoxPro ISAPI Automation server.
?30 | A parameter passed to the method. The question mark is a delimiter that specifies that a parameter follows. For this method, 30 specifies that execution is delayed for 30 seconds. The parameter is passed as a character string.

Passing Parameters to Methods

The following code is from the Delay method in FoxWeb.prg, and demonstrates the structure for methods executed on the Visual FoxPro ISAPI Automation servers.

PROCEDURE Delay
   LPARAMETERS cParm1, cIniFile, nPersistInstance
   *** Your code here ***
   RETURN AnHTMLString
ENDPROC
cParm1
A character string passed to the method. In the Delay method, this parameter specifies the number of seconds that execution is delayed.
cIniFile
The name of the .ini file (passed to the method by Foxisapi.dll) created each time a Visual FoxPro ISAPI Automation server is accessed. Each .ini file is created in the Scripts folder and has a unique name that begins with "Fox." You can use the GetPrivateProfileString function in FoxWeb.prg, for example, to read information from the .ini file and return custom HTML based on a user's configuration.
nPersistInstance
Specifies if the instance of the Visual FoxPro ISAPI Automation server persists after it is finished executing your method. nPersistInstance is passed by reference to the method by Foxisapi.dll. If nPersistInstance is set to 0 in your Web application, the instance of the Automation server remains alive after execution is finished. If nPersistInstance is a value other than 0, the instance of the Automation server is released. For optimal performance, nPersistInstance should be set to 0, otherwise the Automation server must be launched again the next time it is called.

Using Foxisapi.dll to Pool Automation Servers

Because Foxisapi.dll is free-threaded, it can now pool multiple Visual FoxPro ISAPI Automation servers to provide better scalability for your Web applications. Pooled ISAPI Automation servers allow a free ISAPI Automation server to service a request when other ISAPI Automation servers are busy. To take advantage of ISAPI Automation server pooling, the instances of the ISAPI Automation servers should be made persistent by setting nPersistInstance to 0 in your Web application.

The number of ISAPI Automation servers available to service requests is determined by settings in your Foxisapi.ini initialization file. To create a pool of multiple ISAPI Automation servers, include an entry in square brackets with the name of the ISAPI Automation server for which a pool is created. This entry is followed with a list of ISAPI Automation servers that comprise the pool, with a numeric value that specifies the maximum number of instances of each ISAPI Automation server that can be created.

For example, placing the following lines in Foxisap.ini creates a pool of seven ISAPI Automation servers for service requests to FoxWeb.myserver. Foxisapi.dll creates up to four instances of the FoxWeb.server ISAPI Automation server and up to three instances of the FoxWeb2.server ISAPI Automation server to service requests.

[FOXWEB.MYSERVER]
FOXWEB.SERVER=4
FOXWEB2.SERVER=3

The following URL executes the Delay method on either an instance of the FoxWeb.server or the FoxWeb2.server ISAPI Automation servers:

HTTP://MyServer/Scripts/Foxisapi.dll/FoxWeb.Myserver.Delay?30

Foxisapi.ini can specify that the ISAPI Automation servers are instantiated up front before a service request is received. To do so, add a comma followed by an asterisk (*) after the number of instances, as shown in the following example.

[FOXWEB.MYSERVER]
FOXWEB.SERVER=4,*
FOXWEB2.SERVER=3,*

Using the Pool Manager across Multiple Machines

Foxisapi.dll provides the ability to manage Visual FoxPro ISAPI Automation servers on multiple machines. You can use Remote Automation or DCOM (Distributed Component Object Model) to access the ISAPI Automation servers. Note that for optimal performance and scalability the instances of the ISAPI Automation servers should be made persistent by setting nPersistInstance to 0 in your Web application.

The following example describes a scenario where two Visual FoxPro ISAPI Automation servers, FoxWeb and FoxWeb2, are placed on two machines.

Machine_A is your local machine running Windows 98, DCOM, and Personal Web Server. Machine_B is your remote machine, accessible over your network, running Windows NT 4.0 or later and DCOM.

  1. Machine_A is your Visual FoxPro development machine on which you've installed the Visual FoxPro FoxISAPI Automation server samples. On this machine, open the FoxWeb project in the Visual FoxPro Project Manager, and choose Build to create an ISAPI Automation server as an out-of-process .exe file. Building the .exe automatically registers the ISAPI Automation server on the machine as FoxWeb.exe. Now open the FoxWeb2 project in the Visual FoxPro Project Manager, and choose Build to create and register another ISAPI Automation server as an .exe file.
  2. To verify that the ISAPI Automation servers FoxWeb and FoxWeb2 are properly registered, you can use RegEdit and search for FoxWeb and FoxWeb2. Note that the ProgIDs for the servers are FoxWeb.Server and FoxWeb2.Server, respectively. Server is the class name specified in the OLEPUBLIC clause of the DEFINE CLASS command that creates the ISAPI Automation server. FoxWeb.prg is the Visual FoxPro Internet application included in both the FoxWeb and FoxWeb2 projects.

    The ProgIDs for the ISAPI Automation servers both point to Machine_A, the local machine. The Registry settings for the FoxWeb2 ISAPI Automation server need to be changed to point to Machine_B, the remote machine.

  3. Now copy the FoxWeb2.exe, FoxWeb2.vbr, and FoxWeb2.tlb files from Machine_A, the local machine, to Machine_B, the remote machine.
  4. Use the /RegServer option to register FoxWeb2.exe on Machine_B at the MS-DOS prompt:
    C:\VFP\FOXWEB2.EXE /RegServer
  5. Finally, stop and restart the Personal Web Server on Machine_A to ensure that it is aware of the changes to the Registry.

You can execute the Status command on Foxisapi.dll to check the status of all the ISAPI Automation servers registered in Foxisapi.ini. The following URL executes the Status command:

HTTP://Machine_A/Scripts/FoxISAPI.dll/Status

You can execute the Reset command on Foxisapi.dll to reset all the ISAPI Automation servers registered in Foxisapi.ini. The Reset command releases all ISAPI Automation server instances. The following URL executes the Reset command:

HTTP://Machine_A/Scripts/FoxISAPI.dll/Reset

To test the installation, you can open up as many instances of your Web browser as there are ISAPI Automation servers in the pool. The Web browsers can be on multiple machines connected to your network. You can then call the Delay method in the URL from each Web browser so that Foxisapi.dll routes service requests to the other free ISAPI Automation servers. After the Delay method is executed from each Web browser, you can use the Status method to check to see if all ISAPI Automation servers in the pool received service requests.

Using FoxISAPI with DLL Servers

If you use FoxISAPI with multithreaded in-process servers in the previous version of Visual FoxPro, you need to disable Pool Manager support in FoxISAPI. You can do this by using the PoolMode setting in the FoxIsapi.ini file. The PoolMode setting is global to all servers, so we recommend that you do not let a single FoxIsapi.dll service both EXE and DLL servers. Instead, you should copy and rename the FoxIsapi.dll and FoxIsapi.ini files so that you have one set for EXE servers and one for DLL servers.

Debugging your ISAPI Automation Servers

FoxIsapi.dll also makes it possible for you to debug your ISAPI Automation servers on your local machine. Set the number of instances of the ISAPI Automation server you wish to debug to 0 as shown in the following example FoxIsapi.ini file:

[FOXWEB.MYSERVER]
FOXWEB.SERVER=0

The Odebug.prg program file must be present in your Visual FoxPro root folder and the ISAPI Automation server source files must be present. Be sure that the ISAPI Automation server you wish to debug is configured as a persistent ISAPI Automation server, and debugging information is turned on in the project containing the ISAPI Automation server source files.

When the ISAPI Automation server is instantiated, Foxisapi.dll starts Visual FoxPro for debugging, making it possible for you to set breakpoints, trace through code, and so on.

Foxisapi.dll Commands

Foxisapi.dll has commands you can call to determine the status of your ISAPI Automation servers and to reset the servers. The following table lists the Foxisapi.dll commands with a description of each.

Command | Description
MultiMode | Executes the Reset command, then limits the number of ISAPI Automation server instances to the values specified in Foxisapi.ini.
PoolMode | Enables or disables Pool Manager support in FoxISAPI. Use this command to turn off Pool Manager for in-process DLL servers. 0 – disables 1 - enables (default)
Reset | Releases all instances of the ISAPI Automation servers.
SingleMode | Executes the Reset command, then limits the number of ISAPI Automation server instances to one instance. Execute this command to perform maintenance; for example, you can open tables exclusively in when SingleMode is in effect.
Status | Displays the current status of the ISAPI Automation servers, the Foxisapi.ini settings, and whether SingleMode or MultiMode is in effect.

Each of the Foxisapi.dll commands is called by a URL that is specified in Foxisapi.ini. The following is the contents of the sample Foxisapi.ini file with the default URLs:

[FOXISAPI]
StatusURL = Status
ResetURL = Reset
SingleModeURL = SingleMode
MultiModeURL = MultiMode

The following URL executes the Status command:

HTTP://MyServer/Scripts/Foxisapi.dll/Status

In the following sample Foxisapi.ini file, the URL for the Status command is changed from Status to MyStatus:

[FOXISAPI]
StatusURL = MyStatus
ResetURL = Reset
SingleModeURL = MSingleMode
MultiModeURL = MultiMode

After this change to Foxisapi.ini, the following URL executes the Status command:

HTTP://MyServer/Scripts/FoxISAPI.dll/MyStatus
Note You must reset Foxisapi.dll with the Reset command after you make changes to Foxisapi.ini file in order for the changes to take effect.

Additional FoxISAPI.ini Settings

Foxisapi.dll reads Foxisapi.ini and configures its settings according to the items contained in Foxisapi.ini. The following table describes each of the additional items you can place in your Foxisapi.ini file.

Item | Description
AutoRefreshStatus | Specifies the number of seconds between Status page refreshes. The default is 0 seconds (the Status page isn't refreshed) if this item is omitted or if Foxisapi.ini isn't present.
BusyTimeout | Specifies the number of seconds Foxisapi.dll waits for the Visual FoxPro application servers to respond before a time-out message is generated. The default is 2 seconds if this item is omitted or if Foxisapi.ini isn't present.
ReleaseTimeout | Specifies the number of seconds Foxisapi.dll waits for a busy Visual FoxPro application server to respond before the Reset command is executed. The default is 2 seconds if this item is omitted or if Foxisapi.ini isn't present.

The following is taken from the sample Foxisapi.ini file, and demonstrates the formats of the additional items you can place in the file:

[FOXISAPI]
BusyTimeout = 5
ReleaseTimeout = 15
Note You must reset Foxisapi.dll with the Reset command after you make changes to Foxisapi.ini file in order for the changes to take effect.

Configuration Tips for Microsoft Internet Information Services (IIS)

Two Microsoft IIS registry entries, PoolThreadLimit and ThreadTimeout, can be added to your registry to improve performance with the Visual FoxPro FoxISAPI Automation servers. These registry entries determine the total number of threads that Internet Information Services can create, and the length of time the threads exist. For more information about these registry entries, see the Internet Information Services documentation.

A Microsoft Knowledge Base article titled "How to Launch Automation servers from ISAPI Extensions" (number Q156223) is available on www.microsoft.com. This article provides information about the access security permissions required to launch Automation servers such as the Visual FoxPro ISAPI Automation Servers.

See Also

Solutions Samples | FoxISAPI Automation Server Samples | FoxIs, a Visual FoxPro Internet Server


FoxIs, a Visual FoxPro Internet Server

FoxIs, located in the Visual FoxPro ...\Samples\Servers\Foxisapi\FoxIs directory, illustrates creating an out-of-process .exe or in-process .dll with ISAPI functionality that can be accessed from within Visual FoxPro as a stand-alone program, from Automation clients, and from a Web browser. Changes you make to its classes can enhance the Automation server, no matter how it is run.

To open the FoxIs sample project

  • Type the following in the Command window:
    MODIFY PROJECT (HOME(2) + 'servers\foxisapi\foxis\foxis')

Running the FoxIs Sample

You can run the FoxIs sample four different ways. When you are trying out the code, it's a good idea to go run the sample in this order:

Running from Within Visual FoxPro

To run the FoxIs sample from within Visual FoxPro, run the following code in the Command window.

SET DEFAULT TO (HOME(2) + 'servers\foxisapi\foxis\')
SET CLASSLIB TO employee
ox = CREATEOBJECT('employee')
ox.show

Running as an Independent Executable

You can build the sample into an executable file with the following line of code:

BUILD EXE foxis FROM foxis

The compiled file, FOXIS.EXE, is a Windows program that can be added to the Windows Start menu, started from the Windows Explorer, and so on.

Running as an Automation server

Once the FoxIs sample has been compiled into a .exe or a .dll, it is registered as an Automation server in the Windows registry. You can create an object based on the employee class from any OLE controller, for example Excel, Visual Basic, and Visual FoxPro:

ox = CREATEOBJECT('foxis.employee')
ox.SHOW

Running from a Web Browser

You can even run the FoxIs sample from a Web browser, which could be on another machine such as a 286 running MS-DOS, a Unix machine, a Macintosh, or a Personal Digital Assistant.

System Requirements for Internet Use

To run the FoxIs sample from a Web browser, you must be running:

  • Windows 98 or Windows NT 4.0 or later.
  • An ISAPI-compatible Web server, such as the Microsoft Personal Web Server for Windows 98 or Microsoft's Internet Information Services (IIS). IIS comes with Windows NT 4.0 and later and can be downloaded from www.microsoft.com; Personal Web Server also can be downloaded from www.microsoft.com.

If you're using Windows NT 4.0 or later, you need to run the DCOMCNFG utility to configure DCOM to give rights to the IIS service to instantiate OLE objects.

To configure Windows NT 4.0 or later DCOM

  1. At the Command prompt, type DCOMCNFG and press Enter.
  2. In the Applications tab, select the name of the Automation server. When you build the server, the application is "employee" by default.
  3. In the Default Security tab of the Distributed COM Configuration Properties dialog box, choose Edit Default for each area: Default Access Permissions, Default Launch Permissions, and Default Configuration Permissions.
  4. In the Registry Value Permissions dialog box for each area, choose Add.
  5. In the Add Names box of the Add Users and Groups dialog box, type your WWW server's name and your login user name.

    You can see the server's name in the Microsoft Internet Service Manager Properties window. If your machine name is MINE, the following line in the Add Names box sets up a default user:

    \MINE\IUSR_MINE

    If your machine name is MINE and you log in as HOMER, the following line in the Add Names box sets up permissions for you when you login:

    \MINE\HOMER

Setting Up the FoxIs Sample for Internet Access

To set up the FoxIs sample, you need to create a .exe or .dll from the FoxIs project, and then copy the file to your Inetsvr\Scripts directory.

To set up the FoxIs Sample

  1. Open the FOXIS project.
  2. Choose the Build button, and then choose Build COM DLL.
  3. Copy Foxisapi.dll to your Inetsrv\Scripts folder.

Preliminary Testing

You can test the FoxIs sample application at various levels to see if you are configured correctly.

To see if the code works

  1. From the Program menu choose Do.
  2. Select Main.prg in the Visual FoxPro Samples\Servers\Foxisapi folder.
  3. Choose Do.

To see if the .EXE works

  1. From the Visual FoxPro Command window, issue the following command:
    BUILD EXE Foxis.exe FROM foxis
  2. Double-click Foxis.exe in the Windows Explorer.

To see if the FoxIs Automation server works

  • Run the following commands:
    OX= CREATEOBJECT('FOXIS.EMPLOYEE')
OX.Show    && See if it works as a ISAPI Automation server
?OX.Startup( )  && See if it returns html

It is much easier to debug Automation servers from an Automation controller (such as Visual FoxPro) before instantiating it in FoxIs.

Set up the HTML page

To get things started, you need an HTML page that contains a reference to a URL. For example, take the following code and put it in the Wwwroot\default.htm file.

<a HREF="/scripts/foxisapi.dll/FoxIS.employee.startup"> <i>VFP ISAPI AUTOMATION SERVER DEMO PAGE</i> </a>

Then use a browser (which can be on the same machine) and connect to YourMachineName. For example, if your machine name was "myMachine," then type "myMachine" as the URL to go to. This would bring up the Default.htm page on the server named "myMachine"

A CreateObject("foxis.employee") is initiated and the Startup method is invoked on the object, which returns a generated HTML page. If the ISAPI Automation server hasn't been built yet, then the Foxisapi.dll returns an HTML error page.

Then use your Web browser to access the href above. If you get an error HTML page that says "Foxisapi error", then you know the DLL is being loaded and is working.

 <FORM ACTION = "/scripts/foxisapi.dll/foxis.employee.cmd">
<INPUT NAME="Cmd" VALUE = "Reset">
<INPUT TYPE="submit" VALUE="Dos Command">
</FORM>

You can actually put in any valid MS-DOS command and it will be executed on the server machine. If the command is "Reset" (default), then it will make the ISAPI Automation server release the first instance as well as it's own, thus releasing the ISAPI Automation server completely.

In addition, you can evaluate any Visual FoxPro expression. However, if the Visual FoxPro expression displays a modal interface, as the MESSAGEBOX( ) function does, the Automation server will hang waiting for a response that cannot be provided. However, for an in-process .dll, the modal interface is automatically managed and the Automation server won't hang.

<FORM ACTION = "/scripts/foxisapi.dll/foxis.employee.cmd?FOXCMD">
<INPUT NAME="Cmd">
<INPUT TYPE="submit" VALUE="Fox Expression">
like "today is "+ cdow(date()) or 45 * 3 or SYS(2004)
</FORM>

Debugging the Server

A Windows NT service has no Desktop, therefore no user interface will appear on the server machine. This means you should debug your server applications before deploying them.

To trace through Foxisapi.dll with Visual C++ 5.0

  1. Open Foxisapi.mak.
  2. Remove the comment mark from the following line in HttpExtensionProc:
    //   _asm int 3
  3. Rebuild the project.
  4. Start MSDEV with the process id (PID) of Inetinfo.exe. You can get the process id in the Windows Task Manager.

This process applies to Windows NT 4.0 or later.

Tip When debugging, you don't have to shut down the Web server to change the Automation server. You can just terminate the out-of-process component by sending a reset value to the cmd method, as described above, or by using the Win32 SDK tools TLIST, KILL, PVIEW, or the Task Manager in Windows NT 4.0 or later.

The ISForm Class

The "engine" of the sample is the ISForm class in Isapi.vcx.

Entry Points into the ISForm Class

The following methods can be called from the Web browser, by way of Foxisapi.dll, to return HTML pages.

Method | Returns
Cmd | Evaluation of a Visual FoxPro expression or the results of a MS-DOS command.
DoSave | Saves the user changes to the data and returns the employee HTML page.
Skipit | The employee information for the specified employee in the table. Skipit takes cookie information passed in as a parameter from the Web browser, checks the cookies table to find the previous record number, and moves the record pointer forward or backward relative to the record number stored in the cookies table. The new record number is written back to the cookies table and the GenHTML method is called.
Startup | The employee information for the first employee in the table. Startup creates a new cookie id for the user and sends it back as a hidden input area in the HTML.

Keeping the Server Active

Normally, for each request from a Web client, the Automation server is instantiated, generates an HTML page, and is released with the Release( ) call in CallObject( ) in Foxisapi.cpp. This means the entire Visual FoxPro runtime will start up and shut down for each request.

If the ISAPI Automation server is registered as Multi-Use, and the Release( ) is not called, then the first request will start up the server but subsequent requests will use the same instance of the server, making performance much better. Code in Foxisapi.dll and in the Load, Cmd, DoSave, Startup, and Skipit methods of the ISForm manage keeping the same instance of the server active.

Variables in the DLL

Two variables are declared: pdispObj and pdispDoRelease. When the server is initially created, pdispObj is the dispatch handle to the OLE object. The pdispDoRelease variable is set to the same value as pdispObj and passed by reference as a parameter to the method of the ISForm server that was requested by the Web browser. Code in the Visual FoxPro ISForm Automation server can change the value of pdispDoRelease.

Tip For more information about this sample, see the comments in the code in ISForm and Foxisapi.cpp.

The Form Load Event

When the ISForm is created, code in the Load event creates two public variables, gpInstance and gpDisp. The first time the ISForm server is loaded, the gpInstance variable is set to 1. Subsequent instances increment this variable. When an instance is released, gpInstance is decremented.

The Entry Point Methods

When a method (Cmd, DoSave, Skipit, or Startup) of the ISForm is invoked through Foxisapi.dll, the .dll passes a dispatch pointer by reference as a parameter to the method.

The first time the server is run, the instance count is set to 1 and the dispatch pointer is stored to the global variable. Then value 0 is stored to the dispatch pointer.

IF m.gnInstance = 1
   IF TYPE('pDisp') $ 'NI'
      gpDisp = m.pDisp
      pDisp = 0
   ENDIF
ENDIF

At this point, two variables point to the same dispatch pointer value: gpDisp in the ISForm Automation server and pdispObj in Foxisapi.dll. The value of pdispDoRelease in the .dll is 0, as changed in the ISForm Automation server.

Subsequent times the server is called the instance count in incremented, a new pdispObj is generated in the .dll, stored to pdispDoRelease, and passed by reference to the requested method. Because the gnInstance value is not 1, the gpDisp variable is not changed. From this point on, gpDisp in the Automation server holds a different value than pdispObj and pdispDoRelease in the .dll.

Code in the DLL

The following C++ code in Foxisapi.cpp manages releasing the server. After the first instance is created, subsequent instances are released normally with the Release( ) call in CallObject( ) in Foxisapi.cpp because pdispObj and pdispDoRelease are set to the same non-zero value.

if (pdispDoRelease != 0) {
   pdispObj->Release();  //nonzero, so release the current object
   if (pdispObj != pdispDoRelease) {
      __try {
         (pdispDoRelease)->Release();
      } __except  (EXCEPTION_EXECUTE_HANDLER) {

      }
   }
}

The Destroy event of the ISForm decrements the instance count. When there is only one instance, pdispDoRelease has been set to 0 and the release code is not called. if the pdispObject and pdispDoRelease are the same, subsequent instances are released, but the original instance is not released.

Releasing the Server

To force a release, pdispDoRelease cannot be 0 and must be a different value than pdispObject. The following HTML text sends a value to the server that affects a release:

 <FORM ACTION = "/scripts/foxisapi.dll/foxis.employee.cmd">
<INPUT NAME="Cmd" VALUE = "Reset">
<INPUT TYPE="submit" VALUE="Dos Command">
</FORM>

The following code in the cmd method sets the pdispDoRelease value to the dispatch value of the first instance.

CASE 'RESET'$upper(m.p1)
   m.pDisp= m.gpDisp

Code in the .dll will now release the current instance and the original instance that has been kept in existence to prevent the Visual FoxPro runtime from having to be reloaded each time the server was called.

Sending HTML Back to the Client

The GenHTML method of the ISForm class is called from each of the entry point methods. The HTML returned from the GenHTML method is returned to the Web browser through Internet Information Services.

If the mode parameter passed to the GenHTML method is not "FORM," the GenHTML method simply looks up the value in a table and sends back preformatted HTML.

IF m.mode != 'FORM'
   =SEEK(m.mode,'html')
   rv = html.html
  RETURN m.rv
ENDIF

If the mode parameter is "FORM," code in GenHTML identifies each of the labels and textboxes on the form, sorts them in top to bottom and left-to-right order, evaluates the Captions and ControlSources of the controls, and uses Visual FoxPro's text merge capabilities to construct the appropriate HTML text to approximate the display of the form.

If you add additional labels and text boxes to the form, they are automatically displayed in the generated HTML.

Creating and Using Cookies

As a Web server, this application can be hit dozens of times by various clients, and we need to keep track of the user state. In this case, we only track the current record number for that user. We could present the user with a login screen, and use the username as a key for the cookie, but instead we generate a cookie value in the MakeCookie method and pass it as a hidden value in the HTML sent back to the user. Each time the user chooses to go to a different record, we can read the cookie value from the HTTP string sent to the .dll, locate the cookie in the Cookies table, find the current record number and move the record number relative to this number.

The following property and methods are used in the cookie manipulation process:

  • Cookie property
  • GetCookie method
  • MakeCookie method
  • WriteCookieInfo method

Error Handling

If an error occurs, code in the Error event of the ISForm class calls the GenHTML method with a parameter of "ERROR." GenHTML reads the pre-formatted HTML text for errors and returns it to the Error event code. The Error event code substitutes error information for placeholders in the HTML:

   LOCAL rv
   rv = THIS.GenHTML('ERROR')
   rv = strtran(m.rv,'%METHOD%',m.cMethod)
   rv = strtran(m.rv,'%ERRORNO%',STR(m.nError,4))
   rv = strtran(m.rv,'%ERRORMSG%',Message(1))
   rv = strtran(m.rv,'%LINENO%',STR(m.nLine,4))
   THIS.ErrorHTML = m.rv

When the ErrorHTML property isn't empty, GenHTML sends the value of ErrorHTML back to the client.

Tables Used in the FoxIs Sample

In addition to the employee table used for data entry and display, the FoxIs sample uses the following tables.

Table | Description
HTML | Holds HTML text to be sent back to the Web browser as a header for FoxCMD and DosCMD evaluations or in case of an error.
Cookies | Keeps track of record numbers for various Web browsers. The unique cookie field value is passed as a hidden value in HTML text sent to a particular user.

See Also

Solutions Samples | FoxISAPI Automation Server Samples | FoxWeb, a Simplified Visual FoxPro Internet Automation Server


COM+ Samples

Windows 2000 introduces a new set of component services (COM+ Services) that extend the ability to create rich distributed transactional solutions for your Windows or Web applications. Visual FoxPro includes new and enhanced server features to better support many of these services. The COM+ samples are very simple and meant to show basic concepts of using a specific COM+ Service. Samples for using Queued Components, COM+ Events, and Compensation Resource Managers are located in the ...\Samples\COM+ folder. For more information, see the Readme.htm file in the folder.

Some of the COM+ Services, such as Transactions, existed prior to Windows 2000 and were supported by Visual FoxPro. New services, such as COM+ Events and Queued Components, offer new options for your applications that were not available previously in Visual FoxPro.

See Also

Server Samples | FoxISAPI Automation Server Samples


Solutions Samples

Visual FoxPro Solution samples demonstrate particular features of Visual FoxPro and can be run independently. The Solution samples also include examples based on the Visual FoxPro Foundation Classes.

Running Solution Samples

You can run Visual FoxPro Solution samples from the Visual FoxPro Task Pane Manager, which includes functionality for searching and installing additional samples.

To run Solution samples from the Task Pane Manager

  1. To open the Task Pane Manager, select Task Pane from the Tools menu.
  2. From the Task Pane Manager toolbar, select Solution Samples.
  3. From one of the sample categories, choose a sample that you want to run.
  4. To run the sample, click the hyperlink for the sample. To see code for the sample, click the Click here to view the code icon located to the right of the sample description.

For more information about the Task Pane Manager, see Task Pane Manager.

You can also run the Solution samples from the Solution sample application located in ...\Samples\Solution\Solution.app.

See Also

Samples | Walkthroughs | Reference | Using Visual FoxPro


New Visual FoxPro 8.0 Solution Samples

This version of Visual FoxPro contains many Solution samples to demonstrate new features and enhancements.

In This Section

Binding, Raising, Unbinding, and Retrieving Events Sample
Demonstrates binding events, raising events programmatically, unbinding events, and retrieving events.
Controlling MSN Messenger Sample
Demonstrates how to perform operations with MSN Messenger using the Messenger API and Windows Scripting Host.
Creating a Cursor from an XML DataSet Sample
Demonstrates how to create a cursor from an XML DataSet using the CursorAdapter and XMLAdapter classes and how to bind the data to controls on a form.
Creating Irregularly Shaped Windows Sample
Demonstrates how you can use the Windows API SetLayeredWindowAttributes function to change the default rectangular-shaped client area of the main Visual FoxPro window or any forms you create.
Grid Highlighting, Column Resizing, and Header Images Sample
Demonstrates how to select style and colors for grid highlighting, resize columns automatically to the width of data in the column, lock the first grid column so that it does not scroll, and specify images in column headers.
Loading and Generating XMl Using XMLAdapter Class Sample
Demonstrates some of the many uses for the XMLAdapter class, such as select an XML file to create cursors or generate XML from multiple tables.
Managing Data Access Using CursorAdapters Sample
Demonstrates how CursorAdapter objects retrieve data from three different data source types.
Member Classes Sample
Demonstrates how specifying and subclassing member classes makes it possible for you to select a parent container, set the member class library, increase or decrease the member count, and view behavior at design time or run time.
Passing Strongly Typed Arrays Sample
Demonstrates how you can pass a strongly typed array by reference to a COM server using the COMARRAY function. This sample also demonstrates the interface declaration syntax for specifying ByRef type arrays in the generated COM type library.
SCATTER NAME...ADDITIVE Sample
Demonstrates how to update and saves some form properties from and to a table using the SCATTER command with the NAME and ADDITIVE clauses and the GATHER command with the NAME clause.
Structured Exception Handling Sample
This sample demonstrates how to catch exceptions using the TRY and CATCH blocks, clean up resources using the FINALLY block, and throwing, or escalating, exceptions using a THROW statement.
System Tray Icon Sample
Demonstrates some common uses of the Systray class, which supports using icons in the Taskbar Notification Area, or System Tray. The Systray class also supports mouse events, balloon tips, and Visual FoxPro shortcut menus for your System Tray icon so you can use all the features of the Visual FoxPro Menu Designer.
Windows XP Themes Support Sample
Demonstrates different levels of Visual FoxPro support for Windows XP Themes.

Related Sections

Solutions Samples
Contains a collection of independent samples that demonstrate particular Visual Foxpro features. The Solution samples also include examples based on the Visual FoxPro Foundation Classes.
Server Samples
Contains samples that demonstrate automation servers. Automation servers are COM component applications that expose functionality that other applications can use through automation.
Foundation Class Samples
Contains samples that demonstrate the Visual FoxPro Foundation Classes that are provided with the Component Gallery to assist in rapid application development.
Walkthroughs
Describes step-by-step instructions for common scenarios.


Binding, Raising, Unbinding, and Retrieving Events Sample

File: ...\Samples\Solution\Toledo\FrmEvents.scx

This sample demonstrates binding events, raising events programmatically, unbinding events, and retrieving events for _SCREEN system variable, or the main Visual FoxPro window. In the sample, you can manually raise a bound event for _SCREEN by selecting an event from the combo box or invoke the same events and their respective handlers by using the mouse.

For more information about _SCREEN, see _SCREEN System Variable.

Binding Events

To respond to Visual FoxPro events, use the BINDEVENT( ) function. In this sample, the BINDEVENT( ) function is called in the custom InitBindEvent method and binds several _SCREEN events to the form's methods. When one of the _SCREEN events fires, the associated handler method is called:

BINDEVENT(_SCREEN,"Resize",ThisForm,"screenresize")
BINDEVENT(_SCREEN,"Mousedown",ThisForm,"screenmousedown")
BINDEVENT(_SCREEN,"Mouseup",ThisForm,"screenmouseup")
BINDEVENT(_SCREEN,"Rightclick",ThisForm,"screenrightclick")
BINDEVENT(_SCREEN,"Dblclick",ThisForm,"screendblclick")

For more information, see BINDEVENT() Function and Init Event.

Raising Events Programmatically

To raise events programmatically, use the RAISEEVENT( ) function. In this sample, when the combo box is selected, the InteractiveChange event uses the returned value to programmatically raise the specified event.

RAISEEVENT(_SCREEN,this.Value)

For more information, see RAISEEVENT() Function and InteractiveChange Event.

Unbinding Events

To unbind event handlers, use the UNBINDEVENTS( ) function. In this sample, the custom UnbindHandlers method unbinds events for _SCREEN.

UNBINDEVENTS(_SCREEN)

For more information, see UNBINDEVENTS() Function.

Retrieve Event Bindings

To retrieve existing event bindings into an array, use the AEVENTS( ) function. In this sample, the custom ScreenDblClick method, which is bound to the _SCREEN DblClick event, uses the AEVENTS( ) function to report the number of event bindings:

AEVENTS(laEvents,Thisform)

For more information, see AEVENTS() Function, and DblClick Event.

See Also

Solutions Samples | Event Binding for Visual FoxPro Objects


Controlling MSN Messenger Sample

File: ...\Samples\Solution\Toledo\Messenger.scx

This sample demonstrates how to perform operations with MSN Messenger using the Messenger API and Windows Scripting Host. You can use these methods to automate sending messages, e-mail, and files to any MSN user from automated processes. Additionally, if users have mobile messaging, alerts can be sent to their pagers.

This sample is not meant as an alternate user interface to MSN Messenger. For information on the MSN Messenger APIs, see MSDN online at http://msdn.microsoft.com.

MSN Messenger API

This sample demonstrates the Messenger APIs that you can access through the Component Object Model (COM). In this sample, the Messenger object is instantiated in the Init event:

ThisForm.oMessenger = CREATEOBJECT("Messenger.UIAutomation.1")

The Init event also declares some Windows APIs used to bring Messenger windows to the foreground so that you can automate composing e-mail messages and sending files.

DECLARE LONG SetForegroundWindow IN WIN32API LONG
DECLARE INTEGER FindWindow IN WIN32API STRING @ cClass, STRING @ cTitle
DECLARE LONG CloseWindow IN WIN32API LONG
DECLARE Sleep IN WIN32API long

After creating an instance of a Messenger object, you can call methods such as AutoSignin, InstantMessage, OpenInbox, SendFile, SendMail, and SignOut. The SendFile and SendEmail methods also use the Windows APIs to bring Messenger windows to the foreground so that the Windows Scripting Host Shell object can be used to send keystrokes to those windows.

Windows Scripting Host

This sample illustrates how to use Windows Scripting Host to send keystrokes to the activated windows. You can then fill out forms automatically for sending e-mail and files. Windows Scripting Host is required because the MSN Messenger API does not have this functionality. The Windows Scripting Host Shell object is instantiated in the Init event of the sample form:

ThisForm.oWsh = CREATEOBJECT("wscript.Shell")

To send keystrokes to the active window, the SendKeys method of the sample form calls the SendKeys( ) function of the Windows Scripting Host Shell object and automates the composition of e-mail and sending of files.

ThisForm.oWsh.SendKeys(tcKeys)

See Also

Solutions Samples | Init Event


Creating a Cursor from an XML DataSet Sample

File: ...\Samples\Solution\Toledo\CAXML.scx

This sample demonstrates how to create a cursor from an XML DataSet using the CursorAdapter and XMLAdapter classes and how to bind the data to controls on a form.

To see the changes in an XML DiffGram

  • Make changes in the grid and click Show DiffGram.

To view CursorAdapter property settings

  • Click Show CursorAdapter Properties.

For more information about CursorAdapter and XMLAdapter, see CursorAdapter Class and XMLAdapter Class.

Loading XML into a Cursor

In this sample, the XMLAdapter LoadXML method loads an XML DataSet into an XMLAdapter object and works with a CursorAdapter object to create a cursor. Loading the XML DataSet into the XMLAdapter creates XMLTable objects in the XMLAdapter Tables collection corresponding to the tables in the XML DataSet. The CursorAdapter SelectCmd property is set to the XMLTable object you want to display. When the CursorAdapter CursorFill method is called on the CursorAdapter object, the cursor is created.

For more information, see LoadXML Method, XMLTable Class, and CursorFill Method.

This sample uses an ADO.NET DataSet as the XML file, but the XML file can also be a Visual FoxPro-generated XML DataSet.

To load an XML DataSet into an XMLAdapter object

  1. In the Init event of the sample form, add a property that is an object reference to an XMLAdapter by using the Form or Class designers or by using the AddProperty method in code:
    ThisForm.AddProperty('oXMLAdapter',CREATEOBJECT('XMLAdapter'))
  2. To create the Tables collection in the XMLAdapter object, load the XML file as shown in the following code:
    WITH ThisForm.oXMLAdapter
   .LoadXML(ThisForm.cRunPath+'getcustomers.xml',.T.)
ENDWITH
  3. Set CursorAdapter SelectCmd to the XMLTable object and call the CursorAdapter CursorFill method:
    ThisForm.DataEnvironment.cursor1.SelectCmd= ;
   "ThisForm.oXMLAdapter.Tables.Item(1)"
ThisForm.DataEnvironment.cursor1.CursorFill()

To view the properties of the CursorAdapter object, look in the DataEnvironment object. You can open the DataEnvironment Designer by right-clicking the CursorAdapter object and selecting Builder. The CursorAdapter properties have been set by the CursorAdapter Builder.

For more information, see DataEnvironment Object, Init Event, and CursorAdapter Builder.

Controlling Data Binding

The cursor containing the data that the form uses does not exist when data binding usually occurs. This is because the XMLAdapter object is loading the XML in the form's Init event, which occurs after data binding by default. However, you can control when data binding occurs by setting the Form BindControls property.

In this sample, the form's BindControls property is set to False (.F.). After the CursorAdapter CursorFill method creates the cursor containing the data, BindControls is set to True (.T.). You can then bind the controls on the form using the following code:

ThisForm.BindControls = .T.

For more information, see BindControls Property.

Generating XML DiffGrams with the XMLAdapter

To generate an XML DiffGram, use the XMLAdapter ToXML method, as illustrated in the cmdDiffgram.Click event of this sample:

WITH ThisForm.oXMLAdapter
   .ReleaseXML(.F.)      && Release XML document but preserve schema.
   .UTF8Encoded = .T.    && Indicates International characters.
   .IsDiffgram = .T.     && Generate XML DiffGram.
   llIncludeBefore = .T. && Include <diffgram:before> format.
   llChangesOnly = .T.   && Generate only changes made.
   llIsFile = .F.        && XML is a variable.
   lcSchemaLocation = "" && Generate inline schema.
   .ToXml("lcXML",lcSchemaLocation,llIsFile,llIncludeBefore,llChangesOnly)
ENDWITH

See Also

Solutions Samples | XML Functionality Using XMLAdapters


Creating Irregularly Shaped Windows Sample

File: ...\Samples\Solution\Toledo\Irregular.scx

The main Visual FoxPro window and any forms you create have rectangular-shaped client areas by default. To change the shape, you can use the Windows API SetLayeredWindowAttributes function, which sets the opacity and transparency color key of a layered window. SetLayeredWindowAttributes is supported in Microsoft Windows 2000 and Windows XP.

Windows API Function Declarations

In this sample, the form's Init event contains the following declarations for the necessary API functions:

DECLARE INTEGER SetLayeredWindowAttributes IN win32api;
      INTEGER HWND, INTEGER crKey, INTEGER bAlpha, INTEGER dwFlags
DECLARE INTEGER SetWindowLong IN user32.DLL ;
   INTEGER hWnd, INTEGER nIndex, INTEGER dwNewLong
DECLARE INTEGER GetWindowLong IN user32.DLL ;
   INTEGER hWnd, INTEGER nIndex

For more information about the Init event, see Init Event. For detailed information about these declarations and functions, see MSDN online at http://msdn.microsoft.com.

Displaying Irregularly-Shaped Windows

You can display a nonrectangular form by using the SetLayeredWindowAttributes function and setting a transparent color. Shapes that are drawn using this color appear transparent. Also, any mouse clicks in these shapes pass through to the visible form.

This functionality is supported only in Microsoft Windows 2000 and Windows XP but is more efficient than previous techniques for setting a bounding region on the form. Although this technique makes a form transparent, the form must be set up properly to work with this functionality.

To set up the form

  1. On the form, set the Form ShowWindow property to 2 (As Top-Level Form) to make it possible to draw a layered window.
  2. Turn off the window frame because it is not drawn when transparent by setting the following properties for the form:
    BorderStyle   = 0
Caption   = ""
Closable   = .F.
ControlBox   = .F.
TitleBar   = 0
  3. In the MakeIrregular method of the sample, set the magenta areas, as specified by the nColor variable, to transparent using the following code:
    * Gets existing flags from the window.
lnFlags = GetWindowLong(nHWND, GWL_EXSTYLE)
ThisForm.nFlags = lnFlags
* Appends Layered flag to existing flags.
lnFlags = BITOR(lnFlags, WS_EX_LAYERED)
* Sets new flags to the window.
SetWindowLong(nHWND, GWL_EXSTYLE, lnFlags)      SetLayeredWindowAttributes(nHWND, nColor, 0, LWA_COLORKEY)

For more information, see Form Designer, Creating Forms, and ShowWindow Property.

See Also

Solutions Samples


Grid Highlighting, Column Resizing, and Header Images Sample

File: ...\Samples\Solution\Toledo\Griders.scx

This sample demonstrates how you can perform the following actions:

  • Select style and colors for grid highlighting.
  • Resize columns automatically to the width of data in the column.
  • Lock the first grid column so that it does not scroll.
  • Specify images in column headers.

Selecting Grid Highlight Styles

You can use highlighting styles to control how highlighting appears and behaves in a grid when you select rows and the focus moves from the grid. To set highlighting styles, use the Grid HighlightStyle property.

In the sample, to set the HighlightStyle, select a style in the combo box on the form. The combo box contains the following code:

ThisForm.grdCustomers.HighlightStyle = VAL(this.Value)

For more information about HighlightStyle, see HighlightStyle Property.

You can also set highlighting colors. For more information, see HighlightBackColor Property, HighlightForeColor Property, SelectedItemBackColor Property, and SelectedItemForeColor Property.

Fitting Columns to Width of Data

This sample resizes grid columns automatically to fit the width of data in the column using the Grid AutoFit method as follows:

ThisForm.grdCustomers.AutoFit()

You can also resize grid columns by double-clicking the upper-left corner of the grid. To resize an individual column automatically, double-click the dividing line on right side of the column. You can control this behavior using the Grid AllowAutoColumnFit property.

For more information, see AutoFit Method and AllowAutoColumnFit Property.

Locking Grid Columns

You can lock columns so the columns remain fixed when the scrolling horizontally across a grid by using the Grid LockColumns property.

In the sample, you can lock the first column in the grid by setting grdCustomers.LockColumns to 1 as in the following code:

ThisForm.grdCustomers.LockColumns = 1

You can also lock the Customer ID column by clicking the column header. The pushpin in the column header indicates whether the column is locked. To lock individual columns, right-click the area between the column headers.

For more information, see LockColumns Property and LockColumnsLeft Property.

Displaying Images in Column Headers

You can specify an image for a column header using the Picture property and set image orientation using the Header Alignment property.

In the sample, an image appears in the Company Name column header to indicate the direction of the sort order in the column. Clicking the column header displays different images to indicate ascending or descending sort order.

For more information, see Picture Property and Alignment Property.

See Also

Solutions Samples | Customizing a Browse Window


Loading and Generating XML Using XMLAdapter Class Sample

File: ...\Samples\Solutions\Toledo\XMLAdapter.scx

You can use the XMLAdapter class to create multiple cursors from XML, such as ADO.NET DataSets, and in reverse, generate XML from multiple cursors.

This sample demonstrates some of the many uses for the XMLAdapter class, such as select an XML file to create cursors or generate XML from multiple tables.

For more information, see XMLAdapter Class.

Loading XML

In this sample, you can load an XML DataSet into an XMLAdapter object by clicking Load XML on the XMLTables tab and selecting a valid XML file, such as one generated from an ADO.NET DataSet or another XMLAdapter object. The Click event of the Load XML button contains the following code that uses the XMLAdapter LoadXML method:

ThisForm.oXMLAdapter.LoadXML(cFilename, .T.)

The name of the file you select is passed as the first parameter to the LoadXML method. The second parameter of LoadXML indicates that the first parameter is a file; otherwise, it assumes that the first parameter is a variable that contains the XML string.

After selecting a file, the XMLAdapter Tables collection fills with as many XMLTable objects as there are tables in the XML DataSet, which you can use to generate cursors.

Adding Tables

In this sample, you can add tables and generate XML by selecting Add Table on the XMLTables tab, selecting a table, and clicking To XML.

When you select Add Table, a list of Northwind tables appears so you can select one or more tables. After opening a table, the table is added to the XMLAdapter object using the AddTableSchema method as follows:

USE ? SHARED IN 0
cTable = LOWER(ALIAS())
ThisForm.oXMLAdapter.AddTableSchema(cTable)

Generating XML

In this sample, you can generate XML after adding tables to the XMLAdapter object and setting any additional properties on XMLAdapter Properties tab.

To generate XML, select To XML on the XMLTables tab, which calls the XMLAdapter ToXML method:

ThisForm.oXMLAdapter.ToXML(XML_FILENAME,, .T., ;
ThisForm.tabXMLAdapter.Page1.chkBefore.Value, ;
ThisForm.tabXMLAdapter.Page1.chkChangesOnly.Value)

In ToXML, leaving the second parameter blank indicates that schema should be generated inline. The third parameter indicates whether the first parameter is the name of a file (True - .T.) or a variable (False - .F.).

See Also

Solutions Samples | XML Functionality Using XMLAdapters


Managing Data Access Using CursorAdapters Sample

File: ...\Samples\Solution\Toledo\CASample.scx

This sample demonstrates how CursorAdapter objects retrieve data from three different data source types:

  • Native

    This sample demonstrates a Native cursor connected to the Visual FoxPro Northwind database.

  • Open Database Connectivity (ODBC)

    This sample demonstrates an ODBC cursor connected to the SQL Server Northwind Database, if installed.

  • ActiveX Data Objects (ADO)

    This sample demonstrates an ADO cursor connected to the SQL Server Northwind Database, if installed.

The cursors are row buffered and use automatic updates, so when you move off the row, any changes to the row are sent to the database.

To view the property settings of the CursorAdapter objects, click the View CursorAdapter Properties button. These property settings were set using the CursorAdapter Builder.

See Also

Solutions Samples | CursorAdapter Class | Data Access Management Using CursorAdapters | CursorAdapter Builder


Member Classes Sample

File: ...\Samples\Solution\Toledo\frmMember.scx

You can specify member classes for the following container classes:

  • PageFrame (Page member class)
  • OptionGroup (OptionButton member class)
  • CommandGroup (CommandButton member class)
  • Grid (Column member class)
  • Column (Header member class)

You can also create subclasses of the Page, OptionButton, CommandButton, Column, and Header classes.

In this sample, you can select a parent container, set the member class library, increase or decrease the member count, and choose to view behavior at design time or run time.

Note Observe the differences in behavior that exist during design time and run time. Changes to MemberClass affect all member classes at design time. Only new members are affected at run time.

This sample uses program (.prg)-based and visual class library (.vcx)-based member classes. For more information, see Member Classes.

Specifying a Member Class and Member Class Library

You can specify the member class and its member class library you want to use for the PageFrame, OptionGroup, CommandGroup, Grid, and Column containers by setting the MemberClass and MemberClassLibrary properties for those objects as shown in the following code:

MemberClassLibrary = "MyClasses.vcx"
MemberClass = "MyClassName"

-or-

MemberClassLibrary = "MyClasses.prg"
MemberClass = "MyClassName"

You must set MemberClassLibrary before setting the MemberClass property.

For more information, see MemberClass Property, and MemberClassLibrary Property.

See Also

Solutions Samples


Passing Strongly Typed Arrays Sample

File: ...\Samples\Solution\Toledo\ComArray.scx

This sample demonstrates how you can pass a strongly typed array by reference to a COM server using the COMARRAY function. The COM server performs calculations and modifies the contents of the array. The client form then uses the DIMENSION command with the AS clause to declare the strongly typed array.

In this sample, the COM server is written in Visual FoxPro. The sample also demonstrates the interface declaration syntax for specifying ByRef type arrays in the generated COM type library.

When opening the sample, you are prompted to register a COM server. The COM server is removed from the registry when you close the sample.

To pass a matrix as a strongly typed array to a COM server

  • In the sample, type values into the matrix and click Determinant.

The COM server calculates the determinant of the matrix using Gauss-Jordan Reduction.

For more information, see COMARRAY( ) Function and DIMENSION Command.

Passing Strongly Typed Arrays

In the sample, the form uses DIMENSION...AS to declare a strongly typed array as show in the custom CallCOMServer method:

DIMENSION laMatrix(ThisForm.Matrixdim, ThisForm.Matrixdim) AS Double

The array is passed by reference to the Visual FoxPro COM server using the COMARRAY( ) function:

* Instantiate COM server.
loMatrixCalc = CREATEOBJECT("VFPCOMArray.COMARRAYDemo")
* Array is one based and is passed by reference.
COMARRAY(loMatrixCalc,11)
* Pass array to COM server by reference "As Double".
lnResult = loMatrixCalc.Determinant(@laMatrix)

Passing COM Parameters By Reference

In the sample, the custom RegisterCOMServer method contains code that compiles a Visual FoxPro COM server on the fly and registers it. The COM server code illustrates the interface declaration syntax for specifying ByRef typed arrays in the generated COM type library as follows:

FUNCTION Determinant(mat[] AS Double @) AS Double

The array is correctly written to the type library as a strongly typed array. The at sign (@) indicates that the array is passed ByRef in the type library.

See Also

Solutions Samples


SCATTER NAME...ADDITIVE Sample

File: ...\Samples\Solution\Toledo\ScatterName.scx

This sample demonstrates how to update and saves some form properties from and to a table using the SCATTER command with the NAME and ADDITIVE clauses and the GATHER command with the NAME clause.

In this sample, you can update an existing object with values from the current record using the ADDITIVE clause with SCATTER NAME. You can then change the color, resize, move, or minimize the form, and close it. When you run the form again, it appears with the color, size, location, and previous state from when it was closed.

For more information, see GATHER Command and SCATTER Command.

Setting Form Properties from a Table Using SCATTER...NAME... ADDITIVE

In this sample, the following code in the form's Init event opens a table and sets the form's properties from matching fields in the table as shown:

USE (ThisForm.cRunPath+"FormProps")
SCATTER NAME ThisForm ADDITIVE
USE IN FormProps

The ADDITIVE keyword makes it possible to update and add object properties.

Saving Form Properties to a Table Using GATHER NAME

In this sample, when the form closes, the property values are saved in the matching fields of the table, which occurs in the form's Destroy event.

USE (ThisForm.cRunPath+"FormProps")
GATHER NAME ThisForm
USE IN FormProps
Note This table is created in a database so that the lengths of the fields can be longer than 10 characters.

See Also

Solutions Samples


Structured Exception Handling Sample

File: ...\Samples\Solution\Toledo\TryCatch.scx

You can implement structured exception handling using the TRY...CATCH...FINALLY error handling structure to run a particular block of statements if a specified exception occurs when your program runs. When an error, or exception, occurs, an Exception object is created.

This sample demonstrates how to catch exceptions using the TRY and CATCH blocks, clean up resources using the FINALLY block, and throwing, or escalating, exceptions using a THROW statement.

For more information, see Structured Error Handling, TRY...CATCH...FINALLY Command and Exception Object.

Catching Exceptions

In this sample, you can choose an error, or exception, you want to cause in the TRY block and view the properties for the Exception object generated from the exception.

To raise an exception

  • In the CATCHing Exceptions tab, select the error you want from the drop-down list and click Execute TRY block.

The CATCH block runs and displays the Exception object properties.

The following code shows the error handling structure in this particular sample. Usually, code that might generate an exception appears in the TRY block; however, the ERROR command is called specifically to show how the flow of control is passed to the CATCH block only when an exception occurs.

You can use the Exception UserValue property to store any additional information about the error.

TRY
   ERROR nErrorCode
CATCH TO myException
   myException.UserValue = "I can handle this."
ENDTRY

Cleaning Up Resources

The FINALLY block usually cleans up any resources allocated by the TRY block and is always the last code to run before control leaves the TRY...CATCH...FINALLY structure.

To observe how FINALLY executes after all other code

  • In the Using FINALLY tab, select an option or type a table name and path in the combo box and click TRY.

The following code demonstrates how FINALLY executes after all other code.

TRY
   lnPrevArea = SELECT()
   USE CUSTOMERS IN 0 EXCLUSIVE
* Handle when file does not exist.
CATCH TO myException WHEN myException.ErrorNo = 1
* Handle when file is in use.
CATCH TO myException WHEN myException.ErrorNo = 3
* Handle when file access is denied.
CATCH TO myException WHEN myException.ErrorNo = 1704
* Catch everything else.
CATCH TO myException

* Code in FINALLY block always executes.
FINALLY
IF USED('CUSTOMERS')
      USE IN CUSTOMERS
   ENDIF
   SELECT (lnPrevArea)
ENDTRY

Throwing Exceptions

To escalate an exception to a higher-level error handler, use a THROW statement in a CATCH block.

This sample uses nested TRY blocks. The inner TRY block can handle only the first error. For subsequent errors, the inner TRY block escalates the Exception object to the outer TRY block. When a specific exception is thrown, specifically THROW oMyException in this example, the UserValue property of the caught exception in the outer block contains the thrown exception from the inner block.

TRY
   * Run some code.
   TRY
      * Error occurs.
      ERROR 3
      CATCH TO InnerException WHEN InnerException.ErrorNo = 1
      InnerException.UserValue = "INNER TRY: I can handle this."
      CATCH TO InnerException
      InnerException.UserValue = "INNER TRY: I can't handle this."
      * Error cannot be handled so escalate to outer TRY block.
      THROW InnerException
   ENDTRY
CATCH TO OuterException
* In this case, when the exception is escalated, the caught exception's
* UserValue property contains the escalated exception from inner TRY.
? OuterException.UserValue.UserValue
ENDTRY

You can also throw a string message. In this case, the string message is stored in the UserValue property of the outer exception:

TRY
   * Run some code.
   TRY
      * Error occurs.
        ERROR 1
   CATCH
      THROW "INNER TRY: I can't handle this one."
   ENDTRY
CATCH TO OuterException
   ? OuterException.UserValue
ENDTRY

See Also

Solutions Samples


System Tray Icon Sample

File: ...\Samples\Solution\Toledo\SysTray_Sample.scx
Library: ...\ Samples\Solution\Toledo\SysTray.vcx
ReadMe: ...\Samples\Solution\Toledo\SysTray_ReadMe.htm

This sample demonstrates some common uses of the Systray class. This class supports using icons in the Taskbar Notification Area, which is commonly known as the System Tray. The Systray class also supports mouse events, balloon tips, and Visual FoxPro shortcut menus for your System Tray icon so you can use all the features of the Visual FoxPro Menu Designer.

For detailed information about the properties, events, and methods of the Systray class library included with the sample, see SysTray_ReadMe.htm.

See Also

Solutions Samples | Menu and Shortcut Designers


Windows XP Themes Support Sample

File: ...\Samples\Solution\Toledo\Themes.scx

This sample demonstrates different levels of Visual FoxPro support for Windows XP Themes. Themes are turned on by default.

Visual FoxPro supports Windows XP themes at three levels:

  • Application level using SYS(2700) - Enables Windows XP Themes and _SCREEN Themes property
  • Form level using the Form Themes property
  • Control level

Themes Support at the Application Level

In this sample, you can turn Themes on in the entire Visual FoxPro application using the SYS(2700) - Enables Windows XP Themes function by selecting Enable Themes at the application level - SYS(2700), which uses the following code:

SYS(2700,1)

To turn Themes off, pass a zero (0) as the second parameter to SYS(2700).

SYS(2700,0)

To turn Themes on using the _SCREEN variable, select Enable Themes at the application level - _SCREEN.Themes, which sets _SCREEN Themes to True (.T.):

_SCREEN.Themes = .T.

To turn Themes off using _SCREEN, set _SCREEN Themes to False (.F.):

_SCREEN.Themes = .F.

For more information, see SYS(2700) - Enables Windows XP Themes and Themes Property.

Themes Support at the Form Level

In this sample, to turn Themes on at the form level, select Enable Themes at the form level, which sets the form's Themes property to True (.T.):

ThisForm.Themes = .T.

Themes Support at the Control Level

You can also turn on Themes support for individual controls. Turning Themes off at the control level overrides the Themes setting at the application or form level. Depending on the control, you can set Themes support through the Themes or Style properties.

For more information, see Style Property.

See Also

Solutions Samples


Add and Remove Items in a Treeview Control Sample

File: ...\Samples\Solution\OLE\Bldtree.scx

A treeview control displays a collection of Node objects, each of which consists of a label and an optional bitmap. After creating a treeview control, you can add, remove, arrange, and otherwise manipulate Node objects by setting properties and invoking methods.

This sample illustrates adding nodes to a treeview control, deleting nodes, selecting nodes programmatically, writing a treeview hierarchy to a table, and reading a treeview hierarchy from a table.

Adding Nodes

Each node in a treeview control needs to have a unique key that is a character string, generated by the NewKey method in this sample form.

*NewKey method
cKey = THIS.cNextKey
THIS.cNextKey = ALLTRIM(STR(VAL(THIS.cNextKey) + 1) + "_")
RETURN cKey

The Add method of the treeview control is used to add new nodes. The code associated with the Click event of cmdNewNode adds a root level node using the Add method.

o = THISFORM.oleTree
o.Nodes.Add(,1,THISFORM.NewKey(),"Click to edit text",0)

The code associated with the Click event of cmdNewChild adds a node as a child of the currently selected node.

o = THISFORM.oleTree
IF !ISNULL(o.SelectedItem) THEN
   o.Nodes.Add(o.SelectedItem.Key, 4, THISFORM.NewKey(), "Click to edit text",0)
ENDIF

Deleting Nodes

You can delete all of the nodes by calling the Clear method.

THISFORM.oleTree.Nodes.Clear

Or you can use the Remove method to delete selected nodes. All children of the deleted node are also deleted.

THISFORM.oleTree.Nodes.Remove(THISFORM.oleTree.SelectedItem.Key)

Writing and Reading Hierarchies in Tables

To save your treeview hierarchy in a table so you can reload it and edit it, loop through all the nodes in the treeview control and write the Key, the parent node's Key, and the Text to the appropriate fields of a table.

FOR i = 1 TO loNodes.Count
   IF ISNULL(loNodes.Item(i).Parent)
      lcParent = "0_" && Root
   ELSE
      lcParent = loNodes.Item(i).Parent.Key
   ENDIF
   INSERT INTO (lcDBFName) VALUES ;
      (loNodes.Item(i).Key, ;
       lcParent, ;
       loNodes.Item(i).Text)
ENDFOR

To reconstruct the treeview hierarchy, scan through the records in the table, using the parent key, key, and text values that you previously stored.

* Fill the TreeView control with values in the table.
o = THISFORM.oleTree.Nodes
   SCAN
      IF ALLTRIM(parent) = '0_'
         o.add(,1,ALLTRIM(key),ALLTRIM(text),0)
      ELSE
         o.add(ALLTRIM(parent),4,ALLTRIM(key), ALLTRIM(text),0)
      ENDIF
      THISFORM.cNextKey = ALLTRIM(STR(VAL(key) + 1) + "_")
   ENDSCAN

See Also

Treeview/Listbox Drag and Drop | Solutions Samples


Customize the Open Dialog Box Sample

File: ...\Samples\Solution\OLE\Commdlog.scx

This sample demonstrates how you can customize the appearance and behavior of the Open dialog box as exposed through the Common Dialog control.

To specify the behavior of the Open dialog box, you can set the Flags property of the Common Dialog control to the sum of specific flag values. The following table lists the possible individual values you can use.

Value | Description
1 | Causes the read-only check box to be initially checked when the dialog box is created. This flag also indicates the state of the read-only check box when the dialog box is closed.
2 | Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.
4 | Hides the read-only check box.
8 | Forces the dialog box to set the current directory to what it was when the dialog box was opened.
16 | Causes the dialog box to display the Help button.
256 | Specifies that the common dialog box makes it possible for invalid characters in the returned file name.
512 | Specifies that the File Name list box makes it possible for multiple selections. The user can select more than one file at run time by pressing the SHIFT key and using the UP ARROW and DOWN ARROW keys to select the desired files. When this is done, the File Name property returns a string containing the names of all selected files. The names in the string are delimited by spaces.
1024 | Indicates that the extension of the returned file name is different from the extension specified by the DefaultExt property. This flag isn't set if the DefaultExt property is Null, if the extensions match, or if the file has no extension. This flag value can be checked upon closing the dialog box.
2048 | Specifies that the user can enter only valid paths. If this flag is set and the user enters an invalid path, a warning message is displayed.
4096 | Specifies that the user can enter only names of existing files in the File Name text box. If this flag is set and the user enters an invalid file name, a warning is displayed. This flag automatically sets the 2048 flag.
8192 | Specifies that the dialog box prompts the user to create a file that doesn't currently exist. This flag automatically sets the 4096 and 2048 flags.
16384 | Specifies that sharing violation errors will be ignored.
32768 | Specifies using the Windows Explorer Open A File dialog box template.
524288 | Use the Explorer Open A File dialog box template.
1048576 | Do not dereference shell links (also known as shortcuts). By default, choosing a shell link causes it to be dereferenced by the shell.
1048576 | Do not dereference shortcuts (shell links). By default, choosing a shortcut causes it to be dereferenced by the shell.
2097152 | Makes it possible for the user to use long file names.

The following code in the Click event of cmdFiles checks the values of the various check boxes on the form and sets the Flags property of the Common Dialog control.

Set the Read-only Check Box Flag

IF !thisform.chkRead.Value
   m.nFlags = m.nFlags + 4
ENDIF

Set the Multiple Files Flag

IF thisform.chkMulti.Value
   m.nFlags = m.nFlags + 512
ENDIF

Set the Help Button Flag

IF thisform.chkHelp.Value
   m.nFlags = m.nFlags + 16
ENDIF

Set the Enforce File Existence Flag

IF thisform.chkMulti.Value
   m.nFlags = m.nFlags + 4096
ENDIF

Set the Flags Property of the Common Dialog Control

THISFORM.oleCommDlog.Flags = m.nFlags

Set the Filter Property of the Common Dialog Control

You can use the Filter property of the Common Dialog control to specify what files a user is allowed to choose.

THISFORM.oleCommDlog.Filter = "All files" + ;
   "(*.*)|*.*|Text (*.txt)|*.txt" + ;
   "|Pictures(*.bmp;*.ico)|*.bmp;*.ico"

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display System Information Sample

File: ...\Samples\Solution\OLE\Sysinfo.scx

This sample illustrates using the SysInfoControl to display system information and to notify when a system setting changes.

The bulk of the code in this sample is in the CheckStatus method. Code in this method checks the settings of various SysInfoControl properties to see their current settings, and populates a treeview control with this information. For example, the following section of code checks the BatteryLifePercent setting:

IF ThisForm.SysInfo.BatteryLifePercent = 255
   * Add a node to display the information
ENDIF

When a system setting changes, an event of the SysInfoControl occurs. Code associated with each of these events sets the caption of a label and calls the CheckStatus method to refresh the treeview control. For example, the following code is associated with the SysColorsChanged event:

ThisForm.Status.Caption = SysColorsChanged_LOC
ThisForm.CheckStatus

See Also

Add and Remove Items in a Treeview Control | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Play an AVI File in an ActiveX Control Sample

File: ...\Samples\Solution\OLE\Mmsample.scx

This sample shows how to use the Multimedia control to play an AVI file in a control that has an hWnd property.

The control with the hWnd is a custom ActiveX Control called hWin, created with the OLE Control Wizard in Microsoft Visual C++ 4.0. In creating the hWin .ocx, all the default options in the OLE Control wizard were chosen, all the default properties were added to the control, and the code was compiled.

In the Init of the form, the following line of code directs the Multimedia control to play the AVI in the form:

ThisForm.VCR.hWndDisplay = ThisForm.Test.hWnd

See Also

Video Player | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Provide a Hierarchical Display of Items Sample

File: ...\Samples\Solution\OLE\Outline.scx

This sample shows two different types of ActiveX controls, which you can use for outlining. In this sample, a directory structure is displayed. A custom method on the form named FillTree is called recursively to iterate through the entire tree structure.

The Treeview control also allows display of images with each node.

Treeview Control

The Treeview control can give your applications a truly genuine Windows look. Unlike the Outline control, which uses methods and item indexes, the Treeview control uses a Nodes collection.

Note To display images in a treeview control, you must add an ImageList control to the form.
* Add items to treeview control
o = THIS.PageFrame1.Page2.oleTreeview
IF cnt = 1
   oNode = o.nodes.add(,1,LOWER(m.path)+"_",LOWER(m.path),,)
   oNode.Image = "world"   &&name of image
ELSE
   oNode = o.nodes.add(m.pkey,4,LOWER(m.path)+"_",LOWER(m.path),,)
   oNode.Image = "fldr"   &&name of image
ENDIF

See Also

Treeview/Listbox Drag and Drop | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Send Mail Sample

File: ...\Samples\Solution\OLE\Sendmail.scx

This sample illustrates using the mailbtn class in ...\Samples\Classes\Buttons.vcx to create a simple messaging form that can send Visual FoxPro data to an e-mail address.

Mailbtn is a container class that contains a command button and two ActiveX controls: MAPI Session and MAPI Messages, both of which are defined in Msmapi32.ocx. The MAPI Session control establishes a MAPI session, and the MAPI Messages control makes it possible for the user to perform a variety of messaging system functions.

The mailbtn class starts a new Mail session, collects data from the current record, and brings up the Send Mail dialog with the data inserted as the message text.

This class includes two custom methods AddTabs and StripPath for formatting the information gathered from the table and inserted in the mail message.

This class also takes advantage of another custom method called Signon as well as a custom property called logsession, which is set to .F. initially.

When the user clicks the cmdMail button, the following code in the Click event calls the signon method, setting logsession to true (.T.).:

this.logsession = .T.
this.OLEMSess.signon

If there is a failure on signon, the Error event of the class is called and logsession is set to .F.

The MAPI controls are invisible at run time. In addition, there are no events for the controls. To use them, you must specify the appropriate methods. For these controls to work, MAPI services must be present. MAPI services are provided in Microsoft Outlook and Exchange electronic mail systems for Microsoft Windows 95 or later.

See Also

SendMail Buttons | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Use Slider and Status Bar Controls Sample

File: ...\Samples\Solution\OLE\Slider.scx

This sample illustrates using the Slider control and the StatusBar control.

Slider Controls

Code in the Scroll event of each slider control sets the Value property of the other controls.

#DEFINE TXT_LOC "slider value: "
THISFORM.Olecontrol2.Panels(2).Text = TXT_LOC + ALLTRIM(STR(THIS.value))
THIS.Parent.spn1.Value = THIS.Value
THIS.Parent.oleV.Value = THIS.Value

StatusBar Control

The StatusBar Control Properties dialog box makes setting status bar properties easy.

To open the StatusBar Control Properties dialog, choose StatusBar Control Properties from the shortcut menu of a StatusBar Control.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Use the RichText Control Sample

File: ...\Samples\Solution\OLE\Rtf.scx

This sample illustrates using a RichText control to display and edit RTF text stored in the memo field of a table.

You can set the ControlSource of a RichText control directly to a character field, but not a memo field. Instead, create a form property to mediate between the RichText control and the memo field.

To store RTF text in a memo field

  1. Set the ControlSource property of the RichText control to the form property.
    THISFORM.oleRTF.ControlSource = THISFORM.cText
  2. Store the memo field contents to the form property.
    THISFORM.cText = rtf.source
  3. Before moving the record pointer, store the TextRTF property of the RichText control to the memo field.
    REPLACE rtf.Source WITH THISFORM.oleRTF.TextRTF

The text stored in the memo file is standard RTF format, for example:

{\rtf1\ansi\deff0\deftab720{\fonttbl{\f0\fswiss MS Sans Serif;}{\f1\froman\fcharset2 Symbol;}{\f2\fswiss Arial;}{\f3\fswiss Arial;}} {\colortbl\red0\green0\blue0;\red255\green0\blue0;} \deflang1033\pard\qc\plain\f3\fs32\i The RichTextBox Control \par \pard\plain\f3\fs20

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Automate a Microsoft Excel Spreadsheet Sample

File: ...\Samples\Solution\OLE\Olexl.scx

This form shows two samples of Visual FoxPro calling an Excel worksheet through automation.

The Trend button performs a query followed by a cross-tab to create a dataset to pass to Excel through automation using the Excel.Sheet object. Once in Excel, Visual FoxPro can call a Trend function to perform a simple regression analysis.

The Chart button automates the Excel.Chart object to create a chart. Excel supports passing data through automation, but MS Graph does not. However, you can distribute MS Graph with your applications.

See Also

Automate a Microsoft Word Document in a Form | Automate Microsoft Word and Excel | Solutions Samples


Automate a Microsoft Word Document in a Form Sample

File: ...\Samples\Solution\OLE\Oleword.scx

This sample shows how you can automate an embedded Word object on a form, insert some rich text, and then format the text. Typical automation with Word is usually done using the "Word.Basic" object used interactively with a CREATEOBJECT( ) function.

oForm = THISFORM
oForm.AddObject('oWordDoc','OleControl','WordDocument')
oForm.oWordDoc.Visible =  .t.
oForm.oWordDoc.DoVerb(0)

See Also

Automate a Microsoft Excel Spreadsheet | Automate Microsoft Word and Excel | Solutions Samples


Automate Microsoft Word and Excel Sample

File: ...\Samples\Solution\OLE\Oleaut1.scx

This is a simple sample showing Visual FoxPro as an Automation controller. It demonstrates how to select data from a Visual FoxPro database, place the data in a Microsoft Excel worksheet, graph the data using Chart, and then display the graph in Word. To use this sample, you need at least Excel 5.0, Word 6.0, and Testdata.dbc, located in the ...\Samples\Data directory.

The following line of code creates a reference to a Microsoft Excel spreadsheet.

objXLsheet=createobject("Excel.Sheet")

The following line of code adds a chart to the spreadsheet.

objChart1 = objXLsheet.ChartObjects.Add(100, 100, 200, 200)

The following line of code creates a reference to Microsoft Word.

objWDdoc=createobject("word.basic")

oWordRef = GetObject('','word.basic')

See Also

Automate a Microsoft Word Document in a Form | Automate a Microsoft Excel Spreadsheet | Solutions Samples


Manipulate Display Characteristics of a Graph Sample

File: ...\Samples\Solution\OLE\Olegraph.scx

This sample shows how to incorporate MS Graph into your applications. MS Graph 5.0 is an Automation server that Visual FoxPro can automate using the standard CREATEOBJECT( ) function. With Visual FoxPro, Graph objects can be embedded in either bound or unbound OLE Controls. An OleBoundControl (bound to a General field) is the only way to programmatically insert data into a graph.

MS Graph's automation support provides access only to a graph object, not its datasheet. Data can be inserted into a Graph only with the APPEND GENERAL command on a General field. The following code uses the HasLegend property and is an example of automation:

cGData = ""+TAB+"Cats"+TAB+"Dogs"+CRLF+;
      "1994"+TAB+"11"+TAB+"22"+CRLF+;
      "1995"+TAB+"33"+TAB+"44"+CRLF+;
      "1996"+TAB+"55"+TAB+"55"+CRLF
APPEND GENERAL gen1 CLASS "msgraph.chart" DATA m.cGData
THIS.OleBoundControl1.ControlSource = "Gen1"
THIS.OleBoundControl1.HasLegend = .F.

The APPEND GENERAL command in this case creates a new chart object. If you do not include the CLASS "msgraph.chart" clause, then the chart is merely updated. The CLASS clause will create a new chart and override any existing formatting.

See Also

Graph Object | Provide a Hierarchical Display of Items | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Refresh a Graph in a Form Sample

File: ...\Samples\Solution\OLE\Stock.scx

This sample illustrates selecting data from a table and passing it to MS Graph to refresh the values in a chart. Most of the code to do this is associated with the InteractiveChange event of the cboMonth combo box.

Select the data into a cursor

SELECT date, close;
  FROM Stock1 WHERE MONTH(date) = THIS.Value ;
  ORDER BY date INTO CURSOR wtemp

Create a character string containing the selected data

SELECT wtemp

lcData = " " + TAB + "Closing Price" + CRLF

SCAN
 lcData = lcData + DTOC(date)
 lcData = lcData + TAB
 lcData = lcData + ALLTRIM(STR(close)) + CRLF
ENDSCAN

Send the character string to MS Graph

SELECT Graph
APPEND GENERAL msgraph DATA lcData

See Also

Manipulate Display Characteristics of a Graph | Graph Object | Solutions Sample Overview | Visual FoxPro Foundation Classes A-Z


Allow Users to Drag and Drop Controls Sample

File: ...\Samples\Solution\Forms\Ddrop.scx

This sample explains how to implement drag and drop operations. One page on the form illustrates manual dragging of controls by calling the Drag method. Explicitly calling the Drag method makes it possible for you to process other code in the Click event of the control. The other page illustrates using the Automatic DragMode setting so that the Drag and Drop operation is started automatically when the user presses the mouse button over the controls.

Repositioning the Command Button

In the MouseMove event of cmdDrop, if the left mouse button is down, find out how far the mouse pointer is from the top and the left of the command button and begin the drag operation.

LPARAMETERS nButton, nShift, nXCoord, nYCoord
IF nButton = 1 && Left button
   THISFORM.XOffset = nXCoord – THIS.Left
   THISFORM.YOffset = nYCoord - THIS.Top
   THIS.Drag
ENDIF

In the DragDrop event of the page that the command button is on, reposition the command button.

oSource.Left = nXCoord - THISFORM.XOffset
oSource.Top = nYCoord - THISFORM.Yoffset

Changing the Color of the Shape

The DragMode property of the colored squares on the Change Colors page of the form is set to 1 –Automatic. As soon as the user presses the mouse button on the squares, the drag operation begins. Any code added to the Click event of the squares would never be executed.

Code in the DragDrop event of the circle changes its BackColor property to match that of the drag source.

LPARAMETERS oSource, nXCoord, nYCoord
THIS.BackColor = oSource.BackColor

See Also

Allow Users to Choose List Values | Solutions Samples | OLE Drag-and-Drop Data Formats


Hot Tracking and Hover Effects Sample

File: ...\Samples\Solution\Sedona\Dvds.scx

This sample shows several new events and properties that make it possible for you to add special effects such as hot tracking to your controls on forms.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Resize and Reposition Controls at Run Time Sample

File: ...\Samples\Solution\Forms\Cresize.scx

A user can resize this sample form as desired. The controls on the form are resized or repositioned relative to the new Height and Width properties of the form.

This form uses the resizable class in ...\Samples\Classes\Samples.vcx to manage resizing and repositioning of the controls. The following line of code is added to the Resize event of the form, calling the AdjustControls method of the resizable class:

THIS.Resizable2.AdjustControls

In the Init of the resizable class, code loops through all the controls in the form, storing their positions and sizes relative to the form in an array. When the form is resized, the AdjustControls method resizes and repositions the controls to their relative sizes and positions.

You can add more controls to the form and the new controls will also be resized and repositioned.

The RepositionList and ResizeList properties contain a space-delimited list of all the classes that you want to reposition and resize. If you do not want a certain class to be resized, remove it from the ResizeList.

You can prevent a user from making the form too small for the objects contained on it by setting the form's MinHeight and MinWidth properties.

See Also

Resize Object | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Using Check Boxes to Specify States

You can use check boxes to make it possible for a user to specify a Boolean state: True or False, On or Off, Open or Closed. However, there are times when it is not accurate to evaluate something as True or False, such as unanswered questions on a True/False questionnaire.

To see examples of using check boxes

  1. Run Solution.app in the Visual FoxPro ...\Samples\Solution directory.
  2. In the tree view, click Controls, and then click Check boxes.

See Also

Adding Pictures to Items in a List | Accepting Input That Cannot Be Predetermined | CheckBox Control | Using the InputMask Property | Using Controls | Controls and Objects


See Check Box Design Options Sample

File: ...\Samples\Solution\Controls\Checkbox\Checkbox.scx

This sample illustrates a variety of properties that can be set to customize check box display.

Property | Description
ControlSource | A variable or table field that is numeric or logical.
Picture | Bitmap displayed if Style is Graphical.
Style | Graphical for pictures or standard for a box.
Value | .T., .F., 0, 1, 2, or .NULL.

See Also

Distinct Values Combo | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Add New Items to a Combo Box Sample

File: ...\Samples\Solution\Controls\Combobox\Lookup.scx

This sample illustrates adding user-entered text to a combo box drop-down and providing lookup capability.

Adding User Text to a Combo Box Drop-Down

A combo box makes it possible for a user to enter text or select an item from a drop-down list. You can also add the text a user types in the combo box as a new item in the drop-down list so the user won't have to type the same text multiple times.

There are multiple ways to add user text to the drop-down list of a combo box, depending on the RowSourceType property setting of the combo box. In this sample, the RowSourceType of the combo boxes is 1 - Value. If the value the user enters isn't already in the drop-down list for cboCombo, the following code adds a comma and the new value to the RowSource:

cCountryName = ALLTRIM(Custs.Country)
IF ATC(m.cCountryName,THIS.RowSource)=0 AND !EMPTY(m.cCountryName)
   THIS.RowSource=THIS.RowSource+","+m.cCountryName
ENDIF

The combo box in the Programmatically Manipulate Text example has a RowSourceType of 0 - None. The following code in the Valid event of cboSearchString in ...\Samples\Solution\Controls\TXT_EDT\Text.scx adds a user-entered value to the drop-down list of the combo box:

IF !EMPTY(THIS.Text)
   FOR i = 1 TO THIS.ListCount
      IF THIS.List(i) = THIS.Text
         RETURN
      ENDIF
   ENDFOR
   THIS.AddItem(THIS.Text)
ENDIF

If the RowSource of the combo box is an array, you need to add the user text to the array and call the Requery method of the combo box.

If the RowSource is a table or a cursor, you need to add a record, REPLACE the blank field with the user-entered value and Requery the combo box.

Provide Lookup Capability

In addition to illustrating how to add items to a combo box, this sample demonstrates three ways of making it possible for a user to filter a table for particular values. A user can do the following:

  • Enter values in a combo box.
  • Select an item from a drop-down list.
  • Enter partial values in a combo box for incremental search.

Enter Values in a Combo Box

The key code is associated with the LostFocus event of cboCombo. After making sure that the user has entered a value, the LostFocus code selects the records that match the user's text and sets the RecordSource property of the grid to the result set.

cDisplayValue = ALLTRIM(THIS.DisplayValue)

IF THIS.Value = "(All)"
   SELECT country AS location,* FROM CUSTOMER;
      INTO CURSOR Custs
   thisform.grdcust.recordsource = "Custs"
ELSE
   SELECT country AS location,* FROM CUSTOMER ;
    WHERE UPPER(ALLTRIM(Customer.Country)) = UPPER(m.cDisplayValue);
    INTO CURSOR Custs
   THISFORM.grdCust.RecordSource = "Custs"
ENDIF

Select an Item from a Drop-down List

Basically the same lookup code is associated with the InteractiveChange event of cboDrop – if the Value of the combo box is "(All)", select all records into the cursor, otherwise, select the records that match the user's choice.

Enter Partial Values for Incremental Search

Code in the InteractiveChange event of cboIntSearch performs the lookup every time the user types a character in the combo box.

#DEFINE DELKEY 127
LPARAMETERS nKeyCode, nShiftAltCtrl
LOCAL cDisplayValue
IF nKeyCode = DELKEY
   cDisplayValue = ALLTRIM(THIS.DisplayValue)
   IF LEN(m.cDisplayValue)=1
      cDisplayValue = ""
   ELSE
      cDisplayValue = LEFT(cDisplayValue,LEN(cDisplayValue)-1)
   ENDIF
ELSE
   cDisplayValue = ALLTRIM(THIS.DisplayValue)+CHR(nKeyCode)
ENDIF

THISFORM.LockScreen = .T.
DO CASE
CASE EMPTY(m.cDisplayValue)
   THISFORM.grdCust.RecordSource = " "
CASE THIS.Value = "(All)"
   SELECT country AS location,* FROM CUSTOMER;
      INTO CURSOR Custs
   THISFORM.grdCust.RecordSource = "Custs"
OTHERWISE
   SELECT country AS location,* FROM CUSTOMER ;
    WHERE UPPER(ALLTRIM(Customer.Country)) = UPPER(m.cDisplayValue);
    INTO CURSOR Custs
   THISFORM.grdCust.RecordSource = "Custs"
ENDCASE
THISFORM.ResetCombos(THIS)
THISFORM.LockScreen = .F.

See Also

Add Data Lookup Combo Boxes | Programmatically Manipulate Text | Solutions Samples


Allow Users to Choose List Values Sample

File: ...\Samples\Solution\Forms\Datalook.scx

This sample illustrates providing users with a set of values, selected from another table, in a list box and in a drop-down list box. The value the user chooses is stored in the current table.

It is often more convenient for a user to choose from a list of predetermined values, and, of course, you minimize the risk that the user will mistype a value. Setting a few list box properties is all that is required to provide this capability. For example, the following properties were set for cboEmp_id on the Using Combo Box page:

Property | Setting
BoundColumn | 2
ColumnCount | 2
ControlSource | orders.emp_id
RowSource | SELECT DISTINCT ALLTRIM( employee.first_name) + " " + ALLTRIM( employee.last_name) , EMP_ID FROM employee INTO CURSOR cEmpCombo ORDER BY first_name
RowSourceType | 3 – SQL Statement

Rather than having the user choose an employee id number from the drop-down list, the SELECT statement makes it possible for you to show the user the employees' first and last names.

Because the SELECT statement creates a cursor, code in the Destroy event closes the cursor.

IF USED("cEmpCombo") THEN
   USE IN cEmpCombo
ENDIF

See Also

Allow Users to Drag and Drop Controls | Solutions Samples


See Command Button Design Options Sample

File: ...\Samples\Solution\Controls\Buttons\Cmdbtn.scx

This sample illustrates a variety of properties that can be set to customize command button display.

Property | Description
Cancel | The Click event code of the command button with Cancel set to true (.T.) is executed when a user presses ESC.
Default | The Click event code of the command button with Default set to true (.T.) is executed when a user presses ENTER.
Picture | Bitmap displayed if Style is Graphical.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Edit a Memo Field or Text File Sample

File: ...\Samples\Solution\Controls\TXT_EDT\Editbox.scx

This sample enables you to view and edit text from a memo field or a text file in an edit box.

Displaying text from a memo field is as easy as setting the ControlSource of the edit box to the memo field.

There are two ways you can edit a text file in an edit box: using low-level file functions and creating a cursor to hold the text. This sample creates a cursor instead of using low-level file functions.

Editing a Text file with Low-Level File Functions.

You can open a file using FOPEN( ), read the contents of the file using FREAD( ), and store the contents to a memory variable or to the Value property of the edit box. You can then write changes to the file using FWRITE( ) and close the file using FCLOSE( ).

Editing a Text File by Loading it into a Cursor Field

The advantage to creating a cursor for a text file, other than the fact that the code is a little simpler, is that Visual FoxPro manages writing large amounts of text in a cursor to temporary files if there isn't enough memory.

IF SELECT("textfile") = 0
   CREATE CURSOR textfile (filename c(60),mem m)
   APPEND BLANK
ENDIF
REPLACE textfile.FileName WITH GETFILE("TXT")
IF EMPTY(textfile.FileName)
   RETURN
ENDIF

SELECT textfile
APPEND MEMO mem FROM (textfile.FileName) OVERWRITE
THIS.Parent.edtText.ControlSource = "textfile.mem"
THIS.Parent.cmdSave.Enabled = .T.
THIS.Parent.lblFileName.Caption = ALLTRIM(textfile.FileName)
THIS.Parent.Refresh

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Programmatically Manipulate Text Sample

File: ...\Samples\Solution\Controls\TXT_EDT\Text.scx

This sample illustrates using the SelStart, SelLength, and SelText properties of an edit box to manipulate the text at run time. The sample also counts the characters, words, and paragraphs in a text file and makes it possible for a user to search for a string in a text file.

Formatting Text

The following code is included in the Click event of the button that formats selected text to uppercase:

lo = THIS.Parent.edtText
lnOldStart = lo.SelStart
lnOldLength = lo.SelLength

lo.SelText = UPPER(lo.SelText)

lo.SelStart = lnOldStart
lo.SelLength = lnOldLength

If you want to specify the font attributes of selected sections of text, use a RichText control.

Searching for Text

After getting the text to search for, the following code loops through all the text in the edit box, comparing it to the target string:

llKeepLooking = .T.
DO WHILE llKeepLooking
  FOR i = lnStart TO LEN(loEDT.Value)
    loEDT.SelStart = i
     loEDT.SelLength = lnLen
    IF loEDT.SelText = ALLTRIM(loCBO.Text) OR ;
         (!llCaseSensitive AND ;
         (UPPER(loEDT.SelText) = UPPER(ALLTRIM(loCBO.Text))))
      llFound = .T.
      llKeepLooking = .F.
      EXIT
    ENDIF
  ENDFOR

  IF !llFound
    lnChoice=MESSAGEBOX("Search string not found.", ;
        64+0+4)
    IF lnChoice = 6 && Yes
      llKeepLooking = .T.
      lnStart = 0
    ELSE
      llKeepLooking = .F.
    ENDIF
  ENDIF
ENDDO
Tip Be sure to set the form's LockScreen property to true (.T.) before searching and false (.F.) after searching. Otherwise, the form will repaint every time the SelStart property of the edit box is changed.

See Also

Programmatically Manipulate Objects | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Calculated Values in a Column Sample

File: ...\Samples\Solution\Controls\Grid\Calc.scx

This sample illustrates how to display a calculated value in a column.

Set the ControlSource property of the column to an expression with a calculation. For example, the following expression for the ControlSource of the Profit column displays the difference between the price and cost.

Products.Unit_Price - Products.Unit_Cost

When you change one or more values in the expression, the value in the column is automatically updated.

Note Columns that display an expression containing a calculation are read-only.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Child Records from a Relationship Sample

File: ...\Samples\Solution\Controls\Grid\1_many.scx

This sample demonstrates coordinating a one-to-many form with two grids displaying the many sides of the relationships. Very little code is needed in this sample. Setting a few properties is all that is involved.

Property Settings

Text boxes for the "one" side of the relationship:

ControlSource = Customer.cust_id
ControlSource = Customer.company

Grid for the first "many" side of the relationship:

ChildOrder = cust_id
LinkMaster = customer
RecordSource = orders
RecordSourceType = 1 - Alias
RelationalExpr = customer.cust_id
ColumnCount = 4
   Column1.ControlSource = "orders.order_no"
   Column1.Header1.Caption = "Order"
   Column2.ControlSource = "orders.order_date"
   Column2.Header1.Caption = "Date"
   Column3.ControlSource = "orders.to_name"
   Column3.Header1.Caption = "Ship To"
   Column4.ControlSource = "orders.order_amt"
   Column4.Sparse = .F.
   Column4.Header1.Caption = "Total"
   Column4.Text1.InputMask = "$$999,999.99"

Grid for the 2nd "many" side of the relationship:

ChildOrder = order_id
LinkMaster = Orders
RecordSource = Orditems
RecordSourceType = 1 - Alias
RelationalExpr =Orders.order_id
ColumnCount = 4
   Column1.ControlSource = "orditems.line_no"
   Column1.Header1.Caption = "Item"
   Column2.ControlSource = "products.prod_name"
   Column2.Header1.Caption = "Product"
   Column3.ControlSource = "orditems.quantity"
   Column3.Header1.Caption = "Qty."
   Column4.ControlSource = "orditems.unit_price"
   Column4.Sparse = .F.
   Column4.Header1.Caption = "Price"
   Column4.Text1.InputMask = "$$9,999.99"

In addition to the text boxes and the grids, the form contains an object based on the VCR class in Buttons.vcx. The SkipTable property of this class is set to the table you want the record pointer to be moved in when the user chooses a table navigation button. Because the user can easily manually move through the records in the grids (Orders and Orditems), SkipTable is set to Customer.

See Also

Create a One-To-Many Data Entry Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Controls in a Grid Sample

File: ...\Samples\Solution\Controls\Grid\Controls.scx

This sample demonstrates controls displayed in grid columns.

You can add controls to a column in the Form Designer by selecting a column and adding a control, or programmatically with the AddObject method.

There are a few properties that are important for displaying controls in a column.

CurrentControl Property

After you add a control to a grid column, you need to set the column's CurrentControl property to the new control for the new control to be displayed.

Sparse Property

The check boxes on the form make it possible for you to toggle the Sparse property of the grid columns that contain controls. When Sparse is set to .T., the control is only displayed when the focus is on a cell in the column. When Sparse is set to .F., the control is always displayed in each cell in the column.

Controls and Events

Notice that the control in the column processes the events when you set the focus to a cell in the column. For example, if you select a cell in a column with a spinner, when you press the up and down arrows, you increment or decrement the value in the spinner. This is the default behavior for a spinner, not the default behavior for a text box in a grid cell.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Dynamically Format Grid Columns Sample

File: ...\Samples\Solution\Controls\Grid\Dyngrid.scx

This sample illustrates setting the DynamicForeColor and DynamicBackColor properties of grid columns.

The code of interest in this sample is associated with the InteractiveChange event of the drop-down list cboFormat.

First, the code clears the dynamic fore and backcolor settings:

oGrd.SetAll("dynamicbackcolor", "", "Column")
oGrd.SetAll("dynamicforecolor", "", "Column")

Then, code in a CASE statement sets the new DynamicForeColor or DynamicBackColor properties. For example, the following line of code displays discontinued items with a gray ForeColor.

oGrd.SetAll("dynamicforecolor", ;
   "IIF(discontinu, RGB(192,192,192), RGB(0,0,0))", "Column")

Discontinu is a logical field in the Products table.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Add Items Interactively to a List Box Sample

File: ...\Samples\Solution\Controls\Lists\Ladd.scx

This sample demonstrates adding and removing list box items. When a user types text in the text box and presses ENTER, the text in the text box is added to the list and the cursor is returned to the text box so that the user can enter another value.

To make it possible for a user to interactively add items to a list, use the AddItem method. In the sample, the following code in the text box KeyPress event adds the text in the text box to the list box and clears the text box when the user presses ENTER:

PARAMETERS nKeyCode, nShiftCtrlAlt
IF nKeyCode = 13     && Enter Key
   THISFORM.lstAdd.AddItem (This.Value)
   THIS.Value = ""
ENDIF

The following code in the DblClick event of the list box removes the item that was double-clicked, sending the value to the text box:

THISFORM.txtAddText.Value = This.List(This.ListIndex)
THIS.RemoveItem (This.ListIndex)

See Also

Add Menu Items at Run Time | Solutions Samples


Display Multiple Columns in a List Box Sample

File: ...\Samples\Solution\Controls\Lists\Lmulcol.scx

This sample demonstrates displaying multiple columns in a list box. The form displayed contains a list box and a spinner. The number of columns in the list box is set to the Value property of the spinner: 1, 2, 3, or 4.

To set the width of the columns in a multi-column list box, use the ColumnWidths property. For example, if there are 3 columns in the list box, the following command will set the column widths to 10, 15, and 20, respectively:

Form.List.ColumnWidths = "10, 15, 20"

To set the fields to be displayed in the columns, set the RowSource property. For example, the following command sets the sources of three columns in a 3-column list box to the contact, city, and country fields of the customer table:

Form.List.RowSource = "contact,city,country"

The ColumnLines property determines whether lines are displayed between the columns in the list.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Pictures in a List Sample

File: ...\Samples\Solution\Controls\Lists\Piclist.scx

This sample illustrates how you can spice up your list boxes by adding picture graphics beside the individual text items. In this sample, you can pick any database (.dbc) file, and the list box will show different images beside the names of tables, local views and remote views.

The following code from cmdDatabase.Click enumerates through a .dbc and selectively adds pictures to list items using the Picture property. The Picture property relies on an index setting to determine which list item to affect.

FOR i = (m.nTblCount+1) TO thisform.lstDatabase.ListCount
IF DBGETPROP(ALLTRIM(thisform.lstDatabase.List[m.i]),; "view","sourcetype") = 1
       *Local view
      thisform.lstDatabase.Picture[m.i] = m.cLViewBMP
   ELSE
      * Remote view
      thisform.lstDatabase.Picture[m.i] = m.cRViewBMP
   ENDIF
ENDFOR
Note You need to ensure that the images used are sized correctly to fit within the space of a single list box item, which differs with the FontSize of the list.

See Also

Add Items Interactively to a List Box | Display Pictures in an Image Control | Solutions Samples


Fill a List with Values from Different Sources Sample

File: ...\Samples\Solution\Controls\Lists\Multdat1.scx

This sample demonstrates setting the RowSourceType of a list box at run time to a value, an alias, a SQL statement, a query (.qpr), an array, fields in a table, files in a directory, and the structure of a table.

The combo box on the form contains all the possible RowSourceTypes of a list (except for 9 - popup, which is included for backward compatibility). The code associated with the InteractiveChange event sets the new RowSourceType and RowSource properties for the list.

When you change both the RowSourceType and RowSource of a list box at run time, you need to do the following:

  1. Set the RowSourceType to 0.
  2. Set the RowSource to the new source.
  3. Set the RowSourceType to the new type.

If you don't follow this order, the existing RowSource and RowSourceType settings could conflict after one new value is set and before the corresponding value is set.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Move Items Between List Boxes Sample

File: ...\Samples\Solution\Controls\Lists\Lmover.scx

This sample demonstrates moving items from one list box to another. A user can double-click one item to move it, select one or more items and drag them, or use the appropriate command buttons to move the items between the lists.

The two list boxes and four associated command buttons are saved as a class: MoverLists in Samples.vcx. The base class of MoverLists is CONTAINER. To be able to add and remove items from lists, the RowSourceType of the lists must be set to 0 – None. If you want to fill the list box with array elements or values from a table, you can use code like the following:

*array
FOR i = 1 to ALEN(myarray)
   List.AddItem(myarray[i])
ENDFOR

*table
SCAN
   List.AddItem(table.field)
ENDSCAN

To Move Items by Double-clicking

The following code is associated with the DblClick event of the left list box (lstSource). Similar code is associated with the DblClick event of the right list box (lstSelected).

THIS.Parent.lstSelected.AddItem(THIS.List(THIS.ListIndex))
This.RemoveItem(THIS.ListIndex)
THIS.Parent.Refresh

"THIS" refers to lstSource. "THIS.Parent" refers to the moverlists class, the container of the lists.

To Move all Items from One List to Another

The following code is associated with the Click event of cmdAddAll:

  DO WHILE THIS.PARENT.lstSource.ListCount > 0
    THIS.PARENT.lstSelected.AddItem;
        (THIS.PARENT.lstSource.List(1))
   THIS.PARENT.lstSource.RemoveItem(1)
  ENDDO
  THIS.PARENT.Refresh

To Move Selected Items from One List to Another

If you remove an item from a list box, the ListCount property of the list box is decremented, as is the ListIndex of all the subsequent items in the list. To move multiply selected items, you need to use a DO WHILE loop. The following code is associated with the Click event of cmdAdd:

nCnt = 1
DO WHILE nCnt <= THIS.PARENT.lstSource.ListCount
   IF THIS.PARENT.lstSource.Selected(nCnt)
      THIS.PARENT.lstSelected.AddItem;
         (THIS.PARENT.lstSource.List(nCnt))
      THIS.PARENT.lstSource.RemoveItem(nCnt)
   ELSE
      nCnt = nCnt + 1
   ENDIF
ENDDO
THIS.PARENT.Refresh

To Drag and Drop Items from One List to Another

Implementing drag-and-drop between the list boxes involves code associated with the MouseDown, MouseMove, DragOver, and DragDrop events. Three user-defined properties (DragThreshold, MouseX, and MouseY) extend the usability of the class.

The MouseDown code stores the X and Y coordinates of the mouse pointer to class properties.

*MouseDown
Parameters nButton, nShift, nXCoord, nYCoord
THIS.PARENT.MouseX = nXCoord
THIS.PARENT.MouseY = nYCoord

The MouseMove code makes sure the left mouse button is pressed before initiating the drag procedure. In addition, to guard against accidental dragging, this code checks to make sure that the user has moved the mouse a distance greater than a set threshold (8 pixels by default).

*MouseMove
Parameters nButton, nShift, nXCoord, nYCoord
IF nButton = 1 && Left Mouse
   IF ABS(nXCoord - THIS.PARENT.MouseX) > ;
      THIS.Parent.DragThreshold OR ;
         ABS(nYCoord - THIS.PARENT.MouseY) > ;
         THIS.Parent.DragThreshold
      THIS.Drag
   ENDIF
ENDIF

The DragOver code changes the DragIcon of the source when the mouse pointer enters and leaves the list box "air space."

*DragOver
Parameters oSource, nXCoord, nYCoord, nState
DO CASE
   CASE nState = 0 && Enter
      oSource.DragIcon = THIS.Parent.CanDropIcon
   CASE nState = 1 && Leave
      oSource.DragIcon = THIS.Parent.NoDropIcon
ENDCASE

The DragDrop code makes sure that the source of the drag is not the same as the target of the drag and calls the method associated with the Click event of the cmdAdd command button (in the case of lstSelected) or cmdRemove (in the case of lstSource).

*DragDrop
Parameters oSource, nXCoord, nYCoord
IF oSource.Name != THIS.Name
   THIS.PARENT.cmdAdd.Click
ENDIF

See Also

Sort List Box Items | Multiselect Items in a List Box | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Multiselect Items in a List Box Sample

File: ...\Samples\Solution\Controls\Lists\Lmsel.scx

This sample shows how to manage multiple items selected in a list box. The form contains a list box with the MultiSelect property set to True (.T.). A combo box on the form contains all the items that are selected in the list box.

To process the multiple-selected items in a list box — to copy them to an array or incorporate them elsewhere in your application — loop through the list items and process the ones for which the Selected property is set to true (.T.). The following code is included in the Click event of the list box to display the selected items in a combo box and the number of selected items in a text box:

nNoSelected = 0    && variable to track number of selected items
THISFORM.cboSelected.Clear    && clear the combo box

* main processing loop
FOR i = 1 TO THIS.ListCount
   IF THIS.Selected(i)
      nNoSelected = nNoSelected + 1
      THISFORM.cboSelected.Additem (THIS.List(i))
   ENDIF
ENDFOR

THISFORM.txtNoSelected.Value = nNoSelected

In the code associated with the Init event of this form, and in many places throughout this sample application, the character string values initially added to the list are first defined with a #DEFINE directive. Each of the defined constants ends with "_LOC". Microsoft internal localization tools extract these definitions so that the strings can be translated into whatever language the application is being localized in.

See Also

Move Items between List Boxes | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Open Multiple Files Interactively Sample

File: ...\Samples\Solution\Controls\Lists\Multfile.scx

This sample shows how to populate a list with files. When you populate a list with files, built-in functionality makes it possible for a user to select new drives and directories. In this sample, a user can select one or more files in the list and open them for editing.

The following code loops through the items in the list box and opens the selected files for editing:

FOR nFile = 5 to THISFORM.lstFiles.ListCount
   IF THISFORM.lstFiles.Selected(nFile)
      MODIFY FILE (THISFORM.lstFiles.List(2) + ;
         THISFORM.lstFiles.List(nFile)) NOWAIT
   ENDIF
ENDFOR

When the RowSourceType property is set to 7 - Files:

  • lstFiles.List(1) refers to the drive.
  • lstFiles.List(2) refers to the path.
  • lstFiles.List(3) is a separator line.
  • lstFiles.List(4) is [..]. Click to go to the parent directory.

Files can start at lstFiles.List(5)

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Sort List Box Items Sample

File: ...\Samples\Solution\Controls\Lists\Lsort.scx

This sample demonstrates making it possible for a user to rearrange or sort the items in a list. The key properties to set are:

   List.MoverBars = .T.
   List.Sorted = .T.

Set the MoverBars property to true (.T.) to make it possible for a user to reorder an item in the list by dragging the button to the left of the item to the new position.

Set the Sorted property to true (.T.) to display the list items in alphabetical order. You can still rearrange the items in the list after they have been sorted. Set the Sorted property to .T. again to sort the list in alphabetical order again.

The Sorted property applies only if the RowSourceType property of the list is set to 0 (None) or 1 (Value).

See Also

Use Mover List Boxes for Selecting Data | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Treeview/Listbox Drag and Drop Sample

File: ...\Samples\Solution\Tahoe\Listdd.scx

This sample provides demonstrations of settings for OLEDragMode and OLEDropMode properties of the Treeview and Listbox controls.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Add and Remove Items in a Treeview Control | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Change Pages when a User Chooses a Button Sample

File: ...\Samples\Solution\Controls\PgFrame\Msgbox.scx

This sample makes it possible for you to interactively construct a message box.

There are six command button combinations possible in a message box. Each of these combinations is displayed on a separate page in a page frame on the Messagebox Builder form.

The option buttons, labeled 0 through 5, make it possible for you to specify which combination of command buttons you want to be displayed in your message box. The selected button in the page indicates the default Messagebox button selection. The ActivePage property of the page frame is set to the Value of the Option group.

Constructing the MESSAGEBOX Code

In the InteractiveChange event of the controls on the form, the WriteCode method of the form is called to dynamically construct the MESSAGEBOX code.

* WriteCode Method
#DEFINE QM '"'

cString = '=MESSAGEBOX('
cString = cString + QM + ALLTRIM(STRTRAN(THIS.edtMessage.Value, CHR(13)+CHR(10), QM + '+CHR(13)+' + QM)) + QM + ','
cString = cString + THIS.cboIcon.Value + '+'
cString = cString + THIS.DefaultButton + '+'
cString = cString + ALLTRIM(STR(THIS.opgButtons.Value - 1)) + ','
cString = cString + QM + ALLTRIM(THIS.txtCaption.Value) + QM + ')'

THIS.edtCode.Value = cString

See Also

Messagebox Handler | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Present a User with Multiple Choices Sample

File: ...\Samples\Solution\Controls\Buttons\Quiz.scx

This sample illustrates using an option button group with no default selection and binding a character field to the option group.

To display an option group with no selected button, do one of the following:

  • Set the Value property of each of the option buttons in the group to 0 of .F.
  • Set the Value property of the option button group to 0.

To store the caption of option buttons to a table field

  • Set the ControlSource of the option button group to the field.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Change the Number of Tabs at Run Time Sample

File: ...\Samples\Solution\Controls\Pgframe\Pfsam1.scx

This sample illustrates using a page frame with tabs. The number of tabs changes dynamically when a user chooses a new value in a spinner. When the user selects a tab, a list box displays values specific to the tab.

To change the number of tabs at run time

  • Set the PageCount property to the desired number of pages.

The list box in this sample is positioned on the form, not on any of the pages in the page frame. This placement makes it possible for you to have a single control visible in all of your pages.

Two user-defined form methods set the captions on the tabs and make sure the values in the list box match: UpdateList and SetCaption.

UpdateList Method

UpdateList is called when the number of tabs changes and when the user selects a new tab.

LOCAL lnPage, lcHigh, lcLow
#define NO_MATCH_LOC 'No Matching Names for '
DIMENSION THISFORM.aCustomers[1,2]
lnPage = THISFORM.pgfRolodex.activepage
THISFORM.aCustomers[1,1] = NO_MATCH_LOC + ;
   THISFORM.pgfRolodex.Pages(lnPage).Caption
THISFORM.aCustomers[1,2] = ""

lcHigh = substr(THISFORM.pgfrolodex.Pages(lnPage).caption,3,1)
lcLow = substr(THISFORM.pgfrolodex.Pages(lnPage).caption,1,1)
SELECT company, phone FROM customer;
   WHERE company <= lcHigh and company => lcLow;
   ORDER BY company;
   INTO ARRAY THISFORM.aCustomers

THISFORM.lstCustomers.Requery
THISFORM.lstCustomers.Value = 1

SetCaption Method

SetCaption is called in the spinner's UpClick and DownClick events to calculate what captions should appear on the tabs.

THISFORM.LockScreen = .T.
FOR n = 1 to THISFORM.pgfRolodex.PageCount
   FirstLetter = SUBSTR(THISFORM.Alphabet,((n - 1)*ROUND(LEN(THISFORM.Alphabet)/THISFORM.pgfRolodex.PageCount,0))+1,1)
   IF n = THISFORM.pgfRolodex.PageCount   &&last page
      LastLetter = right(THISFORM.Alphabet,1)
   ELSE
      LastLetter = SUBSTR(THISFORM.Alphabet,((n)*ROUND(LEN(THISFORM.Alphabet)/THISFORM.pgfRolodex.PageCount,0)),1)
   ENDIF
   THISFORM.pgfRolodex.Pages(n).Caption = FirstLetter + "-" + LastLetter
ENDFOR
THISFORM.LockScreen = .F.

Alphabet is a user-defined form property that is used to determine the captions for each tab. To get the same functionality in different languages, set the Alphabet property to a string containing all the letters in the target language alphabet.

See Also

Display Different Pages without Tabs | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Different Pages without Tabs Sample

File: ...\Samples\Solution\Controls\PgFrame\Pfsam2.scx

This sample demonstrates manipulating pages without tabs in a form page. The frame in the middle of the form contains three pages that are brought to the front as the user chooses command buttons. Each page can have its own controls and appearance.

The method that brings a particular page to the front is ZOrder. For example, the following line of code in the click event of one of the command buttons brings pagCustomers to the front:

THISFORM.pgfPeople.pagCustomers.ZOrder

You can also use the ActivePage property of the page frame to determine which pages are displayed.

THISFORM.pgfPeople.ActivePage = 1

See Also

Change Pages When a User Chooses a Button | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Format Input and Validate Data in a Text Box Sample

File: ...\Samples\Solution\Controls\TXT_EDT\Textbox.scx

This sample shows how to set text box properties to make it easy for a user to enter data in the required format.

Format | Property | Setting
Allow Only Digits | InputMask | 999999999
Select On Entry | SelectOnEntry | .T.
All Uppercase Format !
Read-Only | ReadOnly | .T.
US Telephone Number | InputMask | (999) 999-9999
Password text PasswordChar
*
Date Formatting | DateFormat | a number between 0 and 14

Validating Input

The following code in the Valid event of a text box prevents a user from leaving the text box if the letter "a" is in the text:

IF "a"$ THIS.Value
   #DEFINE MESSAGE_LOC "The text box value cannot contain the letter 'a'"
   MESSAGEBOX(MESSAGE_LOC,48+0+0)
   RETURN 0
ELSE
   RETURN .T.
ENDIF

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display a Stop Watch Sample

File: ...\Samples\Solution\Controls\Timer\Swatch.scx

This sample includes the Stopwatch class.

The Stopwatch Class

The Stopwatch class includes a timer and several display labels. The Timer increments numeric custom properties of the class and sets the Caption property of the labels accordingly.

The Start method of the class sets the Enabled property of the Timer to true (.T.). The Stop method sets the Enabled property of the Timer to false (.F.). And the Reset method sets the numeric properties to 0.

The Swatch Form

The Swatch form contains an object derived from the Stopwatch class, along with some command buttons. The code written for the Click event of the first command button on the form calls the Start and Stop methods of the Stopwatch class. The second button calls the Reset method of the Stopwatch class.

See Also

Stop Watch | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display a System Clock Sample

File: ...\Samples\Solution\Controls\Timer\Clock.scx

This sample contains the Clock custom control in Samples.vcx on a form. The class includes a text box for displaying the date and time and a timer for updating the display.

The TimeFormat property of the clock class can be set to 0 for 24-hour time format or 1 for 12-hour format. The code in the Timer event of the timer updates the time.

#DEFINE LONGDATE_LOC CDOW(DATE())+" "+CMONTH(DATE())+" "+ ;
         ALLTRIM(STR(DAY(DATE())))+", "+ALLTRIM(STR(YEAR(DATE())))

IF This.Parent.TimeFormat = 0
   This.Parent.txtTime.Value = IIF(VAL(SUBSTR(TIME(),1,2))>12, ;
      ALLTRIM(STR((VAL(SUBSTR(TIME(),1,2))-12)))+SUBSTR(TIME(),3,6),TIME())
ELSE
   This.Parent.txtTime.Value = TIME()
ENDIF

THIS.Parent.txtDate.Value = LONGDATE_LOC

This class contains a separate text box for date and time values. If you want to hide one or the other, you can easily set its Visible property to false (.F.). An easier way to display the time and date is to use a single text box and set the value of this text box in a timer control to DATETIME( ). This will make it possible for you to take advantage of the Hours, Seconds, and DateFormat properties of a text box.

See Also

Clock | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Execute Commands at Specified Intervals Sample

File: ...\Samples\Solution\Controls\Timer\Timecomm.scx

This sample form contains a text box and a spinner. Text you type in the text box is displayed in a WAIT WINDOW. You can set the spinner to the number of seconds you want to elapse between each WAIT WINDOW command.

In the InteractiveChange event of the spinner, the appropriate timer interval is set. The Interval property is 1/1000th of a second, so the interval is set to the spinner value * 1000.

THISFORM.Timer1.Interval = (THIS.Value * 1000)

In the Timer event, the WAIT WINDOW command is issued.

WAIT WINDOW ALLTRIM(THISFORM.Text1.Value) TIMEOUT 0.5

The code associated with the Timer event can include any command or procedure: code to update data, check for mail, display system resources, and so on.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create a Default Unique ID Value for a Field Sample

File: ...\Samples\Solution\Db\Newid.scx

This sample uses a stored procedure in a database to provide a default primary key value.

To create a default unique ID

  1. Add a separate table to the database that stores the next id for each table in the database. The name of this table in the sample is Ids.dbf. It contains two fields: Table C(10), NextID I.
  2. Create a function in the stored procedures of the database to return the next id value from the id table. The name of this function in the sample is NewID. It is listed below.
  3. Set the default value for the field to the function.

NewID Stored Procedure

FUNCTION NewID(tcAlias)
LOCAL lcAlias, lnID, lcOldReprocess, lnOldArea

  lnOldArea = SELECT()

  IF PARAMETERS() < 1
    lcAlias = UPPER(ALIAS())
  ELSE
    lcAlias = UPPER(tcAlias)
  ENDIF

  lcOldReprocess = SET('REPROCESS')

  * Lock until user presses Esc
  SET REPROCESS TO AUTOMATIC

  IF !USED("IDS")
    USE newid!ids IN 0
  ENDIF
  SELECT ids

  IF SEEK(lcAlias, "Ids", "table")
    IF RLOCK()
      lnID = ids.nextid
      REPLACE ids.nextid WITH ids.nextid + 1
      UNLOCK
    ENDIF
  ENDIF

  SELECT (lnOldArea)
  SET REPROCESS TO lcOldReprocess

  RETURN lnID
ENDFUNC

See Also

Create a One-To-Many Data Entry Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create Small Indexes Using BINTOC( ) Sample

File: ...\Samples\Solution\Db\Index1.scx

This sample shows various indexing schemes you can use with numeric and integer data types to get significant savings in index size and disk space consumed. In addition, smaller sized indexes usually result in faster searches. The BINTOC() function makes it possible for you to convert an integer (numeric) value to a binary character representation.

Syntax

BINTOC(nExpression [, nSize])

Depending on the size of your expression, you can set the nSize parameter to accommodate the value of your expression in the least amount of characters.

The following line of code creates an index on a numeric field:

INDEX on line_no TAG line_no

The next time you are working with indexes on numeric integer data, consider using something like the following:

INDEX on BINTOC(line_no,1) TAG line_no

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Index on Expressions Sample

File: ...\Samples\Solution\Db\Index2.scx

This index sample shows several options you might consider when using a character field to represent a Unique ID (one often comprised of numeric data). An index tag based on a character field will sort based on the ASCII values of the data whereas a numeric expression, using the VAL( ) function, will sort on numeric sequences. The following table shows the sort difference of two indexes:

cExpression | VAL(cExpression)
1 | 1
11 | 2
2 | 11
Note When you use the VAL( ) function, all non-numeric values will be converted to 0.

By incorporating the BINTOC( ) function, you also can reduce the size of your index tags considerably.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Nest Transactions Sample

File: ...\Samples\Solution\Db\Trans.scx

This sample illustrates beginning, ending, and rolling back transactions. You can decide to commit or discard changes to a single table when you use table buffering, but you can decide to commit or discard changes to any number of tables when you use transactions.

Before editing either table, click the Begin button. After editing, you can click Begin again to nest another transaction, or you can click End to commit your edits to the table or Rollback to discard your changes.

The key commands in this example are as follows:

BEGIN TRANSACTION

END TRANSACTION

ROLLBACK

The function that returns the current number of nested transactions is as follows:

TXNLEVEL( )

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Programmatically Check Table Properties Sample

File: ...\Samples\Solution\Db\Info.scx

This sample illustrates getting information about a table at run time.

Field Information

The AFIELDS( ) function provides most of the information about table fields displayed in this sample. In addition to the information displayed in this sample, AFIELDS( ) provides information about field and table validation expressions and messages, trigger expressions and messages, as well as long table names and table comments in the database.

Index Information

The TAG( ) and KEY( ) functions provide index information.

lo = THISFORM.edtProperties
FOR i = 1 TO 254
   IF !EMPTY(TAG(i))  && Checks for tags in the index
      lo.Value = lo.Value + TAG(i) + "  " + KEY(i)
   ELSE
      EXIT
   ENDIF
ENDFOR

See Also

Programmatically Manipulate Objects | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Sort or Order a Table at Run Time Sample

File: ...\Samples\Solution\Db\Order.scx

This sample illustrates changing the order in which records in a table are listed. The customer table has index tags on the fields displayed in the grid. In the MouseUp event of each of the headers in the grid, the order of the table is set to the index tag associated with the field displayed in the column. For example, the following code is associated with the MouseUp event of the Company header:

LPARAMETERS nButton, nShift, nXCoord, nYCoord
IF nShift = 2 && CTRL
   SET ORDER TO Company DESCENDING
ELSE
   SET ORDER TO Company ASCENDING
ENDIF

GO TOP
THISFORM.Refresh

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Search Text Using Regular Expressions Sample

File: ...\Samples\Solution\FFC\Regexp.scx

You can use regular expression searching in your applications. Regular expressions provide a more complex set of search/filter criteria against a selection of text than the wildcard pattern searching available in the Find dialog box.

This sample contains the following classes

Class | Library | Description
_regexp | _ regexp.vcx | Provides methods for performing regular expression search capabilities against a chunk of text.

The Regular Expressions Foundation Class provides access to routines for using regular expressions in your applications. For more information, see Regular Expressions Foundation Class.

See Also

Visual FoxPro Foundation Class Samples | Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z


Using DBC Events Sample

File: ...\Samples\Solution\Sedona\Dbcevents.scx

This sample illustrates database events that make it possible for you to have actions taken when a database and its objects (tables, views, relations, etc.) are opened, accessed, or manipulated.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Interactively Build a SELECT Statement Sample

File: ...\Samples\Solution\Forms\Makesql.scx

This sample shows how to make it possible for a user to build a custom query at run time. Combo boxes on the form make it possible for a user to choose fields from the currently open table. The BldSQL method processes the names of the fields and the values users type into text boxes to create an executable SQL SELECT statement.

Additional methods, ValidateType and SetTextboxFormat, make sure that the appropriate values are entered into the text boxes and correctly incorporated into the SELECT statement.

After the WHERE clause has been constructed and stored to the variable lcWhere, the following command creates the SELECT statement:

lcSQL = "SELECT * FROM " + lcAlias + " " + lcWHERE

Once the SELECT statement is constructed, it can be executed with macro substitution.

&lcSQL

See Also

Array Handler | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Select Customers in a Specific Country Sample

File: ...\Samples\Data\Testdata.dbc

This sample illustrates using a parameterized view ("customers in specific country" in the testdata database) to display a subset of records that match a variable set at run time.

To create a parameterized view in the View Designer, enter a variable prefixed with a question mark (?) in the Example box of the Filter tab.

If the variable does not exist at run time, the user is prompted to enter a value for the variable, whichcountry in this example. If the variable already exists, the view displays matching records without prompting for a new value.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Select Records from a Full Outer Join Sample

File: ...\Samples\Data\Fouterj.qpr

The query, FOUTERJ, in the Solution project combines information from the country table and the customer table using a full outer join. Each result record has a field for each of the fields from the country table, and the country and cust_id field for the field from the customer table as specified in the SELECT clause of the SELECT-SQL statement.

SELECT Country.*, Customer.country, Customer.cust_id;
 FROM testdata!customer FULL JOIN country ;
  ON Customer.country = Country.country

Typically, a full outer join answers three questions about the records in your database. Some of the questions this query could answer include:

  • Which customers are in which countries?
  • Which countries do not have any of our customers in them?
  • Which customer records are missing country information?

This information might help someone decide if they should expand their business to other countries, change their marketing strategy in some countries, or simply that some records in the database need the country information updated.

The full outer join returns all records from both tables and combines records that match the join condition. The result set includes the following three subsets of records:

  • Records matching the join condition that combine information from a record in each table.
  • Records from the country table that do not match the join condition.
  • Records from the customers table that do not match the join condition.

Because each record in the results has the same fields, the records that did not have a match in the other table have NULL values in the fields that would otherwise hold values from the other table. For example, if a record for the country, Russia, did not have any related customer records in the customer table, that record appears in the results with NULL as the value of the field, cust_id and country_b.

You can change the results of the query by specifying filters, a sort order, group, or other miscellaneous options for the query.

See Also

Select Records from an Inner Join | Select Records from a Right Outer Join | Select Records from a Nested Join | Select Records from a Left Outer Join | Solutions Samples


Select Records from a Left Outer Join Sample

File: ...\Samples\Data\Louterj.qpr

The query, LOUTERJ, in the Solution project combines information from the orders table and the customer table using a left outer join. Each result record has a field for the order_id from the orders table and for the cust_id, company, country fields from the customer table as specified in the SELECT clause of the SELECT-SQL statement.

SELECT Customer.cust_id, Customer.company, Customer.country,;
 Orders.order_id;
 FROM testdata!orders LEFT OUTER JOIN testdata!customer ;
  ON Orders.cust_id = Customer.cust_id

Typically, a left outer join can answer two questions about the records in your database. Some of the questions this query could answer include:

  • Which orders belong to which customers?
  • Which orders do not have related customer information?

This information helps the database administrator determine which order records are missing information.

The left outer join returns all records from the table on the left of the join condition combined with the records from the table on the right of the condition that match the condition. The results set includes the following two subsets of records:

  • Records matching the join condition that combine information from a record in each table.
  • Records from the orders table that do not match the join condition.

Because each record in the results has the same fields, the records with an order_id that did not have a match in the customer table have NULL values in the fields that would otherwise hold values from the customer table. For example, if the record for order 11079 did not have any related customer records in the customer table, that record appears in the results with the value NULL in the fields, cust_id, company, and country.

You can change the results of the query by specifying filters, a sort order, group, or other miscellaneous options for the query.

See Also

Select Records from a Full Outer Join | Select Records from an Inner Join | Select Records from a Right Outer Join | Select Records from a Nested Join | Solutions Samples


Select Records from a Nested Join Sample

File: ...\Samples\Data\Nested.qpr

The query, NESTED, in the Solution project combines information from the customer, orders, and orditems tables using two inner join conditions. One join condition is between customer and orders; the other between orders and orditems. Each result record has fields for the cust_id and company from the customers table, order_id from the orders table, and line_no from the orditems table as specified in the SELECT clause of the SELECT-SQL statement.

SELECT Customer.cust_id, Customer.company, Orders.order_id, Orditems.line_no;
 FROM testdata!customer INNER JOIN testdata!orders;
 INNER JOIN testdata!orditems ;
 ON Orders.order_id = Orditems.order_id ;
 ON Customer.cust_id = Orders.cust_id

The order in which the tables are joined determines the order in which the join conditions are evaluated. In this query, the join between orders and orditems is evaluated first and produces a subset of records that meets the join condition. This subset of records is matched to the records in the customer table and produces the final results set.

You can change the results of the query by specifying filters, a sort order, group, or other miscellaneous options for the query.

See Also

Select Records from a Left Outer Join | Select Records from a Right Outer Join | Select Records from a Full Outer Join | Select Records from an Inner Join | Select Records from a Right Outer Join | Solutions Samples


Select Records from a Right Outer Join Sample

File: ...\Samples\Data\Routerj.qpr

The query, ROUTERJ, in the Solution project uses the testdata database, and combines information from the orders table and the employee table using a right outer join. Each result record has a field for the order_id from the orders table and for the lastname field from the employee table.

SELECT Orders.order_id, Employee.last_name;
 FROM testdata!employee RIGHT OUTER JOIN testdata!orders ;
 ON Employee.emp_id = Orders.emp_id

Typically, a right outer join can answer two questions about the records in your database. Some of the questions this query could answer include:

  • Which orders were entered by which employees?
  • Which orders do not have an employee specified?

This information might help track specific orders and identify orders that do not have an employee specified as placing the order.

The right outer join retrieves all records from the table on the right of the join condition combined with the records from the table on the left that match the join condition. The results set includes the following two subsets of records:

  • Records matching the join condition that combine information from a record in each table.
  • Records from the orders table that do not match the join condition.

Because each record in the results has the same fields, the records with a lastname that did not have a match in the orders table have NULL values in the field that would otherwise hold values from the orders table. For example, if a record for order number 11078 did not have any related employee records in the employee table, that record appears in the results with the value NULL in the field, lastname.

You can change the results of the query by specifying filters, sort order, group, or other miscellaneous options for the query.

See Also

Select Records from a Nested Join | Select Records from a Left Outer Join | Select Records from a Full Outer Join | Select Records from an Inner Join | Select Records from a Right Outer Join | Solutions Samples


Select Records from an Inner Join Sample

File: ...\Samples\Data\Innerj.qpr

The query, INNERJ, in the Solution project uses the database, TESTDATA, and combines information from the tables, ORDERS and CUSTOMER using an inner join condition. Each result record has fields for the CUST_ID, COMPANY, and COUNTRY from the CUSTOMERS table, and ORDER_ID from the ORDERS table as specified in the SELECT clause of the SELECT-SQL statement.

SELECT Customer.cust_id, Customer.company, Customer.country,;
 Orders.order_id;
 FROM testdata!orders INNER JOIN testdata!customer ;
 ON Orders.cust_id = Customer.cust_id

This query retrieves and combines the records between the two tables that match the join condition. The condition specifies that the records must have the same value in the cust_id field.

An inner join typically answers one basic question. In this query, the question is what orders did each customer place? If a customer has a record in the database but has not placed an order, the record does not appear in the results because it is not part of the subset that matches the join condition.

You can change the results of the query by specifying filters, a sort order, group, or other miscellaneous options for the query.

See Also

Select Records from a Nested Join | Select Records from Both Inner and Outer Joins | Select Records from a Left Outer Join | Select Records from a Full Outer Join | Solutions Samples


Select Records from Both Inner and Outer Joins Sample

File: ...\Samples\Data\Comboj.qpr

The query, COMBOJ, uses the testdata database, and combines information from the tables, customer, orders, and orditems. Each result record has fields for the company from the customer table, the order_date from the orders table, and the line_no from the orditems table as specified in the SELECT clause of the SELECT-SQL statement.

SELECT Customer.company, Orders.order_id, Orditems.line_no;
 FROM testdata!customer LEFT OUTER JOIN testdata!orders;
    INNER JOIN testdata!orditems ;
   ON Orders.order_id = Orditems.order_id ;
   ON Customer.cust_id = Orders.cust_id

The order in which the tables are joined determines the order in which the join conditions are evaluated. In this query, the join between orders and orditems is evaluated first and produces a subset of records that meets the join condition. Because of the inner join, the subset of records has only records from both tables that match the condition. This subset of records is matched to the records in the customer table. Because of the outer join between customer and orders, any customers not having orders also appear in the results and have the value NULL.

You can change the results of the query by specifying filters, a sort order, group, or other miscellaneous options for the query.

See Also

Select Records from a Nested Join | Select Records from a Left Outer Join | Select Records from a Full Outer Join | Solutions Samples


Select the 10 Worst-Selling Products Sample

File: ...\Samples\Data\Worstten.qpr

This query displays the 10 worst-selling products based on sales recorded in the Order Items table. The query uses the TOP n feature of the SELECT statement, and, because the default order is from smallest to largest, ordering by the sum of price and quantity returns the 10 lowest values.

SELECT TOP 10 Products.prod_name,;
  SUM(Orditems.unit_price*Orditems.quantity);
 FROM testdata!products INNER JOIN testdata!orditems ;
   ON Products.product_id = Orditems.product_id;
 GROUP BY Products.prod_name;
 ORDER BY 2

See Also

Select the Top 10 Best-Selling Products | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Select the Top 10 Best-Selling Products Sample

File: ...\Samples\Data\Topten.qpr

This query displays the top 10 best-selling products based on sales recorded in the Order Items table. The query uses the TOP n feature of the SELECT statement. Because the order is set to DESCENDING, ordering by the sum of price and quantity returns the 10 highest values.

SELECT TOP 10 Products.prod_name,;
  SUM( Orditems.unit_price*  Orditems.quantity);
 FROM testdata!products INNER JOIN testdata!orditems ;
   ON Products.product_id = Orditems.product_id;
 GROUP BY Products.prod_name;
 ORDER BY 2 DESC

See Also

Select the 10 Worst-Selling Products | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create a One-To-Many Data Entry Form Sample

File: ...\Samples\Solution\Forms\Many.scx

This sample illustrates the basic tasks associated with a one-to-many data entry form.

When you choose the New button beside the parent table text boxes, the following code is executed:

SELECT CUSTOMER
APPEND BLANK
THISFORM.Refresh

When you choose the New button beside the grid that displays the child records, more code is executed.

After selecting the orders table, the code calculates a new id value for the order, adds the blank record, then stores the parent id and order id to the appropriate fields.

CALCULATE MAX(order_id) ALL TO lMaxID
lMaxID = ALLTRIM(STR(VAL(lMaxID) + 1))

APPEND BLANK

REPLACE cust_id WITH Customer.Cust_id IN orders
REPLACE order_id with lMaxID in orders
Note This method of creating a new id value would not be reliable if multiple users were adding new orders at the same time. Instead, you can create a new id as illustrated in the Create a Default Unique ID Value for a Field sample.

See Also

Create a Single Table Data Entry Form | Solutions Samples | Create a Default Unique ID Value for a Field


Create a Query-By-Example Form Sample

File: ...\Samples\Solution\Forms\Qbf.scx

This sample enables users to search and filter records in the same interface that they view the records.

When a user chooses Enter QBF, the code associated with the Click event of cmdQBFMode begins a transaction and appends a blank record to the table to store the user's query text.

* extract from cmdQBFMode.Click
BEGIN TRANSACTION
APPEND BLANK
THISFORM.Refresh

When the user chooses Query, code associated with the Click event of cmdExecuteQBF rolls back the transaction, throwing away the new record.

You can use transactions only with tables contained in a database. If you want to include QBF capabilities for a table that is not in a database, you can loop through all the controls on the form, save the old ControlSource property setting and set the ControlSource property of the controls to an empty string. After getting the user query string, you can loop back through the controls and reset the ControlSource properties.

Code associated with the Click event of cmdExecuteQBF also loops through the controls on the form, checks for user-entered values, and calls the ParseCondition method to assemble the filter string.

A user can enter a single value to match or an expression. For example, a user can enter either of the values below in the Title text box to set a filter:

Sales Manager

!= "Sales Manager"

If the user doesn't enter an expression, quotation marks aren't required.

The ParseCondition Method

LPARAMETERS cCondition, cControlSource
LOCAL lcRetCondition, lcFieldName
IF TYPE('cCondition') = 'C'
   cCondition = ALLTRIM(cCondition)
ENDIF

lcFieldName = SUBSTRC(cControlSource,(RATC(".",cControlSource)+1))

IF !EMPTY(cCondition) THEN
   IF TYPE('cCondition')$ "CM"
      IF ("<"       $ cCondition OR ;
         "=="    $ cCondition OR ;
         "LIKE"    $ cCondition OR ;
         "<>"    $ cCondition OR ;
         "!="    $ cCondition OR ;
         "#"    $ cCondition OR ;
         "="    $ cCondition OR ;
         ">"    $ cCondition)
           lcRetCondition = lcFieldName + cCondition
      ENDIF
   ENDIF

   IF EMPTY(lcRetCondition)
      DO CASE
         * put quotes around character expressions
         CASE TYPE(cControlSource) $ "CM"
            lcRetCondition = lcFieldName + " = " + CHR(34) + cCondition + CHR(34)

         * put braces around date expressions
         CASE TYPE(cControlSource) $ "DT"
            lcRetCondition = lcFieldName + " = {" + DTOC(cCondition) + "}"

         OTHERWISE
            lcRetCondition = lcFieldName + " = " + STR(cCondition)
      ENDCASE
   ENDIF
ELSE
   lcRetCondition = ""
ENDIF

RETURN lcRetCondition

See Also

Create a One-To-Many Data Entry Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create a Single Table Data Entry Form Sample

File: ...\Samples\Solution\Forms\Single.scx

This sample illustrates the simplest scenario for a single-user, single-table data entry form.

The ControlSource property of each of the text boxes and combo boxes on the form is set to a field in the Customer table.

An APPEND BLANK command is issued in the Click event of cmdNew.

APPEND BLANK
THISFORM.Refresh

The DELETE command is issued in the Click event of cmdDelete.

* cmdDelete.Click
#DEFINE MSGBOX_YES      6
#DEFINE C_MSGBOX1      36
#DEFINE C_DELETE_LOC   "Are you sure you want to delete this record?"

IF MESSAGEBOX(C_DELETE_LOC,C_MSGBOX1) = MSGBOX_YES
   DELETE
   IF !EOF()
      SKIP 1
   ENDIF
   IF EOF() AND !BOF()
      SKIP -1
   ENDIF
   THISFORM.Refresh
ENDIF

Extending the Data Entry Form

To create a more robust data entry form, one that makes it possible for a user to cancel changes or makes it possible for multiple users to access the same data, you need to use transactions and table or row buffering.

See Also

Create a Query-By-Example Form | Create a One-To-Many Data Entry Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create an SDI Form Sample

File: ...\Samples\Solution\Forms\Sdiform.scx

This sample illustrates Visual FoxPro support of SDI forms. In order to create an SDI form, all you have to do is set the form's ShowWindow property to 2 – s Top-Level Form. SDI forms do not require the Visual FoxPro window to be visible.

Adding Forms

There are two ways to add forms to a Top-Level (SDI) form. The first and easiest is to create a new form and set its ShowWindow property to 1 (In Top-Level form). While this might seem the most appropriate, it is not always the best solution because the ShowWindow property can only be set at design time.

Another method is to use the ACTIVATE WINDOW command. The code below from the SDIForm sample shows just this. Since this command is not object-based, you must reference a form by its window name (Name property).

ACTIVATE WINDOW (thisform.oWindows[m.nGetWin].NAME) ;
IN WINDOW (thisform.name)

Adding Menus

Menus can also be added to SDI forms. There is now a new Top-Level Form check box in the Menu Designer's View menu General Options dialog box. A Top-Level Form menu will be generated if you check this option and can be called as shown here.

DO sdiform.mpr WITH THISFORM,.T.
Note If system menu items rely on the main Visual FoxPro window being visible, they won't give the expected results when the main Visual FoxPro window is hidden.

Adding Toolbars

In addition to menus and windows, you can also add toolbars to your SDI forms. Toolbars are objects like forms, so you can take advantage of the Visual FoxPro object model and scope that toolbar to the form. The SDI form sample uses a custom property to create and keep the toolbar in scope.

SET CLASSLIB TO sditbar ADDITIVE
thisform.oToolbar=create("sditb1")
thisform.oToolbar.show

See Also

Create a Single Table Data Entry Form | Create a Query-By-Example Form | Create a One-To-Many Data Entry Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Line Animation on a Form Sample

File: ...\Samples\Solution\Forms\Graphics\Anim.scx

This sample illustrates drawing lines on a form. More specifically, it demonstrates saving coordinates of sets of lines drawn on a form and redrawing them, along with additional lines at intermediate positions, giving the illusion of motion.

Adding Lines to the Table

Each time a user draws a line on the form, its coordinates are stored in a table with the following structure:

Name | Type | Description
Frameno | I | Incremented each time the user chooses New Frame.
Objno | I | Incremented each time a line is added to a frame.
X1 | I | The starting X coordinate for a line.
X2 | I | The ending X coordinate for a line.
Y1 | I | The starting Y coordinate for a line
Y2 | I | The ending Y coordinate for a line.

Playing the Frames

The following code plays the frames, uses the table again in another work area, selects the second work area, and goes to the next frame:

USE (lcTable) AGAIN IN 0 ALIAS shadow
SELECT shadow
LOCATE FOR frameno # &lcTable..frameno

The variable nBetween determines how many intermediate lines are drawn on the form between a line in one frame and the corresponding line in the next frame.

FOR nb = 1 TO nBetween

Inside the FOR loop, the code scans for all of the lines associated with a frame and calculates coordinates for the intermediate lines, for example:

nx1 = frames.x1 + nb * (shadow.x1 - frames.x1) / nBetween
ny1 = frames.y1 + nb * (shadow.y1 - frames.y1) / nBetween

The code then prints each intermediate line, and after a WAIT of .05 seconds clears the form and continues the loop.

THISFORMSET.frmAnimation.line(nx1,ny1,nx2,ny2)

See Also

Draw Lines and Shapes on a Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Pictures in an Image Control Sample

File: ...\Samples\Solution\Forms\Image.scx

This sample illustrates displaying bitmaps or icons in an image control.

The list box on the form displays files. In the InteractiveChange event of the list box, the Picture property of the image control is set to the selected file, if the file is a .bmp or .ico.

* lstFiles.InteractiveChange
cSelected = UPPER(THIS.List(THIS.ListIndex))
CD THIS.List(2)
IF ".BMP"$cSelected OR ".ICO"$cSelected
   THISFORM.imgDisplay.Picture = THIS.List(2) + cSelected
ENDIF

See Also

Display Pictures in a List | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Draw Lines and Shapes on a Form Sample

File: ...\Samples\Solution\Forms\Graphics\Fdmain.scx

This sample illustrates how to use form graphics methods (PSet, Line, and Circle) and properties (DrawMode, DrawStyle, DrawWidth) to make it possible for a user to draw figures and shapes on a form in different colors and different pen widths.

The sample includes a toolbar (defined in Fdproc.prg) and a form (based on frmFD in Fd.vcx). The user can select settings in the toolbar that affect the graphics properties of the form. When the form is set to accept user drawing, the MousePointer is set to 2 (cross-hairs).

The drawing functionality is coded in the methods associated with the MouseDown and MouseMove events of the form.

* MouseDown
PARAMETERS nButton, nShift, nXCoord, nYCoord
IF THIS.MousePointer = 2
   THIS.PSet(nXCoord, nYCoord)
ENDIF

* MouseMove
PARAMETERS nButton, nShift, nXCoord, nYCoord
IF THIS.MousePointer = 2
   THISFORM.LINE(nXCoord, nYCoord)
ENDIF

See Also

Display Line Animation on a Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Graph Equations on a Form Sample

File: ...\Samples\Solution\Forms\Graphics\Graph.scx

This sample shows how to graph equations with form graphics. The user can scale the equation by choosing the Zoom command buttons. The user also can move the graph's origin by clicking and dragging.

The graphing engines for this sample are in two programs: Cgraph.prg and Pgraph.prg. CGRAPH graphs equations based on Cartesian coordinates. PGRAPH graphs equations based on Polar coordinates. These programs use the PSet and Line methods of a form to draw the equation.

The following code, associated with the OneGraph method of the form set, runs the CGRAPH program when a user chooses the Graph button:

THISFORMSET.frmGraph.Draw

   DO cgraph WITH ;
      graph.equation, ;
      graph.step, ;
      graph.ecolor, ;
      graph.connect, ;
      THISFORMSET.nFormX, ;
      THISFORMSET.nFormY, ;
      .F., ;
      THISFORMSET.frmgraph, ;
      THISFORMSET.nFormScale

The following table lists the parameters for CGRAPH:

Parameter | Type | Description
equation | C | The equation in terms of X. Will plot the answer as Y.
step | N | Step increment.
ecolor | N | Equation color.
connect | L | Whether the previous point is connected to the current point with a line.
nFormX | N | Point on form where x = 0
nFormY | N | Point on form where y = 0
lAddCoords |  | Whether to draw coordinate lines.
frmgraph | C | Name of the form to write to.
nFormScale | N | Scale to graph the equation at.

See Also

Graph Object | Refresh a Graph in a Form | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Pass Parameters Between Forms Sample

File: ...\Samples\Solution\Forms\Param.scx

This solution illustrates passing parameters to a form and returning a value back.

PARAM Form

This form has the user enter a question and possible responses. Then, in the Click event of the cmdAsk button, the ParamAsk form is opened by passing the Question and Possible responses.

cParam1 = THISFORM.txtPassValue1.value
nParam2 = THISFORM.opgPassValue2.value

DO FORM LOCFILE("ParamAsk.scx") WITH cParam1, nParam2 TO nRetValue

PARAMASK Form

The PARAMETERS are passed to the Init of the form where they are processed.

PARAMETERS cQuestion, nButtons
THISFORM.txtQuestion.caption = cQuestion

In the Unload event of the form, the value stored in retvalue is returned back to the calling form:

RETURN THISFORM.retValue

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Programmatically Manipulate Objects Sample

File: ...\Samples\Solution\Forms\Objects.scx

This sample shows how to set properties at run time for objects in a form set. The sample form set contains two forms. Code associated with the Click event of controls on both forms changes the property settings of other controls.

When setting properties of controls at run time, remember to reference the control through its container hierarchy. For example, to set the Value property of a control on one form from code in a method of another form, reference the highest-level container (the form set), and all subsequent containers.

THISFORMSET.frmLeft.chkBold.Value = .F.

See Also

Programmatically Manipulate Text | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Provide "What's This?" Help on a Form Sample

File: ...\Samples\Solution\Forms\Whatthis.scx

When you provide "What's This?" Help on a form, a button with a question mark is displayed in the upper right corner of the form.

When a user clicks this button or presses SHIFT+ F1, the form is set to WhatsThis mode. You also can programmatically enter this state by calling the WhatsThisMode method of the form. When the form is in WhatsThis mode, the mouse pointer changes. A user can click a control and get context-sensitive help for that control in a pop-up window.

Note If the WhatsThisHelpID of a control or a form is set to -1 (the default), the text in the pop-up window indicates that no help topic is available for the control.

To provide "What's This?" Help

  1. Create a Help file with a topic for each control on the form.
  2. In the Map section of the Help project, map HelpContextID values to the topics.
  3. Set the WhatsThisHelp property of the form to true (.T.).
  4. Set the WhatsThisButton property of the form to true (.T.).
  5. Set the WhatsThisHelpID of the controls to the appropriate helpcontextID values.
  6. In the Load or Init of the form, use the SET HELP TO command to specify the help file for the form.

In addition to Whatthis.scx, this sample includes the following files:

File | Description
Whatthis.hlp | The Help file for the form
Whatthis.hpj | The Help project file
Whatthis.rtf | The source document for the Help file

See Also

Help Button | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Return a Value from a Form Sample

File: ...\Samples\Solution\Forms\Logform.scx

This sample illustrates returning a value from a logon form. The launching form (Logform.scx) uses the DO FORM command to run the logon form and store the return value to a variable (cUser).

DO FORM Login TO cUser
Note To return a value from a form, the WindowType property of the form must be set to 1 - Modal.

The logon form (Login.scx) makes it possible for a user to enter a user name and a password. Code associated with the Click event of cmdOK checks to make sure that the correct password was entered.

LOCATE FOR UPPER(login.userid) = UPPER(ALLTRIM(THISFORM.txtUserName.Value))

IF FOUND() AND ALLTRIM(password) == ALLTRIM(THISFORM.txtPassword.Value)
   THISFORM.cUser = ALLTRIM(login.userid)
   THISFORM.Release
ELSE
   #DEFINE MISMATCH_LOC "The user name or password is incorrect. Please try again."
   WAIT WINDOW MISMATCH_LOC TIMEOUT 1.5
   THISFORM.txtUserName.Value = ""
   THISFORM.txtPassword.Value = ""
   THISFORM.txtUserName.SetFocus
ENDIF

Code associated with the Unload event of the logon form returns the name of the user, if the user entered the correct password, or an empty string.

RETURN THIS.cUser

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Run Multiple Instances of a Form Sample

File: ...\Samples\Solution\Forms\Launch.scx

This sample demonstrates running multiple instances of a form. aForms is an array property of the form that launches the multiple instances. The following code is associated with the Click event of the command button that launches multiple forms:

Get the number of the last element in the array

nInstance = ALEN(THISFORM.aForms)

Determine the Top and Left Properties to cascade the new forms. These settings are passed as parameters when the form instances are launched.

IF nInstance > 1 AND ;
   TYPE('THISFORM.aForms[nInstance -1]') = 'O'
   nFormTop = THISFORM.aForms[nInstance -1].Top + 1
   nFormLeft = THISFORM.aForms[nInstance -1].Left + 1
ELSE
   nFormTop = 1
   nFormLeft = 1
ENDIF

Set the caption to reflect the instance number

cFormCaption = "Instance" + ALLTRIM(STR(nInstance))

Run the form and assign the object variable to the array element. The Linked keyword indicates that all instances will be released when the array is released. Without LINKED, the multiple instance forms would persist after the array is released.

DO FORM Multi NAME THISFORM.aForms[nInstance] WITH ;
   nFormTop, nFormLeft, cFormCaption LINKED

Redimension the array so that more instances of the form can be launched.

DIMENSION THISFORM.aForms[nInstance + 1]

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Transparent Forms Sample

File: ...\Samples\Solution\Sedona\Fadeaway.scx

Microsoft Windows 2000 has support for layered windows. Using a layered window can improve significantly performance and visual effects for a window that has a complex shape, animates its shape, or wants to use alpha blending effects. The system automatically composes and repaints layered windows and the windows of underlying applications. As a result, layered windows are rendered smoothly, without the flickering typical of complex window regions. In addition, layered windows can be partially translucent, that is, alpha-blended. This sample shows how you can use layered windows in Visual FoxPro to add special opacity and transparency effects.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use an Enhanced Openfile Dialog Box Sample

File: ...\Samples\Solution\FFC\Getfilex.scx

The standard Visual FoxPro GETFILE() and PUTFILE() commands provide file picker dialogs, which do not have the look and feel of the latest dialogs. This sample shows use of the Common File Dialog Foundation Class. With this class, you can now have extended UI features on these dialogs including the Places bar on the left side of the dialog, which provides for quick access to other search locations, such as History, Desktop, and My Document.

This sample contains the following classes

Class | Library | Description
_comdlg | _ system.vcx | Contains a set of properties and methods so that you can use the native Windows open and save file dialogs.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Foundation Class Samples

The Visual FoxPro Foundation Classes are supplied with the Component Gallery to provide rapid application development with as little coding as possible. The classes work immediately by addressing the following needs:

  • Provide common database development tools and structures
  • Provide fast, extensible generic components
  • Provide components that enhance and ease Web page development
  • Provide effective wrappers for system API functions
  • Provide a rich set of functions to a wide range of Visual FoxPro users

In This Section

Guidelines for Using Visual FoxPro Foundation Classes
Provides an overview of the situations and solutions in which to use foundation classes.
Add a Data-Bound Calendar Sample
Demonstrates the use of a data-bound ActiveX calendar control to enhance data entry in date fields in forms.
Add Data Lookup Combo Boxes Sample
Performs a lookup of values in a field to populate a combo box.
Add Data Querying to Forms Sample
Demonstrates options that enable you to navigate within a table and locate data.
Add Data Sorting and Filtering to Forms Sample
Demonstrates the use of advanced querying options in a form as well as options for performing an ascending or descending order sort of data.
Add Miscellaneous Form Buttons Sample
Shows the use of command buttons in applications to perform such tasks as starting and stopping an application, displaying a form, or previewing a report.
Add Navigation to Forms Sample
Demonstrates various options for providing data navigation in forms.
Add Shortcut Menus to Objects Sample
Demonstrates the use of shortcut menus on a form, including using separators, bold text, checked commands, and cascading menus.
Add Web Hyperlinks to a Form Sample
Demonstrates adding hyperlink functionality and launching a Web browser from various controls.
Application Error Handling Sample
Demonstrates application error handling and recording details of the application state.
Create a Visual FoxPro Web Browser Sample
Demonstrates providing a Web browser control in a Visual FoxPro form to display data in HTML.
Create Record Bound Graphs Sample
Shows the use of data from fields to generate graphs on a record-by-record basis.
Create Toolbar Control Effects Sample
Demonstrates various effects you can achieve on toolbar controls when the mouse is moved over them.
Display Data Reporting Output Options Sample
Demonstrates a simple text editor and provides a variety of report output options.
Expanding the SetAll Method Sample
Uses the SetAllx Foundation Class to allow for programmatic setting of object properties based on extended criteria not available with the native SetAll( ) method.
Fun with Access/Assign Methods Sample
Demonstrates ways to use Access/Assign methods in a form.
Fun with OLE Drag and Drop Sample
Shows ways to use OLE drag and drop by adding code to the OLEDragDrop and OLEDragOver events.
Generate HTML Sample
Shows how you can use HTML classes to create Web pages from your data, forms, and reports.
Handle Application Environment Tasks Sample
Demonstrates utilities for saving and restoring critical state settings and handling common application operations.
Handle Common Windowing Tasks Sample
Demonstrates arranging and cascading various forms on the desktop.
Handle Data Conflicts Sample
Demonstrates resolving data conflicts, allowing the user to update data in the form.
OLE Drag-and-Drop Data Formats Sample
Provides data formats for OLE drag and drop source data objects. Shows how to use OLE drag and drop to report data about the dragged item.
Pool Manager Sample
Femonstrates how to use the Pool Manager class, which manages a pool or collection of objects from a class and is useful when you need to use objects repeatedly for a short amount of time.
Retrieve Project Location and Name Sample
Demonstrates providing the user with a place to enter a file and directory location, primarily to create new projects.
Run Word, Excel, and Graph Automation Sample
Demonstrates adding automation routines to an application to create Microsoft Excel pivot tables, Microsoft Word mail merge documents, Visual FoxPro cross-tabs, and Graph charts.
Search Text Using Regular Expressions Sample
Demonstrates the use of regular expression searching in applications.
Tips for the Windows 2000 Logo Program Sample
Shows several Foundation Classes that provide information that might be of use in making applications Windows 2000 Logo compliant.
Track Activities in a Project Sample
Demonstrates how project hooks can be used to track project activity, including adding, deleting, and modifying files.
Treeview/Listbox Drag and Drop Sample
Provides examples of settings for OLEDragMode and OLEDropMode properties of the Treeview and Listbox controls.
Use Access/Assign Methods for Polymorphism Sample
Demonstrates object polymorphism.
Use Array Handling Sample
Demonstrates useful methods for expanding array-handling functionality. This sample uses ACOLSCAN( ) to search a specific column in an array.
Use an Enhanced Openfile Dialog Box Sample
Shows use of the Common File Dialog Foundation Class.
Use Common Application Dialog Boxes Sample
Shows how you can use dialog boxes in applications for common operations such as user logons, splash screens, about boxes, and so on.
Use Edit Buttons for a Complex Form Sample
Demonstrates using buttons for editing forms involving one-to-many relationships.
Use Edit Buttons for a Simple Form Sample
Demonstrates the use of simple data edit buttons for editing simple forms with a single table.
Use Mover List Boxes for Selecting Data Sample
Demonstrates using mover list boxes to load tables and fields from a data source and to handle data sorting.
Use Progress Thermometer Sample
Demonstrates the use of a standard display to show progress in applications.

Related Sections

Visual FoxPro Foundation Classes A-Z
Lists the foundation classes in alphabetical order. Many of these foundation classes are used in the Solutions sample located in the ...\Samples\Solution folder.


Guidelines for Using Visual FoxPro Foundation Classes

The Visual FoxPro .vcx visual class libraries located in the \Ffc\ folder contain a variety of foundation classes for enhancing your Visual FoxPro applications with little or no programming. You can freely distribute the foundation classes with your applications. These foundation classes are contained in the Component Gallery. The Component Gallery provides a quick and easy way to learn more about the properties, events, and methods of each of the foundation classes.

You can also open up a foundation class in the Class Designer or Class Browser to see its structure and code. This is a great way to learn how the foundation class works as well as offering excellent insights into programming with Visual FoxPro.

The following guidelines provide information about how you can add the Visual FoxPro foundation classes to your applications.

Class Types

You need to know the Visual FoxPro base class of a foundation class before you can add the foundation class to your application. Certain foundation classes can be used only as visual objects on forms, while others are non-visual and can be run programmatically without being placed on a form. The Visual FoxPro Foundation Classes documentation indicates the base class of each foundation class so you can determine if the foundation class can be added to a form, or run programmatically in your application. Note that in the Component Gallery you can right-click a foundation class to display a shortcut menu. Choose Properties from the shortcut menu, and then choose the Class tab to display the base class.

The following table lists the Visual FoxPro base classes and how they can be added to your applications.

Category A – base classes that can be dropped onto a form | Category B – base classes that can be dropped onto a form or run programmatically in your application | Category C – base classes that can only be run programmatically in your application
Checkbox | Custom | Form
Combobox | Container | Formset
Commandbutton | Timer | Toolbar
Commandgroup | ProjectHook |
Editbox |  |
Grid |  |
Hyperlink |  |
Image |  |
Label |  |
Line |  |
Listbox |  |
OLE Control |  |
Optionbutton |  |
Optiongroup |  |
Shape |  |
Spinner |  |
Textbox |  |

Adding Foundation Classes to Forms

You will most often add foundation classes to forms. You can drag and drop foundation classes from the Component Gallery, Class Browser, Project Manager, and the Forms Control toolbar onto forms.

Note You can select a foundation class that you have added to a form and then choose Class Browser from the Tools menu to display more information about the foundation class.

Component Gallery The Component Gallery provides the easiest way to add foundation classes to a form. For foundation classes with Category A and B base classes, you can drag the foundation class from the Component Gallery and then drop it on a form. You can also right-click a foundation class in the Component Gallery to display a shortcut menu, and then choose Add to Form to add the foundation class to the form.

Some of the foundation classes have associated builders that are automatically launched to prompt you for more information needed by the foundation class.

Class Browser You can drag foundation classes with Category A and B base classes directly from the Class Browser to a form by using the drag icon in the upper left corner of the Class Browser. Select the foundation class in the Class Browser, click the icon for the foundation class in the upper left corner of the Class Browser, and then drag the icon over the form. Release the mouse button over the form where you would like the foundation class to appear on the form.

Foundation classes dragged from the Class Browser to a form do not launch the associated builder. However, you can launch the builder by after the foundation class has been dropped on the form. Select the foundation class on the form, and then right-click to display the shortcut menu. Choose Builder from the shortcut menu to launch the builder.

Project Manager Foundation classes with Category A and B base classes can be dragged from the Project Manager and dropped on a form.

Foundation classes dragged from the Project Manager to a form do not launch the associated builder. However, you can launch the builder by after the foundation class has been dropped on the form. Select the foundation class, and then right-click to display the shortcut menu. Choose Builder from the shortcut menu to launch the builder.

Form Controls toolbar Foundation classes with Category A and B base classes added to the Form Controls toolbar can be added to a form.

If the Builder Lock is not on, foundation classes dropped from the Form Controls toolbar may launch an associated builder. If the Build Lock is on, you can launch the builder by after the foundation class has been added to the form. Select the foundation class on the form, and then right-click to display the shortcut menu. Choose Builder from the shortcut menu to launch the builder.

Adding Foundation Classes to Projects

When a form containing foundation classes is added to a Visual FoxPro project, the Project Manager automatically adds the visual class libraries containing the foundation classes to the project. However, there are other cases where you may need to add foundation classes to a project. For example, your application may run a Category C foundation class, so the foundation class must be added to the application's project.

Foundation classes can be added to a project from the Component Gallery, by dragging the .vcx visual class library containing the foundation classes from the Windows Explorer, or by choosing the Add button in the Project Manager.

Adding Foundation Classes from the Component Gallery

You can drag a foundation class from the Component Gallery to a project, or you can right-click the foundation class in the Component Gallery to display a shortcut menu, and then choose Add to Project to add the foundation class to the project. When you add a foundation class to a project, the Add Class to Project dialog box is displayed, prompting you with the following options:

Add class to project
Choose this option to add the foundation class and its .vcx class library to the project. Again, this is done automatically for classes dropped onto a form (Categories A and B). For certain Category B and C classes where you plan to call them programmatically from within your application, you will want to choose this option.
Create a new class from selected class
Choose this option to create a new subclass from the foundation class you want to add to the project. This option makes it possible for you to enhance the functionality of the original foundation class, usually by adding additional program code.
Create a new form from selected class
Choose this option for foundation classes with a Form base class (for example, the foundation classes in _dialogs.vcx). This option makes it possible for you to create a new form from the foundation class and enhance the functionality of the original foundation class.

Adding Foundation Classes from the Windows Explorer

A foundation class can be added to a project by dragging the .vcx visual class library containing the foundation class from the Window Explorer to the Project Manager. The visual class library is added to the Class Libraries item in the Project Manager.

Adding Foundation Classes from within the Project Manager

A foundation class can be added to a project by selecting the Classes tab and then choosing the Add button. Select the class library from the \Ffc\ folder that contains the foundation class to add to the project.

Incorporating Classes into your Application

In many situations, most foundation classes do not require additional programming to work with your application. However, you may need to provide additional program code for certain foundation classes (those of Category B and Category C non-visual base classes).

Non-Visual Foundation Classes

For example, foundation classes are often based on the Category B Custom class, and these require additional programming. These non-visual classes often perform common tasks such as checking information in the Windows registry, handling environment settings, managing application errors, and utilizing Automation with other applications, such as performing mail merge with Microsoft Word.

You can drop these non-visual classes onto a form, but you will need to do some additional work in order for them to work with your application. In some cases, a builder is launched when you drag a foundation class onto a form.

The following example demonstrates some of the program code typically necessary to use a non-visual foundation class in your application:

  1. Drag the File Version foundation class from the Component Gallery (Foundation Classes\Utilities folder) onto a form.
  2. Add a command button to the form and add the following code to its Click event:
    WITH THISFORM._FILEVERSION1
   .cFileName = HOME( )+ 'VFP8.EXE'
   .GetVersion( )
   .DisplayVersion( )
ENDWITH
  3. Run the form and click the command button.

You can incorporate a non-visual class in your application without dropping it on a form, as long as you include it in the project used to create the application. The following code illustrates how to executed this same File Version foundation class if the class is not dropped onto a form.

LOCAL oFileVersion
oFileVersion = NewObject('_fileversion', '_utilities.vcx')
WITH oFileVersion
   .cFileName = HOME( )+ 'VFP8.EXE'
   .GetVersion( )
   .DisplayVersion( )
ENDWITH
Note This example assumes that the code can locate the _utilities.vcx class library or from an .app file that is built containing _utilities.vcx.

When you use a non-visual foundation class, you need to know how and when the class is used within your application so it can be scoped correctly. If only a single form uses the class, you can just drag the class onto the form. However, if the class is used by many forms or is used globally by the application, the foundation class should have a global scope in the application so it remains accessible throughout the application. A global scope may also improve performance.

Visual Foundation Classes

You can also programmatically add visual foundation classes, such as those with form base classes, to your application. The following example shows how you can add code to your application to display an About dialog box box.

LOCAL oAbout
oAbout = NewObject('_aboutbox','_dialogs.vcx')
oAbout.Show( )

You can create a subclass of the dialog box foundation class for each of your applications so that you can customize the contents of the dialog box for each application. The following example demonstrates how you can subclass the Aboutbox foundation class:

  1. Drag and drop the Aboutbox class from the Component Gallery (Foundation Classes\Dialogs folder) to the project for your application.
  2. Select Create new form from selected class in the Add Class to Project dialog box that is displayed, and enter name for the form.
  3. Change the Caption property for the new form for your application. Save and close the form.
  4. Add program code (DO FORM FormName) to the procedure that runs the form, such as an About menu item procedure.

    -or-

Drag the Run Form button class from the Component Gallery (Foundation Classes\Buttons folder) onto the form. A builder is launched, and you can specify the name of the form to execute.

If you use the Visual FoxPro 8.0 Application Framework, the Application Builder automatically handles adding forms (both .scx and .vcx form classes). The new Application Wizard or the Component Gallery New Application item installs this framework in the projects they create. The Application Builder interacts directly with the framework and enables you to specify how and where the form is launched.

By using a framework built with the Application Wizard, the Application Builder, and Component Gallery, you have a rich set of tools for creating entire applications with minimal manual coding.

Class Naming Conventions

The Visual FoxPro Foundation classes and their properties and methods use the following naming conventions.

Classes and Class Libraries

Most foundation classes are subclassed from classes in the _base.vcx visual class library, which you can also find in the \Ffc\ folder. The naming conventions for these classes reflect the base class used. For example, a subclass of the Custom class is called _Custom in _base.vcx. All classes use an underscore ( _ ) to preface the name of a class in _base.vcx.

A few class libraries do not contain classes that are subclassed from _base.vcx because these classes are shared with other Visual FoxPro components such as wizards and builders. These classes are contained in class libraries without a preceding underscore, such as Registry.vcx.

Methods and Properties

Methods are often based on an action name such as RunForm. If the name contains several words, for example, RunForm, then capitalization reflects this. Properties are usually prefaced with a single letter characterizing the data type of that particular property. For example, cFileName indicates that the property is of character type. In addition, default values for properties are also set to the appropriate data type. For example, a logical property can be initialized to false (.F.), while a numeric property can be initialized to 0.

Properties of classes that shipped in earlier versions of Visual FoxPro do not strictly adhere to these property-naming conventions, and retain their earlier names to avoid compatibility conflicts with user code referencing these properties.

Enhancing or Modifying FoxPro Foundation Classes

You can enhance or modify the Visual FoxPro foundation classes to meet the needs of your application. However, we recommend that you do not modify the foundation classes themselves. The foundation classes may be periodically updated with new functionality.

Subclassing the Foundation Class

The source code is provided for the foundation classes, so you can subclass any foundation class to override or enhance properties and methods. This choice is common when the behavior of a particular foundation class varies between different applications. One application might use a foundation class directly, while another application uses a subclass of the foundation class.

Updating _base.vcx

If you want to add global changes to the Visual FoxPro foundation classes, you can modify _base.vcx. Since foundation classes are subclassed from _base.vcx, changes to this class library are automatically propagated to the foundation classes. A common set of methods and properties are provided for all the classes in _base.vcx. However, you can alter the classes in _base.vcx if they add desired behavior to your applications (unlike the foundation classes that we recommend that you do not change).

Instead of changing _base.vcx, however, you should redefine the classes in _base.vcx to inherit their behavior from your own custom base classes (rather than from the Visual FoxPro base classes currently used). If you already have a custom class library which subclasses the Visual FoxPro base classes, you can redefine the classes in _base.vcx to inherit from your custom classes so that when components use the _base classes they will inherit from your custom classes too. You can use the Class Browser to redefine the parent class for a particular class.

Note If you redefine the classes to inherit from your own custom base classes, you should add DODEFAULT( ) calls at appropriate locations if you desire that parent class method code be executed.

If you replace the entire _base.vcx class with your own, make sure that you have the same set of named classes; otherwise the foundation classes will have missing links.

See Also

Visual FoxPro Foundation Classes A-Z | Foundation Class Samples | File Version | About Dialog Box Foundation Class | Run Form button


Add a Data-Bound Calendar Sample

File: ...\Samples\Solution\Ffc\Datacal.scx

This sample contains the following classes.

Class | Library | Description
_olecalendar | _datetime.vcx | Displays a calendar that highlights a date, bound to a field in a table.
_nav2buttons | _table.vcx | Displays a pair of navigation buttons.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Data Lookup Combo Boxes Sample

File: ...\Samples\Solution\Ffc\DataLook2.scx

This sample contains the following classes.

Class | Library | Description
_cbodistinctvalues | _dataquery.vcx | Performs a lookup of unique values in the controlsource field to populate a combo box.
_cbolookup | _dataquery.vcx | Performs a lookup of values in a field to populate a combo box.
_nav2buttons | _table.vcx | Displays a pair of buttons that provide GoNext( ) and GoPrevious( ) functions.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Lookup Combobox | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Data Querying to Forms Sample

File: ...\Samples\Solution\Ffc\DataQry.scx

This sample contains the following classes.

Class | Library | Description
_findnextbuttons | _table.scx | Provides a Find/Find Next button set for navigating within a table.
_locatebutton | _table2.vcx | Provides a Locate button to display a dialog box for navigating within a table.
_findbutton | _table.vcx | Provides a generic Find button.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Find Button | Locate Button | Add Data Sorting and Filtering to Forms | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Data Sorting and Filtering to Forms Sample

File: ...\Samples\Solution\Ffc\DataSort.scx

This sample contains the following classes.

Class | Library | Description
_sortbutton | _table2.vcx | Provides buttons to perform an ascending or descending order sort of data.
_navtoolbarclass | _table2.vcx | Provides data navigation controls on a toolbar.
_navmenu | _table2.vcx | Provides a shortcut menu that can include data navigation options.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Data Navigation Object | Data Navigation Buttons | Add Data Querying to Forms | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Encryption to Applications Sample

File: ...\Samples\Solution\FFC\Crypto.scx

This sample shows use of the Crypto Foundation Class that extends the Windows Crypto API routines. You can add encryption to text, files, and data in your applications. A variety of encryption styles are shown as well as file signing.

This sample contains the following classes.

Class | Library | Description
_cryptapi | _ crypt.vcx | Foundation class contains extended properties and methods for adding encryption to your applications. It uses the Windows Crypto API routines.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Miscellaneous Form Buttons Sample

File: ...\Samples\Solution\Ffc\Buttons.scx

This sample contains the following classes.

Class | Library | Description
_shellexecute | _environ.vcx | Runs applications other than Visual FoxPro in the Windows shell.
_mailbtn | _miscbtns.vcx | Uses the MAPI ActiveX control to send an e-mail message from a form.
_cmdlaunch | _miscbtns.vcx | Provides a button to launch an application using the Run command.
_cmdok | _miscbtns.vcx | Releases a form and updates any outstanding buffered data.
_cmdcancel | _miscbtns.vcx | Releases a form and discards any outstanding buffered data.
_cmdhelp | _miscbtns.vcx | Provides a button that displays a Help topic.
_cmdrunform | _miscbtns.vcx | Provides a button to run a form.
_cmdrunreport | _miscbtns.vcx | Provides a button to run a report.

This sample demonstrates adding command buttons to your application. The command buttons perform the following functions:

  • Launch an application
  • Open a Web page in the Windows shell
  • Display a form
  • Preview a report
  • Stop a program with OK or Cancel options
  • Display a Help topic

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Run Form Button | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Navigation to Forms Sample

File: ...\Samples\Solution\Ffc\DataNav.scx

This sample contains the following classes.

Class | Library | Description
_nav2buttons | _table2.vcx | Displays a pair of buttons that provide GoNext( ) and GoPrevious( ) functions.
_nav4buttons | _table2.vcx | Displays two additional buttons that provide GO TOP and GO BOTTOM functions to the _Nav2Button class.
_tablenav | _table.vcx | A non-visual class that provides data navigation to other controls.
_nav2picbuttons | _table2.vcx | Displays a pair of picture buttons that provide GoNext( ) and GoPrevious( ) functions.
_gotobutton | _table2.vcx | Provides a button that displays a Go To dialog box.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Simple Navigation Buttons | Data Navigation Buttons | Add Data Querying to Forms | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Shortcut Menus to Objects Sample

File: ...\Samples\Solution\Ffc\NewMenu.scx

This sample contains the following classes.

Class | Library | Description
_shortcutmenu | _menu.vcx | Dynamically creates shortcut menus.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Shortcut Menu Class | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Web Hyperlinks to a Form Sample

File: ...\Samples\Solution\Ffc\HyperLnk.scx

This sample contains the following classes.

Class | Library | Description
_urlcombobox | Internet.vcx | Creates a combo box for specifying and navigating to Web sites.
_hyperlinklabel | Internet.vcx | Provides Hyperlink functionality and launches a Web browser from a label.
_hyperlinkimage | Internet.vcx | Provides Hyperlink functionality and launches a Web browser from an image.
_hyperlinkcommandbutton | Internet.vcx | Provides Hyperlink functionality and launches a Web browser from a button.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Hyperlink Button | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Application Error Handling Sample

File: ...\Samples\Solution\Ffc\Error.scx

This sample contains the following classes.

Class | Library | Description
_error | _app.vcx | Provides error handling for both object and procedural code.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Create a Visual FoxPro Web Browser Sample

File: ...\Samples\Solution\Ffc\DoHTML.scx

This sample contains the following classes.

Class | Library | Description
_webbrowser4 | _webview.vcx | Provides a Web browser control in a Visual FoxPro form.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Web Browser Control | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Create Record Bound Graphs Sample

File: ...\Samples\Solution\Ffc\GraphRec.scx

This sample contains the following classes.

Class | Library | Description
_graphbyrecord | _utility.vcx | Provides navigation buttons and generates graphs on a record-by-record basis using data from fields.
_nav4buttons | _table2.vcx | Displays two additional buttons that provide GO TOP and GO BOTTOM functions to the _Nav2Button class.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Graph By Record | Data Navigation Buttons | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Create Toolbar Control Effects Sample

File: ...\Samples\Solution\Ffc\MouseFx.scx

This sample contains the following classes.

Class | Library | Description
_mouseoverfx | _ui.vcx | Highlights a control as the mouse is dragged over it.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Display Controls in a Grid | MouseOver Effects | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Display Data Reporting Output Options Sample

File: ...\Samples\Solution\Ffc\Output.scx

This sample contains the following classes.

Class | Library | Description
_showtext | _reports.vcx | Provides a simple text editor in a dialog box that also contains buttons to format or save text, and to close the editor.
_outputdialog | _reports.vcx | Displays a dialog box that prompts the user for a report output option.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Expanding the SetAll Method Sample

File: ...\Samples\Solution\FFC\Setallx.scx

This sample uses the SetAllx Foundation Class to allow for programmatic setting of object properties based on extended criteria not available with the native SetAll( ) method.

This sample contains the following classes

Class | Library | Description
_setallx | _setallx.vcx | Provides wrapper method called SetAllx that adds expanded SetAll capabilities.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Fun with Access/Assign Methods Sample

File: ...\Samples\Solution\Tahoe\Aa_fun.scx

This sample demonstrates ways to use Access/Assign methods in a form.

This sample contains the following classes.

Method | Description
caption_assign | Assigns a new value to a form's Caption property.
mybuttons_access | Returns the index of the button.
oshape_access | Returns the shape of the object.
cshapecolor_access | Returns the color of the object.
this_access | Adds a new property and returns its value.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Use Access/Assign Methods for Polymorphism | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Fun with OLE Drag and Drop Sample

File: ...\Samples\Solution\Tahoe\Oledd.scx

This sample demonstrates ways to use OLE drag and drop by adding code to the OLEDragDrop and OLEDragOver events.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Generate HTML Sample

File: ...\Samples\Solution\Ffc\DoHTML.scx

This sample contains the following classes.

Class | Library | Description
_webform | Webview.vcx | Provides a Visual FoxPro form containing a Web browser control to display HTML text.
_resizable | Controls.vcx | Causes objects dropped onto a form to resize and move with the Form's resize event.
_dbf2html | Internet.vcx | Converts a Visual FoxPro table (.dbf) to HTML.
_frx2html | Internet.vcx | Converts a Visual FoxPro report (.frx) to HTML.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Handle Application Environment Tasks Sample

File: ...\Samples\Solution\Ffc\Environ.scx

This sample contains the following classes.

Class | Library | Description
System Toolbar | _app.vcx | Handles and tracks system toolbars.
_objectstate | _app.vcx | Determines the state of an object, allowing you to save or restore its state.
_traceawaretimer | _app.vcx | Detects if the trace window is open and handles debug timing appropriately.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | System Toolbar | Handle Common Windowing Tasks | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Handle Common Windowing Tasks Sample

File: ...\Samples\Solution\Ffc\WHandler.scx

This sample contains the following classes.

Class | Library | Description
_windowhandler | Ui.vcx | Performs several common window operations, typical for applications.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Window Handler | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Handle Data Conflicts Sample

File: ...\Samples\Solution\Ffc\Conflicts.scx

This sample contains the following classes.

Class | Library | Description
_conflicts | _dataquery.vcx | Displays a dialog box allowing you to resolve conflicting rows encountered during editing sessions under optimistic buffering.
_nav4picbutton | _table.vcx | Displays two additional buttons that provide GO TOP and GO BOTTOM functions to the _Nav2PicButton class.
_resizable | _controls.vcx | Causes objects dropped onto a form to resize and move with the Form's resize event.
_datachecker | _datanav.vcx | Traps for data conflicts.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Conflict Catcher | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


OLE Drag-and-Drop Data Formats Sample

File: ...\Samples\Solution\Tahoe\Querydd.scx

This sample demonstrates how to use OLE drag and drop to report data about the dragged item by adding code to the OLEDragDrop and OLEDragOver events.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Pool Manager Sample

File: ...\Samples\Solution\Ffc\_PoolManager.scx

This sample demonstrates how to use the Pool Manager class, which manages a pool or collection of objects from a class and is useful when you need to use objects repeatedly for a short amount of time.

For more information, see Pool Manager Foundation Class.

Pooling Objects

In this sample, forms are collected in a pool so that you can reuse any form that is available in the pool instead of having to create a new form when you select a customer from the drop-down list.

To use the Pool Manager class in this sample, the following Pool Manager class properties must be set in the Properties window:

cClass = frmCustomer

cClassLibrary = frmCustomer.vcx

Binding to Pool Manager Events

You can bind to _PoolManager events. In this sample, the form's Init event contains code that binds the form's custom handler methods, PoolManager_ObjectRequested and PoolManager_ObjectReturned, to the _PoolManager ObjectRequested and ObjectReturned events so that status can be reported on the sample form:

BINDEVENT(This.PoolManager,"ObjectRequested",ThisForm,"PoolManager_ObjectRequested")
BINDEVENT(This.PoolManager,"ObjectReturned",ThisForm,"PoolManager_ObjectReturned")

Requesting Objects

To request an object from the pool, call the _PoolManager Get method.

To open a customer form in this sample

  1. Select a customer name from the drop-down list.
  2. Click View Customer.

You can open multiple forms by clicking View Customer repeatedly, which requests a form object from the Pool Manager class each time. The form's custom ViewCustomer method contains the following code:

loForm = ThisForm.PoolManager.Get(m.lcCustID)
If Vartype(m.loForm) == "O"
   loForm.Show()
EndIf

In this sample, the Get method returns an unused object that exists in the pool or creates a new object. When a new customer form is created, code in the form's Init event binds to the _PoolManager ObjectRequested and ObjectReturned methods using the private variable THISPOOLMANAGER created in the Get method:

BINDEVENT(THISPOOLMANAGER,"ObjectRequested",This,"PoolManager_ObjectRequested")
BINDEVENT(THISPOOLMANAGER,"ObjectReturned",This,"PoolManager_ObjectReturned")

This event binding makes it possible for the form to call its Hide method instead of the Release method so the form returns to the pool instead of being destroyed.

Returning Objects

To return objects to the pool, call the _PoolManager Free method. In this sample, the form's QueryUnload event occurs when the customer form is closed and returns the form to the pool:

If Vartype(This.oPoolManager) == "O"
   This.oPoolManager.Free(This)
   NoDefault
EndIf

See Also

Visual FoxPro Foundation Classes A-Z | Form Object Properties, Methods, and Events


Retrieve Project Location and Name Sample

File: ...\Samples\Solution\Ffc\GetProject.scx

This sample contains the following classes.

Class | Library | Description
_folder | _controls | Provides a dialog box for retrieving both a file and folder name.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Get File and Directory | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Run Word, Excel, and Graph Automation Sample

File: ...\Samples\Solution\Ffc\Automate.scx

This sample contains the following classes.

Class | Library | Description
Cross Tab | _utility.vcx | Generates a cross-tab report.
Mail Merge | Mailmerge.vcx | Generates a Word mail merge using the core Mail Merge Wizard engine.
Pivot Table | Pivtable.vcx | Generates an Excel pivot table using the core PivotTable Wizard engine.
Graph Object | _utility.vcx | Generates a graph using the core Graph Wizard engine.

This sample demonstrates adding automation routines to your application. Choose the buttons in the dialog box to generate a cross tab summary, an Excel pivot table, a Word mail merge document, and a data graph.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Cross Tab | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Tips for the Windows 2000 Logo Program Sample

File: ...\Samples\Solution\FFC\Logo.scx

Custom applications can be submitted to receive the Windows 2000 Logo. There are a number of requirements your application must adhere to in order to obtain the Logo (see http://www.microsoft.com/winlogo). This sample shows several Foundation Classes that provide information that might be of use in making your application Logo compliant.

This sample contains the following classes

Class | Library | Description
_sysmetrics | _ system.vcx | Returns system information, such as number of mouse buttons, number of monitor, and whether a mousewheel is present.
_userpriv | _ system.vcx | Returns the logged on user access rights (guest, power user, administrator).
_commonfolder | _ system.vcx | Returns path to common system folders such as My Documents.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Track Activities in a Project Sample

File: ...\Samples\Solution\Tahoe\Acttrack.scx

This sample contains the following classes.

Class | Library | Description
activity_tracker | project_hook.vcx | Creates a project and a log to document project activity.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Retrieve Project Location and Name | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Access/Assign Methods for Polymorphism Sample

File: ...\Samples\Solution\Tahoe\Aa_outline.scx

This sample uses Access/Assign methods to demonstrate object polymorphism.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Fun with Access/Assign Methods | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Array Handling Sample

File: ...\Samples\Solution\Ffc\Arrays.scx

This sample contains the following classes.

Class | Library | Description
_arraylib | _utility.vcx | Provides methods for handling certain array operations that are not provided by the Visual FoxPro array functions.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z

See Also

Visual FoxPro Foundation Class Samples | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Common Application Dialog Boxes Sample

File: ...\Samples\Solution\Ffc\Dialogs.scx

This sample contains the following classes.

Class | Library | Description
_splash | _dialogs.vcx | Provides a splash screen for an application.
_login | _dialogs.vcx | Provides a Login box for an application.
_aboutbox | _dialogs.vcx | Provides an About box for an application.
_keywords | _dialogs.vcx | Provides access to the keyword table (.dbf).
_locateitem | _dialogs.vcx | Displays Locate Item dialog boxes for an application.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Password Dialog Box | Splash Screen | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Edit Buttons for a Complex Form Sample

File: ...\Samples\Solution\Ffc\Dataedit.scx

This sample contains the following classes.

Class | Library | Description
picbtns | Wizbtns.vcx | Provides a full set of edit and navigation buttons.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Simple Edit Buttons | Data Edit Buttons | Use Edit Buttons for a Simple Form | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Edit Buttons for a Simple Form Sample

File: ...\Samples\Solution\Ffc\Dataedit2.scx

This sample contains the following classes.

Class | Library | Description
_picformbtns | _wizbtns.vcx | Displays buttons that provide Find, Print, Add, Delete, and Exit functions.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z

See Also

Visual FoxPro Foundation Class Samples | Use Edit Buttons for a Complex Form | Simple Edit Buttons | Data Edit Buttons | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Mover List Boxes for Selecting Data Sample

File: ...\Samples\Solution\Ffc\Movers.scx

This sample contains the following classes.

Class | Library | Description
_tablemover | _movers.scx | Automatically loads tables and fields from the currently selected data source.
_fieldmover | _movers.scx | Automatically loads fields from the current data source.
_sortmover | _movers.scx | Automatically handles sorting of data.
_supermover | _movers.scx | Provides a mover list box with Move, Remove, Move All, and Remove All buttons.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Add Items Interactively to a List Box | Mover | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use Progress Thermometer Sample

File: ...\Samples\Solution\Ffc\Therm.scx

This sample contains the following classes.

Class | Library | Description
_thermometer | _therm.vcx | Provides a standard thermometer progress display class.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Class Samples | Thermometer | Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Working with Microsoft Agent Sample

File: ...\Samples\Solution\FFC\Agent.scx

This sample shows how you can add zest to your applications through the use of animated characters using the Microsoft Agent technology. These characters are similar to Office Assistants and can perform a variety of actions.

This sample contains the following classes

Class | Library | Description
_agent | _agent.vcx | Provides methods for handling operations with Microsoft Agent.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Add Menu Items at Run Time Sample

File: ...\Samples\Solution\Menus\Fillmenu.scx

This sample illustrates adding menu items to a menu at run time.

The menu definition in this sample is defined in the Menu Designer, with a single prompt and an empty submenu named empty_pop.

Code is included to be executed when a user chooses any item in the menu.

PROCEDURE takeaction(cPrompt)
#DEFINE MSG_LOC "You chose " + cPrompt + "."

IF cPrompt = "Release this menu"
   RELEASE PAD dynmenu of _MSYSMENU
ELSE
   WAIT WINDOW MSG_LOC TIMEOUT 1
ENDIF

The code associated with the Click event of cmdRefresh on the form runs the menu.

DO dynamic.mpr

Then, for each item in the list, the code defines a menu item with the prompt and message text.

FOR i = 1 TO THISFORM.lstMenu.ListCount
   DEFINE BAR i OF empty_pop PROMPT (ALLTRIM(THISFORM.lstMenu.List(i,1))) ;
      MESSAGE (THISFORM.lstMenu.List(i,2))
ENDFOR

There is also code to provide the prompt to make it possible for a user to release the menu.

DEFINE BAR i + 1 OF empty_pop PROMPT "\-"
DEFINE BAR i + 2 OF empty_pop PROMPT "Release this menu" ;
   MESSAGE "Remove the Dynamic Items menu from the menu bar."

See Also

Coordinate Menu Items and Toolbar Buttons | Solutions Samples


Add Personalized Menus Sample

File: ...\Samples\Solution\Sedona\Mrumenu.scx

You can add personalized menus similar to Microsoft Office 2000 where only the most common menus items appear in the menu. This sample uses a sample menu (Dvdmenu.mnx), which has the special menu code.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Change Font Attributes Sample

File: ...\Samples\Solution\Toolbars\Format.scx

This example illustrates using a toolbar to set FontName, FontSize, FontBold, FontItalic, ForeColor, and BackColor properties of controls on a form.

The toolbar is the tbrEditing class in ...\Samples\Classes\Samples.vcx. The nAppliesTo property of the class specifies whether to set the properties of the currently selected control, all text boxes and edit boxes on the form, or all controls on the form. The code in the InteractiveChange or Click event of the toolbar controls sets the properties. For example, the following code is associated with the Click event of cmdBold:

IF TYPE("_SCREEN.ActiveForm") = 'O'
   oForm = _SCREEN.ActiveForm
ELSE
   RETURN
ENDIF

DO CASE
   CASE THIS.Parent.nAppliesTo = 1   && Current Control
      oForm.ActiveControl.FontBold = THIS.Value

   CASE THIS.Parent.nAppliesTo = 2   && Text and edit boxes
      oForm.SetAll('FontBold', THIS.Value, 'TEXTBOX')
      oForm.SetAll('FontBold', THIS.Value, 'EDITBOX')

   CASE THIS.Parent.nAppliesTo = 3   && All Controls
      oForm.SetAll('FontBold', THIS.Value)
ENDCASE

The only code in the form is associated with the GotFocus event of the controls. Each GotFocus event contains the following line of code:

THISFORMSET.tbrEditing.Refresh(THIS)

The Refresh method of tbrEditing sets the values of the editing controls of the toolbar to reflect the current settings of the object whose reference is passed in as a parameter.

See Also

Font Combobox | Fontsize Combobox | Solutions Samples


Coordinate Menu Items and Toolbar Buttons Sample

File: ...\Samples\Solution\Menus\Toolmenu.scx

This sample illustrates coordinating menu items and toolbar buttons that provide the same functionality.

Sometimes you'll want to make particular functionality accessible from both menu items and toolbar buttons. For example, in Visual FoxPro you can save a file by choosing the Save toolbar button or by choosing Save from the File menu.

The three components to this sample are as follows:

Component | Description
Toolmenu.scx | the form
tbrBackColor in Solution.vcx | the toolbar
Toolmenu.mnx | the menu

In the Init event of the form, a toolbar object is created whose object reference is a property on the form, oToolbar.

SET CLASSLIB TO ..\solution
This.oToolbar = CREATEOBJECT('tbrbackcolor')

* Position the toolbar and show it
THIS.oToolbar.Left = THIS.Left + 10
THIS.oToolbar.Top = THIS.Top - 50
THIS.oToolbar.Visible = .T.

* Push the current menu on the stack so it can be
* restored in the Destroy event of the form.
PUSH MENU _MSYSMENU

* Run the menu
DO toolmenu.mpr

Rather than coding duplicate functionality in the toolbar and the menu, updating it both places if changes are required, the code associated with the menu items calls the code associated with the toolbar buttons. For example, the following command is associated with the first menu item:

_VFP.ActiveForm.oToolbar.cmdRed.click

The SKIP FOR clause of the menu items causes them to be disabled when the associated toolbar button is disabled. For example, the following expression is associated with the SKIP FOR clause of the first menu item:

!_VFP.ActiveForm.oToolbar.cmdRed.Enabled

See Also

Item Locator | Format Toolbar | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Create Dynamic Shortcut Menus Sample

File: ...\Samples\Solution\Menus\Dynshort.scx

This sample illustrates an alternative way to create shortcut menus.

The shortcut menus in the Display Shortcut Menus sample were created in the Menu Designer. The advantages of using the Menu Designer are ease of design, the ability to create cascading menus, and simple integration on a form. With the Menu Designer, however, you need a separate .mnx, .mnt, and .mpr file for each shortcut menu. If you make a change, you need to generate and compile the menu code again.

The dynamic shortcut menu engine is a custom class that you can add to any form: menulib in ...\Samples\Classes\Utility.vcx. The ShowMenu method of this class defines a menu and displays it at the MousePointer location as determined by the MROW( ) and MCOL( ) functions.

In the RightClick event of the objects you want to create a shortcut menu for, do the following:

  1. Create an array with the shortcut menu items.
  2. Pass the array to the ShowMenu method of the menulib class.
  3. Process the user choice by checking the BAR( ) value.

For example, the following code is associated with the RightClick event of the form:

LOCAL laMenu[5]

laMenu=""
laMenu[1]="\<Center"
laMenu[2]="\<Font..."
laMenu[3]="\<Minimize"
laMenu[4]="\-"
laMenu[5]="E\<xit"
THISFORM.oMenuShortcut.ShowMenu(@laMenu)
DO CASE
   CASE BAR()=1
      THISFORM.AutoCenter=.T.
   CASE BAR()=2
      THISFORM.SetFont
   CASE BAR()=3
      THISFORM.WindowState=1
   CASE BAR()=5
      THISFORM.Release
ENDCASE

See Also

Add Shortcut Menus to Objects | Display Shortcut Menus | Solutions Samples


Disable or Display a Check beside a Menu Item Sample

File: ...\Samples\Solution\Menus\Chkmenu.scx

This sample illustrates dynamically disabling menu items and displaying check marks beside specific menu items.

The menu in this sample was created in the Menu Designer and is run when the form is initialized.

DO chkmenu.mpr

To disable a menu item, include an expression that evaluates to false (.F.) in the SET SKIP OF command. For example, the following line of code in the InteractiveChange event of a check box issues SET SKIP OF with the inverse of the value of the check box, disabling the menu item when the check box is not selected.

SET SKIP OF BAR 1 OF checkitems !THIS.Value

To display a check mark beside a menu item, include an expression that evaluates to true (.T.) after the TO keyword of the SET MARK OF command. For example, the following line of code in the InteractiveChange event of a check box issues the SET MARK OF command with the Value property setting of the check box.

SET MARK OF BAR 1 OF checkitems TO THIS.Value

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Display Shortcut Menus Sample

File: ...\Samples\Solution\Menus\Shortcut.scx

This sample illustrates displaying shortcut menus when a user "right-clicks" an object. When you have created a shortcut menu in the Menu Designer, the code in the form to activate the menu is very simple. The following code is associated with the RightClick event of the form:

DO frmshort.mpr WITH THIS

The following code is associated with the RightClick event of the edit boxes on the form:

DO edtshort.mpr WITH THIS

The FRMSHORT Menu

The FRMSHORT menu was designed to take an object parameter. The following code is included in the menu's setup code:

PARAMETER oREF
#PREPOP

The #PREPOP generative directive causes the code in the menu's cleanup to be generated before the ACTIVATE POPUP command. This makes it possible for you to disable or enable menu items at run time, as well as display check marks beside menu items.

The code associated with the menu items sets properties of the object that was passed to the .mpr as a parameter. For example, the Always on top item sets the AlwaysOnTop property of the form.

The following code, included in the menu's cleanup code, displays a check mark beside the Always on top item when the form's AlwaysOnTop property is set to true (.T.).

SET MARK OF BAR 4 OF frmshort TO oRef.AlwaysOnTop

The EDTSHORT Menu

The EDTSHORT menu also accepts an object parameter in its setup code. Because there is no need to display a check mark beside the items in this menu, the #PREPOP generator directive is not used.

For an alternative way to display shortcut menus, see the Create Dynamic Shortcut Menus sample.

See Also

Solutions Samples | Create Dynamic Shortcut Menus | Visual FoxPro Foundation Classes A-Z


Use Style Toolbars Sample

File: ...\Samples\Solution\Sedona\Newtbars.scx

This sample shows a custom toolbar that has a picture button drop-down similar to those on Microsoft Office style toolbars. These drop-downs can be created easily by combining two command buttons and using the VisualEffect property to show them working together in tandem. A standard popup menu can be used for the actual drop-down itself.

This sample contains the following classes

Class | Library | Description
tbar1 | newtbars.vcx | Contains toolbar class showing picture dropdown sample using simple command buttons.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Print a Percent of Total in a Report Sample

File: ...\Samples\Solution\Reports\Percent.frx

The sample report, Percent.frx, shows one way to calculate and display values at the beginning report before all the records from the record source have been printed. This sample report prints a percentage based on a total that is usually calculated and printed at the end of a report.

The sample report uses the tables, EMPLOYEE and ORDERS, in its Data Environment. A public variable and expressions using the ORDER_AMT field are used to calculate the percentages.

To sort the data appropriately for the group defined in the report, the Order property on Cursor1 is set to the EMP_ID index.

The public variable, nTotalSales, defined in the Init event of Cursor2, stores the total for all orders. The variable is declared public to make it visible beyond the Cursor2 Init code.

A field control in the Group Footer band calculates and displays the percentage for each employee using the following expression:

STR(INT((emp_total / nTotalSales)*100)) + " " + "%"

A field control in the Summary band calculates and displays the total percentage for all employees using the following expression:

STR(INT((nTotalSales / nTotalSales)*100)) + " " + "%"

See Also

Print an Invoice | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print an Invoice Sample

File: ...\Samples\Solution\Reports\Invoice.frx

This report shows an invoice report that uses a view to combine information from multiple tables, a function to collect data from the user, and a one-to-many report layout. When the report is run, the view runs first and prompts the user for a date range using a function called Datepick.prg. After the user provides the dates, the view runs and selects the records to display in the report.

The Record Source The view, INVOICE, used in this report resides in the TESTDATA database provided with the Solution project. This view combines data from four tables, CUSTOMER, ORDERS, ORDITEMS, and PRODUCTS. To filter the tables for records within a date range, the view has two filters each with a parameter, dStart_Date and dEnd_Date.

The Data Environment The view is included in the data environment. To store values collected for the view and to restore the path setting, the BeforeOpenTables method of the data environment declares three public variables: dStart_date, dEnd_Date, and cOldPath. The first two match the parameters specified in the view. The third, cOldPath, saves the current path setting so the path can be restored in the Destroy method. The path is then changed so the report is able to find the function, which prompts the user for a range of dates. The final command runs the function.

The Destroy method of the data environment has public variables for the start and end dates, path setting to return the default path to what it was before the report was run, and release statements for all three of the public variables.

The Datepick.prg This function defines and runs a form class called frmDATEPICK. The form class includes four combo boxes that display and collect values to use in the public variables, dStart_Date and dEnd_Date. The four variables collected are nFromMonth, nFromYear, nToMonth, and nToYear. These variables store the user input and are used to determine the value of dStart_Date and dEnd_Date. The function also checks to make sure the user entered values for each element of the date and verifies that the end date is after the start date.

The Report Layout In the report layout, a Group Header band holds the controls for the customer information, the Detail band has the controls for the order items, and the Group Footer band holds the controls that display the calculated values for the invoice.

To format the address appropriately, an expression in the control concatenates several fields with appropriate punctuation. To calculate values in the Group Footer band, two report variables, nSubtotal and nDiscount, store values for the subtotal and the percentage discount.

See Also

Print Customer Mailing Labels | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print Customer Mailing Labels Sample

File: ...\Samples\Solution\Reports\Cust.lbx

This sample illustrates printing mailing labels, one for each customer in the customer table.

The labels include the following four items:

  • Company
  • Contact + ", " + Title
  • Address
  • City + ", " + Region+ " " + Country

The logo is displayed on each label by using the OLE container control.

See Also

Print an Invoice | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print Data Dictionary Information Sample

File: ...\Samples\Solution\Reports\Dbctofrx.scx

This sample illustrates a simple way to generate a report with the contents of a Visual FoxPro database (dbc). Simply pick a .dbc file when prompted and a report will be generated for you to preview. You can click on the Print button to generate a hard copy of it.

The sample creates a temporary cursor and inserts new records as the .dbc is scanned. Table and view records are added along with their associated field and index information.

See Also

Print an Invoice | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print in Catalog Format Sample

File: ...\Samples\Solution\Reports\Wrapping.frx

The sample report, Wrapping.frx, prints an employee directory and shows how you can wrap text around graphics, alternate the print position of controls, and float controls below fields that stretch. The data environment for this report contains the EMPLOYEE table from the Testdata.dbc in the Solution project.

The Report Layout

The Title band holds the name and description of the report. The Detail band holds the field and label controls that print for each record. For each record the report displays the following four categories of information:

  • Employee name and title
  • Biography
  • Box of quick reference information such as phone and address
  • Photograph

After printing the name and title, this report wraps the text of the biography around the photograph, alternates information from left to right, and floats the box down the page relative to the biography.

Wrap Text around Graphics

To wrap the memo field around the picture, the report uses two field controls to display the contents of the memo field. The first control is above the picture to display two lines of text. The second field is also sized to show two lines of text, but is narrower and positioned next to the picture.

The first field control prints all of the words in the memo field up to the position where a break should occur to continue the words in the second control. The expression is shown below.

LEFTC(employee.notes,nWrapCharPos)

The second field control prints the remaining words from the memo field. The expression for the second field control is shown below.

LTRIM(RIGHTC(employee.notes,(nMemoLen-(nWrapCharPos))))

The expressions for the controls use report variables to determine the words the controls display from the memo field.

  • nFirstMemoLen determines the number of characters that can be displayed in the first field without truncating. For this report, the variables value is always 185. If you use this in your own report, you will need to change this constant to match the maximum number of characters you want above the picture.
  • nMemoLen determines the length of the memo field for the current record. This variable's expression is LENC(employee.notes).
  • nSpace determines the character position of the first space after the characters displayed in the first control. This variable's expression is AT_C(CHR(32),RIGHTC(employee.notes,(nMemoLen - nFirstMemoLen))).
  • nWrapCharPos determines the character position within the memo field where the break should occur. This variable's expression is nSpace + nFirstMemoLen.

Alternate the Position of Printed Objects

In this report, the positions of the employee biography, the quick reference group, and the photograph alternate from left to right with each record. To alternate the positions, the report has two sets of controls for the parts of the report that alternate. Because two controls are used to wrap the biography text, the first control does not alternate and, therefore, does not need to be included in the two sets.

One set of controls specifies printing with the photograph on the left side. A second set specifies the printing for the photograph on the right side. The controls in both sets use a report variable, nCounter, that calculates a count which determines when the set should print. One set prints when nCounter's value is 0; the other when the value is 1. The Print When expression for the first set of controls is MOD(nCounter,2) = 0. For the second set, the expression is MOD(nCounter,2) = 1.

Float Controls below Controls That Stretch

This report prints the box of information that prints below the biography. Since the length of the biography varies with each record, the control that displays the biography information next to the picture is set to stretch and uses only the space necessary to print the contents of the field. The box that prints below the biography floats down the page depending on the length of the biography. This box is a group of field, label, and rectangle controls. To prevent the biography from printing on top of the group, the field position for each of the controls in the group is set to float.

See Also

Print Report Details in a Ledger Style | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print Product Orders By Quarter Sample

File: ...\Samples\Solution\Reports\Ordgraph.scx

This sample illustrates generating and printing graphs on the fly. Visual FoxPro makes it possible for you to add graphs to forms as either OleControls or OleBoundControls. The latter representing a graph, which is bound to data using a General field.

If you intend to use the Visual FoxPro report writer to print graphs, you need to use General fields to store the graphs. The easiest way to create a new graph in a General field is to use the APPEND GENERAL command, for example:

APPEND GENERAL graphfield CLASS "msgraph"

The example above will create a graph in a General field, however, it will not contain your data. The DATA clause actually passes data to the graph.

The following code loops through records already containing data and constructs a string to pass to the graph with APPEND GENERAL .... DATA:

SCAN NEXT m.totrecs
   m.cData = ""+TAB+m.f2+TAB+m.f3+TAB+m.f4+CRLF+;
      EVAL(fields(1))+ TAB + ;
      ALLTRIM(STR(EVAL(field(2))))+ TAB +;
      ALLTRIM(STR(EVAL(field(3))))+ TAB + ;
      ALLTRIM(STR(EVAL(field(4))))
   m.cDetails = ;

f2+"-" +ALLTRIM(STR(EVAL(FIELD(2)))) ;
      + CRLF + f3+"-" +ALLTRIM(STR(EVAL(FIELD(3)))) ;
      + CRLF + f4+" - "+ALLTRIM(STR(EVAL(FIELD(4)))) +CRLF
   INSERT INTO prodsales ;
VALUES(SalesData.prod_name,tmpgrph.graph,m.cDetails)
   APPEND GENERAL prodsales.sales DATA m.cData
ENDSCAN

Once you have a table or cursor containing a General field with your graphs, you can then print it to a Visual FoxPro report using the REPORT FORM command. You cannot include an ActiveX control in a report.

See Also

Create Record Bound Graphs | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Print Report Details in a Ledger Style Sample

File: ...\Samples\Solution\Reports\Ledger.frx

The report, Ledger.frx, prints an employee phone list that alternates printing a gray background behind records. The data environment for this report contains the EMPLOYEE table from the Testdata.dbc in the Solution project.

In the report layout, the Page Header band has label controls that print the report title, description, and column headings. The Detail band has the field and label controls that print the information for each employee.

To print with ledger style, the controls for the employee information are on top of a rectangle. The rectangle's color is gray and its mode is opaque. The report prints the rectangle for every other record by evaluating an expression in the Print When options of the rectangle control. The expression is MOD(nCounter,2) = 1 which uses a report variable, nCounter that increments for each record printed. The report uses the value of this variable to determine when to print the rectangle.

See Also

Print in Catalog Format | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Use Conditional Formatting in a Report Sample

File: ...\Samples\Solution\Reports\Colors.frx

This sample report demonstrates how you can use Print When conditions for controls to change field formatting based on the values in the record. The sample prints a "Product Inventory Report." If the product item is discontinued, it is printed in strikeout. If the In Stock amount is below the reorder level and the product is not discontinued, the item is printed in red. Otherwise, the product item is printed in standard black.

This report uses the table, PRODUCTS, from the database, TESTDATA, in the Data Environment. The Detail band has field controls for the product information such as ID, name, amount in stock, and amount on order. Another field control prints a reminder when the stock goes below a set reorder amount.

To handle the three cases, three sets of field controls for the product information are layered on top of each other in the Detail band. For the first set, the text color is red; for the second, the color is black; and for the third, the font effect is Strikeout.

Each control set has a different Print When expression.

  • For the plain black fields:
    (products.in_stock > products.reorder_at) and products.discontinu = .F.
  • For the strikeout fields:
    products.discontinu = .T.
  • For the red text color fields:
    products.in_stock <= products.reorder_at and products.discontinu = .F.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Get Application Information from the Windows Registry Sample

File: ...\Samples\Solution\WINAPI\Regfile.scx

This sample shows how to access the Windows registry using the native Visual FoxPro DECLARE-DLL command. The Windows API provides a number of functions you can use to access, read and write to the registry. The Registry.prg class library in ...\Samples\Classes contains a complete set of these functions you can use in your applications.

In this specific sample, you can use registry functions to check for the existence of a particular application. For example, you might want to distribute an application, which relies on using Excel to automate the creation of a Pivot Table. The registry contains the location, version, and other information about a particular application.

See Also

Registry Access | Application Registry | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Get Version Information Sample

File: ...\Samples\Solution\WINAPI\Getver.scx

This sample makes it possible for you to display version information from a .dll or .exe.

A new function called GetFileVersion( ) has been added to Foxtool.fll ,which makes it possible for you to obtain version information on a file. The following code illustrates how you can call the function. See Tools\Foxtools.hlp for details on the specific array elements.

SET LIBRARY TO FoxTools ADDITIVE
DIMENSION aFileVer[12]
nRetVal = GetFileVersion(GetFile("EXE"),@aFileVer)
IF nRetVal = 0
   DISPLAY MEMO LIKE aFileVer
ENDIF
SET LIBRARY TO
Note Visual FoxPro now makes it possible for you to add File Version information to EXE and DLL files at build time. This version information is stored in a file resource and can be accessed using the Windows Explorer. EXE files created in Visual FoxPro 3.0 will not have a file version resource.

See Also

File Version | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Play Multimedia Files Using MCI Commands Sample

File: ...\Samples\Solution\Forms\Mci_play.scx

This sample form uses MCI (Multimedia Command Interface) to play multimedia files and can play any visual or non-visual media that is installed on your system. However, the GETFILE( ) function prompts for the most common media files of .avi, .wav, .mov, and .mid. To choose another file, select All Files and choose the desired file. To locate documentation for the MCI commands, search for "Multimedia Commands" in the MSDN Library (<a href="http://msdn.microsoft.com/library/">http://msdn.microsoft.com
/library</a>).

The following three Windows API functions are declared in the Init of the form:

  • mciSendString
  • mciGetErrorString
  • SetWindowPos

The DoMCI method of the form executes an MCI command that is passed in as a parameter.

Classes

You can open the form to see all the code necessary to run multimedia files, but the functionality has also been extracted into classes that you can easily incorporate into your own applications.

VideoFrame Class

The VideoFrame class in the Visual FoxPro ...\Samples\Classes\Samples.vcx class library can be used to play a visual multimedia file, such as a Video for Windows file. The class makes it possible for you to position and size the video to be played, and then provides built-in methods to easily play the media file.

For an example of using this class, see Video.scx in the Visual FoxPro ...\Samples\Solution\Forms directory.

Property | Description
AutoOpen | Specifies whether the video file should automatically open and display when the object is instantiated. The default value is true (.T.).
AutoPlay | Specifies whether the video file should automatically play when it is opened. The default value is true (.T.).
AutoRepeat | Specifies whether the video file will loop the video. Setting this to .T. will cause the video to play continuously. The default value is false (.F.).
ControlSource | Specifies a Field that contains the video file reference. If empty, the class expects a static file name to be in the VideoFile property.
MCIalias | Specifies the alias to be used by MCI. If left empty, the alias defaults to the Name property of the class. Normally this can be left empty, but if the user wants to play the same video file twice at the same time, a different alias would need to be specified for each.
VideoFile | Holds the name of a video file to play, for example: "D:\...\Samples\Solution\FORMS\FOX.AVI"
Method | Description
CloseVideo | Closes the video file and releases all resources associated with it.
DoMCI | Called by the other methods to execute MCI commands. It also can be called by a user to execute a specific MCI command.
OpenVideo | Opens the video file and shows the first frame.
PauseVideo | Pauses a playing video. The video can be restarted by using the PlayVideo method.
PlayVideo | Plays the video file. The video file must be opened in the OpenVideo method before it can be played.
SetPosition | Makes it possible for the user to specify the position of the media file. It can be executed at any time after the video file has been opened. Valid values are "Start", "End", or a specific millisecond into the video.

Sound Player Class

This class is also contained in the ...\Samples\Classes\Samples.vcx class library. It can be used to play a non-visual multimedia file, such as a waveaudio file. The class makes it possible for you to specify the file to be played, and then provides built-in methods to easily play the media file.

Property | Description
AutoOpen | Specifies whether the sound file should be automatically opened and displayed when the object is instantiated. The default value is true (.T.).
AutoPlay | Specifies whether the sound file should be automatically played when it is opened. The default value is true (.T.).
AutoRepeat | Specifies whether the sound file plays continuously. The default value is false (.F.).
ControlSource | Specifies the column that contains the sound file reference. If empty, the class expects a static file name to be in the SoundFile property.
MCIAlias | Specifies the alias to be used by MCI. If left empty, the alias defaults to the Name property of the class. Normally this can be left empty, but if the user wants to play the same sound file twice at the same time, a different alias would need to be specified for each.
SoundFile | Holds the name of a sound file to play, for example: "C:\WINDOWS\CHIMES.WAV"
Method | Description
OpenSound | Opens the sound file.
PlaySound | Plays the sound file. The file must be opened with the OpenSound method before it can be played.
PauseSound | Pauses the playing of a sound file. Play can be contiued by calling the PlaySound method.
SetPosition | Makes it possible for the user to specify the position of the media file. It can be executed at any time after the file has been opened. Valid values are "Start", "End", or a specific millisecond into the sound.
CloseSound | Closes the sound file and releases all resources associated with it.

See Also

Solutions Samples | Visual FoxPro Foundation Classes A-Z


Read and Write Visual FoxPro Registry Values Sample

File: ...\Samples\Solution\WINAPI\Regfox.scx

This sample shows how to access the Windows Registry using the native Visual FoxPro DECLARE-DLL command. The Windows API provides a number of functions you can use to access, read and write to the registry. The Registry.prg class library in ...\Samples\Classes contains a class definition that exposes these functions as methods that you can call in your applications.

The contents of the Visual FoxPro Options dialog, Field Mapping settings, and Label definitions (to name a few) are stored in the Registry. Since many of these settings are not available using SET functions, you can use Registry functions to access these values. The following code populates an array of all the settings in the Options dialog:

regfile = HOME(2)+"classes\registry.prg"
SET PROCEDURE TO (m.regfile) ADDITIVE
oReg = CreateObject("FoxReg")

DIMENSION aFoxOptions[1,2]
m.nErrNum = oReg.EnumFoxOptions(@aFoxOptions)

The following code calls the SetFoxOption method of the FoxReg class (defined in Registry.prg) to set TALK OFF in the registry:

regfile = HOME(2)+"classes\registry.prg"
SET PROCEDURE TO (m.regfile) ADDITIVE
oReg = CreateObject("FoxReg")

m.nErrNum = oReg.SetFoxOption("TALK","OFF")

See Also

Get Application Information from the Windows Registry | Registry Access | Application Registry | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Read ODBC Registry Values Sample

File: ...\Samples\Solution\WINAPI\Regodbc.scx

This sample shows how to access the Windows Registry using the native Visual FoxPro DECLARE-DLL command. The Windows API provides a number of functions you can use to access, read and write to the registry. The Registry.prg class library in ...\Samples\Classes contains a class definition that exposes these functions as methods that you can call in your applications.

The Registry contains a listing of all installed ODBC drivers and data sources. If your application relies on using ODBC, then you might want to perform a Registry check to see if a particular driver or data source is installed. This sample shows how to query for ODBC information.

LOCAL oReg,regfile,nErrNum,lDrivers
PUBLIC aODBCData

regfile = HOME(2)+"classes\registry.prg"
SET PROCEDURE TO (m.regfile) ADDITIVE

oReg = CreateObject("ODBCReg")

DIMENSION aODBCData[1]
m.nErrNum = oReg.GetODBCDrvrs(@aODBCData)

See Also

Registry Access | ODBC Registry | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Set VFP Shell Open Commands Sample

File: ...\Samples\Solution\Winapi\Shellopen.scx

This sample is actually a utility that can be used to change the Shell Open settings of various file types (extensions). The Shell Open settings control how a file is opened when you double-click that file in the Windows Explorer. Prior to Visual FoxPro 7, Visual FoxPro defaults always opened a file in an already running instance of Visual FoxPro. Starting with Visual FoxPro 7, defaults open that file in a new instance. This sample makes it possible for you to control at a file type level how you want files opened.

This sample contains the following classes

Class | Library | Description
registry | registry.vcx | Contains routines to access the Windows Registry.

For details on all classes available in the foundation classes, see Visual FoxPro Foundation Classes A-Z.

See Also

Visual FoxPro Foundation Classes A-Z | Guidelines for Using Visual FoxPro Foundation Classes


Use API Functions that Require a STRUCT Sample

File: ...\Samples\Solution\Winapi\Systime.scx

This example illustrates calling the Windows API function GetSystemTime. GetSystemTime fills in a structure of WORD (16-bit unsigned integer) values with system time information.

C Function Declaration and Struct Definition

VOID GetSystemTime(
    LPSYSTEMTIME lpSystemTime    // address of system time structure
   );

This is the struct definition:

typedef struct _SYSTEMTIME {
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
} SYSTEMTIME;

Calling the Function in Visual FoxPro

The Visual FoxPro code passes GetSystemTime, a reference to a character variable, which is filled in with the WORD values.

* Visual FoxPro Code: cmdSystemTime.Click
DECLARE INTEGER GetSystemTime IN win32api STRING @
cBuff=SPACE(40)

GetSystemTime(@cBuff)

To retrieve the information from the character variable, cBuff, the following code converts 8-bit ASCII characters for year and month in the variable into 16-bit equivalents.

THIS.Parent.lblYear.Caption = ALLTRIM(STR(ASC(SUBSTR(cBuff,2)) * 256 + ASC(SUBSTR(cBuff,1))))

THIS.Parent.lblMonth.Caption = MONTH_LOC + ALLTRIM(STR(ASC(SUBSTR(cBuff,4)) * 256 + ASC(SUBSTR(cBuff,3))))

See Also

Use API Functions That Require Pointers to Arrays | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Use API Functions That Require Pointers to Arrays Sample

File: ...\Samples\Solution\Winapi\Syscolor.scx

This example uses two Windows API functions to first get the system color settings (GetSysColor) and then to reset the system colors to new values (SetSysColors). Two of the three arguments required by SetSysColors are pointers to native C arrays.

GetSysColor

The GetSysColor function accepts an integer parameter, a number between 0 and 18, and returns a DWORD (32-bit unsigned integer) indicating the current color setting.

DWORD GetSysColor(
    int nIndex    // display element
   );

nIndex is a value representing an area of the interface, as defined in the following list:

#define COLOR_SCROLLBAR         0
#define COLOR_BACKGROUND        1
#define COLOR_ACTIVECAPTION     2
#define COLOR_INACTIVECAPTION   3
#define COLOR_MENU              4
#define COLOR_WINDOW            5
#define COLOR_WINDOWFRAME       6
#define COLOR_MENUTEXT          7
#define COLOR_WINDOWTEXT        8
#define COLOR_CAPTIONTEXT       9
#define COLOR_ACTIVEBORDER      10
#define COLOR_INACTIVEBORDER    11
#define COLOR_APPWORKSPACE      12
#define COLOR_HIGHLIGHT         13
#define COLOR_HIGHLIGHTTEXT     14
#define COLOR_BTNFACE           15
#define COLOR_BTNSHADOW         16
#define COLOR_GRAYTEXT          17
#define COLOR_BTNTEXT           18
#define COLOR_INACTIVECAPTIONTEXT 19
#define COLOR_BTNHIGHLIGHT      20

#if(WINVER >= 0x0400)
#define COLOR_3DDKSHADOW        21
#define COLOR_3DLIGHT           22
#define COLOR_INFOTEXT          23
#define COLOR_INFOBK            24

#define COLOR_DESKTOP           COLOR_BACKGROUND
#define COLOR_3DFACE            COLOR_BTNFACE
#define COLOR_3DSHADOW          COLOR_BTNSHADOW
#define COLOR_3DHIGHLIGHT       COLOR_BTNHIGHLIGHT
#define COLOR_3DHILIGHT         COLOR_BTNHIGHLIGHT
#define COLOR_BTNHILIGHT        COLOR_BTNHIGHLIGHT
#endif /* WINVER >= 0x0400 */

SetSysColors

The SetSysColors function requires three arguments: the number of elements in two arrays and the addresses of the two arrays.

BOOL WINAPI SetSysColors(
    int cElements,                  // number of elements to change
    CONST INT *lpaElements,         // address of array of elements
    CONST COLORREF *lpaRgbValues    // address of array of RGB values
   );

Calling SetSysColors in Visual FoxPro

The following code is extracted from cmdSetSysColors.Click:

DECLARE INTEGER SetSysColors IN win32api INTEGER, STRING, STRING

Construct the elements of the first array in a character variable.

cElements = ""
FOR i = 0 TO 18
   cElements = cElements + THISFORM.DecToHex(i)
ENDFOR

Construct the elements of the second array in a character variable. The cursor that is scanned was filled with GetSysColor values in the Init of the form.

cColors = ""
SCAN
   cColors = cColors + THISFORM.DecToHex(INT(color))
ENDSCAN

=SetSysColors(18,cElements,cColors)

See Also

Use API Functions that Require a STRUCT | Solutions Samples | Visual FoxPro Foundation Classes A-Z


View Type Library Information Sample

File: ...\Samples\Solution\Winapi\Typelib.scx

The TYPELIB sample uses a Visual FoxPro class named Typelib, which is stored in ...\Samples\Classes\Typelib.vcx. This container class has an ActiveX control called FoxTlib that contains a number of methods to read Type Library information from any .dll, .exe, or .tlb file.

The Typelib wrapper class saves you time by handling much of the dirty work for you. There is a method called ExportTypeLib in this class, which exports the contents of a specified Type Library to a text File.

THISFORM.typelib1.TypeLibName = THISFORM.txtFileName.Value
THISFORM.typelib1.ExportTypeLib( )

If you take a look at the generated text file, you will notice that a Type Library can consist of multiple Type Infos. Each Type Info represents a specific class. When you generate a new EXE or DLL from a project using Visual FoxPro, each class in the project, which is marked as OLEPUBLIC will generate a separate Custom OLE Server.

Note You only have a single .exe/.dll file, however, this file can contain multiple servers (one for each OLEPUBLIC class). And Visual FoxPro generates a single TLB file for the project. This Type Library file contains a separate Type Info for each OLEPUBLIC class.

Within each Type Info (OLEPUBLIC class), there are also Function descriptions. These represent all of the properties and methods of a class. For methods, the Type Library contains both parameter and return types. Some of the possible types are Boolean, string, and variant. Because Visual FoxPro does not strong type memory variables, many of the types used in your custom methods will be variant.

If you take a close look at the functions exported, you will notice double entries for many of the properties. This is because users can set or get the value of this property. And some languages such as Visual Basic make it possible for you to have code executed when one of these properties is accessed or assigned. Hence, the Type Library will represent a single property with 2 entries. If only a single entry exists, then that property is read-only. Properties and methods, which are marked as Hidden or Protected will not appear in the Type Library.

See Also

Type Library | Solutions Samples | Visual FoxPro Foundation Classes A-Z


Walkthroughs

Walkthroughs give step-by-step instructions for common scenarios, which makes them a good place to start learning about Visual FoxPro or a particular feature area.

In This Section

Walkthrough: Creating Applications with Visual FoxPro
Provides steps for creating a simple program, including moving data and creating forms, and shows how to use it as the basis for an application.
Walkthrough: Creating Reports with Visual FoxPro
Provides steps for creating reports using the Report wizard and the Report designer, and discusses issues to consider when planning and creating reports.
Walkthrough: Retrieving Data from Different Data Sources
Provides steps for retrieving data from Visual FoxPro native tables or data using Open Database Connectivity (ODBC), ActiveX Data Objects (ADO), or XML data sources.
Walkthrough: Creating Tables with Visual FoxPro
Provides steps for creating tables for new and existing data and discusses the many tools used to access and manipulate all kinds of data quickly.
Walkthrough: Creating XML Web Services with Visual FoxPro
Provides steps for how to create and publish a Visual FoxPro COM server as an XML Web service.
Walkthrough: Creating a Visual FoxPro Application Setup Program Using InstallShield Express
Provides steps for packaging and deploying your applications using InstallShield Express, making it possible for users to install and configure your products efficiently.

Related Sections

Using Visual FoxPro
Microsoft Visual FoxPro provides the tools needed to create and to manage high-performance, 32-bit database applications and components. With its robust tools and data-centric object-oriented language, you can build modern, scalable, multi-tier applications that integrate client/server computing and the Internet.
Overview of Visual FoxPro Features
Visual FoxPro gives you more of everything you have come to expect in a database management system (DBMS) — speed, power, and flexibility.
Customizing the Visual FoxPro Environment
Describes how, after you install Visual FoxPro, you can customize your development environment settings such as the main window title, default directory, project, editor, debugger and form tool options, temporary file storage, field mappings for drag-and-drop operations, and many other options.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Explains how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity so you can access the full power of Visual FoxPro.
Development Productivity Tools
Explains that Visual FoxPro provides developer tools for application development within the FoxPro application and the FoxPro language.


Creating Applications with Visual FoxPro

Visual FoxPro Walkthroughs

Walkthrough: Creating Applications with Visual FoxPro

Visual FoxPro can create simple programs or elaborate enterprise level applications, servers, and XML Web Services. Because of the unique design of Visual FoxPro, you can write a program, have Visual FoxPro create a program, or do any combination of both using code, menus, wizards, designers, builders, objects, and so on.

Contents

Introduction

Using Data

Creating a Program for a Form

Creating an Application

Introduction

Microsoft Visual FoxPro programs (.prg files) are created easily by using menu options or Visual FoxPro tools, such as designers, wizards, and builders. Applications are Visual FoxPro programs that are compiled, after creation, into .app files to run in a Visual FoxPro environment or into .exe or .dll files that can be called from anywhere in a Microsoft Windows environment.

This paper walks you through the steps to create a simple program and then shows you how to use it as the basis for an application.

Using Data

Visual FoxPro programs and applications are based on data in tables or cursors. Data can exist already on your hard disk, a remote server, or a Web site, or you can create it in Visual FoxPro. Data can be in any of the formats that Visual FoxPro recognizes, including OLE objects.

For this sample application, the data you use will be copied from the Orders table, which is included with Visual FoxPro in the \Program Files\Microsoft Visual FoxPro 8\Samples\Data folder.

To move data from one table to another

  1. On the File menu, click Export.
  2. In the Type drop-down list in the Export dialog box, select Visual FoxPro 3.0 (DBF).
  3. In the To text box, type myApp as the name of the file you want to create.
  4. Click the ellipsis (...) button and save the file in the Visual FoxPro Projects folder (..\My Documents\Visual FoxPro Projects).
  5. In the From text box in the Export dialog box, click the ellipsis (...) button, and locate the Orders.dbf table in \Program Files\Microsoft Visual FoxPro 8\Samples\Data folder.
  6. In the Export dialog box, click Options .
  7. In the Export Options dialog box, click Fields, move cust_id, to_city, to_country, and order_amt from the All fields list to the Selected fields list, and then click OK. Click OK twice more to close the Export Options dialog box and the Export dialog box.
  8. On the File menu, click Open.
  9. In the Files of type drop-down list, choose Table, select the open exclusive check box, and browse to myApp.dbf.
  10. On the View menu, click Table Designer.
  11. On the Fields tab, select the to_city row, click the Index drop-down list, and choose Ascending.
  12. Click OK, and click Yes to make the structure change permanent.
  13. On the Window menu, click Data Session to order the table according to your new index.
    Note You have created a table that, because it is indexed, supports group calculations in the Report Designer.
  14. In the Data Session window, click Properties.
  15. In the Index Order drop-down list, select myApp:to_city, and then click OK.

    You have now exported selected fields from one table to another and then set an index on the new table. Leave the Data Session window open, and use this table immediately for the rest of this sample.

Creating a Program for a Form

You can create simple Visual FoxPro programs from the menus and the IDE. These programs either run in Visual FoxPro or access the Visual FoxPro Runtime.

To create the form

  1. On the File menu, click New.
  2. Click Form, and then click New file.

    This opens the Form Designer, adds the Form menu and the Form Controls toolbar, and displays the Properties window for the form. If the toolbar is not visible, you can open it from the View menu.

  3. In the Properties window for the form, select Caption, and type myForm.

To add a label

  1. On the Form Controls toolbar, click Label, and drag a rectangle on the form.
  2. In the Properties window for the label control, select Caption, and change it to My Data Form. Then, select FontSize, and type 20.
  3. If necessary, resize the label so the text fits.

To add a grid

  1. On the Form Controls toolbar, click Grid, and then draw a rectangle on the form.
  2. Right-click the Grid control, and select Builder from the shortcut menu.
  3. In the Grid Builder, select the table, myApp.
  4. On the Grid Items tab, move all the items in the Available fields list to the Selected fields list, and then close the builder.

To add a button

  1. On the Form Controls toolbar, click the Command Button icon, and then draw a rectangle on the form below the grid.
  2. Double-click the newly created button, and type the following code in the code editor. Close the code editing window when you are finished.
    THISFORM.RELEASE

    This code will close the form when you do not need it any more.

  3. In the Properties window for the button control, select Caption, and type Exit.
  4. On the File menu, click Save As, and save the form as myForm.
  5. Click Run (!) on the toolbar to preview your form.

To complete the program

  1. On the File menu, click New.
  2. Click Program, and then click New file. This opens the Visual FoxPro editor.
  3. In the editor, type the following:
    DO FORM myForm.scx
  4. Save this program as myProgram. This creates a Visual FoxPro program (.prg) file that runs your form from the following command in the Command window:
    DO myProgram

Now you have placed a table (as a grid), a label, and a button on a form. You created a program to run from the Command window or Program menu. In the next section, the application exchanges a data review form for the grid and adds it to the program before compiling it to a file.

Creating an Application

Running the program you created earlier requires Visual FoxPro to be installed on the computer. However, you can create an application with Visual FoxPro that will run on a computer that does not have Visual FoxPro installed on it.

The earlier program has only one form and does not have much functionality. This section walks you through adding a data review form with some additional controls and then compiling the two forms — first into a Visual FoxPro application and then into a Windows application. A Visual FoxPro application (.app) file or a Visual FoxPro executable (.exe) file can each run on Windows platforms if Visual FoxPro is installed. A Visual FoxPro application compiled as an executable (.exe) file also can run on Windows platforms with only the Visual FoxPro Runtime installed.

In this section, you will create an application using the Application wizard, the Application builder, and the Project manager.

  • The Application wizard creates a project and provides the advanced application framework so you can add components you might have created already or create an application from start to finish, including splash screens and other enhancements.
  • The Application builder makes it possible for you to add tables, forms, and reports to an existing project.
  • The Project manager, the most fundamental application-building tool in Visual FoxPro, provides access to all the components you might want to include in an application and contains them for compilation.

For this walkthrough, you use the Application wizard first.

To create an application

  1. On the Tools menu, point to Wizards, and click Application.
  2. In the Project name box, type MyApplication, save the project in your Visual FoxPro Projects folder (..\My Documents\Visual FoxPro Projects), and then click OK.

Visual FoxPro prepares to create a project file with the name you specified. When it has finished creating the project, two windows appear: the Project Manager and the Application Builder. In the following procedures, you use the Application Builder to add components and functionality to your application.

To specify splash screen and About dialog box information

  1. On the General tab of the Application Builder, click the ellipsis (...) button next to the Image box.
  2. Find the Visual FoxPro logo, fox.bmp, in your Visual FoxPro folder (..\Program Files\Microsoft Visual FoxPro 8), and click OK. This image will appear on your application splash screen.
    Note If you close the Application builder, you can reopen it by clicking the Tools menu, pointing toWizards, and clicking All Wizards. Click Application Builder in the Wizard Selection dialog box, and then click OK.
  3. On the Credits tab of the Application Builder, add the appropriate authoring and version information.

To specify the data source

  • On the Data tab, click Select, and find and select myAPP (the table you used earlier in the simple program).
    Note You can choose any available table. This tab also provides buttons, so you can create tables or a database easily.

To create a form and a report

  • On the Data tab, you can select from lists of form and report templates that are part of the Advanced Application Framework (included in the Application Builder). Accept the default values in the drop-down lists, and then click Generate.

    Visual FoxPro generates a form and a report from the table you specify and gives you access to them from the Forms and Reports tabs of the Application builder. These components become part of the project you are building, and the files are saved in the Forms or Reports folder in your Visual FoxPro Projects folder (..\My Documents\Visual FoxPro Projects).

To add controls to the form

  1. On the Forms tab of the Application Builder, click Edit to open the Form Designer, where you can make any additions or changes.

    As is, the form will display only the first record, so you must add at least one more control; in this procedure, you add two.

  2. On the Form Designer toolbox, click the Button icon, and drag a rectangle in the form. In the Caption property, type Next.
  3. Double click the Next button on the form, and type the following code in the code editor.Close the code-editing window when you are finished.
    IF ! EOF()
   SKIP
   THISFORM.REFRESH
ELSE
   GO TOP
ENDIF

    This code steps through the table records and displays each record. You also could add another button, with appropriate code, to move back through the table.

  4. Copy the Next button, and place the copy at the far right of the form. In the Caption property, type Exit.
  5. Double click the Exit button, and, in the Click event edit window, replace the code in the window with the following code, and then close the window:
    THISFORM.RELEASE

    This code closes your form.

To add calculations to the report

  1. On the Reports tab of the Application Builder, click Edit for MyApp to open the Report Designer. Expand all the bands of the report to make it easier to perform the following operations.
    Note This is where you can make any additions or changes, such as rearranging fields or adding controls.
  2. On the View menu, click Data Environment.
  3. Right click the Data Environment window, and select Properties from the shortcut menu.

    This will set the Properties window to the Dataenvironment.

  4. In the Properties window, choose the cursor from the Properties Description drop-down list, and change the Order property to to_city to make grouping possible.
  5. On the Report menu, click Data Grouping.
  6. In the Data Grouping dialog box, click the ellipsis (...) button under Group expressions. In the Expression Builder, double-click to_city in the Fields list. Click OK in both dialog boxes.
  7. In the Report Designer, copy and paste the to_city element, and then drag the pasted element from the Detail band to the Group Footer band for group totals. Repeat this procedure to place another copy of the to_city element in the Page Footer for the entire table.
  8. For each copy of the to_city element, double-click the element to open the Report Expression dialog box.
  9. Click Calculations.
  10. In the Calculation Field dialog box, click Count.

    The Reset drop-down list should display the default selection, which is the to_city field. This means the Count function will reset to zero each time the value of the to_city element changes in the pass through the table. This is correct for the Group Footer band, but you must change this selection for the to_city element in the Page Footer band.

  11. After you select Count in the Calculate Field dialog box of the to_city element you placed in the Page Footer band, change the Reset value to End of Report.
  12. After setting the Calculation field of each to_city element, click OK to close the dialog box.
  13. Click OK to close the Application Builder.
Note In addition to the features you specified in the Application wizard, Visual FoxPro created other components for your application. When you run your application, you will discover a customized File menu and a dialog box from which you can run your form and your report.

Now you can use the Project manager to review the components you have created. You will find that the Application wizard created many components, which you modified in the Application builder and the Form and Report designers. You can examine and modify these components in various Visual FoxPro tools, such as the designers or the Class Browser and Object Browser.

At this point, the most important use of the Project manager is to complete the compilation of your files into an application.

To complete the application

  1. In the Project Manager, click Build.
  2. Click Application (app) to create an application to be run only in Visual FoxPro.
    Note If you select Win 32 executable / COM server (exe), you create an application that can be run on a computer with only the Visual FoxPro Runtime installed.
  3. Click OK.

When the build process is complete, you have an application you can run in Visual FoxPro by double-clicking the .app file. When the program opens, it displays the splash screen and then the Quick Start dialog box from which you can view your form and your report. The application also provides a Quick Start menu item.

For more information on creating programs and applications, see Application Wizard and Application Builder.

For more information on the Project Manager and for details on application build options, see Project Manager Window, and Build Options Dialog Box.

See Also

Application Wizard | Application Builder | Walkthroughs


Creating Reports with Visual FoxPro

Visual FoxPro Walkthroughs

Walkthrough: Creating Reports with Visual FoxPro

This walkthrough shows how to create Visual FoxPro reports and discusses issues to consider beyond direct data access, issues related to the needs for reports, and issues related to planning and creating online and offline reports. You can use the Report wizard to quickly get a report of any single or related tables. If you want to customize your report, or add non-data elements, use the Report designer.

Contents

Introduction

What is Data?

Planning a Report

Creating a Single-table Report

Creating a Multi-table Report

Introduction

Although Microsoft Visual FoxPro data can be reported to the screen simply as a Browse window or a form, properly designed reports lend clarity, readability, and distributability to data that turns it from developer data to user information. Reports are great for display and distribution of the information available from data, because they are easily repeated, duplicated, and shared.

It is easy to build simple reports in Visual FoxPro. Indeed, the very tools you use to create tables provide ways to immediately see all the data available (for more information, see Walkthrough: Creating Tables with Visual FoxPro.

The Report designer or Report wizard are helpful especially if you want to create a report that displays in one view the relationships or the combined information between two or more tables. This topic uses the Report wizard to create two reports — a simple single-table report and a multiple-table report.

What is Data?

Visual FoxPro deals with data in tables. Data is discrete and can be found in an ever-expanding range of types. Visual FoxPro can access most of it, but access is often not enough. To use data effectively, you must turn it into information — you must report it. This is not always a magical process. Usability can be as simple as a little pre-planning. Effectiveness can take more effort. Typically, you spend more time using or designing reports then you spend creating tables.

Planning a Report

With reports, not only is planning important, but it is recurrent and, sometimes, recursive. Use a report when you want to get the same information repeatedly or when you want to encourage specific activity or aid particular processes.

An effective report is one that makes it possible for you to use information quickly, whether you use all the available data or not. The way to start report planning is to think about how that report will be used.

Often, information is more inspiring or thought provoking when it is formatted properly or organized carefully. For example, if you are preparing for a staff meeting, it might be helpful to create reports in which data is organized by staff responsibilities, as well as by time, geographic, or financial relationships. If it is your address book or contacts list, you might find it helpful to create one or more reports organized by zip code (state), or birth month, phone area code, or hobby.

When you gather information for records in an address book or contact list, you enter all the information about one individual; however, you might create each record at different times and places. Even if you create several records at one time, you still complete one record before you begin the next. Several records can have identical values, but without a report it can be difficult to know which ones or how many. It can be important and useful to have a way to see these and other relationships.

Online or Printed Reports

If you are going to display data online or in print, there are some issues you should consider:

  • Scrolling If your information cannot be displayed in one screen page, then consider separate pages rather than a long scroll. In addition, consider a different visual organization of the data, such as labels, positioning, or the use of white space.
  • Labels This influences both the eye (where users look for information) and the mind (what users expect to find).
  • Spacing and positioning This can be as important as font size for focus and clarity.
  • White space Most people do not enjoy reading large blocks of text online, so good use of white space can make your report more effective.
  • Location This is as important in screen real estate as it is in land. The top, the center, the right, and then the left are most often the important screen areas.

If your report can access background information or relevant data directly rather than always display it, then the basic report is more effective (and you have more room for the most important information).

Creating a Single-table Report

If you only want to look at what you have, use the Browse window on any table.

To access the Browse window

  1. From the File menu, open the table.
  2. On the View menu, select Browse.

If you want to print or mail a report quickly, you can export the file as text, and then print or mail the new text file. The Export dialog box options make it possible for you to select portions of the table to convert to text. (Remember to check the paper orientation for wide tables.)

To report raw data from a table as text quickly

  1. On the File menu, click Open.
  2. In the Open dialog box, select Table in the Files of type drop-down list, locate the table you want, and click OK.
  3. On the View menu, click Browse.

    This displays the selected table. At this time, in the IDE, you can change the column widths or locations, or you can make lasting changes from the Table menu.

  4. On the File menu, click Export.
  5. In the Export dialog box, select Delimited Text from the Type drop-down list.

    If you were going to use the table in another application, such as Microsoft Excel, you could select the application from the list, and the table would be converted to the proper format and saved with the correct extension.

  6. Click To, and enter the file name of your new file, including the extension.
  7. In the Field separator drop-down list, select the delimiter you want in the new file, and then click OK.

Visual FoxPro Report Wizard

If you find you must have formal presentations, summaries, or calculations, or you must use the same information repeatedly, then use the Report wizard or the Report designer to generate reusable, updateable, modifiable reports.

The Report wizard prompts you with choices that make it possible for you to create a well-formatted report of one or more tables quickly. In many circumstances, these quick reports work very well.

To use the Report wizard

  1. On the File menu, click New.
  2. In the New dialog box, select Report.
  3. Click the Wizard button, and select the type of report you want to create.

In the wizard, you can preview a report before you save it. In addition, you can save it and then open it in the Report designer to use the Visual FoxPro IDE to add to your report design.

To experiment with the Report wizard, use the Labels.dbf table, which ships with Visual FoxPro. Use the following procedures to work with simple, one-table reports

To create a simple Report using the Labels.dbf table

  1. On the File menu, click New.
  2. In the New dialog box, select Report and then click the Wizard button.
  3. In the Wizard selection dialog box, double-click Report Wizard.
  4. In the Report wizard, select Free Tables in the Databases and tables drop-down list box, and select or locate the Labels table.
  5. Select any or all of the available fields, and continue the wizard, making the appropriate selections up to Step 5.
  6. In Step 5, choose a report style and orientation.

    In addition, you can click Summary options to access five functions — Sum, Avg, Count, Min, and Max — for fields displayed in your report. The selected functions are added automatically with appropriate labeling and positioning.

  7. In Step 6, click the Preview button to see the report your selections would create if you click Finish. You can print the preview without creating a report file.

    The Report wizard creates labels and selects fonts, font sizes, indentation, and other styling and formatting characteristics to help turn the table data into report information. Often, creating reports with the wizard is as fast as creating the ad hoc Browse window copy, and the results often look much nicer.

  8. Click Finish.

For more information, see Report Wizard and One-To-Many Report Wizard.

Visual FoxPro Report Designer

You can use the Report designer to create simple reports, called Quick Reports. In addition, the Report designer is a powerful tool for creating formatted reports. The main difference between using the Report wizard and using the Report designer is that the designer provides greater control of the positioning of data and other content.

To create Quick Reports with the Report designer

  1. On the File menu, click New.
  2. In the New dialog box, select Report, and click the New File button.
  3. On the Report menu, click Quick Report.

    If you have a table open, Visual FoxPro will use it as the source for your report. If no table is open, Visual FoxPro displays the Open dialog box, so you can choose a table.

The Report designer populates the Detail and Page Footer bands. Then, the details are up to you. You have more control than with the Report wizard; you also have more responsibility. If you want to generate information, such as sums, averages, or counts, use Data Grouping on the Report menu. Your specification for a data group can be as simple as the name of the index field selected from the Expression builder.

To create a report containing a calculation

To perform this operation, open an ordered table (indexed on cust_id), create a Quick Report as basis, specify data grouping, and then specify how and where in the report the calculation is displayed. The final steps are to preview, print, and save the report.

  1. From the File menu, open the ..\samples\DATA\orders.dbf table.
  2. On the Window menu, click Data Session, and click Properties for the orders table.
  3. In the Work Area Properties dialog box, choose Orders.cust_id as the Index order, click OK, and then close the Data Session dialog box.
  4. On the File menu, click New. In the New dialog box, select Report, and then click New File.
  5. On the Report menu, click Quick Report, and then select the vertical layout.
    Note For this example, you do not need all the fields, so you might want to remove the labels and fields following order_amt, as well as the labels and fields between emp_id and order_date. Move the fields together, and resize the report bands.
  6. On the Report menu, click Data Grouping.
  7. In the Data Grouping dialog box, click the ellipsis (...) button under Group Expressions. In the Fields list in the Expression builder, double-click Orders.cust_id. Click OK in both dialog boxes.
  8. In the Report Designer, place a copy of the order_amt field in the Group Footer band for group totals, and place another copy in the Page Footer for the entire table.
  9. Copy, paste, and then drag the copied fields from the Detail band.
  10. For each copy of order_amt, double-click the field to open the Report Expression dialog box.
  11. Click the Calculations button.
  12. Select the Sum function from the Option Group.

    The Reset drop-down list box should display the default selection, which is the Order.cust_id field. This means that the Sum function resets to zero each time the value of the cust_id field changes in the pass through the table. This is fine for the group sub totals, but you must change this selection for the order_amt field in the Page Footer band.

  13. After you select Sum in the Calculate Field dialog box of the order_amt field you placed in the Page Footer band, change the Reset value to End of Report.
  14. After setting the Calculation field of each order_amt, close the dialog boxes by clicking OK.

Use the print preview to see what you have created and to make sure that you are getting the information you expected. Save the report if you are satisfied with it. The last page displays the total for all orders — information not specifically included in the table.

While the Report designer is open, you have access to tools and other designers, so you can review the current table or modify the data environment by selecting other tables or indexes. In addition, you can add functionality to the report through the Report Controls toolbar and the Report menu.

For more information on the Report designer, see Report Designer and Report Designer Band Dialog Boxes.

Creating a Multi-table Report

In addition to single-table data, Visual FoxPro reports can display data from several related tables and can perform calculations and produce summaries.

This procedure uses two tables, customer and orders, from the testdata.dbc database in the Samples folder.

To create a report using the Testdata database that ships with Visual FoxPro

  1. On the File menu, click New.
  2. In the New dialog box, select Report, and click the Wizard button.
  3. In the Wizard selection dialog box, double-click One-To-Many Report Wizard.
  4. In the One-To-Many Report wizard, select the TESTDATA database in the Databases and Tables drop-down list, and select the Customer table.
  5. In Step 1 of the wizard, highlight the Customer table, and select the cust_id and Customer fields from the Available Fields drop-down list.
  6. In Step 2, highlight the Orders table, and select the cust_id, to_city, and order_amt fields from the Available Fields drop-down list.

    In Step 3, you see the way the two tables are related — customer.cust_id to orders.cust_id; in other words, the tables are indexed on matching fields.

    If you want a different relationship, you could choose from the drop-down lists for the parent and child tables. If you change the specified relationship, you would also have to make sure you had chosen the correct fields in steps 1 and 2.

  7. In Step 5, choose a report style and orientation.

    In addition, you can click Summary options to access five functions — SUM, AVG, COUNT, MIN, and MAX — for fields displayed in your report. The selected functions are added automatically with appropriate labeling and positioning.

  8. In Step 6, click Preview to see the report your selections would create if you click Finish. You can print the preview without creating a report file.
  9. Click Finish.

You can create the same report in the Report designer, but to specify the database and the tables, you must establish the data environment of the report. You then use that data environment in a Quick Report or through drag-and-drop in the IDE to create your report.

For samples of various kinds of report you can create, see the Solutions Samples.

For more information on using reports, see Using Expressions and Functions in Field Control in a Report.

See Also

Report Wizard | One-To-Many Report Wizard | Report Designer | Report Designer Band Dialog Boxes | Solutions Samples | Using Expressions and Functions in Field Control in a Report | Walkthroughs


Retrieving Data from Different Data Sources

Visual FoxPro Walkthroughs

Walkthrough: Retrieving Data from Different Data Sources

This walkthrough guides you through the basic steps of retrieving data using various data source connection types. You can then create Visual FoxPro cursors or cursor adapters using the retrieved data. Cursor adapters can retrieve data from a wider range of data sources than is possible with conventional cursors.

Specifically, this walkthrough explains how to build a data environment for a Visual FoxPro form using the DataEnvironment Builder and how to create cursor adapters in the data environment using the CursorAdapter Builder.

This walkthrough requires the following:

  • Data sources using the following connection types:
    • Native Northwind.dbc database included with Visual FoxPro and located in the ...\Samples\Northwind directory
    • ODBC or ADO Access to a local or remote SQL server (SQL Server 7 or 2000) with Northwind.dbc database installed
    • XML GetCustomers.XML DataSet file included with Visual FoxPro and located in the ...\Samples\Solution\Toledo directory
  • A Visual FoxPro form based on the FrmSolution class included with the Solution.vcx class library, which is located in the ...\Samples\Solution folder. A form based on the FrmSolution class appears similar to the forms used in the Solution samples.

You can create a form based on the FrmSolution class by creating a category in the Toolbox, adding the FrmSolution class to the Toolbox, and creating a form based on that class.

To create the form used in this walkthrough

  1. On the Tools menu, click Toolbox.
  2. Right-click the Toolbox, and click Add Category.
  3. In the Category name box type a category name.

    The category you created appears in the Toolbox.

  4. In the Toolbox, right-click the category, and click Add Class Library.
  5. In the Add Class Library dialog box, click the ellipsis (...) button, browse to the ...\Samples\Solution folder, and select Solution.vcx.

    The classes in the Solution.vcx class library appear in the category you created in the Toolbox.

  6. In the Toolbox, right-click frmsolution (SOLUTION), and click Create Form.

Contents

Introduction

Data Environment for a Form

Retrieving Data for Cursor Adapters

Using the Cursor Adapter on the Form

Introduction

In Visual FoxPro, you can retrieve data from local and remote data sources with the following types:

  • Native
  • Open Database Connectivity (ODBC)
  • ActiveX Data Object (ADO)
  • Extensible Markup Language (XML)

You can then create Visual FoxPro cursors from the data retrieved, based on the data source type, through cursor adapters. Cursor adapters provide the following capabilities when working with different data sources:

  • Retrieve data from data sources with the listed data source types.
  • Control loading of data into the cursor associated with the cursor adapter.
  • Control how data is added, updated, and deleted using CursorAdapter object properties and methods.
  • Add cursor adapters to containers other than a data environment, such as a form, form set, or other container.

For more information cursor adapters, see Data Access Management Using CursorAdapters and CursorAdapter Class.

You can configure a data source and, if needed, a connection type that applies to all cursor adapters in the data environment using the DataEnvironment Builder. You can then quickly create cursors that have specific properties for accessing data using the CursorAdapter Builder.

For more information, see DataEnvironment Builder and CursorAdapter Builder.

Data Environment for a Form

When you create a form, Visual FoxPro creates a DataEnvironment object as a container for Cursor, CursorAdapter, and Relation objects that are associated with the form, a form set, or a report. You need to open and set the form's data environment to the appropriate data source type and data source to retrieve data from.

For more information about DataEnvironment objects, see DataEnvironment Object.

Opening the Data Environment

Open the form's data environment and the DataEnvironment Builder before selecting the data source type and data source from which to retrieve data.

To open the form's data environment and the DataEnvironment Builder

  1. Open the form.
  2. In the Form Designer, right-click the form, and click DataEnvironment to open the data environment.

    For a form with an empty data environment, the Open dialog box appears.

  3. In the Open dialog box, click Cancel.
  4. To open the Data Environment Builder, right-click the Data Environment surface, and click Builder.

    The DataEnvironment Builder opens and displays the following tabs: Data Source and Cursors.

Setting Data Source Types and Data Sources

Set the data source type and configure the appropriate data source that you want to retrieve data by from setting options on the Data Source tab in the DataEnvironment Builder.

To select the data source type for the form's data environment

  1. In the DataEnvironment Builder, click the Data Source tab to make it visible if not already visible.
  2. On the Data Source tab, select the appropriate data source type: ADO, Native, ODBC, or XML.

Depending on your selection, the appropriate options appear. The following procedures demonstrate how to set the data environment to native Visual FoxPro tables, ODBC, ADO, and XML.

For more information, see Data Source Tab, DataEnvironment Builder.

Specifying Native Visual FoxPro Data Sources

Follow this procedure to use native Visual FoxPro data sources.

To set the form's data environment to native Visual FoxPro tables

  1. After selecting Native on the Data Source tab, click the ellipsis (...) button to the right of the Database box
  2. Browse to the ...\Samples directory and select the Northwind.dbc database.

To continue this walkthrough, see Retrieving Data for Cursor Adapters.

Specifying Data Sources Using ODBC

Follow this procedure to use data sources connected through ODBC.

To set the form's data environment to data sources using ODBC

  1. After selecting ODBC in the Data Source tab, click Use connection string.
  2. Type the connection string to connect to the Northwind.dbc database on your local or remote SQL Server. For example:
    Driver={Sql Server};Server=localhost;Database=Northwind;Int Security=yes;
    Note You must have access to a local or remote SQL Server (SQL Server 7 or 2000) with Northwind.dbc database installed. If your SQL Server is not local, you can change the value of the Server= parameter in the connection string to the name of the remote server.
  3. Click Test Connection to test the connection.

If the connection is successful, you can continue and retrieve data from the data source.

To continue this walkthrough, see Retrieving Data for Cursor Adapters.

Specifying Data Sources Using ADO

Follow this procedure to use data sources connected through ADO.

To set the form's data environment to data sources using ADO

  1. After selecting ADO on the Data Source tab, click Use connection string.
  2. Type the connection string to connect to the Northwind.dbc database on your local or remote SQL Server. For example:
    Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=localhost
    Note You must have access to a local or remote SQL Server (SQL Server 7 or 2000) with Northwind.dbc database installed. If your SQL Server is not local, you can change the value of the Data Source= parameter in the connection string to the name of the remote server.
  3. Click Test Connection to test the connection.

    If the connection is successful, you can continue and retrieve data from the data source.

If you want to construct a connection string instead of typing one on the Data Source tab, click Build to open the Data Link Properties dialog box in the Visual FoxPro OLE DB Provider. For more information, see OLE DB Provider for Visual FoxPro.

To continue this walkthrough, see Retrieving Data for Cursor Adapters.

Specifying XML Data Sources

In this walkthrough, the method for creating cursor adapters from XML demonstrates only one example of how you can access an XML data source, more specifically, an XML DataSet file generated from ADO.NET. Actual code can vary depending on your specific needs.

You can also use cursor adapters with cursors generated from XML with XML adapters or XMLAdapter objects. You can use this combination to access more advanced features of the design-time environment and to bind controls on a form to fields in the cursor adapter. The XML adapter performs the actual work at run time.

To set the form's data environment to XML data sources

  • After selecting XML on the Data Source tab, click the Cursors tab.

When you create a cursor adapter from XML, you can use the CursorAdapter Builder to set the CursorAdapter properties. However, you need to create an XMLAdapter object to load the XML into its Tables collection. After creating the XML adapter, you can load an XML file into the XML adapter, set the Select command of the cursor adapter to the desired XMLTable object reference in the XMLAdapter Tables collection, and then call the CursorAdapter CursorFill method to populate the cursor with XML data.

To continue this walkthrough, see Retrieving Data for Cursor Adapters.

For more information about how cursor adapters work with XML adapters, see the Creating a Cursor from an XML DataSet Sample as an example of how to access an XML file and generate XML DiffGrams and XML Functionality Using XMLAdapters.

For more information about XML adapters and cursor adapters, see XMLAdapter Class and CursorAdapter Class.

Retrieving Data for Cursor Adapters

After setting the form's data environment in the DataEnvironment Builder to data source you want to use, create CursorAdapter objects in the form's data environment to retrieve data from the data source. You can create CursorAdapter objects by setting options on the Cursors tab of the CursorAdapter Builder.

To create a new cursor adapter

  1. In the DataEnvironment Builder, click the Cursors tab to make it visible.
  2. On the Cursors tab, click New to open the CursorAdapter Builder.

The CursorAdapter Builder appears, displays the Properties, Data Access, and Auto-Update tabs, and creates a new cursor adapter named Cursor1.

For more information, see Cursors Tab, DataEnvironment Builder.

Setting Properties for Cursor Adapters

Set properties for a new cursor adapter by editing settings in the Properties tab of the CursorAdapter Builder.

To set properties for a new cursor adapter

  1. In the CursorAdapter Builder, click the Properties tab to make it visible if not already visible.
  2. On the Properties tab, edit the name for Cursor1 if you want; rename the cursor adapter alias to Customer.
    Note Usually, you type the name and alias you want for the cursor adapter.
  3. Click Use DataEnvironment data source to use the data source previously set for the form's data environment.

For more information, see Properties Tab, CursorAdapter Builder.

Specifying How Cursor Adapters Retrieve Data

After creating a new cursor adapter, specify how the cursor adapter retrieves data from the data source by setting options in the Data Access tab of the CursorAdapter Builder.

If you are using the Native, ODBC, or ADO data source type, following the instructions for constructing the Select command to retrieve data from the data source. If you are using the XML data source type, follow the instructions for specifying a well-formed XML file that contains schema.

To construct the Select command for data sources using Native, ODBC, and ADO

  1. In the CursorAdapter Builder, click the Data Access tab to make it visible.
  2. On the Data Access tab, click Build to open the Select Command Builder dialog box.
  3. In the Select Command Builder dialog box, select the CUSTOMERS table in the Table list.

    The fields that the CUSTOMERS table contains appear in the list on the left side of the Select Command Builder dialog box.

  4. In the list on the left, click CUSTOMERS.* to include the CUSTOMERS table and all its fields in the Select command.
    Note Usually, if you want to select individual fields in the table for the Select command, click tableName.fieldName to add each field separately to the list of selected fields appearing on the right side of the Select Command Builder dialog box.
  5. Click the single right arrow (>) to add CUSTOMERS.* to the list of selected fields, and then click OK.

    The constructed Select command appears in the Select command box, and the schema for the cursor adapter appears in the Schema box.

You can set additional options for data retrieval. However, this walkthrough uses the default settings for these options.

Note In this walkthrough, buffer mode for the cursor adapter is set to optimistic row buffering by default on the Data Access tab for Native, ODBC, and ADO data source types. Therefore, when you make changes in a grid row on the form and move to another row, those changes are sent to the Customer.dbf table in the data source through the appropriate connection type. For more information about buffer modes, see BufferModeOverride Property.

For more information about additional options you can set, see Data Access Tab, CursorAdapter Builder.

To specify an XML file for XML data sources

  1. In the CursorAdapter Builder, click the Data Access tab to make it visible.
  2. On the Data Access tab, click Build located above the Schema box to display the Open dialog box.
  3. Browse to the ...\Samples\Solution\Toledo\ folder, and select the GetCustomers.XML file.

    The schema for the cursor adapter appears in the Schema box.

  4. In the Buffer mode override box, select Optimistic table buffering.
    Note In this walkthrough, buffer mode for the cursor adapter is set to optimistic table buffering on the Data Access tab for XML data source types to make it possible for the XML adapter to create XML DiffGrams. For more information about buffer mode settings, see BufferModeOverride Property.
  5. Click OK to close the CursorAdapter Builder, and then click OK again to close the DataEnvironment Builder.

    The new cursor adapter, now named Customer, appears in the Data Environment for the form and contains all the fields from the GetCustomer.xml file.

You can set additional options for data retrieval. However, except for the buffer mode setting for the cursor created by the cursor adapter in the XML example, this walkthrough uses the default settings for these options. For more information about these options, see Data Access Tab, CursorAdapter Builder.

To continue with the XML example, see Using the Cursor Adapter on the Form.

Configuring Updating for Cursor Adapters

After constructing the Select command for the cursor adapter to retrieve data, you can specify how the cursor adapter performs updates to the data source by setting options on the Auto-Update tab of the CursorAdapter Builder.

To configure how the cursor adapter updates the data source

  1. In the CursorAdapter Builder, click the Auto-Update tab.
  2. On the Auto-Update tab, select the Auto-update check box.

    Selecting the Auto-update check box populates the field list on the Auto-Update tab with fields that you selected on the Data Access tab and enables automatic updating for specified fields.

  3. Select the Update all fields check box to designate all fields from the specified table for automatic updating.

    A check mark appears in the automatic updating column, indicated by a pencil symbol, for each field in the field list.

  4. Select the check box in the key field column, indicated by a key symbol, for the CUSTOMERID field to designate it as the primary key field.
  5. Clear the check box in the automatic updating column for the CUSTOMERID field to prevent it from being modified as the primary key.
  6. Click OK to close the CursorAdapter Builder, and then click OK again to close the DataEnvironment Builder.

    The new cursor adapter, now named Customer, appears in the Data Environment for the form and contains all the fields from the Customer table as specified.

You can set additional options for how the cursor adapter updates the data source. However, this walkthrough uses the default settings for these options.

For more information, see Auto-Update Tab, CursorAdapter Builder.

Using the Cursor Adapter on the Form

After creating the cursor adapter in the form's data environment, you can drop the cursor adapter on the form to create a grid.

To create a grid using the created cursor adapter

  1. In the form's data environment, click and drag the Customer cursor adapter to the form to create a grid.

    If you are using the XML data source type, type the following code in the form's Init event to create and configure the XMLAdapter object:

    LOCAL oXMLAdapter as XMLAdapter
DODEFAULT()
ThisForm.AddProperty('oXMLAdapter',CREATEOBJECT('XMLAdapter'))
WITH ThisForm.oXMLAdapter
   .LoadXml(ThisForm.cRunPath+'getcustomers.xml',.T.)
ENDWITH
ThisForm.DataEnvironment.cursor1.SelectCmd="ThisForm.oXMLAdapter.Tables.Item(1)"
ThisForm.DataEnvironment.cursor1.CursorFill()
GO TOP
ThisForm.BindControls = .T.
ThisForm.grdCustomer.AutoFit()
  2. In the Properties window, set the form's BindControls property to False (.F.).
  3. Save the form in the ...\Samples\Solution\Toledo folder.
  4. On the Visual FoxPro toolbar, click the Run (!) button to run the form.

The form appears and displays a grid that contains the following:

  • Native, ODBC, and ADO data source types: Data from the fields in the CUSTOMER table
  • XML data source type: Data loaded from the XML DataSet, GetCustomer.xml

    When using XML adapters with cursor adapters, you can generate XML DiffGrams using the XML adapter created. For example, the following code creates an XML DiffGram string in a local variable called lcXML:

    LOCAL lcXML, llIncludeBefore, llChangesOnly, llIsFile, lcSchemaLocation
WITH ThisForm.oXMLAdapter
   * Release XML document but preserve schema.
   .ReleaseXML(.F.)
   .UTF8Encoded = .T.    && Indicates international characters.
   .IsDiffgram = .T.       && Generate XML DiffGram.
   llIncludeBefore = .T. && Include <diffgram:before> format.
   llChangesOnly = .T.   && Generate only changes made.
   llIsFile = .F.        && Sample XML is a stream.
   lcSchemaLocation = "" && Sample schema is inline.
   .ToXML("lcXML",lcSchemaLocation,llIsFile,llIncludeBefore,llChangesOnly)
ENDWITH

See Also

Walkthroughs | Managing Data Access Using CursorAdapters Sample | Loading and Generating XML Using XMLAdapter Class Sample


Creating Tables with Visual FoxPro

Visual FoxPro Walkthroughs

Walkthrough: Creating Tables with Visual FoxPro

With Visual FoxPro, you can create and manage, individually and relationally, tables of data from many sources. You can use the Visual FoxPro language, or you can use the many tools to access or manipulate all kinds of data quickly, whether it is on a local disk, a network, or the Internet.

Contents

Introduction

What is Data?

Importing Data into Tables

Arranging Data in Tables

Accessing Data in Tables

Introduction

Microsoft Visual FoxPro is an application, a language, and a set of application development tools. Visual FoxPro tools are written in the Visual FoxPro language and are themselves based on tables.

In Visual FoxPro, you can use wizards, builders, or commands to create or to manipulate tables of data quickly. You can use the Import and Table wizards to create tables, the Table designer to manage tables, and the Visual FoxPro Browse command to view tables.

For simple access to data, use Visual FoxPro directly from commands, menus, and the Data Session window. For more complex data access and manipulation, you can create forms, reports, or views to enter and display tables.

This topic describes how to access existing data with the Import wizard and how to create the structure for new data using the Table wizard and the Table designer from Visual FoxPro menus.

What is Data?

Visual FoxPro works with and manipulates data in tables. The data can be composed of any of the following types of information alone or in combinations: Character, Currency, Date, DateTime, Logical, Numeric, Memo, General, Float, and Double. Visual FoxPro also accesses objects (such as Word and Excel documents), graphics, or sound files, as data.

You can use data that resides in many different kinds of tables, including tab or comma-delimited text files or tables produced in other applications, such as Microsoft Excel or Microsoft SQL Server.

For more information on valid data types, see Data and Field Types.

Importing Data into Tables

To get data that is already in tabular format, open Visual FoxPro, and import the file using the Import wizard. If you want to create the data in Visual FoxPro, use the Table wizard.

The Import Wizard

The Import wizard gives you the option of importing text files in which data is delimited by commas, spaces, tabs, or other separators.

When you use the Import wizard to copy the data into a new Visual FoxPro table, you must know how the text is delimited. In addition, you must make sure the same character delimits all the fields or your data does not import correctly.

To use the Import wizard

  1. On the File menu, click Import.
  2. In the Import dialog box, click the Import Wizard button.

You can use this wizard for other data formats, but it is especially great for text files. For example, if your data is in a file created in Microsoft Excel, you can select Excel from the list provided in the Import wizard. If you are more familiar with another data-generating application, it might be easier to output a delimited text file from that application for importing into Visual FoxPro.

The Table Wizard

When you use the Table wizard to create a new Visual FoxPro table, you must know the type and maximum size of data that you plan to place in each field. In addition, you should consider how the data will be entered and used, so you can decide whether to allow null values.

The Table wizard provides many templates that you can use or customize:

  • Business templates Twenty-six templates for data you might use in commercial environments and transactions.
  • Personal templates Twenty templates for items or activities related to your hobbies, your household, or personal possessions.

To use the Table wizard

  1. On the File menu, click New.
  2. Click Table, and then click the Wizard button.
    Note The New file option also makes it possible for you to create a table, but you must do more of the work unprompted.

After you select a template, follow the remainder of the wizard steps to select fields, specify whether and how the table is indexed, and specify whether the table is a free table or contained in a database. When you complete the wizard, Visual FoxPro creates the empty table structure you have specified. You then can save the table structure and go on to something else, view the table, or modify the new table in the Table designer.

The Table Designer

If you want to create a table without a wizard, use the Table designer. In the Table designer, you can enter the name, data type, and size of each field. In addition to these characteristics, you also have opportunities to specify decimal value width of numeric fields, whether there is an index, and whether NULL values are allowed.

Note Don't confuse NULL values with blank or empty values. The NULL setting has nothing to do with whether blank or empty values can be stored in a field.

If your table is in a database, you can specify input and display formats, field validation rules, and value tip messages, as well as setup your table to behave in specific and powerful ways whenever you use fields from the table on a form.

To access the Table designer

  1. On the File menu, click New.
  2. In the New dialog box, select the Table file type, and click the New File button.

Arranging Data in Tables

Visual FoxPro tables can be standalone or associated with a database. A database acts as a container for one or more tables, views, connections, and stored procedures. Tables that are not contained in a database are called free tables.

When you open a database-contained table, the associated database is also opened. When a free table is opened, only that table is opened.

To open a table

  1. On the File menu, click Open
  2. In the Files of type drop-down list, select Table (*.dbf), and then select a table from the File name drop-down list.
  3. Click OK to open the table.

There are benefits to using a database-contained table instead of a free table. For example, database-contained tables can have field names exceeding 10 characters in length; free tables cannot.

Tables can be simple or complex. You can make using data in tables more efficient through good planning — carefully designing not only table structure but table relationships.

For example, if you were designing an invoice tracking system, you could create one table that held all information on each invoice. It would be more efficient, however, to create tables that contained information on customers (name, address, phone numbers, customer ID, and zip code), on inventory (item, cost, price, quantity on hand, and supplier), on suppliers (name, address, phone numbers, ID, discount info, and contact), and other groups of information (zip code, city, state, and so on). Then, these tables would combine to produce invoices at one time, vendor orders another time, and reports of various kinds, including billing statements, at other times. Each individual file would be more manageable, duplications could be eliminated, and daily or repetitive operations would take less computer and personnel time. Some data entry would be simplified, enhanced, or eliminated, because the related tables would get the information automatically.

For more information on designing tables, see Choosing Data Types.

Accessing Data in Tables

When you have the data in tables, there are countless ways to use or manipulate it, but first you must access it.

The Data Session window provides the most effective way of accessing tables. Each table opens in its own work area. The Data Session window provides information on table properties and any relationships you might set up between tables.

To clear the data environment

  1. In the Command window, type the following:
    CLOSE ALL TABLES
  2. Press ENTER.

To view Table properties

  1. On the Window menu, click Data Session.
  2. In the Data Session window, select a table
    • If a table is already open, it is listed in the Aliases drop-down box, so you can select it.
    • If no table is open, click Open to access the Open dialog box, which makes it possible for you to specify the table to open.
    • If the listed table is in a database, and you click Open, the Open dialog box displays a list of the other tables in that database. You can select one from the list or click the Other button to specify a free table.
      Note The Open dialog box shows available table (.dbf) files. You can open as many of these as you like. If you select a table that is part of a database, a second dialog box opens for the next table Open selection. This dialog box displays the tables available in the database you opened by selecting the table within it. If you want to select more free tables, click Other, and then choose a table.

To access a table for viewing or editing

  • In the Data Session window, select an open table, and then click Browse. You can continue until all the listed (open) tables are displayed.
    Note Each time you browse a table in the Data Session window, the Command window displays a new SELECT statement followed by a BROWSE statement.

To view and modify table characteristics

  • In the Data Session window, select an open table, and then click Properties. This opens the Work Area dialog box, which provides information and access to the table structure and indexes.

In this environment, you can select any table and edit it, append and delete records, or modify the table structure.

When it opens, you can navigate the table, change or delete record contents, or add new data. Use View menu options to select the type of access you want. Use the Table menu options to navigate or modify the table.

Note If you want more access control or complex manipulation of data, or if you want to use remote views, and related tables, create a database for your table. If you want to create an application, COM Server, or Web Service, using more features, such as labels, forms, reports, objects and class libraries, create a Visual FoxPro Project (starting in a Project is the best way any time).

For more information on using tables, see Working with Tables. For more information on the Data Session window, see Using Data Sessions.

See Also

Visual FoxPro Data and Field Types | Choosing Data Types | Working with Tables | Using Data Sessions | Walkthroughs


Creating XML Web Services with Visual FoxPro

Visual FoxPro Walkthroughs

Walkthrough: Creating XML Web Services with Visual FoxPro

XML Web services are the fundamental building blocks for distributed computing on the Internet. They are available anywhere on the Internet with HTTP. You can create them yourself, or you can access them on the Web from wherever they are published. You can use Visual FoxPro to create an XML Web service, or you can use Visual FoxPro to access an XML Web service created in other programming languages.

Contents

Introduction

XML Web Services

Internet Information Services

Creating a COM Server

Creating and Publishing an XML Web Service

Testing an XML Web Service

Using an XML Web Service

Introduction

Creating an XML Web service using Visual FoxPro involves using Microsoft Internet Information Services (IIS), SOAP, and Visual FoxPro COM Servers.

SOAP is automatically installed when you install Visual FoxPro. IIS is an optional component for Windows 2000 and is automatically installed on Windows 2000 Server.

IIS serves your XML Web services from your virtual directory to users on the Internet. Its virtual directory references the location on your hard disk where you place your XML Web services.

You use Visual FoxPro to create COM objects. After your COM objects are created, you can then use the Visual FoxPro XML Web Service builder to publish them to your virtual directory.

This walkthrough explains how to create a COM Server and publish it as an XML Web service. Additionally, it guides you through using your newly created XML Web service. The XML Web service provides a list of customers from a table where the customers meet a certain requirement. The list is sent as an XML string that is then placed into a cursor using the XMLAdapter class.

XML Web Services

An XML Web service is an object or class that is deployed on the Internet and that you can access programmatically through typical method calls. XML Web services provide functionality and access to data between platforms and across diverse connections. The most important aspect of XML Web services is that because of how they use HTTP and SOAP, functionality is available through firewalls. You can call an XML Web service regardless of the platform you are running because HTTP and SOAP operate independently from your computer platform. In some cases, this can provide functionality that was unavailable under distributed COM.

Internet Information Services

IIS provides the reference to the location of your XML Web service to users accessing it from the Internet. To publish an XML Web service, you must create a virtual directory in IIS that contains the necessary Web Services Description Language (.wsdl) files. These files are created by the Web Service Wizard from your COM component.

To create a virtual directory

  1. In the main Visual FoxPro directory (..\Program Files\Microsoft Visual FoxPro 8), create a folder named Web Services.
  2. In Control Panel, click Administrative Tools of , and then click Internet Information Services.

    The Internet Information Services window opens, displaying a tree control on the left that displays a list of Internet information services on your computer.

  3. Right-click the Default Web Site node.
  4. Click New, and then click Virtual Directoryto open the Virtual Directory Creation Wizard.
  5. Follow the instructions in the wizard, and specify the Web Services folder that you created in step 1 as your virtual directory.

    This virtual directory references the Web Services folder where you will store all the XML Web service files you create.

Creating a COM Server

Because an XML Web service is a dynamic-link Library (.dll) or executable (.exe) file, you must use a COM Server as the basis for your XML Web service. A COM Server in Visual FoxPro is a file with a .dll or .exe extension, containing a custom class based on the Session object. The custom class is specified as OLEPUBLIC when it is define. This exposes functionality that can be used and reused by other applications through automation.

For this COM Server example, you create a custom class that reports some basic information. You write a program that creates a class with one method, compile the project containing it into a COM Server, and then publish it as an XML Web service.

To create a COM Server

  1. On the File menu in Visual FoxPro, click New.
  2. In the New dialog box, click Project, and then click New file. Save the project as myWServ1.
  3. In the All tab of Project Manager, expand Code, click Programs, and then click New.
  4. Copy the following code into the Editing window.
    DEFINE CLASS ShowCustomers AS Session OLEPUBLIC
   PROCEDURE CustomersInGermany AS String
      LOCAL loXMLAdapter AS XMLAdapter
      LOCAL lcXMLCustomers AS String

      loXMLAdapter = CREATEOBJECT("XMLAdapter")

      OPEN DATABASE "C:\Program Files\Microsoft Visual FoxPro 8\" + ;          "Samples\Northwind\northwind.dbc"

      USE customers
      SELECT * ;
         FROM customers ;
         WHERE country LIKE "Germany%" ;
         INTO CURSOR curCustomers

      loXMLAdapter.AddTableSchema("curCustomers")
      loXMLAdapter.UTF8Encoded = .T.
      loXMLAdapter.ToXML("lcXMLCustomers")

      CLOSE DATABASES ALL

      RETURN lcXMLCustomers
   ENDPROC
ENDDEFINE

    This program defines one class, ShowCustomers, that has one method, CustomersInGermany.

  5. On the File menu, click Save.
  6. In the Save As dialog box, name the program myWServ1, and click Save.
  7. Close the Editing window.
  8. In Project Manager, click Build.
  9. Select Multi-threaded COM server (dll), click OK, and accept the name myWServ1.

Visual FoxPro now compiles the file myWServ1 into a COM Server called myWServ1.dll. You can now publish it as an XML Web service.

Creating and Publishing an XML Web Service

From the myWServ1.dll file, created in the previous procedure, a new Web Services Description Language (.wsdl) file is generated when you publish the XML Web service. The .wsdl file is an XML file that describes the XML Web service and the classes it contains.

To add the components necessary to turn your COM Server into an XML Web service, you must compile the COM Server as an XML Web service. After you specify the settings in the Web Services Publisher, Visual FoxPro creates the SOAP files necessary to turn your COM Server into an XML Web service, publishes them in your virtual directory, and registers your new XML Web service in IntelliSense.

To compile and publish an XML Web service

  1. On the Tools menu, click Task Pane.
  2. In Task Pane Manager, click XML Web Services.
  3. Under XML Web Service Tools, select Publish Your XML Web Service.
  4. If the file myWServ1.dll is not listed in the COM Server field, click the Ellipsis (...) button, and select myWServ1.dll.
  5. Click Advanced to display the Visual FoxPro XML Web Services Publisher dialog box.
  6. Make sure the Listener URI box displays your virtual directory. If it does not, click the Ellipsis (...) button, and select your virtual directory.
  7. Click the Methods tab, and make sure that CustomersInGermany is selected.
  8. Click the Namespaces table, replace tempuri.org with your domain in all fields, and click OK.

    If you do not have your own domain, you can leave tempuri.org for this example.

  9. Click OK to close the Visual FoxPro XML Web Services Publisher dialog box.
  10. Click Generate.

    Visual FoxPro generates the XML Web service files. After it is finishes, the XML Web Services Publishing Results dialog box appears, displaying a list of files generated, .wsdl file, ISAPI or ASP listener, and whether the file was generated properly.

At this point, you have created and published your XML Web service. Anyone who has access to the virtual directory you established earlier can use HTTP to access the XML Web service you published.

Testing an XML Web Service

After you have published your new XML Web service, you should test it to make sure it is working correctly. Visual FoxPro provides a mechanism to test XML Web services that is available in the XML Web Service pane in Task Pane Manager. The test mechanism displays any results returned from the XML Web service, XML schemas used, error feedback.

To test a XML Web service

  1. On the Tools menu in Visual FoxPro, click Task Pane.
  2. In Task Pane Manager, click XML Web Services.
  3. Under Explore an XML Web Service, click ShowCustomers in the Service Name box.
  4. In the The following methods are supported by this XML web service box, click CustomersInGermany.

    This box lists all the available methods on the XML Web service.

  5. Click Test this XML Web Service.

If testing is successful, the Web Service Test Results window appears. It displays the results from the XML Web service, and you can view the .wsdl file associated with the XML Web service. If there is an error in testing, the Web Service Test Results window displays information on the error.

Using an XML Web Service

You use an XML Web service the same way you would any COM Server: to expose functionality of one application to another. In the following procedure, you create a program (.prg) file to access your XML Web service and use the Toolbox to add the required code that references the XML Web service properly.

To use an XML Web service

  1. On the File menu in Visual FoxPro, click New.
  2. In the New dialog box, select Project, and click New file. Save the project as wsTest.
  3. On the All tab of Project Manager, expand Code, select Programs, and then click NewOn the Tools menu, click Toolbox.
  4. In the Toolbox, click the My XML Web Services.
  5. Click and drag the ShowCustomers XML Web service from the Toolbox to the Editing window.

    This adds the proper code to your XML Web service.

  6. In the Editing window, below the line that reads, "Call your XML Web service here," insert the following code.
    LOCAL lcXML, lcAlias AS String
LOCAL loXMLAdapter AS XMLAdapter

lcXML = loShowCustomers.CustomersInGermany

loXMLAdapter = CREATEOBJECT("XMLAdapter")
loXMLAdapter.LoadXML(lcXML)

lcAlias = loXMLAdapter.Tables.Item(1).Alias
loXMLAdapter.Tables.Item(1).ToCursor()

SELECT(lcAlias)
BROWSE
CLOSE DATABASES ALL
  7. On the File menu, click Save.
  8. In the Save As dialog box, name the program WebServiceTest, and click Save.
  9. Close the Editing window.
  10. In Project Manager, select the WebServiceTest program file, and click Run.

    A browse window appears with all the customers from Germany selected in the Northwind database. This cursor was populated from XML provided from your XML Web service using the XMLAdapter class.

For more information on Web Services, see Creating Web Services and Components. For more information on COM Servers, see Creating Automation Servers.

See Also

Creating Web Services and Components | Creating Automation Servers


Creating a Visual FoxPro Application Setup Program Using InstallShield Express

Visual FoxPro Walkthroughs

Walkthrough: Creating a Visual FoxPro Application Setup Program Using InstallShield Express

When you are ready to distribute an application, you can create a setup program to help your customers install it. This walkthrough explains considerations you should make prior to distributing the application and shows how to create a Setup project, include files and set their properties, and distribute the application files from Setup using InstallShield Express Visual FoxPro Limited Edition.

Both the limited and full editions of InstallShield Express use Microsoft Installer, which features comprehensive and flexible Setup creation technology. This technology makes it possible for your customers to install and configure your application efficiently.

This walkthrough does not act as a replacement for the InstallShield Express documentation, which you should read first. It is a supplement to assist you in using InstallShield Express to package and distribute applications. To learn how to install InstallShield Express Limited Edition on your computer, follow the instructions in Installing Visual FoxPro.

For more information about distributing applications, see Distributing Applications.

Contents

Introduction

Before Distributing An Application

Creating the Setup Program Using InstallShield Express

Distributing An Application

Additional Information

Introduction

Visual FoxPro includes the limited edition of InstallShield Express version 3.54, replacing the Setup Wizard found in versions prior to Visual FoxPro 7.0.

Note You can use any setup creation program that uses Microsoft Windows Installer technology to create a Setup program (.msi) or merge modules (.msm) that are compatible with Microsoft Windows Installer. Some distribution scenarios require merge modules in addition to the Visual FoxPro run-time files. For more information, see Visual FoxPro Distribution Scenarios in this walkthrough.

The Windows 2000 Logo guidelines require that setup programs be based on Windows Installer technology. The Windows Installer is part of the Windows 2000 and Zero Administration Windows efforts to reduce the overall cost of deploying, using, and managing desktop computers.

Before Distributing An Application

You should consider several issues when preparing an application for distribution. In addition to following the procedure outlined in the Application Distribution Process, you must identify the structure of your application, decide how to deliver the application to users, and how to best organize your Setup program. When you have addressed all these issues, you are ready to distribute your Visual FoxPro application.

Creating the Setup Program Using InstallShield Express

Creating the Setup project is the first step in creating a Setup program. The Setup project (.ism) file you create with InstallShield Express is based on the Windows Installer project file. This file stores all the logic and information necessary to build a setup program compatible with Windows Installer.

To create a Setup project

  1. On the Start menu, point to All Programs. Point to InstallShield, and click Express to open InstallShield Express.
  2. On the File menu, click New to open the New Project dialog box.
  3. Browse to the location where you want to save your project, rename the default project file name in the Project Name and Location box, and click OK.
  4. To create your setup program in a language other than English, select an alternate language in the Project Language list.
    Note After you choose a language, you cannot change it for the project.

Defining Project Properties

After you create a Setup project, you can define properties, such as:

  • Product name
  • Product version
  • Product icons
  • Default installation folder for all application files
  • Name and location of a Readme file

At the minimum, you should specify the product name and a default installation folder for your application files. The INSTALLDIR property in InstallShield Express specifies the location of the default installation folder, for example, the application home directory. The location of the default installation folder specified by INSTALLDIR is:

[ProgramFilesFolder]Your Company Name\Your Product Name

Note It is recommended that you change Your Company Name and Your Product Name to the appropriate names for your application.

You can also specify a different folder for your application by setting INSTALLDIR to a folder with the name of your application as specified by MyApp in the following example:

[ProgramFilesFolder]\MyApp

If you plan to install any data or database files, you can also edit the DATABASEDIR property to specify the default destination folder for those files.

To specify general information for your Setup project

  1. In the Organize Your Setup node, click General Information.
  2. In the property list, double-click the value field of a property to edit its value.
  3. Click elsewhere in the property list to see your changes take effect.

Dividing Your Product into Features

From the perspective of the application user and InstallShield Express, a feature is considered a building block of an application. Features make it possible for users to install parts of an application. For example, during Visual FoxPro installation, you can specify whether to install the Visual FoxPro Samples and Visual FoxPro Tools as features.

Note Dividing your product into features is not required when creating a Setup program, although it can be helpful to users.

The default setting for installing features is Always Install, which lists the components that install with all Setup Types.

To create a feature

  1. In the Organize Your Setup node, click Features.
  2. To add a new feature, right-click the Features node in the tree view in the middle pane, and click New Feature Ins.
  3. Type a name for the new feature, and press ENTER.

When you have identified the your product features, you can set feature properties, such as feature description, how the feature is advertised, and whether the feature is required. Although advertised features appear to be installed to the user, they are not installed during setup. Windows Installer installs the advertised feature when the user tries to use the feature for the first time.

To set a feature property

  1. Select the feature for which you want to modify properties.
  2. In the property list, double-click the value field of the property to edit its value.

    To display more options, click the ellipsis (...) or arrow button that appears next to the property value field when additional options are available.

  3. Type or select a new value for the property.

For example, suppose you wanted to provide the option of installing the Help file for your application. Follow the steps to create the feature, and name it "Help file." If you want to make the Help file installation optional, set the Required property to No. If you want the feature to be installed the first time the user tries to invoke the feature by pressing F1 for Help, set the Advertised property to Yes.

Specifying Features for a Setup Type

You can include different Setup types in a Setup program and specify which features each Setup type should install. Setup types offer different levels of installation that the user can choose:

  • Typical Setup installs all features and files.
  • Minimal Setup installs the minimum number of features and files necessary for an application to function.
  • Custom Setup makes it possible to specify which features to install.

You must include at least one Setup type.

All three Setup types install features listed by Always Install. For example, a basic Setup includes features listed by Always Install and the &Typical Setup type. The ampersand (&) in the Setup type name indicates the access key for a particular Setup type in the Setup user interface. You can include or remove Setup types depending on whether you want it included, as long as one remains available, or rename the Setup types.

Note Specifying features for each Setup type is not required when creating a Setup program.

To select Setup types and specify features for each Setup type

  1. In the Organize Your Setup node, click Setup Types.
  2. In the Setup Types pane, select the check box for each Setup type you want to include.
  3. In the Features installed for <selected> setup type pane, select the check box for each feature you want to this Setup type to install.

Adding Files to Setup

The executable (.exe) file is usually needed for the user to start an application. You can add this file first along with other files your application requires, followed by any optional files.

Visual FoxPro provides resource files that extend the basic functionality of your applications, including FoxUser resource files, API libraries, and Microsoft ActiveX controls. If you use these files, you must add them to the Setup program so they can be installed when running Setup. For more information about resource files that you can use, see Resource Files in Applications.

To view files you can add to Setup

  • In the Specify Application Data node, click Files.

The Files view is divided into four panes. The left panes display folders on the source and destination computers. The right panes display the files in those folders. The Feature box appears above the four panes.

Note The INSTALLDIR property specifies the directory containing the root folder for your application files and is usually specified as the destination installation directory.

Before adding files to the Setup project, you must specify the feature to associate those files with by selecting it in the Feature box.

Note Add required files as Always Install features.

Make sure the feature appears in the Feature box. After selecting the feature, you can add files to the Setup project by copying them from the source folders to the folders on the destination computer.

To add files from the source folder to the destination folder

  1. In the Destination computer's folders pane, select the destination folder where you want to install the application file.
  2. In the Source computer's files pane, drag the source file to the destination folder.
    Note The folder specified by INSTALLDIR in the General Information node as the default installation directory should appear in the Destination computer's folders pane. Dragging the source file to the destination folder only instructs InstallShield Express where to locate the source file when you build your Setup program. It does not move or remove any files on the source computer.

You can also view a list of predefined folders, such as the desktop folder, that you can select and add to the list of destination computer folders.

To view and add predefined folders

  1. In the Destination computer's folders pane, right-click Destination Computer.
  2. Click Show Predefined Folders.
  3. Select the folder you want to add.

    The folder appears in the list of destination computer folders.

You can create one or more subfolders in a destination folder.

To create a subfolder in a destination folder

  1. Right-click the destination folder, and click Add.
  2. Type a name for the new folder, and press ENTER.

Registering Files

Windows Installer includes the following capabilities:

  • Roll back an unsuccessful installation, returning the target computer to its preinstallation state.

    For example, COM Servers, such as ActiveX, COM, and COM+ files, require special registration so applications can access their interfaces. These .ocx, .exe, and .dll files traditionally contained self-registration functions that can be invoked to register the files during installation. However, relying on self-registration can cause some problems with Windows Installer.

    Note When registering a COM Server, it is highly recommended that you select Extract COM Information instead of Self-registration as the registration type for the file. If you select Self-registration, Windows Installer will not have the information needed to remove the COM Server from the registry properly.

    With traditionally scripted Setup programs, self-registration was acceptable for installing COM objects and is still valid. However, self-registering COM objects do not pass their installation and registration information to Windows Installer. Therefore, Windows Installer cannot roll back installation and registration of self-registered COM objects or advertise those objects.

  • Advertise installed products or individual product elements, such as COM objects.

    Advertising makes a product or COM object available to the user or target computer without installing the product until the user or another computer function attempts to access the advertised element. Advertisement occurs by placing a shortcut in the appropriate location such as the Start menu or registry.

To register a COM server with InstallShield Express

  1. In the Specify Application Data node, click Files.
  2. Copy the file for the COM Server from the source folder to the destination folder.
  3. Right-click the file you want to register, and click Properties.
  4. In the Properties dialog box, click the COM & .NET Settings tab.
  5. Select a Registration Type.

For more information registering COM Servers, see Visual FoxPro Distribution Scenarios.

Selecting Objects and Merge Modules

A merge module (.msm file) contains all of the logic, registry entries, and files needed to install an application or run-time files successfully. If you were to install your application manually, you would need to copy the Visual FoxPro run-time files to the destination computer and register those files. However, if you select the Microsoft Visual FoxPro 8 Runtime Libraries merge module, InstallShield Express copies and registers the run-time files properly.

For a Visual FoxPro application, you should select, at the minimum, the Microsoft Visual FoxPro 8 Runtime Libraries and XML 4.0 modules. For more information about Visual FoxPro run-time libraries, see Visual FoxPro Run-Time Libraries.

Note When you select the Microsoft Visual FoxPro 8 Runtime Libraries module in InstallShield Express, the check boxes for the Microsoft Visual C++ Runtime Library 7.0 and GDI Plus Redist modules are automatically selected and should remain selected. Visual FoxPro 8.0 requires these modules; therefore, do not clear selection of these modules.

To select objects and merge modules for installation

  1. In the Specify Application Data node, click Objects/Merge Modules.
  2. In the InstallShield Objects/Merge Modules pane, select the check box for each merge module you want to install.
  3. You can install a merge module feature by feature by selecting or clearing the check boxes in the Conditional Installation pane when available.

For more information on merge modules, see Visual FoxPro Distribution Scenarios.

Creating Shortcuts and Folders

InstallShield Express makes it possible for you to create shortcuts and folders in the Start menu and on the desktop.

To create folders or shortcuts

  1. In the Configure the Target System node, click ShortCuts/Folders.
  2. From the Shortcuts tree view in the middle pane, right-click the node where you want to install a shortcut or folder, and click New Shortcut or New Folder.
  3. If you created a shortcut, you must specify a target file. In the Browse for Shortcut Target dialog box, double-click the file for which you want to create a shortcut in the Look in list.

    You can also associate your shortcut with a feature by navigating to the folder containing the file associated with the feature and selecting the file from the list.

  4. Type a name for the shortcut or folder, and press ENTER.

    To rename the folder or shortcut right-click it, click Rename, type a new name, and press ENTER.

    Note Files for your application are at the bottom of the Look in list.

Creating Registry Keys

If your application uses registry keys, for example, to keep track of user options, InstallShield Express can add them to the target computer during setup. If the keys do not exist on the development computer, you can create them manually.

Note Creating registry keys is not required when creating a Setup program.

Registry entries are created in registry hives. Registry hives categorize registry entries by function. For example, COM Server classes are stored in the HKEY_CLASSES_ROOT registry hive. Software options, such as options for Visual FoxPro, are stored in the Software folder in the HKEY_CURRENT_USER hive.

To create registry keys

  1. In the Configure the Target System node, click Registry.
  2. In the Destination computer's Registry view pane, right-click the desired registry hive.
  3. On the shortcut menu, point to New, and click Key.
  4. Type a name for the key, and press ENTER.
  5. Right-click the new key, point to New, and select the type of value you want to add to the key.
  6. In the Destination computer's registry data pane, double-click the key to enter a data value.

    Depending on the type of key, you can enter a name for it.

Creating Open Database Connectivity (ODBC) Data Source Names (DSNs)

If the development computer has previously existing DSNs, you can instruct InstallShield Express to install the DSN on the destination computer. If you are installing DSNs, you should include the MDAC merge module when selecting merge modules in case the destination computer does not have ODBC components installed.

Note Creating ODBC DSNs is not required when creating a Setup program.

To create DSNs

  1. In the Configure the Target System node, click ODBC Resources.
  2. In the ODBC Resources tree view, select the check boxes for the DSNs you want to create on the destination computer.

Customizing Setup Appearance

You can select and change the appearance of dialog boxes that users see when installing your application. You can specify bitmap (.bmp) images for each dialog box and add additional dialog boxes, for example, to allow the user to specify a destination folder.

Note Customizing Setup appearance is not required when creating a Setup program.

To select dialog boxes

  1. In the Customize the Setup Appearance node, select Dialogs.
  2. In the Dialogs tree view, select the dialog boxes you want to display during installation.

    When you select a dialog box, an image of the dialog box appears in the lower-left pane, and properties for the dialog box appear in the upper-right pane.

To make it possible for the user to specify a destination folder

  1. In the Customize the Setup Appearance node, select Dialogs.
  2. In the Dialogs tree view, click Destination Folder.

Building Your Setup Program

After you have finished designing and setting the properties for all the elements in your Setup project, including the features, files, shortcuts, registry entries, and user interface, you are ready to build your Setup program.

The most commonly selected build types are CD-ROM or single image. Selecting CD_ROM creates a Setup program that contains files organized in a directory structure. Selecting SingleImage combines the files into a single file.

To build a Setup program

  1. In the Prepare for Release node, click Build Your Release.
  2. In the Builds tree view, select the type of media you want to build.
  3. In the property list, set or edit the build properties.
  4. To build your Setup program, right-click the selected media type, and click Build.

    InstallShield Express places the built Setup package into the following folder:

    <project directory>\Express\<media type>\DiskImages\DISK1

Testing Your Setup Program

It is important to test your Setup program. You can do so without running the actual installation using InstallShield Express.

To test your Setup program with InstallShield Express

  1. In the Prepare for Release node, click Test Your Setup.
  2. In the Builds tree view, select the media type containing the build you want to test.
  3. If you want to run the Setup program and install your application and its files on the development computer, click Run Your Setup.

    -or-

    If you want to test only the Setup dialog boxes and any custom actions you have chosen, click Test Your Setup.

    This option does not install any files or make any system changes.

Distributing an Application

After building and testing your Setup program, you are ready to distribute it.

To distribute your Setup program

  1. In the Prepare for Release node, click Distribute Your Release.
  2. In the Builds tree view, select the media type containing the build you want to distribute.
  3. Enter the location, or click Browse and navigate to the location where your Setup package will be copied.
  4. Click Distribute to Location.

You can also copy your Setup package to an FTP location.

For additional information and options for distributing applications, see the InstallShield Express documentation.

Visual FoxPro Distribution Scenarios

This walkthrough assumes you are installing a simple Visual FoxPro application that does not have dependencies other than the Visual FoxPro Runtime Libraries. The following information includes instructions needed for distribution scenarios other than installing only Visual FoxPro applications and their native data. For these scenarios, add the following appropriate merge modules when selecting objects and merge modules for your Setup program.

Web Services and SOAP

If your application uses Web services or SOAP, you must include the following merge modules:

  • SOAP SDK Files (Soap_Core.msm)
  • Visual Basic Virtual Machine (MSVBVM60.msm)
  • Microsoft Component Category Manager Library (Comcat.msm)
  • Microsoft OLE 2.40 (OLEAUT32.msm)

Microsoft Visual FoxPro OLE DB Provider

The Visual FoxPro OLE DB Provider makes it possible for both Visual FoxPro and other applications to access Visual FoxPro data using OLE DB or ActiveX Data Objects (ADO). To install the Visual FoxPro OLE DB Provider on the destination computer, include the Microsoft Visual FoxPro OLE DB Provider (VfpOLEDB.msm) merge module.

ActiveX Controls

ActiveX controls are a common element of many Visual FoxPro applications. To include ActiveX controls with your InstallShield Express Setup, you should include the Microsoft Component Category Manager Library (Comcat.msm) merge module.

Note Windows 2000 and Windows XP also install files in this merge module.

The ActiveX controls you install affect the type of merge modules you need to install and the extra steps you must take to install them.

  • Common ActiveX Controls

    These are common ActiveX controls that ship with Visual FoxPro and Microsoft Visual Studio. InstallShield Express ships with merge modules for most of these controls.

    If necessary, add the appropriate merge module for the needed control. For example, if your application uses the Treeview control, you should include the MSCOMCTL.msm merge module.

    Note The Common ActiveX Controls included in the InstallShield Express merge modules contain registration information that is compliant with Windows Installer.
  • Microsoft Foundation Class (MFC) Controls

    Some older controls, such as the Calendar control, use the MFC libraries; therefore, it is recommended that you include the appropriate MFC merge modules, such as MFC42.msm. As with VBCCE controls, you must add the control manually to the project and set various settings.

  • Third-party controls

    Be sure to register any included third-party controls. In addition, you might need to add specific registry keys using the InstallShield Express Registry window for any necessary licensing requirements.

    For more information about third-party controls, see the documentation provided by the vendor about how and where to install these controls. Third-party control documentation should also provide information about any needed dependency files, such as MFC files.

To make sure that Windows Installer can roll back or advertise installed files, you must install files in a manner compliant with Windows Installer requirements. Self-registration of files is not compliant with Windows Installer requirements. You can make sure InstallShield Express installs COM objects that are compliant with Windows Installer by following the instructions about registering files in this topic. For more information, see the InstallShield Express online documentation.

Applications Using HTML Help

The Microsoft Visual FoxPro HTML Help Support Library (VFPHTMLHelp.msm) merge modules include both FOXHHELP.exe and FOXHHELPPS.dll files needed to support context-sensitive HTML Help within your Visual FoxPro applications.

In addition to your application-specific .chm file, you can include the core HTML Help viewer files. Later versions of Microsoft Internet Explorer include these files. You also can distribute them with the HHUPD.exe file available on the Microsoft Developer Network (MSDN).

Applications Using MDAC Components

For Visual FoxPro applications running on operating systems earlier than Windows 2000 or Windows XP, it is recommended that you include the Microsoft Data Access Components (MDAC) merge module (MDAC25.msm) if your applications use any of the following data components:

  • ODBC drivers, including Microsoft Visual FoxPro ODBC Driver (VfpODBC.msm)
  • OLE DB Provider
  • ADO, RDS

COM Servers

The Windows Installer rollback and advertising features make it possible to undo component installation and registration if the product installation does not succeed. However, you must install and register COM objects correctly to make these features available. To register installed COM objects correctly, set the Registration Type to Extract COM Information. Self-registering installed COM objects sacrifices Windows Installer rollback and advertising functionality.

For more information, see the instructions about registering files in this topic.

Localized Applications

The Visual FoxPro Runtime Libraries (VFP8Runtime.msm) contain the standard language-neutral resource file (VFP8renu.dll) used for shipping all English (US) applications. If you want to include support for another localized resource file (VFP8rxxx.dll), include the appropriate Microsoft Visual FoxPro Resource merge module that contains the localized resource file you want.

Note Localized resource files do not localize Setup dialog boxes. You can select the desired language for Setup dialog boxes when you create your Setup project.

To include a localized Visual FoxPro resource file

  1. In the Specify Application Data node, click Objects/Merge Modules.
  2. To identify the Microsoft Visual FoxPro Resource merge module you want, look at the description for each merge module in the lower-left pane.
  3. Select the merge module you want.

    For example, to include the German resource file, select the VFP8rdeu.msm merge module. The following table lists available merge modules containing the corresponding localized resource files.

    Language | Merge Module
    Chinese, Simplified | VFP8rchs.msm
    Chinese, Traditional | VFP8rcht.msm
    Czech | VFP8rcsy.msm
    French | VFP8rfra.msm
    German | VFP8rdeu.msm
    Korean | VFP8rkor.msm
    Russian | VFP8rrus.msm
    Spanish, International Sort | VFP8resn.msm

Additional Information

You can download the Platform SDK Components for Windows Installer Developers from the Microsoft download Web site at http://www.microsoft.com/msdownload/platformsdk/sdkupdate/.

See Also

Walkthroughs | Resource Files in Applications | Distributable and Restricted Visual FoxPro Features and Files


Reference

The Visual FoxPro reference includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.

In This Section

General Reference
Includes Visual FoxPro related technical information, including file types, file structures, and other reference information about Visual FoxPro elements.
Language Reference
Provides a list of language reference topics in alphabetical order
User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Error Messages
Provides information about some of the more common error messages in Visual FoxPro.

Related Sections

Getting Started with Visual FoxPro
Provides information about installing, upgrading, and configuring Visual FoxPro, as well as customizing the development environment.
Using Visual FoxPro
Gives an overview of Visual FoxPro features, concepts, and productivity tools for developing and managing high-performance database applications and components.
Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
Samples
Provides code samples that you can use for experimenting and becoming acquainted with features.


General Reference

This section contains more general technical information, including file types, file structures, and other reference information about Visual FoxPro elements.

In This Section

Autoincrementing Field Values in Tables
Explains how to automatically increment, or autoincrement, field values for both database container (DBC) tables and free tables by using Visual FoxPro commands or the Table Designer.
Data and Field Types
Provides links to information about data types used in Visual FoxPro and conversions to other data types, such as XML Schema data types.
Data Manipulation
Provides information on expressions that you can build to get full access to the power of manipulating data in Visual FoxPro.
Data Storage Containers
Discusses how you determine which type of data storage container to use and summarizes the scope differences between different data containers.
Expression Building
Provides information on how Visual FoxPro expressions combine data and operators to create a value of a given data type.
File Structures
Contains technical information about file structures and file types.
Fonts Overview
Shows how Visual FoxPro can use the fonts you have installed to determine the appearance of displayed or printed text as well as the position and size of controls.
Graphics Support in Visual FoxPro
Discusses Graphics Device Interface+ (GDI+), the graphics device interface for Microsoft Windows XP and future releases of the Windows operating system. Visual FoxPro supports all graphics formats that GDI+ supports.
Join Conditions for Tables, Queries, and Views
Describes join conditions used to specify relationships between tables, usually based on the primary and foreign keys, when retrieving data from tables to create queries and views.
Keyboard Shortcuts
Provides information on keyboard shortcuts supported in Visual FoxPro.
Naming Conventions
Discusses the choice of names for exposed objects, properties, and methods that can be understood by users of the application easily.
Regular Expressions and Operators
Describes regular expressions and operators, which are symbols that you can use to create more complex searches for finding and replacing patterns of text.
Reserved Words
Provides a list of reserved words that you should avoid using as names when programming.
Special Terms for Configuration Files
Provides a list of special terms you can use in configuration files.
System Menu Names
Provides a list of the internal names and user interface names for the Visual FoxPro system menu bar, menu titles, menus, and menu items. With these names, you can use the Visual FoxPro system menu bar to create a menu system for your own application.
Visual FoxPro and Other Programming Languages
Provides a comparison of Visual FoxPro language elements with other programming languages.
Visual FoxPro System Capacities
Lists the maximum and minimum system limits for Visual FoxPro table and index files, field characteristics, variables and arrays, program and procedure files, Report Designer capacities, and so on.
XSource Folder
Lists the .zip files in the XSource folder that expand into the Solution Sample HTML Help files and folders that contain other additions to Visual FoxPro, such as the Addlabel, Browser, Builder, Coverage, and Wizards source files.

Related Sections

Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Error Messages
Provides information about some of the more common error messages in Microsoft Visual FoxPro.
Using Visual FoxPro
Gives an overview of Visual FoxPro features, concepts, and productivity tools for developing and managing high-performance database applications and components.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Autoincrementing Field Values in Tables

You can specify automatically incrementing field values for both database container (DBC) tables and free tables. A table can contain multiple fields that use autoincrementing, which Visual FoxPro supports only for fields of Integer data type but not for local, remote, or offline views.

You can turn on autoincrementing for a field in a database container (DBC) or free table by using Visual FoxPro commands or the Table Designer. You can retrieve the autoincrement settings for a field using the DISPLAY STRUCTURE and LIST commands.

A field that uses autoincrementing becomes read-only and cannot be changed with an insert, update, or replace operation. Attempting to update such a field generates an error message unless you set the AutoIncError cursor property to False (.F.) or turn the error message off by using the SET AUTOINCERROR command. For more information, see the AutoIncError property in CURSORSETPROP( ) Function and SET AUTOINCERROR Command.

When you change a table that does not contain an autoincrementing field to include one, either by using ALTER TABLE or the Table Designer, autoincrementing begins with the next added row. Previous rows in the table are not updated with autoincrementing values starting with the first record. You need to make sure that no conflicts occur as a result.

When you turn on autoincrementing for any field in a table, Visual FoxPro sets byte 0 to 0x31 for the file type "Visual FoxPro, Autoincrement enabled" in the table (.dbf) header record structure. Visual FoxPro sets byte 18, bytes 19 to 22, and byte 23 in the field subrecords structure to the following values, respectively:

  • 0x0C for the autoincrementing column
  • Next autoincrement value
  • Step autoincrement value

For more information, see Table File Structure.

Issues Concerning Using Automatically Incrementing Field Values

Tables containing automatically incrementing field values append table-buffered records approximately 35% slower than tables without automatically incrementing field values, which might affect performance. When using table buffering, the table header is locked when the record is appended.

Visual FoxPro does not manage gaps in generated sequences. Gaps can be caused by reverting an appended or inserted record or by failing to update the base table and so on. In all cases, the unused value is lost, and the next generated value remains the same as if the append or insert operation succeeded.

Older versions of Visual FoxPro cannot recognize tables that use autoincrementing. If you remove autoincrementing, the current state containing the last incrementing and incremental values is cleared from the .dbf field subrecord and discarded. The .dbf type is restored to the current Visual FoxPro type value. The autoincrement values previously stored in each record remain.

Autoincrement Using Visual FoxPro Commands

You can use the AUTOINC clause in the CREATE TABLE and ALTER TABLE SQL commands to turn on autoincrementing for fields. For more information about using the AUTOINC clause, see CREATE TABLE - SQL Command and ALTER TABLE - SQL Command.

Autoincrement Using the Table Designer

The Fields tab in the Table Designer includes a data type called Integer (AutoInc) in the Type drop-down list for a particular field. When you select the Integer (AutoInc) data type for a particular field, Visual FoxPro enables autoincrementing for that field.

Note When you select the Integer (AutoInc) data type for a newly created field, the default value field in the Fields tab becomes unavailable. If you want to specify a default value, you must first change the Integer (AutoInc) data type.
When you select the Integer (AutoInc) data type for an existing field with a default value, the default value field becomes unavailable. However, Visual FoxPro neither discards nor uses the value. The default value field becomes available again when you change the data type from Integer (AutoInc). Additionally, expressions that you type in the default value field remain when you change the field type to or from Integer (AutoInc). You can still use code such as DBGETPROP( ) that retrieves the default value for a field.

The Fields tab includes the AutoIncrement group box, which contains the Next Value and Step spin boxes. You can use these spin boxes to set the start and increment values for the field value. For more information about the Next Value and Step values and setting autoincrementing properties using the Table Designer, see Fields Tab, Table Designer and Setting Autoincrementing Field Values.

Local Views

Views do not "inherit" autoincrementing behavior of the base table, and the fields in the view that represent autoincrementing fields in the base table are read/write. Autoincrementing occurs in the base table when the row or rows are updated in the base table. You must use the REQUERY( ) function if you want to refresh the view with the autoincrement value previously generated.

Buffered Tables

Visual FoxPro does not perform any autoincrementing management relative to buffered tables. All appended and inserted records have autoincrementing values generated regardless of whether table or row buffering is active. In the case of buffering, when the TABLEUDPATE( ) function is called, the base table is updated with the previously generated value. If the update does not occur, for example, the TABLEREVERT( ) function is called, any autoincrementing values that are generated are discarded, thus resulting in gaps in the sequence.

Record Locking

When you turn on autoincrementing for a field, the start and incremental values, Next Value and Step, are stored in the table (.dbf) header in the unused or reserved portion of the field subrecord for the specified field. Next Value is stored as a 4-byte integer. The Step value is stored as a 1-byte integer with a maximum value of 255. The value actually used to increment the field value is the sum of the value stored in the .dbf header and the incremental value. The operation sequence occurs as follows:

  • Perform an insert or append operation.
  • Lock header.
  • Increase the currently stored increment value by the Step value and apply to the field.
  • Store the new value, which is the value of the newly added record, in the .dbf file header.
  • Unlock header when insert or append operation completes. The header contains the last incremented value.

See Also

General Reference | Adding Fields | Editing Fields | DBGETPROP( ) Function | LIST Commands | DISPLAY STRUCTURE Command | CURSORGETPROP( ) Function


Data and Field Types

This section contains a list of data types and functions you can use to operate on data types.

In This Section

Visual FoxPro Data and Field Types
Provides information about Visual FoxPro data types, including descriptions and permissible values and the range and size of those values.
Visual FoxPro and XML Schema Data Type Mapping
Describes XML Schema data types and shows how they map to Visual FoxPro data types and the reverse.
Character Data Type
Discusses when you would choose the Character data type.
Currency Data Type
Discusses when you would use the Currency data type as opposed to Numeric.
Date Data Type
Discusses the Date data type and the rules that apply to it.
DateTime Data Type
Discusses when you would choose this data type and the rules that apply.
Double Field Type
Describes when you would use this type instead of Numeric.
Float Field Type
Provides information about the Float data type, which is functionally equivalent to Numeric.
General Field Type
Provides information about when you would use the General field type.
Integer Field Type
Discusses the Integer field type, which is used for non-decimal numeric values where performance and table storage limitations are important.
Logical Data Type
Describes an efficient way to store data that has only two values
Memo Field Type
Describes the Memo field type, which is used to store blocks of data.
Numeric Data Type
Discusses when you would use Numeric data.
Variant Data Type
Discusses data types that can contain any kind of data except fixed-length data.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Visual FoxPro Data and Field Types

All data in Visual FoxPro have a particular data type, which defines the values permitted for the data and the range and size of those values. After you identify and specify the data type you are using, Visual FoxPro can efficiently store and manipulate the data.

When you create a table, you can specify the type of data to be stored in each field of the table. You can specify more data types for fields in a table than for variables and arrays. Variables and arrays can store only a subset of the available Visual FoxPro data types; however. The value you store in a variable or array element determines the type of data in the variable or array element. For more information, see Choosing Data Types.

Tip You can use the TYPE( ) function to determine the type of data stored in a variable, array element, or field.

The following table lists the data types in Visual FoxPro.

Visual FoxPro Data Types

Data type | Description | Size | Range
Character | Alphanumeric text For example, a customer address | 1 byte per character to 254 | Any characters
Currency | Monetary amounts For example, the price of an item | 8 bytes | - $922337203685477.5807 to $922337203685477.5807
Date | Chronological data consisting of month, day, and year For example, an order date | 8 bytes | When using strict date formats, {^0001-01-01}, January 1st, 1 A.D to {^9999-12-31}, December 31st, 9999 A.D.
DateTime | Chronological data consisting of month, day, year, hours, minutes, and seconds For example, date and time of arrival | 8 bytes | When using strict date formats, {^0001-01-01}, January 1st, 1 A.D to {^9999-12-31}, December 31st, 9999 A.D., plus 00:00:00 a.m. to 11:59:59 p.m.
Logical | Boolean value of True or False For example, whether or not an order has been filled | 1 byte | True (.T.) or False (.F.)
Numeric | Integers or decimal numbers For example, the quantity of items ordered | 8 bytes in memory; 1 to 20 bytes in table | - .9999999999E+19 to .9999999999E+20
Variant | A variant can contain any of the Visual FoxPro data types and the null value. Once a value is stored to a variant, the variant assumes the data type of the data it contains. Variants are designated with an e prefix in language syntax. | See data types above. | See data types above.

In addition, Visual FoxPro provides data types that apply only to fields in tables.

Visual FoxPro Field Types

Field type | Description | Size | Range
Character (Binary) | Any Character data that you do not want translated across code pages For example, user passwords stored in a table and used in different countries or regions | 1 byte per character to 254 | Any characters
Double | A double-precision floating-point number For example, scientific data requiring a high degree of precision | 8 bytes | +/-4.94065645841247E-324 to +/-8.9884656743115E307
Float | Same as Numeric | 8 bytes in memory; 1 to 20 bytes in table | - .9999999999E+19 to .9999999999E+20
General | Reference to an OLE object For example, a Microsoft Excel worksheet | 4 bytes in table | Limited by available memory
Integer | Numeric value with no decimals For example, a line number in an order | 4 bytes | -2147483647 to 2147483647
Integer (Autoinc) | Same as Integer but also an automatically incrementing value. Read-only. | 4 bytes | Value controlled by autoincrement Next and Step values.
Memo | Alphanumeric text of indeterminate length or reference to a block of data For example, notes about a phone call in a phone log | 4 bytes in table | Limited by available memory
Memo (Binary) | Same as Memo except that memo field data does not change across code pages For example, a login script used in different countries or regions | 4 bytes in table | Limited by available memory

Each data type has its own characteristics, including storage size:

Data Type Storage Differences

To see a list of the functions you can use with each data type, see Language Categories.

See Also

Data and Field Types


Visual FoxPro and XML Schema Data Type Mapping

The following tables show the following data type mappings:

  • XML Schema primitive data types to Visual FoxPro data types
  • XML Schema derived types to Visual FoxPro data types
  • Visual FoxPro data types to XML Schema Definition (XSD) data types
  • XML Data Reduced (XDR) Schema data types to Visual FoxPro data types

XML Schema Primitive Data Types to Visual FoxPro Data Types

XML data type | Facets | Description | Visual FoxPro data type
anyURI | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents a Uniform Resource Identifier (URI) as defined by RFC 2396. An anyURI value can be absolute or relative and might have an optional fragment identifier. | Memo. Visual FoxPro applies a hyperlink to a URI in a Memo.
base64Binary | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents base64-encoded arbitrary binary data. A base64Binary is the set of finite-length sequences of binary octets. | Memo (Binary) or Character (Binary)
boolean | pattern, whiteSpace | Represents Boolean values, which are either true or false. | Logical
date | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a calendar date. The pattern for date is CCYY-MM-DD with an optional time zone indicator as allowed for dateTime. | Date
dateTime | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | This representation might be followed immediately by letter "Z" to indicate Coordinated Universal Time (UTC) or to indicate the time zone. For example, the difference between the local time and UTC, immediately followed by positive or negative sign (+ or -), followed by the difference from UTC represented as hh:mm. Minutes are required. If the time zone is included, both hours and minutes must be present. | DateTime
decimal | enumeration, pattern, totalDigits, fractionDigits, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents arbitrary precision numbers. | Numeric, Currency, or Character
double | pattern, enumeration, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents double-precision 64-bit floating-point numbers. | Double
duration | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents duration of time. The pattern for duration is PnYnMnDTnHnMnS, where nY represents the number of years, nM the number of months, nD the number of days, T the date/time separator, nH the number of hours, nM the number of minutes, and nS the number of seconds. For example, to indicate a duration of 1 year, 2 months, 3 days, 10 hours, and 30 minutes, you write: P1Y2M3DT10H30M. You could also indicate a duration of minus 120 days as -P120D. | Character (C(30))
float | pattern, enumeration, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents single-precision 32-bit floating-point numbers. | Double
gDay | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a Gregorian day that recurs, specifically a day of the month, such as the fifth day of the month. A gDay is the space of a set of calendar dates. Specifically, it is a set of one-day long, monthly periodic instances. The pattern for gDay is --DD with an optional time zone indicator as allowed for date. | Character (C(10))
gMonth | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a Gregorian month that recurs every year. A gMonth is the space of a set of calendar months. Specifically, it is a set of one-month long, yearly periodic instances. The pattern for gMonth is -MM- with an optional time zone indicator as allowed for date. | Character (C(10))
gMonthDay | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a specific Gregorian date that recurs, specifically a day of the year, such as the third of May. A gMonthDay is the set of calendar dates. Specifically, it is a set of one-day long, annually periodic instances. The pattern for gMonthDay is --MM-DD with an optional time zone indicator as allowed for date. | Character (C(10))
gYear | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a Gregorian year. A set of one month-long, nonperiodic instances. The pattern for gYear is CCYY with an optional time zone indicator as allowed for dateTime. | Character (C(15))
gYearMonth | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents a specific Gregorian month in a specific Gregorian year. A set of one month-long, nonperiodic instances. The pattern for gYearMonth is CCYY-MM with an optional time zone indicator. | Character (C(15))
hexBinary | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents arbitrary hex-encoded binary data. A hexBinary is the set of finite-length sequences of binary octets. Each binary octet is encoded as a character tuple, consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. | Character (Binary) when maxLength is specified and less than 255 characters. Otherwise, Memo (Binary).
NOTATION | length, enumeration, pattern, maxLength, minLength, whiteSpace | Represents a NOTATION attribute type. A set of QNames. | Memo
QName | length, enumeration, pattern, maxLength, minLength, whiteSpace | Represents a qualified name. A qualified name is composed of a prefix and a local name separated by a colon. Both the prefix and local names must be an NCName. The prefix must be associated with a namespace Uniform Resource Identifier (URI) reference, using a namespace declaration. | Memo
string | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents character strings. | Character when maxLength is specified and less than 255 characters. Otherwise, Memo.
time | enumeration, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, whiteSpace | Represents an instance of time that recurs every day. The pattern for time is hh:mm:ss.sss with an optional time zone indicator. | Character (C(20))

XML Schema Derived Types to Visual FoxPro Data Types

XML data type | Facets | Description | Visual FoxPro data type
anyType | Unknown | Unknown. Not an XSD type but exists in MSXML. | Memo
byte | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum value of -128 and maximum of 127. This data type is derived from short. | Integer
ENTITIES | length, maxLength, minLength, enumeration, whiteSpace | Represents the ENTITIES attribute type and contains a set of values of type ENTITY. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
ENTITY | length, enumeration, pattern, maxLength, minLength, whiteSpace | Represents the ENTITY attribute type in XML 1.0 Recommendation. This is a reference to an unparsed entity with a name that matches the specified name. An ENTITY must be an NCName and must be declared in the schema as an unparsed entity name. This data type is derived from NCName. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
ID | length, enumeration, pattern, maxLength, minLength, whiteSpace | Represents the ID attribute type defined in the XML 1.0 Recommendation. The ID must be a no-colon-name (NCName) and must be unique within an XML document. This data type is derived from NCName. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
IDREF | length, enumeration, pattern, maxLength, minLength, whiteSpace | Represents a reference to an element that has an ID attribute that matches the specified ID. An IDREF must be an NCName and must be a value of an element or attribute of type ID within the XML document. This data type is derived from NCName. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
IDREFS | length, maxLength, minLength, enumeration, whiteSpace | Represents the IDREFS attribute type and contains a set of values of type IDREF. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
int | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum value of -2147483648 and maximum of 2147483647. This data type is derived from long. | Integer
integer | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents a sequence of decimal digits with an optional leading sign (+ or -). This data type is derived from decimal. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
language | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents natural language identifiers (defined by RFC 1766). This data type is derived from token. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
long | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum value of -9223372036854775808 and maximum of 9223372036854775807. This data type is derived from integer. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
Name | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents names in XML. A Name is a token that begins with a letter, underscore, or colon and continues with name characters (letters, digits, and other characters). This data type is derived from token. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
NCName | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents noncolonized names. This data type is the same as Name, except it cannot begin with a colon. This data type is derived from Name. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
negativeInteger | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer that is less than zero and consists of a negative sign (-) and sequence of decimal digits. This data type is derived from nonPositiveInteger. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
NMTOKEN | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents the NMTOKEN attribute type. An NMTOKEN is set of name characters, such as letters, digits, and other characters, in any combination. Unlike Name and NCName, NMTOKEN has no restrictions on the starting character. This data type is derived from token. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
NMTOKENS | length, maxLength, minLength, enumeration, whiteSpace | Represents the NMTOKENS attribute type and contains a set of values of type NMTOKEN. | Memo
nonNegativeInteger | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer that is greater than or equal to zero. This data type is derived from integer. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
nonPositiveInteger | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer that is less than or equal to zero and A nonPositiveInteger consists of a negative sign (-) and sequence of decimal digits. This data type is derived from integer. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
normalizedString | length, pattern, maxLength, minLength, enumeration, whiteSpace | Represents white space normalized strings. This data type is derived from string. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
positiveInteger | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer that is greater than zero. This data type is derived from nonNegativeInteger. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
token | enumeration, pattern, length, minLength, maxLength, whiteSpace | Represents tokenized strings. This data type is derived from normalizedString. | Character, if maxLength is specified and less than 255. Otherwise, Memo.
short | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum value of -32768 and maximum of 32767. This data type is derived from int. | Integer
unsignedByte | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum of zero and maximum of 255. This data type is derived from unsignedShort. | Integer
unsignedInt | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum of zero and maximum of 4294967295. This data type is derived from unsignedLong. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
unsignedLong | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum of zero and maximum of 18446744073709551615. This data type is derived from nonNegativeInteger. | Integer, if totalDigits is less than 10. Otherwise, Character with totalDigits respected.
unsignedShort | enumeration, fractionDigits, pattern, minInclusive, minExclusive, maxInclusive, maxExclusive, totalDigits, whiteSpace | Represents an integer with a minimum of zero and maximum of 65535. This data type is derived from unsignedInt. | Integer

Visual FoxPro Data Types to XML Schema Definition (XSD) Data Types

Visual FoxPro data type | XSD data type and examples | Restrictions and sample restriction | Comments
Character xs:string

Confirm this is electric

<xs:element name="cc04" minOccurs="0">

   <xs:simpleType>
       <xs:restriction base="xs:string">
      <xs:maxLength value="128"/>
       </xs:restriction>
   </xs:simpleType>
</xs:element>
Character (Binary) xs:base64Binary <xs:element name="cc04" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:base64Binary">

<xs:maxLength value="128"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

 Content is translated to base64 encoding.
Character (Binary) xs:hexBinary <xs:element name="cc04" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:hexBinary">

<xs:maxLength value="128"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

 Content is translated to hexBinary encoding.
Currency xs:decimal

-1.23, 0, 123, 4, 1000.00

<xs:element name="yc07" minOccurs="0">

    <xs:simpleType>
   <xs:restriction base="xs:decimal">
      <xs:totalDigits value="19"/>
      <xs:fractionDigits value="4"/>
   </xs:restriction>
    </xs:simpleType>
</xs:element>
Currency is always 19,4.
Date xs:date

1999-05-31

 None
DateTime xs:dateTime

1999-05-31T13:20:00.000-05:00

 None
Double xs:double

-INF, -1E4, -0, 0, 12.78E-2, 12, INF, NaN

 None The export value should include the maximum scale allowed for double and not be limited to display scale (internal value of double).
Float xs:decimal <xs:element name="fc06" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:decimal">

<xs:totalDigits value="14"/>

<xs:fractionDigits value="4"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

 totalDigits is the number of digits not including decimal point.
General | Not supported
Integer xs:int

-1, 126789675
Logical xs:boolean

true, false, 1, 0

 Values are either true and false or 1 and 0.
Memo xs:string <xs:element name="mc03" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:string">

<xs:maxLength value="2147483647"/>

</xs:restriction>

</xs:simpleType>

</xs:element>
Memo (Binary) xs:base64Binary <xs:element name="ts12" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:base64Binary"/>

</xs:simpleType>

</xs:element>

 Content is translated to base64 encoding.

Maps to SQL Binary.
Memo (Binary) xs:hexBinary <xs:element name="ts12" type="xs:hexBinary" minOccurs="0"> Contents are not encoded or decoded.

Maps to SQL Binary.
Numeric xs:decimal

-1.23, 0, 123, 1000.00

 <xs:element name="nc00" minOccurs="0">

<xs:simpleType>

<xs:restriction base="xs:decimal">

<xs:totalDigits value="10"/>

<xs:fractionDigits value="4"/>

</xs:restriction>

</xs:simpleType>

</xs:element >

 totalDigits is the number of digits not including decimal point.

XML Data Reduced (XDR) Schema Data Types to Visual FoxPro Data Types

XDR data type | Description | Visual FoxPro data type | XSD type
bin.base64 | Specifies MIME-style Base64-encoded binary data. | Character (Binary, less than 255) or Memo (Binary) | base64Binary
bin.hex | Specifies hexadecimal-encoded binary data. | Character (Binary) or Memo (Binary) | hexBinary
boolean Specifies a Boolean value of either 0 or 1.

Example: 0 is false and 1 is true.

 Logical boolean
char | Specifies a number corresponding to the Unicode representation of a single character. | None | Not supported
date Specifies the date in a subset of the ISO 8601 format without the time data.

Example: "1994-11-05"

 Date date
dateTime Specifies a date in a subset of the ISO 8601 format with optional time and no optional zone. Fractional seconds can be as precise as nanoseconds.

Example: "1988-04-07T18:39:09"

 DateTime dateTime
dateTime.tz Specifies a date in a subset of the ISO 8601 format with optional time and optional zone. Fractional seconds can be as precise as nanoseconds.

Example: "1988-04-07T18:39:09-08:00"

 None None
entity | Specifies a reference to an unparsed entity, requiring a matching <!ENTITY> declaration for each instance of the entity. | None | None
entities | Specifies a list of entities delimited by white space. | None | None
enumeration Similar to nmtoken but with an explicit list of allowed values. Supported on attributes only.

Example: "Red Blue Green"

 None None
fixed.14.4 Specifies a number with no more than fourteen digits to the left of the decimal point and no more than four to the right of the decimal point.

Example: 9999.0044

 Currency decimal 18,4.
float Specifies a real floating point number.

Examples: 111, 3.14, -123.456E+10

 Double double
i1 Specifies a 1-byte integer with an optional sign ranging from -128 to 127.

Examples: 1, 127, -128

 Integer byte
i2 Specifies a 2-byte integer with optional sign ranging from -32768 to 32767.

Examples: 1, 703, -32768

 Integer short
i4 Specifies a 4-byte integer with optional sign ranging from -2147483648 to 2147483647

Examples: 1, 703, -32768, 148343, -1000000000

 Integer int
i8 Specifies an 8-byte integer with optional sign ranging from -9223372036854775808 to 9223372036854775807.

Examples: 1, 703, -32768, 1483433434334, -1000000000000000

 Character or Integer long
id Specifies a value that identifies an attribute as an id type attribute. The id values must be unique throughout the document.

In a document, idref(s) attributes refer to an id type attribute, forming a relationship similar to primary key and foreign key in relational databases.

Example: Cust1

 None None
idref Specifies a value corresponding to an id type, enabling intra-document links.

Example: Cust1

 None None
idrefs Similar to idref, except it contains multiple id type values separated by white space.

Example: Cust1 Cust2 Cust3

 None None
int Specifies a signed integer.

Examples 11123, -123

 Integer int
nmtoken Contains values that conform to the rules of the name token.

Example: Cust1

 None None
nmtokens Similar to nmtoken except it can have a list of nmtoken values separated by white space.

Example: Cust1 Cust2 Cust3

 None None
notation | A NOTATION type | None | None
number A number with no limits on the digits

Examples: 111, 3.14, -123.456E+10

Note For ADO RecordSets, a special case exists where the number might have Currency type. When dt:type='number' in an ADO XDR Schema, Visual FoxPro checks for the existence of rs:dbtype='currency'.
 Character, Currency, or Numeric as appropriate decimal
r4 | Same as float but only 4-byte encoding. Value ranges from 1.17549435E-38F to 3.40282347E+38F. | Double | float
r8 | Specifies a floating point number. This data type supports only 15 digits of precision and value ranges from 2.2250738585072014E-308 to 1.7976931348623157E+308. | Double | double
string Specifies a string.

Example: "This is a string"

 Character, if maxLength is less than 255. Otherwise, Memo. string
time Specifies a time in a subset of the ISO 8601 format with no date and no time zone.

Example: "08:15:27"

 None None
time.tz Specifies a time in a subset of the ISO 8601 format with no date but optional time zone.

Example: "08:15:27-05:00"

 None None
ui1 Specifies a 1-byte unsigned integer ranging from 0 to 255.

Examples: 1, 255

 Integer unsignedByte
ui2 Specifies a 2-byte unsigned integer ranging from 0 to 65535.

Examples: 1, 255, 65535

 Integer unsignedShort
ui4 Specifies a 4-byte unsigned integer ranging from 0 to 4294967296.

Examples: 1, 703, 3000000000

 Character or Integer unsignedInt
ui8 Specifies an 8-byte unsigned integer ranging from 0 to 18446744073709551615.

Example: 1483433434334

 Character or Integer unsignedLong
uri Identifies a Uniform Resource Identifier (URI).

Example: "urn:schemas-microsoft-com:Office9"

 Memo anyURI
uuid Contains hexadecimal digits representing octets with optional embedded hyphens that are ignored.

Example: 333C7BC4-460F-11D0-BC04-0080C7055A83

 Character (C(40)) string

See Also

Data and Field Types | Visual FoxPro Data and Field Types | XMLAdapter Class | XMLTable Class | XMLField Class


Character Data Type

To include letters, numbers, spaces, symbols, and punctuation, use the Character data type. Character fields or variables store text information, such as names, addresses, and numbers, that is not used in mathematical calculations. For example, phone numbers or zip codes, though they include mostly numbers, are actually best used as Character values.

For specifications about the Currency data type , see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | Character Operators | CREATE TABLE - SQL Command | Character Expression Creation


Currency Data Type

For monetary values or precise financial calculations, use the Currency data type instead of Numeric.

To assign the Currency data type, use the dollar sign:

money = $50.33
moremoney = $675.43886

If you specify more than four decimal places in a currency expression, Visual FoxPro rounds to the expression to four places before evaluating the expression. In the example, the variable moremoney is internally rounded to 675.4389.

Currency fields respect system settings, such as SET CURRENCY, when displayed in Browse windows, fields, or when listed to the screen.

For more specifications about the Currency data type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | CREATE TABLE - SQL Command | Date Data Type | SET CURRENCY Command


Date Data Type

To store dates without time values, use the Date data type.

Visual FoxPro 5.0 and later supports a strict Date and DateTime format that provides year 2000 compliance. It is recommended that you use strict date formats for all Date and DateTime constants and expressions.

In both Date and DateTime data types, the following rules apply:

  • {00:00:00AM} is equivalent to {12:00:00AM}, Midnight.
  • {00:00:00PM} is equivalent to {12:00:00PM}, Noon.
  • {00:00:00} to {11:59:59} is equivalent to {12:00:00AM} to {11:59:59AM}.
  • {12:00:00} to {23:59:59} is equivalent to {12:00:00PM} to {11:59:59PM}.

See Also

Data and Field Types | CREATE TABLE - SQL Command | Date Expression Creation | Visual FoxPro Data and Field Types | Date and DateTime Operators


DateTime Data Type

To store values that are both dates and times or only dates, use the DateTime data type. A DateTime value is stored in eight bytes — two four-byte integers.

Visual FoxPro versions 5.0 and later support a strict Date and DateTime format that provides year 2000 compliance. It's recommended that you use strict date formats for all Date and DateTime constants and expressions. In both Date and DateTime data types, the following rules apply:

  • {00:00:00AM} is equivalent to {12:00:00AM}, Midnight.
  • {00:00:00PM} is equivalent to {12:00:00PM}, Noon.
  • {00:00:00} to {11:59:59} is equivalent to {12:00:00AM} to {11:59:59AM}
  • {12:00:00} to {23:59:59} is equivalent to {12:00:00PM} to {11:59:59PM}

See Also

Data and Field Types | Visual FoxPro Data and Field Types | CREATE TABLE - SQL Command | Date Expression Creation | Date and DateTime Operators


Double Field Type

When you need more accuracy, such as for a fixed amount of storage in your table or true floating-point values, use the Double data type instead of Numeric. For specifications about the Double field type, see Visual FoxPro Data and Field Types.

In a table, unlike Numeric data, you determine the position of the decimal point when you enter the value.

When the Double data type is used in a table, the number of decimals specified is for presentation purposes only. Visual FoxPro stores the real value.

The following example illustrates this behavior:

#define xml_name 'myxmlfile.xml'
#define database_name 'xmldatabase'
#define table_name 'xmltable'

&& Closes old database
CLOSE DATABASES ALL
CLEAR

&& Deletes database if it exists
IF FILE(database_name) THEN
   DELETE DATABASE (database_name) deletetables
ENDIF

&& Creates a new database
CREATE DATABASE (database_name)

CREATE TABLE (table_name) (myfield B(2))

INSERT INTO (table_name) VALUES (1234.561234)

? EVALUATE(table_name+".myfield")
? EVALUATE(table_name+".myfield") = 1234.56
? EVALUATE(table_name+".myfield") = 1234.561234

See Also

Data and Field Types | Visual FoxPro Data and Field Types |

Numeric Expression Creation | Numeric Operators |


Float Field Type

Included for compatibility reasons, the Float data type is functionally equivalent to Numeric. For specifications for the Float field type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | CREATE TABLE - SQL Command | Numeric Expression Creation | Numeric Operators


General Field Type

To store OLE objects, use the General field type. The General field contains a ten-byte reference to the actual contents of the field: a spreadsheet, a word processor document, or a picture, created by another application. The actual type and amount of data, however, depends on the Automation server that creates the object and whether you link or embed the OLE object.

If you link an OLE object, your table contains only the reference to the data and to the application that created it. If you embed an OLE object, the table contains a copy of the data as well as a reference to the application that created it. The size of a General field is limited only by the amount of available disk space. For more information about using OLE in your application, see Adding OLE.

For specifications about the General field type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | APPEND GENERAL Command | CREATE TABLE - SQL Command | General Field Window | Adding OLE


Integer Field Type

For non-decimal numeric values where performance and table storage limitations are especially important, use the Integer field type.

In tables, the integer field type is stored as a 4-byte binary value, consequently it requires less memory than other numeric data types. As a binary value, it requires no ASCII conversion. For specifications about the Integer field type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | CREATE TABLE - SQL Command | Numeric Expression Creation | Numeric Operators


Logical Data Type

To store data that has only two values, use the Logical data type when you want an efficient way t. Logical data is stored as true (.T.) or false (.F.).

For specifications about the Logical data type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | CREATE TABLE - SQL Command | Logical Operators


Memo Field Type

Use the Memo field type to store blocks of data. The Memo field contains a ten-byte reference to the actual contents of the memo. The actual size of memos, however, depends on the amount of data you enter into them. Data from Memo fields of records in a table are stored in a separate file with the same name as the table and an .FPT extension. Memo fields are limited only by the amount of available disk space. For specifications about the Memo field type, see Visual FoxPro Data and Field Types.

Visual FoxPro memos can contain any data whatsoever, including nulls, assembler code, printer drivers, and so on. You can store contents of Memo fields as memory-resident strings. You can then manipulate these strings with all functions that operate on character data.

See Also

Data and Field Types | CREATE TABLE - SQL Command | MODIFY MEMO Command


Numeric Data Type

To indicate magnitude, use the Numeric data type. Numeric values contain digits from 0 to 9 and, optionally, a sign and a decimal point. Visual FoxPro supports hexadecimal values for numeric data. For example, the decimal value 255 can be represented as 0xFF. For precise financial calculations, use the Currency data type instead.

In fields with Numeric type, the length of the decimal portion is determined at design time when you create the field. The length of the decimal portion is part of the total length. For example, if you specify a length of 6 for a numeric field and a decimal setting of 4, the field can store values up to 9.9999.

For specifications about the Numeric data type, see Visual FoxPro Data and Field Types.

Numeric Precision

Numeric precision when storing floating-point numbers in Numeric fields is limited to approximately 15 digits in Visual FoxPro. Therefore, precision more than 15 digits might be lost when converting from decimal to binary numbers, storing numbers with infinitely repeating decimal values in binary, performing multiple repeated operations, and storing numeric values in Character fields and in memory variables in binary format.

This limitation is based on the way Pentium-based processors calculate and store floating-point numbers and follows the Institute of Electrical and Electronics Engineers (IEEE) floating-point specification for manipulating floating-point numbers in binary format. This standard makes it possible for floating-point numbers to be stored in reasonable amount of space and for performing calculations more quickly.

For example, the fraction 1/10 can be represented as a decimal value of 0.1. However, when storing 1/10 in binary, the decimal value is not the same as the fraction. Instead, the fraction is a repeating binary decimal of 0001100110011100110011 and so on. This type of number cannot be represented in memory that is finite or limited; therefore, the decimal value is rounded when stored in binary.

For values requiring higher precision, see Double Field Type.

For more details about floating-point numbers are stored and how Pentium-based processors handle their calculation, see the Microsoft Knowledge Base Article - Q78113, "XL: Floating-Point Arithmetic May Give Inaccurate Results" at http://support.microsoft.com/default.aspx?scid=kb;en-us;Q78113.

Example

The following example illustrates the limit on numeric precision for floating-point numbers for Numeric data types:

x=1234567890.0987654321
? x

The result is 1234567890.0987650000.

See Also

Data and Field Types | Currency Data Type | CREATE TABLE - SQL Command | Numeric Expression Creation | Numeric Operators


Variant Data Type

Variant is a special data type that can contain any kind of data except fixed-length string data. Variant data can also be the special values Empty, Error, and NULL. This data type is used in extrinsic clients to Visual FoxPro applications because Visual FoxPro is not a strongly typed language.

For specifications about the Variant data type, see Visual FoxPro Data and Field Types.

See Also

Data and Field Types | EMPTY( ) | ERROR | NULL as a Value


Data Manipulation

The expressions you can build give you full access to the power of manipulating data in Visual FoxPro. You can extend the power with user-defined functions, manipulate fields, records and arrays, use classes and objects, and manipulate null values.

To use | See
Arrays | Data Transfer and Arrays
Classes | Class and Object Manipulation
Fields | Field and Record Manipulation
Null values | Null Value Handling
Objects | Class and Object Manipulation
Records | Field and Record Manipulation
User-defined functions | User-Defined Functions

See Also

General Reference | Calling a Procedure | Calling a Function | Passing Parameters by Reference | Passing Parameters by Value | Parameter Passing by Value or by Reference | Variable Parameters


User-Defined Functions

User-defined functions make it possible for you to extend the Visual FoxPro language. You can create specialized functions to use in one or more of your applications. User-defined functions (UDFs) include stand-alone programs saved in files with .prg extensions, as well as procedures and functions contained inside a program.

To create a function or a procedure, use the FUNCTION or PROCEDURE commands to assign a name to the function or procedure. Follow the first line with any number of statements. Use a PARAMETERS or LPARAMETERS statement as the first executable line of a stand-alone UDF that receives parameters. End a UDF that returns values to the calling program with a RETURN statement. You can call UDFs as procedures or as functions. You can pass up to 24 parameters to a UDF.

See Also

Calling a Function | Calling a Procedure | FUNCTION Command | PARAMETERS Command | Parameter Passing by Value or by Reference | PROCEDURE Command | RETURN Command | Data Manipulation


Calling a Procedure

In a program, through the DO Command, you can access a procedure just as if it were an independent program.

To call a procedure

  • Use the DO command followed by the procedure name.
    DO cMyUDF

See Also

DO Command | User-Defined Functions | Data Manipulation | Procedures and User-defined Functions


Calling a Function

Functions return a value. You can display, capture, or use the return value, depending on how you call it.

To call a function

  • Use the = (equal) operator, followed by the function name and parentheses that contain any parameters you pass to the function.
    =cMyUDF()
=cMyUDF(p1,p2)
  • You can also omit the = (equal) operator. For example,
    cMyUDF()
cMyUDF(p1,p2)

In other words, = is optional.

You should avoid using a ? before a function call because ? will send output to the screen.

If you omit the RETURN statement in a UDF, the default return value is true (.T.).

See Also

= Command | RETURN Command | User-Defined Functions | Data Manipulation


Parameter Passing by Value or by Reference

You can pass variables or array elements as parameters by reference or by value. To change parameters passed to and returned from a UDF, pass by reference. To maintain the original value of parameters passed to a UDF, even if the UDF changes the values within the UDF, pass by value.

By default, Visual FoxPro passes parameters to UDFs by value. Objects are always passed by reference.

See Also

Passing Parameters by Reference | Passing Parameters by Value | User-Defined Functions | Data Manipulation


Passing Parameters by Reference

You can pass parameters by reference every time or only in a specific instance.

To pass parameters by reference

  • Use the TO REFERENCE clause of the SET UDFPARMS command before calling the UDF:

    -or-

  • Use the @ token to pass a variable or array by reference, as in the following example:
    ? "UDF value: " + STR(plusone(@nX))
  • To properly reference a variant data type in a COM object, you first must create an instance of the variable to the type you expect to retrieve. This applies only when you use Visual FoxPro as an early binding client.
       DEFINE CLASS varianttest AS SESSION OLEPUBLIC
      FUNCTION varret(outVal AS VARIANT@, inVal AS VARIANT) AS VOID
         OutVal = inVal
      ENDFUNC
   ENDDEFINE

    After this class is built into a DLL named myServer, you can reference the data as in the following code:

       x = CREATEOBJECT("myServer.varianttest","","")
   ov = ""
   tt.varret(@ov, "string")   && Sets string value.
   ov = 0
   tt.varret(@ov, 123)         && Sets ov to an integer value.
   ov = 0.0
   tt.varret(@ov, 44.44)      && Sets ov to a real numeric value.
   ov = l
   tt.varret(@ov, f)            && Sets ov to a Boolean value.

See Also

Passing Parameters by Value | SET UDFPARMS Command | User-Defined Functions | Data Manipulation


Passing Parameters by Value

You can pass parameters by value every time or only in a specific instance.

To pass parameters by value

  • Use the TO VALUE clause of the SET UDFPARMS command before calling the UDF:

    -or-

  • Use parentheses to pass a variable or array by value, as in the following example.
    ? 'UDF value: ' + STR(plusone((nX)))

See Also

Passing Parameters by Reference | SET UDFPARMS Command | User-Defined Functions | Data Manipulation


Variable Parameters

You can pass a variable number of parameters to a UDF. Use the PARAMETERS( ) function to determine the number of parameters passed to the UDF.

You can pass fewer parameters to a UDF than the number of parameters listed in the PARAMETERS or LPARAMETERS statement. If you pass fewer parameters to the UDF than the number listed, the remaining parameters are initialized to false (.F.). If you pass more parameters to the UDF than the number listed, Visual FoxPro generates a "Wrong number of parameters" error message.

See Also

PARAMETERS( ) | Passing Parameters by Reference | Passing Parameters by Value | Parameter Passing by Value or by Reference | Passing Parameters to a Form | User-Defined Functions | Data Manipulation


Field and Record Manipulation

You access data in fields by specifying one or more records that contain the target data. You can use the record pointer to access a particular record through the GOTO command or you can access fields in several records by identifying the records with a Scope, FOR, or WHILE clause in a command.

To | See
Specify a record range | Scope Clauses
Find records that match a logical condition | FOR Clauses
Operate on records while a logical condition is true | WHILE Clauses

See Also

Fields | FOR Clauses | GOTO Command | Records | Scope Clauses | WHILE Clauses | Data Manipulation


Scope Clauses

If a Visual FoxPro command has a Scope clause, you can specify a record range for the command to act on by replacing Scope with one of the clauses in the following table.

Scope clause | Effect
ALL | Command affects all records in the table.
NEXT nExpr Command affects a range of records beginning at the current record and continuing for the specified number of records.
For instance, the following example acts on the current record and the two following records:
REPLACE status WITH "open" NEXT 3
RECORD nNumber Command affects only the specified record number.
The following example acts on record five.
REPLACE status WITH "open" RECORD 5
REST Command affects a range of records beginning with the current record and ending with the last record in the table.
The following example stores a null value in the remaining records.
REPLACE status WITH .NULL. REST

You can also specify record ranges with FOR and WHILE clauses.

See Also

FOR Clauses | REPLACE Command | WHILE Clauses | Field and Record Manipulation | Data Manipulation


FOR Clauses

A FOR clause causes a command to act on each record that meets the specified logical condition. FOR clauses have the following syntax:

FOR lExpr

The following example stores low balance in the alert field of all records that contain less than 500 in the total field.

REPLACE ALL alert WITH "low balance" FOR total < 500

The following table lists commands in which you can use a FOR clause.

Commands That Use FOR Clauses

APPEND FROM ARRAY | COUNT | LOCATE
APPEND FROM | DEFINE PAD | RECALL
AVERAGE | DELETE | REPLACE FROM ARRAY
BLANK | DISPLAY | REPLACE
BROWSE | EXPORT | REPORT
CALCULATE | FOR( ) | SCAN...ENDSCAN
CHANGE | INDEX | SORT
COPY TO ARRAY | LABEL | SUM
COPY TO | LIST |

Using the FOR clause can speed operation of single-table commands. For more information about performance enhancement, see Optimizing Applications.

See Also

REPLACE Command | Scope Clauses | WHILE Clauses | Field and Record Manipulation | Data Manipulation


WHILE Clauses

A WHILE clause causes a command to act on each record as long as the logical expression evaluates to true (.T.). The first time the expression evaluates to false (.F.), the command ceases without attempting any remaining records. This expression is typically used with a table that's been sorted or indexed on the field(s) included in the WHILE expression. For instance, the following example navigates an indexed table to locate the first record that meets the condition, then the REPLACE command acts on those records that meet the WHILE condition.

USE Mytable INDEX street
LOCATE FOR UPPER(street) = "MAIN"
REPLACE street WITH "Maine" WHILE UPPER(street) = "MAIN"

You can use Scope, FOR, and WHILE expressions in the same Visual FoxPro command. For instance, the following examples store a new value in the status field of several records.

REPLACE ALL status WITH "Active" FOR total > 30 ;
   WHILE expd > {^1998/02/16}

When you specify both FOR and WHILE, the WHILE expression takes precedence and the FOR clause is used to filter the records selected by WHILE.

The following table lists commands in which you can use a WHILE clause.

Commands That Use WHILE Clauses

AVERAGE | COUNT | RECALL
BLANK | DELETE | REPLACE
BROWSE | DISPLAY | REPLACE FROM ARRAY
CALCULATE | EXPORT | REPORT
CHANGE | LABEL | SCAN ... ENDSCAN
COPY TO ARRAY | LIST | SORT
COPY TO | LOCATE | SUM

See Also

LOCATE Command | REPLACE Command | Field and Record Manipulation | Data Manipulation


Data Transfer and Arrays

Arrays provide a way to quickly order information. Once information is in an array, you can easily search, sort, and perform other data manipulation. To get information to and from arrays, you transfer data to a table or transfer data from a table to an array.

Visual FoxPro makes no size or data type restrictions on array contents. The only restriction on size is the amount of memory available.

To transfer data from | See
Arrays to tables | Data Transfer from an Array to a Table
SQL statements to arrays | Arrays and SQL - SELECT
Tables to arrays | Data Transfer from a Table to an Array

See Also

Arrays and SQL - SELECT | Data Transfer from a Table to an Array | Data Transfer from an Array to a Table | Field and Record Manipulation | Data Manipulation


Data Transfer from a Table to an Array

The following Visual FoxPro commands transfer data from a table to an array:

  • SCATTER transfers data from a single table record to an array.
  • COPY TO ARRAY transfers data from a series of records to an array.
  • SELECT - SQL can transfer the results of a query to an array. For details about SELECT - SQL, refer to the topic Arrays and SELECT - SQL.

SCATTER and COPY TO ARRAY differ in the following respects:

  • SCATTER transfers data from the current record in the current table. COPY TO ARRAY can transfer data from multiple records in the current table.
  • The SCATTER BLANK option automatically creates an array having elements the same size and type as the fields in the table, but the array elements are empty.
  • The SCATTER VAR option automatically creates a set of variables having the same size, type, and name as the fields in the table.

See Also

Arrays and SQL - SELECT | COPY TO ARRAY Command | SCATTER Command | SELECT - SQL Command | Data Transfer From an Array to a Table | Data Transfer and Arrays | Data Manipulation


Data Transfer from an Array to a Table

The following Visual FoxPro commands transfer data from an array to a table:

  • GATHER transfers data from an array to a single table record.
  • APPEND FROM ARRAY adds new records to a table and fills the records with data from an array.
  • INSERT - SQL appends a single new record to a table and fills the record with data from an array.

GATHER, APPEND FROM ARRAY, and INSERT - SQL differ in the following respects:

  • GATHER transfers data from an array to the current record in the current table. Additionally, the GATHER MEMVAR option transfers data from a set of variables to the current table record.
  • APPEND FROM ARRAY appends new records to the end of the current table and then transfers data from the array to the newly appended records.
  • INSERT - SQL appends a new record and then transfers data from the array to the newly appended record. Unlike GATHER and APPEND FROM ARRAY, INSERT - SQL can append a record in an unselected table (a table open in a work area other than the current work area).
    Note APPEND FROM ARRAY or INSERT - SQL performs faster than APPEND BLANK followed by REPLACE, especially on a network.

See Also

APPEND FROM ARRAY Command | GATHER Command | INSERT - SQL Command | Data Transfer from a Table to an Array | Data Transfer and Arrays | Data Manipulation | Arrays and SELECT - SQL


Arrays and SELECT - SQL

SELECT - SQL is a versatile command for querying tables and can direct query results to an array.

To send SELECT - SQL query results to an array, specify the INTO ARRAY clause with an array name. If the array doesn't exist, it is automatically created. If the array does exist, it is redimensioned automatically to accommodate the query results.

Example

In the following example, SELECT - SQL directs its query results to an array named RESULTS:

SELECT DISTINCT a.cust_id, a.company, b.amount ;
FROM customer a, payments b ;
WHERE a.cust_id = b.cust_id INTO ARRAY results

DISPLAY MEMORY LIKE results

RESULTS   Priv A            TEST
  ( 1, 1)   C  "000004"
  ( 1, 2)   C  "Stylistic Inc."
  ( 1, 3)   N    13.91  (    13.91000000)
  ( 2, 1)   C  "000008"
  ( 2, 2)   C  "Ashe Aircraft"
  ( 2, 3)   N    4021.98  (  4021.98000000)
  ( 3, 1)   C  "000010"
  ( 3, 2)   C  "Miakonda Industries"
  ( 3, 3)   N     9.84  (   9.84000000)

See Also

SELECT - SQL Command | Data Transfer and Arrays | Data Manipulation | Data Transfer from a Table to an Array | Data Transfer from an Array to a Table


Class and Object Manipulation

Visual FoxPro provides two special operators for object programming: the dot operator (.) and the scope resolution operator (::). Visual FoxPro also adds commands that enable you to create a class, and to create and add objects to a class.

Operator, Command, Function | Description
. (Dot operator) | Scopes objects to their parents and properties, events, and methods to objects.
:: (Scope resolution operator) | Calls a parent class method from within the subclass.
CREATEOBJECT( ) | Creates an object from a class, a subclass, or an OLE object.
DEFINE CLASS with ADD OBJECT clause | Creates a class definition. The ADD OBJECT clause adds an object based on an existing class or subclass at design time.
GETOBJECT( ) | Returns a reference to an OLE object.

For more information about using classes and objects, see Object-Oriented Programming.

See Also

:: Scope Resolution Operator | CREATEOBJECT( ) Function | DEFINE CLASS Command | GETOBJECT( ) Function | Data Transfer and Arrays | Data Manipulation | Null Value Handling


Null Value Handling

Visual FoxPro provides support for null values. This support simplifies the task of representing unknown data and makes it easier to work with Microsoft Access or SQL databases that may contain null values.

Null values are:

  • Equal to the absence of any value.
  • Different than zero, the empty string (""), or blank.
  • Sorted ahead of other data.
  • Propagated in calculations and most functions.

Null values affect the behavior of commands and functions, logical expressions, and parameters.

Visual FoxPro support for null values complies with ANSI standards and affects any area of the product where values and expressions are used.

To use null values in | See
Commands and functions | Behavior of Null Values in Commands and Functions
Expressions | Behavior of Null Values in Logical Expressions
Parameters | NULL as a Parameter

Using NULL in Values and Expressions

In Visual FoxPro, you assign the null value programmatically with the .NULL. token or interactively with CTRL+0 in a field. Note that the periods around .NULL. are optional. To detect whether a field or variable contains a null value, or whether an expression evaluates to a null value, use ISNULL( ).

See Also

Behavior of Null Values in Logical Expressions | Behavior of Null Values in Commands and Functions | EMPTY( ) Function | ISBLANK( ) Function | ISNULL( ) Function | NULL as a Parameter | NULL as a Value | Data Manipulation


NULL as a Value

A null value is different from an empty string, a blank field, or zero. For instance, both EMPTY( ) and ISBLANK( ) return true (.T.) when a variable contains blank or an empty string. EMPTY( ) also returns true (.T.) for zero. ISNULL( ) returns false (.F.) for these values and both EMPTY( ) and ISBLANK( ) return false (.F.) for null values.

You can use null values with array and field commands like STORE, GATHER, and SCATTER. The following example assigns .NULL. to each member of the array aX:

DIMENSION aX[4]
STORE .NULL. TO aX

The null value is not a data type. When you assign .NULL. to a field or variable, the value changes to .NULL. but the data type of the field or variable does not change. For example:

STORE 5 TO nX
nX = .NULL.
? TYPE ("nX")  && Data type reported as numeric

See Also

Behavior of Null Values in Logical Expressions | Behavior of Null Values in Commands and Functions | EMPTY( ) Function | ISBLANK( ) Function | ISNULL( ) Function | Null Value Handling | Data Manipulation | NULL as a Parameter


Behavior of Null Values in Commands and Functions

The following table describes how commands and functions interpret null values.

Data type | Behavior
Logical | Most logical expressions that evaluate to .NULL. return .NULL. or generate an error. EMPTY( ), ISBLANK( ), and ISNULL( ) are exceptions.
Numeric | Numeric expressions that evaluate to .NULL. return .NULL. A numeric function evaluates to .NULL. when passed a null value.
Date | Date expressions containing null values return .NULL.

See Also

Null Value Handling | Date Data Type | EMPTY( ) Function | ISBLANK( ) Function | ISNULL( ) Function | Logical Data Type | Numeric Data Type | Behavior of Null Values in Logical Expressions | NULL as a Value | NULL as a Parameter


Behavior of Null Values in Logical Expressions

Null values persist through logical expressions in most cases. The following table describes the behavior of null values in logical expressions.

Logical expression | Result if x=TRUE | Result if x=FALSE | Result if x=.NULL.
x AND .NULL. | .NULL. | FALSE | .NULL.
x OR .NULL. | TRUE | .NULL. | .NULL.
NOT x | FALSE | TRUE | .NULL.

When a conditional expression encounters a null value, the condition fails, because .NULL. is not true (.T.). For example, a FOR clause that evaluates to .NULL. is treated as false (.F.). Note that null values are treated as .NULL. until the entire expression is evaluated.

See Also

FOR Clauses | Null Value Handling | Data Manipulation | Behavior of Null Values in Commands and Functions | NULL as a Value | NULL as a Parameter


NULL as a Parameter

Passing a null value as a parameter affects the behavior of many commands and functions in Visual FoxPro. The following general rules apply to null values passed to commands and functions:

  • Commands generate errors when passed a null value.
  • Functions that accept .NULL. as a valid value propagate .NULL. to the result.
  • Functions that accept parameters that could be numeric values generate an error if you supply .NULL. for those parameters.
    STORE .NULL. TO n
USE Mytable ALIAS &n            && Expected a workarea
                              && name or number
? SUBSTR("Hello, world",n,5)   && Expected a position
                              && in the string
  • ISBLANK( ), ISDIGIT( ), ISLOWER( ), ISUPPER( ), ISALPHA( ), and EMPTY return false (.F.) when passed a null value. ISNULL( ) returns true (.T.) when passed a null value.
  • The commands INSERT - SQL and SELECT - SQL process null values through the IS NULL and IS NOT NULL clauses and, in the case of INSERT, UPDATE, and REPLACE, place null values into records.
  • SQL Aggregate functions ignore instead of propagate null values.
  • Visual FoxPro aggregate functions only propagate .NULL. if all supplied values are null values; otherwise, any null value is ignored.

For more information on using null values in your application, see Working with Tables.

See Also

EMPTY( ) Function | INSERT - SQL Command | ISALPHA( ) Function | ISBLANK( ) Function | ISDIGIT( ) Function | ISLOWER( ) Function | ISNULL( ) Function | ISUPPER( ) Function | REPLACE Command | SELECT - SQL Command | SQL Commands and Functions | UPDATE Command | Null Value Handling | Data Manipulation | NULL as a Value


Data Storage Containers

You choose a data storage container according to the amount and type of data you need to store, and how you want to use it. You determine the availability of data by the way you declare it and where you create it in the program. This range of availability or effectiveness is called scope.

Most programming languages make it possible for you to store data in constants, variables, and arrays. In Visual FoxPro, you can also store data in records and objects. For more information about differences, see Visual FoxPro and Other Programming Languages.

Scope of Data Containers

The following table summarizes the scope differences between data containers.

Container Scope Example
Constants Private
#DEFINE ERRSTR "Error!"
Variables Public, private, or local
Var = 7
Arrays Public, private, or local
ArrayName[1,1] = "John Brown"
Fields Permanent storage, accessible while the table containing the records is open
REPLACE name WITH "John Brown"
Object Properties Referenced through the object and the object's container hierarchy
txtCustomer.Value = "John Brown"

See Also

General Reference | Access to Variables | LOCAL Command | Objects | PRIVATE Command | PUBLIC Command | Records | Visual FoxPro and Other Programming Languages


Arrays

An array is an ordered series of data values, called elements, which are referenced by number. Because arrays exist in memory, they provide fast data access and easy manipulation. You can easily specify, locate, or manipulate elements in an array.

Arrays have the same scoping options as variables. A single Visual FoxPro array may contain any and all data types as values.

Create an array with the DIMENSION or DECLARE command and assign value to each element by identifying the element by array name and position. The following example creates a two-dimensional array of five rows and two columns, then assigns a value to the second column of the first row:

DIMENSION ArrayName[5,2]
ArrayName[1,2] = 966789

You can also use SCATTER, GATHER, COPY TO ARRAY, and APPEND FROM ARRAY to move field values to and from array elements. For more information about using arrays in your application, see Data Transfer and Arrays.

See Also

Variables | APPEND FROM ARRAY Command | COPY TO ARRAY Command | DECLARE Command | DIMENSION Command | GATHER Command | SCATTER Command | Data Storage Containers


Constants

A constant is a named item that retains its value throughout all operations. The value π, or 3.1415926535, is an example of a numeric constant; the letter A is an example of a character constant.

You can create compile-time constants that exist throughout the operation of a Visual FoxPro application. You can use a constant and know that its value doesn't change during the operation of your application. At design time, you can effect a change throughout an application by changing only the value of a single constant.

A constant can contain any data type value.

To assign a value to a constant

  • Use the #DEFINE preprocessor directive.

In the following example, the constant TABLERR1 is defined as a character string.

#DEFINE TABLERR1 "This table is not available. Please try later."

In an application, wherever you would normally specify the character string "This table is not available. Please try later." you can use TABLERR1 instead.

To release a defined constant

  • Use the #UNDEFINE preprocessor directive.
    #UNDEF TABLERR1

See Also

Variables | #DEFINE ... #UNDEF Preprocessor Directive | PI( ) Function | Constant is already created with #DEFINE (Error 1725) | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive | Data Storage Containers


Fields

A field is a named location in a record that contains a particular type of data. Fields can be any Visual FoxPro data type or field type.

A field's data type is specified at design time in the Table Designer, or at run time with the CREATE TABLE command.

See Also

CREATE TABLE - SQL Command | Records | Table Designer, | Data Storage Containers


Objects

An object is an instance of a class. A class is a description of the data and behavior characteristics of a group of objects. Visual FoxPro objects can be forms, form sets, or controls. Use Visual FoxPro objects to implement consistent, dependable behavior throughout your application, to reduce the amount of code, and to increase the reusability of code.

Each object responds to specific events, and has properties and methods. You manipulate these objects through their events, methods, and properties.

To create objects

  • Use the Form Designer.

    -or-

  • Use the CREATEOBJECT( ) function.

For more information about programming with objects, see Object-Oriented Programming. For more information about Visual FoxPro properties, events, and methods, see Understanding the Event Model. For a list of other controls you can use, see the ActiveX Controls Overview.

See Also

CREATEOBJECT( ) Function | Form Designer | Classes and Objects | Controls and Objects | Data Storage Containers


Records

A record is a set of fields in a table. Records can have up to 255 fields. All records in a table contain the same fields. Though the content of fields differ from record to record, the size of a field is the same for all records in a table. The data type for each field is the same for all records in a table.

To create records

  • Use the INSERT - SQL command or the APPEND command.

For more information about creating records and using tables, see Working with Tables.

See Also

APPEND Command | Fields | INSERT - SQL | Data Storage Containers


Variables

A variable is a memory location whose value can change throughout the operation of a program. A variable can contain any data type value. You can change the value of a variable at any time. This option enables you to monitor the status of anything that changes throughout the operation of an application.

Variables exist only while an application is running or in the Visual FoxPro session in which they are created. To specify the scope of a variable, use the LOCAL, PRIVATE, and PUBLIC keywords.

Creating Variables

To create a variable, store a value to a named Visual FoxPro element using the STORE command or the = (equal) operator.

Example

The following examples are simple assignment statements that are functionally equivalent.

STORE 7 TO nVar
nVar = 7

The following example uses a variable, nInc, to hold the value of a loop counter. Visual FoxPro assigns a new value to the variable during each loop.

FOR nInc = 1 TO 10
   ? nInc
ENDFOR

The following example uses a variable, cName, to hold the value of the Firstname field from the Customer table.

USE Customer
STORE Customer.Firstname TO cName

See Also

Access to Variables | = Command | FOR ... ENDFOR Command | LOCAL Command | PRIVATE Command | PUBLIC Command | STORE Command | Data Storage Containers


Access to Variables

Variables exist only while an application is running or during the Visual FoxPro session in which they are created. To specify the scope of a variable, use the LOCAL, PRIVATE, and PUBLIC keywords.

  • LOCAL creates variables or arrays that can be used and modified only in the program they are created, and cannot be accessed by higher or lower level programs. Local variables and arrays are released once the program containing them stops running.
  • PRIVATE hides variables or arrays that were defined in a calling program from the current program. You can then reuse those variable names in the current program without affecting the original variables. Once the program containing PRIVATE has stopped running, all variables and arrays that were declared privately are again available.
  • PUBLIC defines global variables or arrays. Global variables and arrays can be used and modified from any program you run during the current Visual FoxPro session. Any variable or array you create in the Command window is automatically public.

Accessing Variables

If a variable has the same name as a field, Visual FoxPro always gives precedence to the field name. You can reference the variable using m. or m-> plus the variable name, as in the following examples.

?  m.cFname
?  m->cFname      && print value in cFname
?  cFname         && prints contents of field cFname

For more information about these commands, see the appropriate topics in Help.

Note In object-oriented programming you can create properties of objects to hold values instead of using variables. For more information, see Object-Oriented Programming.

See Also

Variables | PUBLIC | PRIVATE | LOCAL | Object-Oriented Programming | Data Storage Containers


Expression Building

Visual FoxPro expressions combine data and operators to create a value of a given data type. Whenever you need a value of a given data type, you can usually also supply an expression.

To combine | See
Character data | Character Expression Creation
Date or time data | Date Expression Creation
Numeric data | Numeric Expression Creation
Logical values | Logical Expression Creation

See Also

General Reference | Command and Function Usage | Name Expression Creation | Visual FoxPro Name Creation | Macro Substitution


Visual FoxPro Name Creation

Data containers and some parameters to commands and functions require a name. When you create a name in Visual FoxPro, apply the following rules:

  • Use only letters, underscores, and numbers.
  • Begin the name with a letter or underscore.
  • Use 1 to 128 characters, except for field names in free tables and index tags — those can be 10 characters at most.
  • Avoid words reserved by Visual FoxPro.

File names follow your operating system's conventions.

See Also

Name Expression Creation | FullName Property | Name Property | Expression Building


Character Expression Creation

Compose character expressions by combining character operators with the following Visual FoxPro elements:

  • Character fields.
  • Functions that return character values.
  • Variables and array elements that contain character data.
  • Character constants, called string literals.

You can embed quotation marks(" and ') in a character string by enclosing the character string within square brackets ([ ]):

STORE [Robert's Diner] TO cCompanyName
STORE [See the "Sunday Special"] TO cBanner

You can also embed quotation marks by enclosing the character string with quotation marks of the alternate type:

STORE "Robert's Diner" TO cCompanyName
STORE 'See the "Sunday Special"' TO cBanner

See Also

Character Operators | Name Expression Creation | STORE Command | Expression Building


Command and Function Usage

You use Visual FoxPro commands and functions to perform an action or to return values for use in other commands and functions. Commands and functions can occur in expressions, or they can accept expressions as parameters. You can also use user-defined functions (UDFs) whenever you can use a Visual FoxPro command or function.

Commands and functions behave differently:

  • Commands perform an action. For example, you can use the BROWSE command to look at the contents of a table.
  • Functions return a value of a given data type. For example, the DATE( ) function returns the system date from your computer. Functions end with a pair of parentheses that distinguish them from commands.

Functions are not used by themselves, but are always combined with a Visual FoxPro command. For example, the question mark (?) is a command that sends output to the screen. DATE( ) is a function that returns the current system date. You can combine them to output the system date to the screen:

? DATE( )

Commands and functions have a prescribed syntax for parameters and clauses you can supply. For a full description of the syntax of any command or function, see the Language Reference A-Z.

See Also

BROWSE Command | DATE( ) Function | Language Reference A-Z | Expression Building


Date Expression Creation

Compose date expressions by combining date operators with the following Visual FoxPro elements:

  • Date or DateTime fields.
  • Functions that return dates or dates and times.
  • Variables and array elements that contain dates or times.
  • Date and DateTime constants.

Visual FoxPro treats an invalid date as an empty date.

See Also

Date Operators | Numeric Expression Creation | DATETIME( ) Function | DateTime Data Type | Expression Building


Logical Expression Creation

Logical expressions have one of two values — true or false. .T. and .F. are used to specify true and false in Visual FoxPro.

Compose logical expressions by combining logical operators with the following Visual FoxPro elements:

  • Logical type fields.
  • Functions that return logical values.
  • Variables and array elements that contain logical values.
  • Any expression that evaluates to a logical value.

Visual FoxPro evaluates logical expressions from left to right, and only for as long as necessary. In the following example, the AND operator is used to create a logical expression. If any of the values in the expression are false (.F.), the entire expression is false. When Visual FoxPro encounters the first logical false (.F.), it doesn't evaluate the rest of the expression.

.T. AND .T. AND .F. AND .T. AND .T. AND .T.

See Also

Logical Operators | _RetLogical( ) API Library Routine | Logical Data Type | Expression Building


Macro Substitution

You can replace names with variables by using macro substitution. To use macro substitution, place an ampersand (&) before the variable to tell Visual FoxPro to use the value of the variable as a name, and use a period (.) to end the macro substitution expression.

For example, the following print statement produces "FoxPro":

x = "Fox"
? "&x.Pro"

A command or function containing a name expression runs faster than one containing macro substitution, so use a name expression instead of macro substitution whenever possible. For more information about macro substitution, see the & Command topic in Help.

See Also

Name Expression Creation | & Command | Expression Building | Character Expression Creation


Name Expression Creation

Many Visual FoxPro commands and functions require that you supply a name. Although a name cannot be a variable or an array element, you can create a name expression that substitutes the value of a Character variable or array element as the name.

When you store the name to the variable or array element, you can substitute the name into a command or function by enclosing the variable in parentheses. To use a list of names, separate the names with commas. A name is not an expression, a variable or array element, or a field. A name should not be surrounded by quotation marks. Otherwise, names follow the Visual FoxPro naming rules described in the section Visual FoxPro Name Creation.

For example, the REPLACE command requires a field name. You can store a field name to a variable and use a name expression in REPLACE where the field name occurs:

STORE 'city' TO cVarCity
REPLACE (cVarCity) WITH 'Paris'

Visual FoxPro stores the field name city to the variable cVarCity, then stores the value "Paris" in the field, city, which is the value of the name expression cVarCity.

See Also

Macro Substitution | Expression Building | Visual FoxPro Name Creation | REPLACE Command


Numeric Expression Creation

Compose numeric expressions by combining numeric operators with the following Visual FoxPro elements:

  • Numeric type fields.
  • Functions that return numeric values.
  • Variables and array elements that contain numeric data.
  • Numeric constants.

See Also

Numeric Operators | Numeric Data Type | Accepting Numeric Input in a Given Range | Expression Building


File Structures

This section contains technical information about file structures and file types.

In This Section

Compound Index File Structure (.cdx)
Describes how the compound file structure is different from the compact index file structure.
Compact Index File Structure (.idx)
Provides information about the compact index header record.
File Extensions and File Types
Contains lists of the extensions and their associated file types that are used with Microsoft Visual FoxPro.
FoxUser Resource File Structure
Contains a variety of resource information, including window positions, color sets, Browse window configurations, label definitions, and so on.
Index File Structure (.idx)
Describes the contents of index files, index header records, and index node records.
Macro File Format (.fky)
Provides a description of the file header and individual macros.
Memo File Structure (.FPT)
Describes the contents of the memo header record, memo block header, and memo text.
Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx)
Provides a list of file types that are saved as tables, as well as the table header record and field subrecords structure.
Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx)
Provides information about the reports available that document table structures.

Related Sections

General Reference
Provides Visual FoxPro related technical information, including file types, file structures, and other reference information about Visual FoxPro elements.
Naming Conventions
Provides links to additional information about choosing names for exposed objects, properties, and methods that can be understood by users of the application easily.
Visual FoxPro and Other Programming Languages
Provides a comparison of Visual FoxPro language elements with other programming languages.


Compound Index File Structure (.cdx)

All compound indexes are compact indexes.

One file structure exists to track all the tags in the .cdx file. This structure is identical to the compact index file structure with one exception — the leaf nodes at the lowest level of this structure point to one of the tags in the compound index.

All tags in the index have their own complete structure that is identical to the compact index structure for an .idx file.

See Also

Index File Structure (.idx) | Compact Index File Structure (.idx) | Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Memo File Structure (.FPT) | Macro File Format (.fky) | File Extensions and File Types


Compact Index File Structure (.idx)

Compact Index Header Record

Byte offset | Description
00 – 03 | Pointer to root node
04 – 07 | Pointer to free node list ( -1 if not present)
08 – 11 | Reserved for internal use
12 – 13 | Length of key
14 | Index options (any of the following numeric values or their sums): 1 – a unique index 8 – index has FOR clause 32 – compact index format 64 – compound index header
15 | Index signature
16 – 19 | Reserved for internal use
20 – 23 | Reserved for internal use
24 – 27 | Reserved for internal use
28 – 31 | Reserved for internal use
32 – 35 | Reserved for internal use
36 – 501 | Reserved for internal use
502 – 503 | Ascending or descending: 0 = ascending 1 = descending
504 – 505 | Reserved for internal use
506 – 507 | FOR expression pool length1
508 – 509 | Reserved for internal use
510 – 511 | Key expression pool length1
512 – 1023 | Key expression pool (uncompiled)

1 This information tracks the space used in the key expression pool.

Compact Index Interior Node Record

Byte offset | Description
00 – 01 | Node attributes (any of the following numeric values or their sums): a. 0 – index node b. 1 – root node c. 2 – leaf node
02 – 03 | Number of keys present (0, 1 or many)
04 – 07 | Pointer to node directly to left of current node (on same level, -1 if not present)
08 – 11 | Pointer to node directly to right of current node (on same level; -1 if not present)
12 – 511 | Up to 500 characters containing the key value for the length of the key with a four-byte hexadecimal number (stored in normal left-to-right format): This node always contains the index key, record number and intra-index pointer.2 The key/four-byte hexadecimal number combinations will occur the number of times indicated in bytes 02 – 03.

Compact Index Exterior Node Record

00 – 01 | Node attributes (any of the following numeric values or their sums): 0 – index node 1 – root node 2 – leaf node
02 – 03 | Number of keys present (0, 1 or many)
04 – 07 | Pointer to the node directly to the left of current node (on same level; -1 if not present)
08 – 11 | Pointer to the node directly to right of the current node (on same level; -1 if not present)
12 – 13 | Available free space in node
14 – 17 | Record number mask
18 | Duplicate byte count mask
19 | Trailing byte count mask
20 | Number of bits used for record number
21 | Number of bits used for duplicate count
22 | Number of bits used for trail count
23 | Number of bytes holding record number, duplicate count and trailing count
24 – 511 | Index keys and information2

2 Each entry consists of the record number, duplicate byte count and trailing byte count, all compacted. The key text is placed at the logical end of the node, working backwards, allowing for previous key entries.

See Also

Compound Index File Structure (.cdx) | Index File Structure (.idx) | Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Memo File Structure (.FPT) | Macro File Format (.fky) | File Extensions and File Types


File Extensions and File Types

This table lists the extensions and their associated file types that are used with Visual FoxPro.

Extension | File type
.act | Documenting Wizard action diagram
.app | Generated application
.cdx | Compound index
.chm | Compiled HTML Help
.dbc | Database
.dbf | Table
.dbg | Debugger configuration
.dct | Database memo
.dcx | Database index
.dll | Windows Dynamic Link Library
.err | Compilation error
.exe | Executable program
.fky | Macro
.fll | Visual FoxPro Dynamic Link Library
.fmt | Format File
.fpt | Table memo
.frt | Report memo
.frx | Report
.fxp | Compiled program
.h | Header file (for inclusion in a Visual FoxPro or C/C++ program)
.hlp | WinHelp
.htm | HTML
.idx | Index, compact index
.lbt | Label memo
.lbx | Label
.log | Coverage log
.lst | Documenting Wizard list
.mem | Variable save
.mnt | Menu memo
.mnx | Menu
.mpr | Generated menu program
.mpx | Compiled menu program
.ocx | ActiveX control
.pjt | Project memo
.pjx | Project
.prg | Program
.qpr | Generated query program
.qpx | Compiled query program
.sct | Form memo
.scx | Form
.spr | Generated Screen Program (previous versions of FoxPro only)
.spx | Compiled Screen Program (previous versions of FoxPro only)
.tbk | Memo backup
.txt | Text
.vct | Visual class library memo
.vcx | Visual class library
.vue | FoxPro 2.x view
.win | Window file
.xml | XML

See Also

Compact Index File Structure (.idx) | Compound Index File Structure (.cdx) | Index File Structure (.idx) | Memo File Structure (.FPT) | Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx)


FoxUser Resource File Structure

The FoxPro resource file FoxUser.dbf holds a variety of resource information (for example, window positions, color sets, Browse window configurations, label definitions, and so on.). FoxUser.dbf is a standard FoxPro table with an associated memo file (.FPT). If the index file does not exist, it is created when the FoxUser.dbf file is opened.

Unlike in earlier versions of Visual FoxPro, the FoxUser.dbf resource file is opened SHARED

While RESOURCE is SET ON, FoxPro handles all resource management. You can modify the data contained in this file in two ways:

  1. Special window configurations or other window preferences, once established and saved in the resource file, can be protected from subsequent interactive changes by modifying the READONLY field for the specific resource (see the example in the Predefining Browse Window Configuration section).
  2. Resources that are no longer needed or wanted may be deleted and the resource file may be packed.

Modifying the READONLY field and/or deleting records from the resource file are the only actions you should perform on the FoxUser.dbf file. You should make a copy of the resource file before making any modifications.

The FoxUser.dbf table has the following structure:

Field | Field Name | Type | Width
1 | TYPE | Character | 12
2 | ID | Character | 12
3 | NAME | Memo | 4
4 | READONLY | Logical | 1
5 | CKVAL | Numeric | 6
6 | DATA | Memo | 4
7 | UPDATED | Date | 8
TYPE
Identifies the type of information the resource holds
ID
Identifies the record with the TYPE
NAME
Contains the name assigned to the resource, for instance the name assigned to color sets, BROWSE windows, and system windows
READONLY
A logical field that can be set to true (.T.) to indicate that the resource should be used for read-only access and cannot be changed
CKVAL
Used by FoxPro to verify the data (in the memo field DATA) is valid
DATA
Memo field that holds the actual data for the resource
UPDATED
The date the current resource was last changed

You can make the FoxUser.dbf resource file read-only by marking it at the MS-DOS level. The MS-DOS command ATTRIB uses the <+R> setting to mark a file as read only. Marking a file read-only is useful in multiuser situations, because the FoxUser.dbf can be shared on a network.

Modifying the FoxUser.dbf Resource File

The following SET RESOURCE commands make it possible for you to open and easily modify the FoxUser.dbf file's contents, as well as use a resource file other than FoxUser.dbf.

SET RESOURCE TO <resourcefile>
SET RESOURCE TO
SET RESOURCE ON
SET RESOURCE OFF

If you want to make changes to your resources, in the Command window, use the following commands:

SET RESOURCE OFF
USE FOXUSER
BROWSE

With the resource file open, you can use CHANGE, EDIT, BROWSE, DELETE, REPLACE and other FoxPro commands to modify or delete data. You can even use COPY TO to create a new resource table. When you have finished modifying the resource file, pack it if you marked records for deletion, and close it. Then, set the resource feature on with the following commands:

USE
SET RESOURCE ON

You can open the FoxUser.dbf file in a work area without setting resource OFF by issuing the command USE SYS(2005) AGAIN. SYS(2005) returns the name of the current resource file.

Predefining Browse Window Configuration

One useful modification that you can make to the FoxUser.dbf file is changing the READONLY field for predefined Browse window configurations.

First, adjust a BROWSE window to display specific fields that are sized for easy manipulation, position the window and size it, split the window into two partitions, with one partition in BROWSE mode and one in CHANGE, then close the window. When the BROWSE window is closed, its configuration is saved in the current resource file, provided the field named READONLY is not set to T, and provided the window was not closed with Ctrl+Q.

Then, issue USE SYS(2005) AGAIN and edit the READONLY field, setting it to true ("T"). To do this, look for the BROWSE window resource that has a TYPE of PREFW, and ID of WINDBROW, and a NAME field with the alias of the table you just browsed. When the READONLY field is true (T), the corresponding resource data will not be overwritten if the Browse window configuration is later changed interactively.

Now, whenever the table is browsed with the BROWSE LAST command, the Browse window appears in the same position with all its field, size, and placement configurations the same as the last session. No matter how much the Browse window is changed by the user, it will always return according to the data in the resource when you BROWSE LAST.

See Also

Resource Files in Applications | Visual FoxPro Configuration


Index File Structure (.idx)

Index files contain one header record and one or many node records. The header record contains information about the root node, the current file size, the length of the key, index options and signature, and printable ASCII representations of the key1 and FOR expressions. The header record starts at file position zero.

The remaining node records contain an attribute, number of keys present, and pointers to nodes on the left and right (on the same level) of the current node. They also contain a group of characters encompassing the key value and either a pointer to a lower level node or an actual table record number. The size of each record that is output to a file is 512 bytes.

Index Header Record

Byte offset | Description
00 – 03 | Pointer to the root node
04 – 07 | Pointer to the free node list ( -1 if not present)
08 – 11 | Pointer to the end of file (file size)
12 – 13 | Length of key
14 | Index options (any of the following numeric values or their sums): 1 – a unique index 8 – index has FOR clause
15 | Index signature (for future use)
16 – 235 | Key expression (uncompiled; up to 220 characters)1,3
236 – 455 | FOR expression (uncompiled; up to 220 characters ending with a null value byte)
456 – 511 | Unused

Index Node Record

Byte offset | Description
00 – 01 | Node attributes (any of the following numeric values or their sums): 0 – index node 1 – root node 2 – leaf node
02 – 03 | Number of keys present (0, 1 or many)
04 – 07 | Pointer to the node directly to left of the current node (on same level; -1 if not present)
08 – 11 | Pointer to the node directly to right of the current node (on same level; -1 if not present)
12 – 511 | Up to 500 characters containing the key value for the length of the key with a four-byte hexadecimal number stored in normal left-to-right format: If the node is a leaf (attribute = 02 or 03) then the four bytes contain an actual table number in hexadecimal format; otherwise, the 4 bytes contain an intra-index pointer.2 The key/four-byte hexadecimal number combinations will occur the number of times indicated in bytes 02 – 03.

1 The type of the key is not stored in the index. It must be determined by the key expression.
2 Anything other than character strings, numbers used as key values, and the four-byte numbers in the leaf node are represented in reversed bytes (Intel 8086 format).
3 Numbers are a special case when used as a key. They are converted through the following algorithm so they can be sorted using the same ASCII collating sequence as characters:

  • Convert the number to IEEE floating point format. For details, see Visual FoxPro System Capacities.
  • Swap the order of the bytes from Intel 8086 order to left-to-right order.
  • If the number was negative, take the logical complement of the number (swap all 64 bits, 1 to 0 and 0 to 1); otherwise, invert only the leftmost bit.

Example of an Ordered Tree Structure

Finding a key in the structure below requires searching a single path between the root and leaf nodes. Nodes at the lowest level are leaf nodes. Because the keys are sorted, all keys in the sub-tree are less than or equal to the parent node.

In the illustration above, the letters are used as the key values. Each key would also have a four-byte hexadecimal number. The numbers associated with the keys in the leaf nodes would be actual table numbers — all keys in other nodes would have intra-index pointers associated with them.

Bytes 12-511 in the index node record could be viewed as follows:

The key value/hexadecimal number combination occurs in bytes 12 – 511 n times where n is the number of keys present.

See Also

Compact Index File Structure (.idx) | Compound Index File Structure (.cdx) | Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Memo File Structure (.FPT) | Macro File Format (.fky) | File Extensions and File Types


Macro File Format (.fky)

File Header

Byte offset | Description
01 – 03 | Signature, Hex 79FF
04 – 15 | Ignored
16 – 17 | Number of macros (binary)
18 – end | The macros

Individual Macros

Byte offset | Description
00 – 19 | Macro name
20 – 21 | Macro length (in keystrokes, binary)
22 – 23 | Keystroke (two bytes, binary)
24 – end | Macro keystrokes

See Also

Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Compound Index File Structure (.cdx) | File Extensions and File Types | Memo File Structure (.FPT) | Compact Index File Structure (.idx) | Index File Structure (.idx)


Memo File Structure (.FPT)

Memo files contain one header record and any number of block structures. The header record contains a pointer to the next free block and the size of the block in bytes. The size is determined by the SET BLOCKSIZE command when the file is created. The header record starts at file position zero and occupies 512 bytes. The SET BLOCKSIZE TO 0 command sets the block size width to 1.

Following the header record are the blocks that contain a block header and the text of the memo. The table file contains block numbers that are used to reference the memo blocks. The position of the block in the memo file is determined by multiplying the block number by the block size (found in the memo file header record). All memo blocks start at even block boundary addresses. A memo block can occupy more than one consecutive block.

Memo Header Record

Byte offset | Description
00 – 03 | Location of next free block1
04 – 05 | Unused
06 – 07 | Block size (bytes per block)1
08 – 511 | Unused

1 Integers stored with the most significant byte first.

Memo Block Header and Memo Text

Byte offset | Description
00 – 03 | Block signature 1 (indicates the type of data in the block) 0 – picture (picture field type) 1 – text (memo field type)
04 – 07 | Length 1 of memo (in bytes)
08 – n | Memo text (n = length)

1 Integers stored with the most significant byte first.

See Also

Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | SET BLOCKSIZE | Index File Structure (.idx) | Compact Index File Structure (.idx) | Compound Index File Structure (.cdx) | Macro File Format (.fky) | File Extensions and File Types | Memo File Structure (.FPT)


Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx)

Visual FoxPro uses tables to store data that defines different file types. The following list includes the file types that are saved as tables:

  • Table (.dbf)
  • Database (.dbc)
  • Form (.scx)
  • Label (.lbx)
  • Menu (.mnx)
  • Project (.pjx)
  • Report (.frx)
  • Visual Class Library (.vcx)

You can use and browse these files in the same way that you browse any table file because these files are actually tables.

A table file consists of a header record and data records. The header record defines the structure of the table and contains any other information related to the table. The header record starts at file position zero. Data records follow the header, in consecutive bytes, and contain the actual text of the fields.

Note The data in the data file starts at the position indicated in bytes 8 to 9 of the header record. Data records begin with a delete flag byte. If this byte is an ASCII space (0x20), the record is not deleted. If the first byte is an asterisk (0x2A), the record is deleted. The data from the fields named in the field subrecords follows the delete flag.

The length of a record, in bytes, is determined by summing the defined lengths of all fields. Integers in table files are stored with the least significant byte first.

For information about the table structures of the different file types, see Table Structures of Table Files.

Table Header Record Structure

Byte offset | Description
0 | File type: 0x02 FoxBASE 0x03 FoxBASE+/Dbase III plus, no memo 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x43 dBASE IV SQL table files, no memo 0x63 dBASE IV SQL system files, no memo 0x83 FoxBASE+/dBASE III PLUS, with memo 0x8B dBASE IV with memo 0xCB dBASE IV SQL table files, with memo 0xF5 FoxPro 2.x (or earlier) with memo 0xFB FoxBASE
1 - 3 | Last update (YYMMDD)
4 – 7 | Number of records in file
8 – 9 | Position of first data record
10 – 11 | Length of one data record, including delete flag
12 – 27 | Reserved
28 | Table flags: 0x01 file has a structural .cdx 0x02 file has a Memo field 0x04 file is a database (.dbc) This byte can contain the sum of any of the above values. For example, the value 0x03 indicates the table has a structural .cdx and a Memo field.
29 | Code page mark
30 – 31 | Reserved, contains 0x00
32 – n | Field subrecords The number of fields determines the number of field subrecords. One field subrecord exists for each field in the table.
n+1 | Header record terminator (0x0D)
n+2 to n+264 | A 263-byte range that contains the backlink, which is the relative path of an associated database (.dbc) file, information. If the first byte is 0x00, the file is not associated with a database. Therefore, database files always contain 0x00.

Field Subrecords Structure

Byte offset | Description
0 – 10 | Field name with a maximum of 10 characters. If less than 10, it is padded with null characters (0x00).
11 | Field type: C – Character Y – Currency N – Numeric F – Float D – Date T – DateTime B – Double I – Integer L – Logical M – Memo G – General C – Character (binary) M – Memo (binary) P – Picture
12 – 15 | Displacement of field in record
16 | Length of field (in bytes)
17 | Number of decimal places
18 | Field flags: 0x01 System Column (not visible to user) 0x02 Column can store null values 0x04 Binary column (for CHAR and MEMO only) 0x06 (0x02+0x04) When a field is NULL and binary (Integer, Currency, and Character/Memo fields) 0x0C Column is autoincrementing
19 - 22 | Value of autoincrement Next value
23 | Value of autoincrement Step value
24 – 31 | Reserved

For information about limitations on characters per record, maximum fields, and so on, see Visual FoxPro System Capacities.

Remarks

Visual FoxPro modifies the table header when you turn on or add autoincrementing for field values.

Visual FoxPro does not modify the header of a file that has been saved to a FoxPro 2.x file format unless one of the following features has been added to the file:

  • Null value support
  • DateTime, Currency, and Double data types
  • CHAR or MEMO field is marked as Binary
  • A table is added to a database (.dbc) file
    Tip You can use the following formula to return the number of fields in a table file: (x – 296/32). In the formula, x is the position of the first record (bytes 8 to 9 in the table header record), 296 is 263 (backlink info) + 1 (header record terminator) + 32 (first field subrecord), and 32 is the length of a field subrecord.

See Also

Code Pages Supported by Visual FoxPro | Data and Field Types | Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Visual FoxPro System Capacities | Checking for Differences in Forms, Reports, and Other Table Files | File Extensions and File Types


Table Structures of Table Files (.dbc, .frx, .lbx, .mnx, .pjx, .scx, .vcx)

The descriptions of the table structures are stored in files located in the FILESPEC directory. The FILESPEC directory contains two project files: 60SPEC.pjx and 26SPEC.pjx. The 60SPEC.pjx file contains tables and reports that document Visual FoxPro versions 8.0, 7.0, 6.0, and 5.0 table files. The 26SPEC.pjx file contains tables and reports that document FoxPro version 2.6 table files.

To see the descriptions for any table structure, print the appropriate report. The following tables list the file types and their associated reports. Some file types require more than one report because there are too many columns to fit across a single page.

Note All the reports are formatted for landscape printing.

Visual FoxPro 8.0, 7.0, 6.0, and 5.0 File Types

To see the table structure of a... | Print this report | Which uses
Database1 | 60DBC.frx | 60DBC.dbf
Form and Visual Class Library | 60SCX1.frx 60SCX2.frx | 60SCX.dbf
Menu2 | 60MNX.frx | 60MNX.dbf
Project | 60PJX1.frx 60PJX2.frx | 60PJX.dbf
Report and Label | 60FRX1.frx 60FRX2.frx | 60FRX.dbf

1 The database properties can be printed from 60DBCPRO.frx.
2 The location field in Visual FoxPro 6.0 structure differs from Visual FoxPro 5.0 structure. Additional fields to support pictures in Visual FoxPro 7.0 are included in the report.

FoxPro version 2.6

To see the table structure of a... | Print this report | Which uses
Screen | 26SCX1.frx 26SCX2.frx | 26SCX.dbf
Menu | 26MNX.frx | 26MNX.dbf
Project | 26PJX1.frx 26PJX2.frx | 26PJX.dbf
Report and Label | 26FRX1.frx 26FRX2.frx | 26FRX.dbf

See Also

Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Code Pages Supported by Visual FoxPro | Data and Field Types | Checking for Differences in Forms, Reports, and Other Table Files | File Extensions and File Types


Fonts Overview

Visual FoxPro can use the fonts you have installed. Fonts determine the appearance of displayed or printed text. In addition, fonts determine the position and size of controls.

Control Size and Position

In Visual FoxPro, the ScaleMode property for the Form on which a control is placed determines the control's size and position. If ScaleMode is set to Pixels (3), the size of a control is specified in pixels. If ScaleMode is set to Foxels (0), the size of a control is determined by the Form's current font and font size.

Foxel is a Visual FoxPro term that corresponds to the maximum height and average width of a character in the current font. The row height corresponds to the maximum height of a letter in the current font; the column width corresponds to the average width of a letter in the current font.

In Visual FoxPro, you can use decimal fractions for row and column coordinates to facilitate precise positioning of controls and output. In FoxPro for MS-DOS, fractional portions of row and column coordinates are ignored.

In Visual FoxPro, to determine or change the font for the main Visual FoxPro window, press SHIFT while you display the Format menu, then choose the Screen Font option. The font for a user-defined window can be specified by including the FONT clause when you create the window with DEFINE WINDOW.

Font Substitution

If you specify a font that is not available, Windows substitutes a font with similar font characteristics. Windows considers the point size, serif characteristics and the pitch of the font you request. A TrueType font is typically substituted. A raster or vector font is only substituted when the characteristics of the font you request closely match those of the raster or vector font.

Font Functions

Several functions can be used to return information about fonts and text in a specific font.

These functions include:

Function | Description
AFONT( ) | Places information about available fonts into an array.
FONTMETRIC( ) | Returns font attributes for installed fonts.
GETFONT( ) | Displays the Font dialog and returns the name of the font you choose.
SYSMETRIC( ) | Returns the size of a display element.
SCOLS( ) | Returns the number of columns available in the main Visual FoxPro window. Useful when centering text or controls in the main Visual FoxPro window.
SROWS( ) | Returns the number of rows available in the main Visual FoxPro window.Useful when centering text or controls in the main Visual FoxPro window.
WCOLS( ) | Returns the number of columns within the specified window.Useful when centering text or controls in a user-defined window.
WFONT( ) | Returns the name, size or style of the current font for a window.
WROWS( ) | Returns the number of columns within the specified window.Useful when centering text or controls in a user-defined window.

See Also

AFONT( ) | FONTMETRIC( ) | GETFONT( ) | SYSMETRIC( ) | ScaleMode Property | SCOLS( ) | SROWS( ) | WCOLS( ) | WFONT( ) | WROWS( )


Graphics Support in Visual FoxPro

Visual FoxPro 8.0 replaces native support for rendering Graphics Interchange Format (.gif) and Joint Photographic Electronic Group (.jpeg) formats with Graphics Device Interface+ (GDI+), the next generation graphics device interface for Microsoft Windows XP and future releases of the Windows operating system. Visual FoxPro supports all formats that GDI+ handles such as the following, including animated .gif files:

File extension | File type name
.ani | Animated Cursor
.bmp | Bitmap
.cur | Cursor
.dib | Device Independent Bitmap
.emf | Windows Enhanced Metafile
.exif | Exchangeable Image File
.gif, .gfa | Graphics Interchange Format
.ico | Icon
.jpg, .jpeg, .jpe, .jfif | Joint Photographic Electronic Group, JPEG File Interchange Format
.png | Portable Networks Graphics
.tif, .tiff | Tag Image File Format
.wmf | Windows Metafile
Note In Visual FoxPro, cursor, animated cursor, and icon files can be used as graphics files. For example, you can specify an animated cursor file for the Picture property for the Image control. However, the Image control displays the static representation of the cursor.

If Visual FoxPro does not recognize a particular version of a natively supported format such as a .bmp, .dib, .cur, .ani, or .ico, it passes them to GDI+ for rendering. Therefore, as new static file formats become supported in future versions of GDI+, Visual FoxPro can support them automatically.

With GDI+, Visual FoxPro includes the RotateFlip property on the Image control so you can rotate and invert, or flip, an image. For more information, see RotateFlip Property.

Note GDI+ is installed with the Windows XP operating system and is required to run Visual FoxPro. Visual FoxPro includes a merge module for redistribution with custom applications running on Windows 98, Windows Me, Windows NT 4.0, and Windows 2000 platforms.

Visual FoxPro provides graphics support in the following three areas:

  • Language
  • Controls and objects
  • User interface

Language

You can use the GETPICT( ) function to access the Visual FoxPro dialog that provides access to valid file formats. You also can access graphics through properties in the controls and objects described here.

Controls and Objects

The following table lists Visual FoxPro controls and objects with properties for which you can specify graphics files. You can now specify .gif, .jpg, .cur, .ani, and .ico graphic files for these properties in addition to the .bmp and .dib graphic files supported in previous versions of Visual FoxPro.

Control or object | Properties
CheckBox Control | DisabledPicture DownPicture Picture
CommandButton Control | DisabledPicture DownPicture Picture
ComboBox Control | Picture
Container Object | Picture
Control Object | Picture
Custom Object | Picture
Form Object | Picture
Image Control* | Picture
ListBox Control | Picture
OptionButton Control | DisabledPicture DownPicture Picture
Page Object | Picture
_SCREEN System Variable | Picture

* Visual FoxPro supports animated .gif files only for the Picture property of an Image control.

User Interface

You can choose graphics files by using the Open dialog box in several Visual FoxPro designers. The Open dialog box for the following designers includes all valid graphic file formats.

Form Designer and Class Designer

You can find and select an image by opening the Open dialog box in the Form and Class designers for a property in those controls that support graphics files.

To select an image in the Form and Class designers

  • In the Properties window, double-click the Picture property.

Visual FoxPro displays the Open dialog box for you to find and select an image.

Project Manager

You can find, select, and add a graphics file to a project in the Project Manager.

To add a graphics file to a project

  • In the Project Manager, select Other Files in the All or Other tabs and click Add.

Visual FoxPro displays the Open dialog box for you to find and select an image.

Report Designer

You can find and select an image using the Open dialog box in the Report Designer.

To select an image in the Report Designer

  1. On the Report Controls toolbar, click the Picture/ActiveX Bound Control button. Drag the cursor, which appears as a crosshair, to a band of the Report Designer and click the left mouse button once to make the Report Picture dialog box appear.
  2. In the Report Picture dialog box, click the File radio button and click the ellipsis (...) button.

Visual FoxPro displays the Open dialog box for you to find and select an image.

GDI+ Image Support

GDI+ is a class-based application programming interface (API) for C/C++ programmers. It enables applications to use graphics and formatted text on both the video display and the printer. Applications based on the Microsoft Win32 API do not access graphics hardware directly. Instead, GDI+ interacts with device drivers on behalf of applications. GDI+ is also supported by the 64-bit Windows operating system.

GDI+ can be used in all Windows-based applications. GDI+ is included in Microsoft Windows XP and Windows Server 2003 operating systems. GDI+ is required and available as a redistributable for Visual FoxPro applications that run on the Windows NT 4.0 SP6, Windows 2000, Windows Millennium Edition, and Windows 98 operating systems. To download the most recent distributable, visit the Platform SDK Redistributables Web site at:

http://www.microsoft.com/msdownload/platformsdk/sdkupdate/psdkredist.htm

or the Microsoft Download Center Web site at:

http://www.microsoft.com/downloads/release.asp?releaseid=32738

Visual FoxPro 8.0 might include both Vfp8r.dll and Vfp8t.dll run-time libraries. The Gdiplus.dll file must be present in the system directory of the user's computer.

Animated .gif Image Support

Animated .gif files are a popular variety of the .gif file format. They use the same file extension (.gif) and contain specific image frames that cycle through to produce an animated effect. The animated .gif file contains the number of times the .gif file cycles through before stopping. Visual FoxPro supports animated .gif files as follows:

  • Visual FoxPro supports animated .gif files only for the Picture property in the Image control.
  • Animated .gif files are displayed at both design and run time.
  • Visual FoxPro displays only the first frame of an animated .gif file when it appears anywhere else but the Image control.
  • Visual FoxPro cycles through an animated .gif file based only on its internal loop count setting.
  • Visual FoxPro pauses between animation loops for one second.
  • If the size or location of the Image control changes at run time while an image animation plays, Visual FoxPro resets to the first frame and continues.
  • Visual FoxPro draws the .gif image size as specified by the .gif file author, not the Image control. Visual FoxPro does not clip or stretch the image.
  • During animations, the entire image or part of it is erased so that the next frame can be redrawn. Visual FoxPro minimizes unnecessary redrawing to avoid flickering. If the image position is moved, for example, the control or its container is moved, the entire image needs to be redrawn.
  • Because Visual FoxPro internally stores a single representation of a particular image as an off-screen bitmap, multiple Image controls using the same animated .gif file are always synchronized together. If you want the animations of the same image to behave differently for each Image control, you should create a copy of each animated .gif file and rename each one.
  • The author of animated .gif files can specify the amount of time between frames. This amount of time can differ between each frame. Therefore, it is possible for animated .gif files to have excessively long delays between frames.
  • If you use an animated .gif file in a control other than an Image control, animation of the image does not play. However, if you later use the image in an Image control, the image animates only if you first issue a CLEAR...RESOURCES command. This occurs because the image is already stored in memory, and the animation attribute is being ignored when the image is rendered in a non-image control. You must use CLEAR...RESOURCES to reload the image into memory.

See Also

Creating Access and Assign Methods | Access and Assign Methods | Picture Property | Image Control | CLEAR Commands


Join Conditions for Tables, Queries, and Views

When retrieving data from tables to create queries and views, you can use join conditions, or joins, to specify relationships between tables, usually based on the primary and foreign keys. For example, you can use join conditions to compare values in two tables that have common fields and return only those records where those fields have the same values. You can set join conditions for queries and views in the Query and View Designers and when using the Visual FoxPro language. For more information, see Join Tab, Query and View Designers and SELECT - SQL Command.

Specifying joins on fields other than the primary and foreign keys can be useful in specific instances; however, these types of joins are not used in most views.

Aspects of Join Conditions

The following list describes some aspects of join conditions and criteria that you can set between tables or in queries and views:

  • Join type between tables or between table fields in a query or view
  • Table fields in the join
  • Comparison condition operators between fields, such as Equal (=), Greater Than (>), and Between
  • Sequence of joins for more than two tables

Join Types

You can specify join types between tables or fields to expand or narrow the results of your search. For example, choosing a full join expands the results to include records that match and do not match the join condition.

The following table describes join types you can set to expand or narrow your data results.

Join type | Behavior
Inner join | Retrieve only those records from tables on both sides of the join that match the join criteria, or comparison condition between fields involved in the join. Inner joins are the most common type of join.
Left join | Retrieve all records from the table on the left side of the join and only those records that match the join criteria from the table on the right side of the join.
Right join | Retrieve only those records from the table on the left side of the join condition that match the join criteria but all records from the right side of the join condition.
Full join | Retrieve all records from tables on both sides of the join condition regardless of whether records match the join criteria.

For more information about join types you can set between tables, see Join Condition Dialog Box.

Join Conditions for Multiple Tables

When you use two or more tables, you can modify the results by selecting the join order of tables in the Query and View designers or in the FROM clause of the SQL SELECT statement. For more information, see Join Tab, Query and View Designers and SELECT - SQL Command.

For example, suppose you want to find information about customer orders, including information about the customer who placed the order information and the employee who made the sale. You can create a view using the customer, orders, and employee tables and specify inner join conditions for the fields they have in common: both customer and orders tables have a customer ID field; and both the orders and employee tables have an employee ID field.

The following code creates a view using the WHERE clause that retrieves the orders in the orders table matching the customers in the customer table and the employees in the employee table who took those orders:

OPEN DATABASE testdata
CREATE SQL VIEW cust_orders_emp_view AS ;
   SELECT * FROM testdata!customer ;
      INNER JOIN testdata!orders ;
      ON customer.cust_id = orders.cust_id ;
      INNER JOIN testdata!employee ;
      ON orders.emp_id = employee.emp_id

Join Criteria in Queries and Views

In addition to modifying join types between tables, you can also change the join criteria for queries and views. You can use comparison condition operators to control which records are compared and returned, similar to a filter.

For example, you can use the Equal (=) criteria when querying two tables joined on their respective customer ID fields, where Customer.cust_id = Orders.cust_id. The query retrieves only those records in which these two fields match and meet any other filter you set in the query. As another example, if you are using a date field in a join, you can use a comparison condition operator to include only records before or after a certain date.

Joins do not have to be based solely on the exact field matching. You can set up different join relationships using join criteria such as on Like, Exactly Like, More Than, or Less Than.

Join criteria behave similarly to filter criteria in that both compare values and then include records that match the criteria. However, join criteria compare the field value from one table to the field value of the other table, while filter criteria compare a field value to a filter value.

For more information about the join criteria you can set for queries and views, see Join Tab, Query and View Designers.

Non-Matching Records in Results

If you want to include any rows that do not match the join criteria in your results, you can use an outer join between tables. For example, suppose you want to create a view containing a list of all customers, whether or not they have placed an order. In addition, you want order numbers for the customers who have placed orders included in the view. When you use an outer join, the empty fields of the non-matching rows return null values.

The following code illustrates this example by creating a view using a join condition that retrieves all customers from the customer table and only the order numbers from the orders table for those customers matching the customer ID number in both tables:

OPEN DATABASE testdata
CREATE SQL VIEW cust_orders_view AS ;
   SELECT * FROM testdata!customer ;
      LEFT OUTER JOIN testdata!orders ;
      ON customer.cust_id = orders.cust_id

The following table describes join types that you can use to specify non-matching records that a query or view can include.

Join type | Behavior
Inner join | Retrieve only those records from tables on both sides of the join that match the join criteria, or comparison condition between fields involved in the join.
Left outer join | Retrieve all records from the table on the left side of the join and only those records that match the join criteria from the table on the right side of the join.
Right outer join | Retrieve only those records from the table on the left side of the join condition that match the join criteria but all records from the right side of the join condition.
Full outer join | Retrieve all records from tables on both sides of the join condition regardless of whether records match the join criteria.

Join Criteria in the WHERE Clause

When using filters, you can specify join criteria on the Filter tab in the Query and View Designers, which inserts a WHERE clause in the SQL SELECT statement generated for the query or view. However, you cannot specify a join condition as you can with the FROM clause. For remote views, a join condition always appears in the WHERE clause.

For example, suppose you want to find information about customer orders, including information about the customer who placed the order information and the employee who made the sale. You can create a view using the customer, orders, and employee tables and specify inner join conditions for the fields they have in common: both customer and orders tables have a customer ID field; and both the orders and employee tables have an employee ID field.

The following code creates a view using the WHERE clause that retrieves the orders in the orders table matching the customers in the customer table and the employees in the employee table who took those orders:

OPEN DATABASE testdata
CREATE SQL VIEW cust_orders_emp_view AS ;
   SELECT * FROM testdata!customer, ;
      testdata!orders, testdata!employee ;
   WHERE customer.cust_id = orders.cust_id ;
   AND orders.emp_id = employee.emp_id

For more information about the WHERE clause, see Filter Tab, Query and View Designers and SELECT - SQL Command.

See Also

Working with Views | Creating Views | Creating Local Views | Creating a Multitable View | Accessing Remote Data with Views | Project Manager Window | Query and View Designers | Displaying Data with Views | CREATE SQL VIEW Command


Keyboard Shortcuts

Visual FoxPro supports keyboard shortcuts in these areas:

  • Browse window
  • Class Browser
  • Code window
  • Controls
  • Editor
  • Form and Class Designer
  • Help
  • Menu commands
  • Print Preview window
  • Properties window
  • Report and Label Designer
  • Window manipulation

Browse Window

Shortcut | Action
CTRL+HOME | Moves to first record of a cursor or table in a grid and when using the BROWSE command.
CTRL+END | Moves to the last record of a cursor or table in a grid and when using the BROWSE command.

Class Browser

Shortcut | Action
F5 | Refreshes the current view.
SHIFT+F10 | Displays a shortcut menu.
Right-click+Open button Right-click+Add button Right-click+Component Gallery button | Displays a history of last 32 files loaded.
Right-click+View Class Code button | Displays the class code in a webview form.
CTRL+Right-click+Class icon (in upper left corner of the Class Browser) | Creates an instance of the class with the NEWOBJECT( ) function in the Command window. Identical to dragging the Class icon onto the Command window.
SHIFT+Right-click+Class icon (in upper left corner of the Class Browser) | For forms, runs the form. For other controls and objects, creates an instance of the control or object. For controls, also adds the control to the Visual FoxPro desktop at 0,0. Identical to dragging the Class icon onto the Visual FoxPro desktop.

Code Window

Shortcut | Action
ALT+I | Presses the View Parent Code button.

Controls

Shortcut | Action
CTRL+TAB | When a Grid control has focus, exits the grid. When an EditBox control has focus, and EditBox AllowTabs property is True (.T.), exits the edit box. When inside a form or dialog box containing a PageFrame control, moves to the next page in the page frame. However, this behavior is not supported in project files or when the page frame contains an ActiveX control.
CTRL+SHIFT+TAB | If inside a form or dialog box containing a PageFrame control, moves to the previous page in the page frame. However, this behavior is not supported in project files or when the page frame contains an ActiveX control.
TAB | When a Grid control has focus, moves to the next field.

Editor

To edit windows in Visual FoxPro, you can use modifier keys to choose either cut-and-paste or copy-and-paste dragging.

In Visual FoxPro, you can change the default drag-and-drop behavior by selecting the option, Drag drop between words, in the Editor tab in the Options dialog box. You can see the Editor tab by selecting Options from the Tools menu and choosing the Editor tab. Use ALT+Drag to toggle to the alternate setting (drag to within words or drag between words only).

Shortcut | Action
ALT+Drag (previous Visual FoxPro default) | Cuts and pastes.
CTRL+Drag | Copies and pastes.
CTRL+I | Show IntelliSense information.
CTRL+J | Show members or list values using IntelliSense.
F2 | Moves to the line containing the next bookmark.
SHIFT+F2 | Moves to the line containing the previous bookmark.
ALT+SHIFT+F2 | Toggles a bookmark for the current line on and off.
F3 | Finds the next occurrence of the specified text.
CTRL+F3, CTRL+G | Finds the next occurrence of the selected text.
SHIFT+F3 | Finds the previous occurrence of the specified text.
CTRL+SHIFT+F3 | Finds the previous occurrence of the selected text.
CTRL+DOWNARROW | Scrolls window up without moving cursor.
CTRL+UPARROW | Scrolls window down without moving cursor.
CTRL+LEFTARROW | Moves the cursor one word to the left.
CTRL+RIGHTARROW | Moves the cursor one word to the right.
F9 | Inserts or removes a breakpoint.
CTRL+F9 | Enables or disables a breakpoint.
CTRL+B | Brings up Breakpoints dialog box.
ALT+F2 | Adds/Removes Task List shortcut.
CTRL+U | Makes the selection all lowercase.
CTRL+SHIFT+U | Makes the selection all uppercase.
CTRL+BACKSPACE | Deletes a word to the left.

Form Designer and Class Designer

Shortcut | Action
CTRL+E | Runs the form in the Form Designer.
CTRL+SHIFT+Click the control | Drills down to a control in a container.
CTRL+Click the container | Drills down through the container.

Help

Shortcut | Action
F1 | Displays Help Contents or context-sensitive Help on active items, for example, a highlighted keyword in the Command window or the current property in the Properties window.
SHIFT+F1 | Enables user-prompted context-sensitive Help. The insertion pointer changes to a question mark so that you can click an item, for example, a menu command or toolbar, to display context-sensitive Help.

Menu Commands

Shortcut | Command
CTRL+A | Select All on the Edit menu
CTRL+C | Copy on the Edit menu
CTRL+D | Do on the Program menu
CTRL+E | Delete Item on the Menu menu
CTRL+E | Do <program> on the Program menu Run Form on the Form menu
CTRL+F | Find on the Edit menu
CTRL+G | Find Again on the Edit menu
CTRL+H | Change Partitions on the Table menu
CTRL+I | Insert Item on the Menu menu
CTRL+J | Project Info on the Project menu
CTRL+L | Replace on the Edit menu
CTRL+M | Resume on the Program menu
CTRL+N | New on the File menu
CTRL+O | Open on the File menu
CTRL+P | Print on the File menu
CTRL+Q | Closes current text window and discards changes. See also CTRL+W. Run Query on the Query menu
CTRL+R | Redo on the Edit menu
CTRL+S | Save on the File menu
CTRL+T | Toggle Deletion Mark on the Table menu
CTRL+V | Paste on the Edit menu
CTRL+W | Closes current text window or dialog box and saves changes.
CTRL+X | Cut on the Edit menu
CTRL+Y | Append New Record on the Table menu
CTRL+Z | Undo on the Edit menu

Print Preview Window

Shortcut | Action
Z | Zooms in and out of the page.
L | Toggles between various zoom levels.
G | Opens Goto page dialog box.
ESC | Closes Print Preview window.
LEFTARROW | Scrolls to the left of the page in the Print Preview window.
RIGHTARROW | Scrolls to the right of the page in the Print Preview window.
UPARROW | Scrolls towards the top of the page in the Print Preview window.
DOWNARROW | Scrolls towards the bottom of the page in the Print Preview window.
PAGEDOWN | Moves to the next page in the Print Preview window.
PAGEUP | Moves to the previous page in the Print Preview window.
HOME | Moves to the first page in the Print Preview window.
END | Moves to the last page in the Print Preview window.

Properties Window

Shortcut | Action
ALT+DOWN ARROW | Expands the object list.
ALT+UP ARROW | Closes the object list.
CTRL+PAGE DOWN or DOWN ARROW or RIGHT ARROW | Moves to next object in the object list.
CTRL+PAGE UP or UP ARROW or LEFT ARROW | Moves to previous object in object list.
CTRL+END | Moves to last object in the object list.
CTRL+HOME | Moves to first object in the object list.
TAB | Moves to the next control in the Properties window.
SHIFT+TAB | Moves to the previous control in the Properties window.
SHIFT+F10 | Displays the appropriate shortcut menu.
CTRL+ALT+letter | Selects the next property in the properties list that begins with the letter character. For example, pressing CTRL+ALT+B selects the next property that begins with B.

Report Designer

Shortcut | Action
ALT+ENTER | Opens the appropriate properties dialog box for a selected field.
CTRL+E | Enters Edit mode for a Label control when it is selected in the Report designer.
ESC | Exits Edit mode for a Label control and returns to Select mode.
TAB | Enters Tab mode automatically and moves to the next object in the Report Designer.
SHIFT+TAB | Moves to the previous object on the Report designer when in Tab mode.

Window Manipulation

Visual FoxPro preserves the order of windows and brings the newest window to the foreground instead of shifting the last window to the background when cycling through windows.

Shortcut | Action
CTRL+F1 | Cycles through windows.
CTRL+TAB | Moves to the next window.
CTRL+SHIFT+TAB | Moves to the previous window.
CTRL+F2 | Displays Command window
CTRL+F4 | Closes active window.
CTRL+F6 | Moves to the next window.
CTRL+ALT+SHIFT | Hides all child windows while the keys are pressed down. Hiding windows makes it easy to see output displayed in the main application window.
CTRL+F10 | Toggles window size between maximum and restore.

See Also

Debugger Keyboard Shortcuts and Menus | Command Window | Class Browser Window


Naming Conventions

When naming exposed objects, properties, and methods, choose names that can be understood by users of the application easily.

In This Section

Constant Naming Conventions
Provides a suggested format for naming constants.
Object Naming Conventions
Provides a suggested format for naming objects.
Table Field Naming Conventions
Provides a suggested format for naming fields in tables. These conventions are recommended, not required.
Variable Naming Conventions
Provides a suggested format for naming variables.
Window Naming Conventions
Provides a suggested format for naming windows.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Language Reference A-Z
Contains a list of language reference topics in alphabetical order.
Using Visual FoxPro
Discusses Visual FoxPro programming features that are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Provides conceptual information about how to develop Visual FoxPro applications, including instructions for creating databases and the user interface, and other programming tasks.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Constant Naming Conventions

Follow this suggested format for naming constants.

NAME

Remarks

It is recommended that constants be entered in uppercase.

Example

#DEFINE MAX_VALUE 10

For more information, see Visual FoxPro Naming Rules.

See Also

Object Naming Conventions | Table Field Naming Conventions | Variable Naming Conventions | Visual FoxPro Naming Rules | Window Naming Conventions


Object Naming Conventions

Follow this suggested format for naming objects.

PrefixName

Suggested prefixes for object names are listed in the following table.

Prefix Object Example
chk CheckBox
chkReadOnly
col Collection
colFormObjects
cbo ComboBox
cboEnglish
cmd CommandButton
cmdCancel
cmg CommandGroup
cmgChoices
cnt Container
cntMoverList
ctl Control
ctlFileList
cad CursorAdapter
cadInventory
<user-defined> Custom
user-defined
dte DataEnvironment
dteSalesForm
edt EditBox
edtTextArea
frm Form
frmFileOpen
frs FormSet
frsDataEntry
grd Grid
grdPrices
grc Column
grcCurrentPrice
grh Header
grhTotalInventory
hpl HyperLink
hplHomeURL
img Image
imgIcon
lbl Label
lblHelpMessage
lin Line
linVertical
lst ListBox
lstPolicyCodes
olb OLEBoundControl
olbObject1
ole OLE
oleObject1
opt OptionButton
optFrench
opg OptionGroup
opgType
pag Page
pagDataUpdate
pgf PageFrame
pgfLeft
prj ProjectHook
prjBuildAll
sep Separator
sepToolSection1
shp Shape
shpCircle
spn Spinner
spnValues
txt TextBox
txtGetText
tmr Timer
tmrAlarm
tbr ToolBar
tbrEditReport
xad XMLAdapter
xadRemoteXMLData
xfd XMLField
xfdPrices
xtb XMLTable
xtbInventory

Remarks

Prefixes aren't required, but are recommended as good programming practice. Using a prefix does not dictate the contents of an object variable — in Visual FoxPro, prefixes are used only as a naming convention. For example, adding the prefix "cbo" does not check that the object referenced by the variable is a combo box, but it does help you remember the object referenced by the variable.

For more information, see Visual FoxPro Naming Rules.

See Also

Constant Naming Conventions | Table Field Naming Conventions | Variable Naming Conventions | Visual FoxPro Naming Rules | Window Naming Conventions


Table Field Naming Conventions

Follow this suggested format for naming fields in tables. These conventions are recommended, not required.

Alias.TypeName

Parameters

Type
Notes the data type for a field in a table. Suggested prefixes for Type are as follows.
Type Description Example
c Character
Customer.cLastName
d Date
Customer.dBirthDay
t Datetime
Customer.tLastMod
b Double
Customer.bRate
f Float
Customer.fValue
g General
Customer.gPicture
l Logical
Customer.lSellMail
m Memo
Customer.mComments
y Currency
Customer.yYearTDate
n Numeric
Customer.nItems
I Integer
Customer.iCustID

Remarks

Prefixes aren't required, but are recommended as good programming practice. Using a prefix does not dictate the contents of a field — in Visual FoxPro, prefixes are used only as a naming convention. For example, adding the prefix "d" does not check that the contents of a field is a date, but it does help you remember the data type contained in the field.

For more information, see Visual FoxPro Naming Rules.

See Also

Constant Naming Conventions | Object Naming Conventions | Variable Naming Conventions | Visual FoxPro Naming Rules | Window Naming Conventions


Variable Naming Conventions

Follow this suggested format for naming variables.

[Scope]TypeName

Parameters

Scope
Optional. A convention for noting the range of reference for the variable. For example, local variables can be prefixed with "l," which reminds you that they can be referenced only within the procedure they were defined in. Suggested expressions for Scope are as follows.
Scope Description Example
l Local
lnCounter
p Private (default)
pnStatus
g Public (global)
gnOldRecno
t Parameter
tnRecNo
Type
Convention for noting the data type of a variable. Suggested prefixes for Type are as follows.
Type Description Example
a Array
aMonths
c Character
cLastName
y Currency
yCurrentValue
d Date
dBirthDay
t Datetime
tLastModified
b Double
bValue
f Float
fInterest
l Logical
lFlag
n Numeric
nCounter
o Object
oEmployee
u Unknown
uReturnValue

Remarks

Prefixes aren't required, but are recommended as good programming practice. Using a prefix does not dictate the value of a variable — in Visual FoxPro prefixes are used only as a naming convention. For example, adding the prefix "c" does not check that only character data is stored to the variable, but it does help you remember that the variable was created to accept character data.

Note The scope prefix is recommended but not required. In some cases, explicit scoping does not apply. For example, in the main program of a stand-alone application there is no difference in visibility for variables scoped as PUBLIC or PRIVATE. The type prefix is always relevant and is required in sample programs.

For more information, see Visual FoxPro Naming Rules.

See Also

Constant Naming Conventions | Object Naming Conventions | Table Field Naming Conventions | Visual FoxPro Naming Rules | Window Naming Conventions


Window Naming Conventions

Follow this suggested format for naming windows.

wName

Remarks

Do not use a prefix on class definitions; use prefixes only when the object is instantiated.

Example

When creating a window object, use the following code:

DEFINE WINDOW wCustomerInvoices ;
   FROM nFirstRow, nFirstColumn TO nLastRow, nLastColumn

For more information, see Visual FoxPro Naming Rules.

See Also

Constant Naming Conventions | Object Naming Conventions | Table Field Naming Conventions | Variable Naming Conventions | Visual FoxPro Naming Rules


Regular Expressions and Operators

Regular expressions are sets of symbols that you can use to create searches for finding and replacing patterns of text. Regular expressions provide a concise and flexible way to specify more complex search and filter criteria against a selection of text than the wildcard character pattern searching available in the Find dialog box.

The following table describes the behavior of regular expression operators in a query.

Operator | Behavior
. | Matches any single character except the newline (\n) character.
* | Matches the preceding character zero or more times. You can also use a question mark (?). Example "zo*" matches either "z" or "zoo". The expression "a?ve?" matches the "ve" in "never".
+ | Matches the preceding character one or more times. Example "zo+" matches "zoo" but not "z".
^ | Matches the beginning of the line.
$ | Matches the end of the line.
[xyz] | Matches any one character in the set. Both opening and closing brackets are required. Example "[abc]" matches the "a" in "plain".
[^xyz] | Matches any one character not in the set. Both opening and closing brackets are required. Example "[^abc]" matches the "p" in "plain".
[a-z] | Matches any character in the specified range. Example "[a-z]" matches any lowercase alphabetic character in the range of "a" through "z".
[^a-z] | Matches any character not in the specified range. Example "[^m-z]" matches any character not in the range of "m" through "z".
\ | Marks the next character as either a special character such as an escape character or a literal. Example "\\" matches "\", and "\(" matches "(".
(pattern) | Matches a pattern group. Both the opening and closing parentheses are required. Example "(tress)" matches "mattress" but not "mattres". To match parenthesis characters, use "\(" or "\)".
x|y | Matches either x or y. Example "z|wood" matches "z" or "wood". The expression "(z|w)ood" matches "zood" or "wood".
{m} | Matches the preceding character exactly m number of times, where m is nonnegative. Both opening and closing braces are required. Example "o{2}" does not match the "o" in "Bob" but matches the first two letter o's in "food" or "foooood".
{m,} | Matches the preceding character at least m number of times, where m is nonnegative. Example "o{2,}" does not match the "o" in "Bob" but matches all the o's in "fooooood". In addition, the expression "o{1,}" is equivalent to "o+", and "o{0,}" is equivalent to "o*".
{m,n} | Matches the preceding character at least m and at most n number of times, where both m and n are nonnegative. Example "o{1,3}" matches the first three o's in "foooooood". In addition, the expression "o{0,1}" is equivalent to "o?".
All else | Matches itself.

The following rules apply when you use regular expression operators:

  • You can enclose regular expressions in matching quotation marks (" "). You must enclose regular expressions in quotation marks if the expression contains a space or a closing parenthesis ()).

The Regular Expressions Foundation Class provides access to routines for using regular expressions in your applications. For more information, see Regular Expressions Foundation Class.

Visual FoxPro provides a regular expressions sample that you can use to determine how to incorporate regular expression text searching in your application. For more information, see Search Text Using Regular Expressions.

You can refer to MSDN for general details about regular expressions and pattern property matching.

See Also

General Reference | Look Up Reference Dialog Box | Find Dialog Box


Reserved Words

Reserved words in Microsoft Visual FoxPro include functions, system variables, properties, events, methods, commands, menu constants, and clauses. When programming, avoid using reserved words as names, for example, window, table, or field names. If you use a reserved word as a name, it might generate a syntax error.

The following are all Visual FoxPro reserved words.

-

!

!=

#

#DEFINE

#ELIF

#ELSE

#ENDIF

#IF

#ITSEXPRESSION

#READCLAUSES

#REGION

#SECTION

#UNDEF

#WNAME

$

%

(

)

*

**

,

.

.AND.

.F.

.N.

.NOT.

.NULL.

.OR.

.T.

.Y.

/

/R

:

::

;

?

??

???

@

[

]

^

_ALIGNMENT

_ASCIICOLS

_ASCIIROWS

_ASSIST

_BEAUTIFY

_BOX

_BROWSER

_BUILDER

_CALCMEM

_CALCVALUE

_CLIPTEXT

_CODESENSE

_CONVERTER

_COVERAGE

_CUROBJ

_DATETIMEFORMAT

_DBLCLICK

_DIARYDATE

_DOS

_FONTCLASS

_FOXBASECLASS

_FOXCODE

_FOXDOC

_FOXDRAGDROP

_FOXDROPTARGET

_FOXREF

_FOXGRAPH

_FOXTASK

_GALLERY

_GENGRAPH

_GENHTML

_GENMENU

_GENPD

_GENSCRN

_GENXTAB

_GETEXPR

_HELPWEBDEVONLY

_HELPWEBDIRECTORY

_HELPWEBFILLER1

_HELPWEBFILLER2

_HELPWEBMSDNONLINE

_HELPWEBMSFTHOMEPAGE

_HELPWEBSEARCH

_HELPWEBTUTORIAL

_HELPWEBVFPFAQ

_HELPWEBVFPFREESTUFF

_HELPWEBVFPHOMEPAGE

_HELPWEBVFPONLINESUPPORT

_HELPWEBVFPSENDFEEDBACK

_HELPWEBVSPRODNEWS

_INCLUDE

_INCSEEK

_INDENT

_LMARGIN

_MAC

_MBR_APPND

_MBR_CPART

_MBR_DELET

_MBR_FONT

_MBR_GOTO

_MBR_GRID

_MBR_LINK

_MBR_MODE

_MBR_MVFLD

_MBR_MVPRT

_MBR_SEEK

_MBR_SP100

_MBR_SP200

_MBR_SZFLD

_MBROWSE

_MDA_APPND

_MDA_AVG

_MDA_BROW

_MDA_CALC

_MDA_COPY

_MDA_COUNT

_MDA_LABEL

_MDA_PACK

_MDA_REPRT

_MDA_RINDX

_MDA_SETUP

_MDA_SORT

_MDA_SP100

_MDA_SP200

_MDA_SP300

_MDA_SUM

_MDA_TOTAL

_MDATA

_MDIARY

_MED_BEAUT

_MED_BLDEX

_MED_CLEAR

_MED_COPY

_MED_CUT

_MED_CVTST

_MED_EXBLK

_MED_FIND

_MED_FINDA

_MED_GOTO

_MED_INSOB

_MED_LINK

_MED_OBJ

_MED_PASTE

_MED_PREF

_MED_PSTLK

_MED_REDO

_MED_REPL

_MED_REPLA

_MED_SLCTA

_MED_SP100

_MED_SP200

_MED_SP300

_MED_SP400

_MED_SP500

_MED_SP600

_MED_UNDO

_MEDIT

_MFI_CLALL

_MFI_CLOSE

_MFI_EXPORT

_MFI_IMPORT

_MFI_NEW

_MFI_OPEN

_MFI_PGSET

_MFI_PREVU

_MFI_PRINT

_MFI_PRINTONECOPY

_MFI_QUIT

_MFI_REVRT

_MFI_SAVAS

_MFI_SAVE

_MFI_SAVEASHTML

_MFI_SEND

_MFI_SETUP

_MFI_SP100

_MFI_SP200

_MFI_SP300

_MFI_SP400

_MFI_SYSPRINT

_MFILE

_MFILER

_MFIRST

_MLABEL

_MLAST

_MLINE

_MMACRO

_MMB_DELET

_MMB_GENER

_MMB_GOPTS

_MMB_INSBR

_MMB_INSRT

_MMB_MOPTS

_MMB_PREVU

_MMB_QUICK

_MMB_SP100

_MMB_SP200

_MMB_SP300

_MMBLDR

_MOUSEEVENTS

_MOUSEEVENTSNODBL

_MPR_BEAUT

_MPR_CANCL

_MPR_COMPL

_MPR_DO

_MPR_DOCUM

_MPR_FORMWZ

_MPR_GENER

_MPR_GRAPH

_MPR_RESUM

_MPR_SP100

_MPR_SP200

_MPR_SP300

_MPR_SUSPEND

_MPROG

_MPROJ

_MRC_APPND

_MRC_CHNGE

_MRC_CONT

_MRC_DELET

_MRC_GOTO

_MRC_LOCAT

_MRC_RECAL

_MRC_REPL

_MRC_SEEK

_MRC_SP100

_MRC_SP200

_MRECORD

_MREPORT

_MRQBE

_MSCREEN

_MSM_DATA

_MSM_EDIT

_MSM_FILE

_MSM_FORMAT

_MSM_PROG

_MSM_RECRD

_MSM_SYSTM

_MSM_TEXT

_MSM_TOOLS

_MSM_VIEW

_MSM_WINDO

_MST_ABOUT

_MST_ASCII

_MST_CALCU

_MST_CAPTR

_MST_DBASE

_MST_DIARY

_MST_DOCUM

_MST_FILER

_MST_HELP

_MST_HPHOW

_MST_HPSCH

_MST_MACRO

_MST_MSDNC

_MST_MSDNI

_MST_MSDNS

_MST_OFFICE

_MST_PUZZL

_MST_SAMP

_MST_SP100

_MST_SP200

_MST_SP300

_MST_SPECL

_MST_TECHS

_MSYSMENU

_MSYSTEM

_MTABLE

_MTB_APPND

_MTB_CPART

_MTB_DELET

_MTB_DELRC

_MTB_GOTO

_MTB_LINK

_MTB_MVFLD

_MTB_MVPRT

_MTB_PROPS

_MTB_RECAL

_MTB_SP100

_MTB_SP200

_MTB_SP300

_MTB_SP400

_MTB_SZFLD

_MTI_CALLSTACK

_MTI_DBGOUT

_MTI_LOCALS

_MTI_RUNACTIVEDOC

_MTI_TRACE

_MTI_WATCH

_MTL_BROWSER

_MTL_COVERAGE

_MTL_DEBUGGER

_MTL_GALLERY

_MTL_MACRO

_MTL_OPTNS

_MTL_SP100

_MTL_SP200

_MTL_SP300

_MTL_SP400

_MTL_SPELL

_MTL_WZRDS

_MTOOLS

_MVI_TOOLB

_MVIEW

_MWI_ARRAN

_MWI_CLEAR

_MWI_CMD

_MWI_COLOR

_MWI_DEBUG

_MWI_HIDE

_MWI_HIDEA

_MWI_MIN

_MWI_MOVE

_MWI_ROTAT

_MWI_SHOWA

_MWI_SIZE

_MWI_SP100

_MWI_SP200

_MWI_TOOLB

_MWI_TRACE

_MWI_VIEW

_MWI_ZOOM

_MWINDOW

_MWIZARDS

_MWZ_ALL

_MWZ_APPLIC

_MWZ_APPLICATION

_MWZ_DATABASE

_MWZ_FORM

_MWZ_FOXDOC

_MWZ_IMPORT

_MWZ_LABEL

_MWZ_MAIL

_MWZ_PIVOT

_MWZ_QUERY

_MWZ_REPRT

_MWZ_SETUP

_MWZ_TABLE

_MWZ_UPSIZING

_MWZ_WEBPUBLISHING

_NETWARE

_OBJECTBROWSER

_OLEBASECONTROL

_OLEDRAGDROP

_ORACLE

_PADVANCE

_PAGENO

_PAGETOTAL

_PBPAGE

_PCOLNO

_PCOPIES

_PDPARMS

_PDRIVER

_PDSETUP

_PECODE

_PEJECT

_PEPAGE

_PFORM

_PLENGTH

_PLINENO

_PLOFFSET

_PPITCH

_PQUALITY

_PRETEXT

_PSCODE

_PSPACING

_PWAIT

_RECTCLASS

_RMARGIN

_RUNACTIVEDOC

_SAMPLES

_SCCTEXT

_SCREEN

_SHELL

_SPELLCHK

_SQLSERVER

_STARTUP

_TABS

_TALLY

_TASKLIST

_TEXT

_THROTTLE

_TRANSPORT

_TRIGGERLEVEL

_UNIX

_VFP

_VIEWPORT

_VSBUILD

_WEBDEVONLY

_WEBMENU

_WEBMSFTHOMEPAGE

_WEBVFPHOMEPAGE

_WEBVFPONLINESUPPORT

_WINDOWS

_WIZARD

_WRAP

+

<

<??>

<=

<>

=

=

==

=>

>

->

>=

A

A

ABS

ACCELERATE

ACCEPT

ACCESS

ACLASS

ACOPY

ACOS

ACTIVATE

ACTIVATECELL

ACTIVECOLUMN

ACTIVECONTROL

ACTIVEDOC

ACTIVEFORM

ACTIVEOBJECTID

ACTIVEPAGE

ACTIVEROW

ADATABASES

ADBOBJECTS

ADD

ADDBS

ADDCOLUMN

ADDITEM

ADDITIVE

ADDLISTITEM

ADDOBJECT

ADDPROPERTY

ADDRELATIONTOENV

ADDTABLETOENV

ADDTABLESCHEMA

ADOCKSTATE

ADEL

ADIR

ADLLS

ADMIN

ADOCKSTATE

AELEMENT

AERROR

AEVENTS

AFIELDS

AFONT

AFTER

AFTERBUILD

AFTERCLOSETABLES

AFTERCURSORATTACH

AFTERCURSORCLOSE

AFTERCURSORDETACH

AFTERCURSORFILL

AFTERCURSORREFRESH

AFTERCURSORUPDATE

AFTERDELETE

AFTERDOCK

AFTERINSERT

AFTERROWCOLCHANGE

AFTERUPDATE

AGAIN

AGETCLASS

AGETFILEVERSION

AINDENT

AINS

AINSTANCE

ALANGUAGE

ALEN

ALIAS

ALIGN

ALIGNMENT

ALIGNRIGHT

ALINES

ALL

ALLOWADDNEW

ALLOWAUTOCOLUMNFIT

ALLOWCELLSELECTION

ALLOWDELETE

ALLOWEXTERNAL

ALLOWHEADERSIZING

ALLOWINSERT

ALLOWOUTPUT

ALLOWRESIZE

ALLOWROWSIZING

ALLOWTABS

ALLOWTABS+

ALLOWUPDATE

ALLTRIM

ALT

ALTER

ALTERNATE

ALWAYSONBOTTOM

ALWAYSONTOP

AMEMBERS

AMOUSEOBJ

AND

ANETRESOURCES

ANSI

ANSI

ANSITOOEM

ANY

APLABOUT

APP

APPEND

APPLICATION

APPLYDIFFGRAM

APRINTERS

APROCINFO

ARRAY

AS

ASC

ASCAN

ASCENDING

ASCII

ASELOBJ

ASESSIONS

ASIN

ASORT

ASSERT

ASSERTS

ASSIST

ASTACKINFO

ASUBSCRIPT

ASYNCHRONOUS

AT

AT_C

ATAGINFO

ATAN

ATC

ATCC

ATCLINE

ATGETCOLORS

ATLINE

ATLISTCOLORS

ATN2

ATTACH

ATTRIBUTES

AUSED

AUTOACTIVATE

AUTOCENTER

AUTOCLOSETABLES

AUTOFIT

AUTOFORM

AUTOINC

AUTOINCERROR

AUTOMATIC

AUTOOPEN

AUTOOPENTABLES

AUTORELEASE

AUTOREPORT

AUTOSAVE

AUTOSIZE

AUTOVERBMENU

AUTOYIELD

AVAILNUM

AVCXCLASSES

AVERAGE

AVG

B

B

BACKCOLOR

BACKSTYLE

BACKSTYLE

BAR

BARCOUNT

BARPROMPT

BASECLASS

BATCHMODE

BATCHUPDATECOUNT

BEFORE

BEFOREBUILD

BEFORECURSORATTACH

BEFORECURSORCLOSE

BEFORECURSORDETACH

BEFORECURSORFILL

BEFORECURSORREFRESH

BEFORECURSORUPDATE

BEFOREDELETE

BEFOREDOCK

BEFOREINSERT

BEFOREOPENTABLES

BEFOREROWCOLCHANGE

BEFOREUPDATE

BEGIN

BELL

BELLSOUND

BETWEEN

BINDCONTROLS

BINDEVENT

BINTOC

BITAND

BITCLEAR

BITLSHIFT

BITMAP

BITNOT

BITOR

BITRSHIFT

BITSET

BITTEST

BITXOR

BLANK

BLINK

BLOCKSIZE

BOF

BORDER

BORDERCOLOR

BORDERSTYLE

BORDERWIDTH

BOTTOM

BOUND

BOUNDCOLUMN

BOUNDTO

BOX

BROWSE

BROWSEALIGNMENT

BROWSECELLMARG

BROWSEDESTWIDTH

BROWSEIMECONTROL

BROWSEREFRESH

BRSTATUS

BUCKET

BUFFERING

BUFFERMODE

BUFFERMODEOVERRIDE

BUFFERS

BUILD

BUILDERLOCK

BUTTONCOUNT

BUTTONINDEX

BUTTONS

BUTTONSBOF

BY

C

C

CALCULATE

CALL

CANACCELERATE

CANCEL

CANDIDATE

CANGETFOCUS

CANLOSEFOCUS

CAPSLOCK

CAPTION

CARRY

CASCADE

CASE

CATALOG

CATCH

CD

CDOW

CDX

CEILING

CENTER

CENTERED

CENTRAL

CENTURY

CGA

CHANGE

CHANGESTOCURSOR

CHAR

CHARACTER

CHDIR

CHECK

CHECKBOX

CHILDALIAS

CHILDORDER

CHILDORDER

CHILDTABLE

CHR

CHRSAW

CHRTRAN

CHRTRANC

CIRCLE

CLASS

CLASS

CLASSLIB

CLASSLIBRARY

CLEAR

CLEARDATA

CLICK

CLIPCONTROLS

CLIPRECT

CLOCK

CLONEOBJECT

CLOSABLE

CLOSE

CLOSEEDITOR

CLOSETABLES

CLS

CMONTH

CNT

CNTBAR

CNTPAD

CODEPAGE

COL

COLLATE

COLLECTION

COLOR

COLORSCHEME

COLORSOURCE

COLUMN

COLUMNCOUNT

COLUMNHEADERS

COLUMNLINES

COLUMNORDER

COLUMNS

COLUMNWIDTHS

COM1

COM2

COMARRAY

COMBOBOX

COMCLASSINFO

COMMAND

COMMANDBUTTON

COMMANDGROUP

COMMANDTARGETEXEC

COMMANDTARGETQUERY

COMMENT

COMPACT

COMPAREMEMO

COMPATIBLE

COMPILE

COMPLETED

COMPOBJ

COMPRESS

COMPUTE

COMRETURNERROR

CONCAT

CONFIRM

CONNECTBUSY

CONNECTHANDLE

CONNECTION

CONNECTIONS

CONNECTNAME

CONNECTSTRING

CONNECTTIMEOUT

CONNSTRING

CONSOLE

CONTAINER

CONTAINERRELEASE

CONTAINERRELEASETYPE

CONTINUE

CONTINUOUSSCROLL

CONTROL

CONTROLBOX

CONTROLCOUNT

CONTROLINDEX

CONTROLS

CONTROLSOURCE

CONVERSIONFUNC

COPIES

COPY

COS

COT

COUNT

COVERAGE

CPCOMPILE

CPCONVERT

CPCURRENT

CPDBF

CPDIALOG

CPNOTRANS

CREATE

CREATEBINARY

CREATEOBJECT

CREATEOBJECTEX

CREATEOFFLINE

CRSBUFFERING

CRSFETCHMEMO

CRSFETCHSIZE

CRSMAXROWS

CRSMETHODUSED

CRSNUMBATCH

CRSSHARECONNECTION

CRSUSEMEMOSIZE

CRSWHERECLAUSE

CSV

CTOBIN

CTOBIN

CTOD

CTOT

CURDATE

CURDIR

CURRENCY

CURRENTCONTROL

CURRENTX

CURRENTY

CURRENTY

CURRLEFT

CURRSYMBOL

CURSOR

CURSORADAPTER

CURSORATTACH

CURSORDETACH

CURSORFILL

CURSORGETPROP

CURSORREFRESH

CURSORSCHEMA

CURSORSETPROP

CURSORSOURCE

CURSORSTATUS

CURSORTORS

CURSORTOXML

CURTIME

CURVAL

CURVATURE

CUSTOM

CYCLE

D

D

DATABASE

DATABASES

DATAENVIRONMENT

DATAOBJECT

DATASESSION

DATASESSIONID

DATASOURCE

DATASOURCEOBJ

DATASOURCETYPE

DATATOCLIP

DATATYPE

DATE

DATEFORMAT

DATEMARK

DATETIME

DAY

DAYNAME

DAYOFMONTH

DAYOFWEEK

DAYOFYEAR

DB_BUFLOCKROW

DB_BUFLOCKTABLE

DB_BUFOFF

DB_BUFOPTROW

DB_BUFOPTTABLE

DB_COMPLETTE

DB_DELETEINSERT

DB_KEYANDMODIFIED

DB_KEYANDTIMESTAMP

DB_KEYANDUPDATABLE

DB_LOCALSQL

DB_NOPROMPT

DB_PROMPT

DB_REMOTESQL

DB_TRANSAUTO

DB_TRANSMANUAL

DB_TRANSNONE

DB_UPDATE

DB4

DB4

DBALIAS

DBC

DBC_Activate

DBC_AfterAddRelation

DBC_AfterAddTable

DBC_AfterAppendProc

DBC_AfterCloseTable

DBC_AfterCopyProc

DBC_AfterCreateConnection

DBC_AfterCreateOffline

DBC_AfterCreateTable

DBC_AfterCreateView

DBC_AfterDBGetProp

DBC_AfterDBSetProp

DBC_AfterDeleteConnection

DBC_AfterDropOffline

DBC_AfterDropRelation

DBC_AfterDropTable

DBC_AfterDropView

DBC_AfterModifyConnection

DBC_AfterModifyProc

DBC_AfterModifyTable

DBC_AfterModifyView

DBC_AfterOpenTable

DBC_AfterRemoveTable

DBC_AfterRenameConnection

DBC_AfterRenameTable

DBC_AfterRenameView

DBC_AfterValidateData

DBC_BeforeAddRelation

DBC_BeforeAddTable

DBC_BeforeAppendProc

DBC_BeforeCloseTable

DBC_BeforeCopyProc

DBC_BeforeCreateConnection

DBC_BeforeCreateOffline

DBC_BeforeCreateTable

DBC_BeforeCreateView

DBC_BeforeDBGetProp

DBC_BeforeDBSetProp

DBC_BeforeDeleteConnection

DBC_BeforeDropOffline

DBC_BeforeDropRelation

DBC_BeforeDropTable

DBC_BeforeDropView

DBC_BeforeModifyConnection

DBC_BeforeModifyProc

DBC_BeforeModifyTable

DBC_BeforeModifyView

DBC_BeforeOpenTable

DBC_BeforeRemoveTable

DBC_BeforeRenameConnection

DBC_BeforeRenameTable

DBC_BeforeRenameView

DBC_BeforeValidateData

DBC_CloseData

DBC_Deactivate

DBC_ModifyData

DBC_OpenData

DBC_PackData

DBF

DBFDBLCLICK

DBGETPROP

DBLCLICK

DBMEMO3

DBSETPROP

DBTRAP

DBUSED

DDEABORTTRANS

DDEADVISE

DDEENABLED

DDEEXECUTE

DDEINITIATE

DDELASTERROR

DDEPOKE

DDEREQUEST

DDESETOPTION

DDESETSERVICE

DDESETTOPIC

DDETERMINATE

DEACTIVATE

DEACTIVATE

DEBUG

DEBUGGER

DEBUGOUT

DECIMALS

DECLARE

DECLASS

DECLASSLIBRARY

DEFAULT

DEFAULTEXT

DEFAULTFILEPATH

DEFAULTSOURCE

DEFAULTVALUE

DEFBUTTON

DEFBUTTONORIG

DEFHEIGHT

DEFINE

DEFINEWINDOWS

DEFLEFT

DEFOLELCID

DEFTOP

DEFWIDTH

DEGREES

DELAYBIND

DELETE

DELETECMD

DELETECMDDATASOURCE

DELETECMDDATASOURCETYPE

DELETECOLUMN

DELETED

DELETEMARK

DELETETABLES

DELETETRIGGER

DELIMITED

DELIMITERS

DESC

DESCENDING

DESCRIPTION

DESIGN

DESKTOP

DESTROY

DETAILS

DEVELOPMENT

DEVICE

DIF

DIFFERENCE

DIMENSION

DIR

DIRECTORY

DISABLED

DISABLEDBACKCOLOR

DISABLEDBYEOF

DISABLEDFORECOLOR

DISABLEDITEMBACKCOLOR

DISABLEDITEMFORECOLOR

DISABLEDPICTURE

DISABLEENCODE

DISCONNECTED

DISKSPACE

DISPLAY

DISPLAYCOUNT

DISPLAYPATH

DISPLAYVALUE

DISPLAYVALUEDIRTY

DISPLOGIN

DISPPAGEHEIGHT

DISPPAGEWIDTH

DISPWARNINGS

DISTINCT

DLL

DLLS

DMY

DO

DOC

DOCK

DOCKED

DOCKPOSITION

DOCMD

DOCREATE

DOCUMENTFILE

DODEFAULT

DOEVENTS

DOHISTORY

DOS

DOSCROLL

DOSMEM

DOUBLE

DOVERB

DOW

DOWN

DOWNCLICK

DOWNPICTURE

DRAG

DRAGDROP

DRAGICON

DRAGMODE

DRAGOVER

DRAGSTATE

DRAW

DRAW

DRAWMODE

DRAWSTYLE

DRAWWIDTH

DRIVER

DRIVETYPE

DROP

DROPDOWN

DROPOFFLINE

DTOC

DTOR

DTOS

DTOT

DUPLEX

DYNAMICALIGNMENT

DYNAMICBACKCOLOR

DYNAMICCURRENTCONTROL

DYNAMICFONTBOLD

DYNAMICFONTITALIC

DYNAMICFONTNAME

DYNAMICFONTOUTLINE

DYNAMICFONTSHADOW

DYNAMICFONTSIZE

DYNAMICFONTSTRIKETHRU

DYNAMICFONTUNDERLINE

DYNAMICFORECOLOR

DYNAMICINPUTMASK

E

E

EACH

ECHO

EDIT

EDITBOX

EDITFLAGS

EDITOROPTIONS

EDITSOURCE

EDITWORK

EGA25

EGA43

EJECT

ELIF

ELSE

EMPTY

EMS

EMS64

ENABLED

ENABLEDBYREADLOCK

ENABLEHYPERLINKS

ENCRYPT

ENCRYPTION

END

ENDCASE

ENDDEFINE

ENDDO

ENDFOR

ENDFUNC

ENDIF

ENDPRINTJOB

ENDPROC

ENDSCAN

ENDTEXT

ENDTRY

ENDWITH

ENGINEBEHAVIOR

ENTERFOCUS

ENVIRONMENT

ENVLEVEL

EOF

ERASE

ERASEPAGE

ERROR

ERRORMESSAGE

ERRORNO

ESCAPE

EVALUATE

EVENTHANDLER

EVENTLIST

EVENTS

EVENTTRACKING

EVL

EXACT

EXCEPT

EXCEPTION

EXCLUSIVE

EXE

EXECSCRIPT

EXISTS

EXIT

EXITFOCUS

EXP

EXPORT

EXPRESSION

EXTENDED

EXTERNAL

F

F

F11F12

FCHSIZE

FCLOSE

FCOUNT

FCREATE

FDOW

FEOF

FERROR

FETCH

FETCHMEMO

FETCHSIZE

FFLUSH

FGETS

FIELD

FIELDS

FIELDSF

FILE

FILER

FILES

FILETOSTR

FILL

FILLCOLOR

FILLSTYLE

FILTER

FINALLY

FIND

FIRSTELEMENT

FIXED

FKLABEL

FKMAX

FLAGS

FLDCOUNT

FLDLIST

FLOAT

FLOCK

FLOOR

FLUSH

FOLDCONST

FONT

FONTBOLD

FONTCHARSET

FONTCLASS

FONTCONDENSE

FONTEXTEND

FONTITALIC

FONTMETRIC

FONTMETRIC

FONTNAME

FONTOUTLINE

FONTSHADOW

FONTSIZE

FONTSTRIKETHRU

FONTUNDERLINE

FOOTER

FOPEN

FOR

FORCE

FORCECLOSETAG

FORCEEXT

FORCEFOCUS

FORCEPATH

FORECOLOR

FOREIGN

FORM

FORMAT

FORMATCHANGE

FORMATTEDOUTPUT

FORMCOUNT

FORMINDEX

FORMPAGECOUNT

FORMPAGEINDEX

FORMS

FORMSCLASS

FORMSET

FORMSETCLASS

FORMSETLIB

FORMSLIB

FOUND

FOX2X

FOXCODE

FOXDOC

FOXFONT

FOXGEN

FOXGRAPH

FOXPLUS

FOXPRO

FOXTASK

FOXVIEW

FPUTS

FRACTIONDIGITS

FREAD

FREE

FREEZE

FRENCH

FROM

FSEEK

FSIZE

FTIME

FULL

FULLNAME

FULLPATH

FUNCTION

FV

FW2

FWEEK

FWRITE

G

G

GATHER

GENERAL

GERMAN

GET

GETBAR

GETCOLOR

GETCP

GETCURSORADAPTER

GETDATA

GETDIR

GETENV

GETEXPR

GETFILE

GETFLDSTATE

GETFONT

GETFORMAT

GETHOST

GETINTERFACE

GETKEY

GETNEXTMODIFIED

GETOBJECT

GETPAD

GETPEM

GETPICT

GETPRINTER

GETS

GETWORDCOUNT

GETWORDNUM

GLOBAL

GO

GOBACK

GOFIRST

GOFORWARD

GOLAST

GOMONTH

GOTFOCUS

GOTO

GRAPH

GRID

GRIDHITTEST

GRIDHORZ

GRIDLINECOLOR

GRIDLINES

GRIDLINEWIDTH

GRIDSHOW

GRIDSHOWPOS

GRIDSNAP

GRIDVERT

GROUP

GROW

H

H

HALFHEIGHT

HALFHEIGHTCAPTION

HASCLIP

HAVING

HEADER

HEADERCLASS

HEADERCLASSLIBRARY

HEADERGAP

HEADERHEIGHT

HEADING

HEADINGS

HEIGHT

HELP

HELPCONTEXTID

HELPFILTER

HELPON

HELPTO

HIDDEN

HIDE

HIDEAPPOBJ

HIDEDOC

HIDESELECTION

HIGHLIGHT

HIGHLIGHTBACKCOLOR

HIGHLIGHTFORECOLOR

HIGHLIGHTSTYLE

HIGHLIGHTROW

HISTORY

HMEMORY

HOME

HOSTNAME

HOTKEY

HOUR

HOURS

HPROJ

HSCROLLSMALLCHANGE

HWND

HYPERLINK

I

I

IBLOCK

ICON

ID

IDHISTORY

IDLETIMEOUT

IDXCOLLATE

IF

IFDEF

IFNDEF

IGNOREINSERT

IIF

IMAGE

IMEMODE

IMESTATUS

IMPORT

IN

INCLUDE

INCREMENT

INCREMENTALSEARCH

INDBC

INDEX

INDEXES

INDEXSEEK

INDEXTOITEMID

INFORMATION

INIT

INITIALSELECTEDALIAS

INKEY

INLIST

INNER

INPUT

INPUTMASK

INRESIZE

INSERT

INSERTCMD

INSERTCMDDATASOURCE

INSERTCMDDATASOURCETYPE

INSERTTRIGGER

INSMODE

INSTRUCT

INT

INTEGER

INTEGRALHEIGHT

INTENSITY

INTERACTIVECHANGE

INTERSECT

INTERVAL

INTO

IS

ISALPHA

ISATTRIBUTE

ISBASE64

ISBINARY

ISBLANK

ISCOLOR

ISDIFFGRAM

ISDIGIT

ISEXCLUSIVE

ISFLOCKED

ISHOSTED

ISLEADBYTE

ISLOADED

ISLOWER

ISMOUSE

ISNULL

ISOMETRIC

ISREADONLY

ISRLOCKED

ISUPPER

ISXMLDOMELEMENT

ITALIAN

ITEM

ITEMBACKCOLOR

ITEMDATA

ITEMFORECOLOR

ITEMIDDATA

ITEMIDTOINDEX

ITEMTIPS

J

J

JAPAN

JOIN

JUSTDRIVE

JUSTEXT

JUSTFNAME

JUSTPATH

JUSTREADLOCKED

JUSTSTEM

K

KEY

KEYBOARD

KEYBOARDHIGHVALUE

KEYBOARDLOWVALUE

KEYCOLUMNS

KEYCOMP

KEYFIELD

KEYFIELDLIST

KEYMATCH

KEYPRESS

KEYPREVIEW

KEYSET

KEYSORT

L

LABEL

LANGUAGEOPTIONS

LAST

LASTKEY

LASTPROJECT

LCASE

LDCHECK

LEDIT

LEFT

LEFTC

LEFTCOLUMN

LEN

LENC

LENGTH

LEVEL

LIBRARY

LIKE

LIKEC

LINE

LINECONTENTS

LINENO

LINESLANT

LINKED

LINKMASTER

LIST

LISTBOX

LISTCOUNT

LISTINDEX

LISTITEM

LISTITEMID

LOAD

LOADPICTURE

LOADXML

LOCAL

LOCFILE

LOCK

LOCKCOLUMNS

LOCKCOLUMNSLEFT

LOCKDATASOURCE

LOCKSCREEN

LOG

LOG10

LOGERRORS

LOGOUT

LONG

LOOKUP

LOOP

LOSTFOCUS

LOWER

LPARAMETER

LPARAMETERS

LPARTITION

LTRIM

LTRJUSTIFY

LUPDATE

M

MAC

MACDESKTOP

MACHELP

MACKEY

MACROS

MACSCREEN

MAIL

MAP19_4TOCURRENCY

MARGIN

MARK

MASTER

MAX

MAXBUTTON

MAXHEIGHT

MAXLEFT

MAXLENGTH

MAXMEM

MAXRECORDS

MAXTOP

MAXWIDTH

MBLOCK

MCOL

MD

MDI

MDIFORM

MDOWN

MDX

MDY

MEMBERCLASS

MEMBERCLASSLIBRARY

MEMLIMIT

MEMLINES

MEMO

MEMORY

MEMOS

MEMOWIDTH

MEMOWINDOW

MEMVAR

MENU

MENUS

MESSAGE

MESSAGEBOX

MESSAGES

METHOD

MIDDLE

MIDDLECLICK

MIN

MINBUTTON

MINHEIGHT

MINIMIZE

MINUS

MINUTE

MINWIDTH

MKDIR

MLINE

MOD

MODAL

MODIFY

MODULE

MONO

MONO43

MONO43

MONTH

MONTHNAME

MOUSE

MOUSEDOWN

MOUSEICON

MOUSEMOVE

MOUSEPOINTER

MOUSEUP

MOUSEWHEEL

MOVABLE

MOVE

MOVED

MOVEITEM

MOVERBARS

MOVERS

MRKBAR

MRKPAD

MROW

MTB_SP100

MTON

MULTILOCKS

MULTISELECT

MVARSIZ

MVCOUNT

MWINDOW

N

NAME

NAPTIME

NATIVE

NAVIGATETO

NDX

NEAR

NEGOTIATE

NETWORK

NEWINDEX

NEWITEMID

NEWOBJECT

NEXT

NEXTVALUE

NOALIAS

NOAPPEND

NOCLEAR

NOCLOSE

NOCONSOLE

NOCPTRANS

NODATA

NODATAONLOAD

NODEBUG

NODEFAULT

NODEFINE

NODELETE

NODIALOG

NODUP

NOEDIT

NOEJECT

NOENVIRONMENT

NOFILTER

NOFLOAT

NOFOLLOW

NOGROW

NOINIT

NOLGRID

NOLINK

NOLOCK

NOLOG

NOMARGIN

NOMDI

NOMENU

NOMINIMIZE

NOMODIFY

NOMOUSE

NONE

NOOPTIMIZE

NOORGANIZE

NOOVERWRITE

NOPROJECTHOOK

NOPROMPT

NOREAD

NOREFRESH

NOREQUERY

NORGRID

NORM

NORMAL

NORMALIZE

NOSAVE

NOSHADOW

NOSHOW

NOSPACE

NOT

NOTAB

NOTE

NOTIFY

NOTIFYCONTAINER

NOUPDATE

NOVALIDATE

NOVERIFY

NOW

NOWAIT

NOWINDOW

NOWRAP

NOZOOM

NPV

NTOM

NULL

NULLDISPLAY

NULLSTRING

NUMBER

NUMBEROFELEMENTS

NUMLOCK

NVL

O

OBJECTS

OBJNUM

OBJREF

OBJTOCLIENT

OBJVAR

OCCURS

ODBCHDBC

ODBCHSTMT

ODOMETER

OEMTOANSI

OF

OFF

OLDVAL

OLEBASECONTROL

OLEBOUNDCONTROL

OLECLASS

OLECLASSID

OLECLASSIDISPOUT

OLECOMPLETEDRAG

OLECONTROL

OLECONTROLCONTAINER

OLEDRAG

OLEDRAGDROP

OLEDRAGMODE

OLEDRAGOVER

OLEDRAGPICTURE

OLEDROPEFFECTS

OLEDROPHASDATA

OLEDROPMODE

OLEDROPTEXTINSERTION

OLEGIVEFEEDBACK

OLEIDISPATCHINCOMING

OLEIDISPATCHOUTGOING

OLEIDISPINVALUE

OLEIDISPOUTVALUE

OLELCID

OLEOBJECTS

OLEPUBLIC

OLEREQUESTPENDINGTIMOU

OLESERVERBUSYRAISEERRO

OLESERVERBUSYTIMOUT

OLESETDATA

OLESTARTDRAG

OLETYPEALLOWED

ON

ONETOMANY

ONLINE

ONLY

ONMOVEITEM

ONRESIZE

OPEN

OPENEDITOR

OPENTABLES

OPENVIEWS

OPENWINDOW

OPTIMIZE

OPTIONBUTTON

OPTIONGROUP

OR

ORACLE

ORDER

ORIENTATION

OS

OTHERWISE

OUTER

OUTPUT

OUTSHOW

OVERLAY

OVERWRITE

P

PACK

PACKETSIZE

PAD

PADC

PADL

PADPROMPT

PADR

PAGE

PAGECOUNT

PAGEFRAME

PAGEHEIGHT

PAGEHEIGHT

PAGEORDER

PAGES

PAGEWIDTH

PAINT

PALETTE

PANEL

PANELLINK

PAPERLENGTH

PAPERSIZE

PAPERWIDTH

PARAMETERS

PARENT

PARENTALIAS

PARENTCLASS

PARENTTABLE

PARTITION

PASSWORD

PASSWORDCHAR

PATH

PATTERN

PAUSE

PAYMENT

PCOL

PCOUNT

PDOX

PDSETUP

PEMSTATUS

PEN

PERCENT

PFS

PI

PICTURE

PICTUREPOSITION

PICTURESELECTIONDISPLAY

PIVOT

PIXELS

PLAIN

PLATFORM

PLAY

POINT

POP

POPUPS

POWER

PRECISION

PREFERENCE

PRESERVEWHITESPACE

PRETEXT

PREVIEW

PRIMARY

PRIMARYKEY

PRINT

PRINTER

PRINTFORM

PRINTJOB

PRINTQUALITY

PRINTSTATUS

PRIVATE

PRMBAR

PRMPAD

PROCEDURE

PROCEDURES

PRODUCTION

PROGRAM

PROGRAMMATICCHANGE

PROGWORK

PROJECT

PROJECTCLICK

PROJECTHOOK

PROMPT

PROPER

PROTECTED

PROW

PRTINFO

PSET

PSET

PUBLIC

PUSH

PUTFILE

PV

Q

QPR

QUARTER

QUERY

QUERYADDFILE

QUERYMODIFYFILE

QUERYNEWFILE

QUERYREMOVEFILE

QUERYRUNFILE

QUERYTIMEOUT

QUERYUNLOAD

QUERYUNLOAD

QUIT

R

RADIANS

RAISEEVENT

RAND

RANDOM

RANGE

RANGEHIGH

RANGELOW

RAT

RATC

RATLINE

RD

RDLEVEL

READ

READACTIVATE

READBORDER

READCOLORS

READCYCLE

READDEACTIVATE

READERROR

READEXPRESSION

READFILLER

READKEY

READLOCK

READMETHOD

READMOUSE

READONLY

READSAVE

READSHOW

READSIZE

READTIMEOUT

READVALID

READWHEN

RECALL

RECCOUNT

RECENTLYUSEDFILES

RECNO

RECOMPILE

RECORD

RECORDMARK

RECORDSOURCE

RECORDSOURCETYPE

RECOVER

RECSIZE

RECT

RECTCLASS

RECYCLE

REDIT

REFERENCE

REFERENCES

REFRESH

REINDEX

RELATEDCHILD

RELATEDTABLE

RELATEDTAG

RELATION

RELATIONALEXPR

RELATIVE

RELATIVECOLUMN

RELATIVEROW

RELEASE

RELEASEERASE

RELEASETYPE

RELEASEWINDOWS

RELEASEXML

REMOTE

REMOVE

REMOVEITEM

REMOVELISTITEM

REMOVEOBJECT

REMOVEPROPERTY

RENAME

REPEAT

REPLACE

REPLICATE

REPORT

REPROCESS

REQUERY

REQUESTDATA

REQUIRED

RESET

RESETTODEFAULT

RESHEIGHT

RESIZABLE

RESIZE

RESOURCE

RESOURCEON

RESOURCES

RESOURCETO

RESPECTCURSORCP

REST

RESTORE

RESTRICT

RESUME

RESWIDTH

RETRY

RETURN

REVERTOFFLINE

RGB

RGBSCHEME

RIGHT

RIGHTC

RIGHTCLICK

RIGHTTOLEFT

RLOCK

RMDIR

ROLLBACK

ROLLOVER

ROTATEFLIP

ROUND

ROW

ROWCOLCHANGE

ROWHEIGHT

ROWSET

ROWSOURCE

ROWSOURCETYPE

RPD

RSTOCURSOR

RTLJUSTIFY

RTOD

RTRIM

RULEEXPRESSION

RULETEXT

RUN

RUNSCRIPT

RUNTIME

RVIEW

S

SAFETY

SAME

SAMPLE

SAVE

SAVEAS

SAVEASCLASS

SAVEPICTURE

SAY

SCALE

SCALEMODE

SCALEUNITS

SCAN

SCATTER

SCHEME

SCOLS

SCOREBOARD

SCREEN

SCREENS

SCROLL

SCROLLBARS

SCROLLED

SCROLLSCROLLBARS

SDF

SDIFORM

SEC

SECOND

SECONDS

SECONDS

SEEK

SELECT

SELECTCMD

SELECTED

SELECTEDBACKCOLOR

SELECTEDFORECOLOR

SELECTEDID

SELECTEDITEMBACKCOLOR

SELECTEDITEMFORECOLOR

SELECTION

SELECTONENTRY

SELFEDIT

SELLENGTH

SELSTART

SELTEXT

SENDUPDATES

SEPARATOR

SET

SETALL

SETDATA

SETDEFAULT

SETFLDSTATE

SETFOCUS

SETFORMAT

SETUP

SETVAR

SETVIEWPORT

SHADOWS

SHAPE

SHARECONNECTION

SHARED

SHEET

SHELL

SHIFT

SHORTCUT

SHOW

SHOWDOC

SHOWINTASKBAR

SHOWOLECONTROLS

SHOWOLEINSERTABLE

SHOWTIPS

SHOWVCXS

SHOWWHATSTHIS

SHOWWINDOW

SHUTDOWN

SIGN

SIN

SINGLE

SIZABLE

SIZE

SIZE<HEIGHT>

SIZE<MAXLENGTH>

SIZE<WIDTH>

SIZEBOX

SKIP

SKIPFORM

SKPBAR

SKPPAD

SOM

SOME

SORT

SORTED

SORTWORK

SOUNDEX

SOURCENAME

SOURCETYPE

SPACE

SPARSE

SPECIALEFFECT

SPINNER

SPINNERHIGHVALUE

SPINNERLOWVALUE

SPLITBAR

SQL

SQLASYNCHRONOUS

SQLBATCHMODE

SQLCANCEL

SQLCOLUMNS

SQLCOMMIT

SQLCONNECT

SQLCONNECTTIMEOUT

SQLDISCONNECT

SQLDISPLOGIN

SQLDISPWARNINGS

SQLEXEC

SQLGETPROP

SQLIDLETIMEOUT

SQLL

SQLMORERESULTS

SQLPREPARE

SQLQUERYTIMEOUT

SQLROLLBACK

SQLSETPROP

SQLSTRINGCONNECT

SQLSTRINGCONNECT

SQLTABLES

SQLTRANSACTIONS

SQLWAITTIME

SQRT

SROWS

STACKLEVEL

STANDALONE

STATUS

STATUSBAR

STATUSBARTEXT

STD

STEP

STICKY

STORE

STR

STRCONV

STRETCH

STRICTDATE

STRICTDATEENTRY

STRING

STRTOFILE

STRTRAN

STRUCTURE

STUFF

STUFFC

STYLE

SUBCLASS

SUBSTR

SUBSTRC

SUBSTRING

SUM

SUMMARY

SUSPEND

SYLK

SYS

SYSFORMATS

SYSMENUS

SYSMETRIC

SYSTEM

SYSTEMREFCOUNT

T

TAB

TABFIXEDHEIGHT

TABFIXEDWIDTH

TABHIT

TABINDEX

TABLE

TABLEREFRESH

TABLEREVERT

TABLES

TABLEUPDATE

TABLEVALIDATE

TABORDERING

TABORIENTATION

TABS

TABSTOP

TABSTRETCH

TABSTYLE

TAG

TAGCOUNT

TAGNO

TALK

TAN

TARGET

TASKPANE

TEDIT

TERMINATEREAD

TEXT

TEXTBOX

TEXTHEIGHT

TEXTMERGE

TEXTWIDTH

THEMES

THEN

THIS

THISFORM

THISFORMSET

THROW

TIME

TIMEOUT

TIMER

TIMESTAMP

TIMESTAMPDIFF

TITLEBAR

TITLES

TMPFILES

TO

TOCURSOR

TOOLBAR

TOOLBOX

TOOLTIPTEXT

TOP

TOPIC

TOPINDEX

TOPITEMID

TOTAL

TOXML

TRANSACTION

TRANSACTIONS

TRANSFORM

TRAP

TRBETWEEN

TRIGGER

TRIM

TRUNCATE

TRY

TTOC

TTOD

TTOPTION

TXNLEVEL

TXTWIDTH

TYPE

TYPEAHEAD

U

UCASE

UDFPARMS

UIENABLE

UNBINDEVENT

UNDEFINE

UNDOCK

UNICODE

UNION

UNIQUE

UNLOAD

UNLOCK

UNLOCKDATASOURCE

UNPACK

UP

UPCLICK

UPDATABLE

UPDATABLEFIELDLIST

UPDATE

UPDATECMD

UPDATECMDSOURCE

UPDATECMDSOURCETYPE

UPDATED

UPDATEDATASOURCE

UPDATENAME

UPDATENAMELIST

UPDATETRIGGER

UPDATETYPE

UPPER

UPSIZING

USA

USE

USED

USEMEMOSIZE

USERID

USERS

USERVALUE

UTF8ENCODED

V

VAL

VALID

VALIDATE

VALUE

VALUEDIRTY

VALUES

VAR

VARREAD

VARTYPE

VERB

VERSION

VGA25

VGA50

VIEW

VIEWPORTHEIGHT

VIEWPORTLEFT

VIEWPORTTOP

VIEWPORTWIDTH

VIEWS

VISIBLE

VISUALEFFECT

VOLUME

VSCROLLSMALLCHANGE

W

WAIT

WAITTIME

WASACTIVE

WASOPEN

WBORDER

WCHILD

WCOLS

WDOCKABLE

WEEK

WEXIST

WFONT

WHATSTHISBUTTON

WHATSTHISHELP

WHATSTHISHELPID

WHATSTHISMODE

WHEN

WHERE

WHEREWHERETYPE

WHILE

WIDTH

WINDCMD

WINDHELP

WINDMEMO

WINDMENU

WINDMODIFY

WINDOW

WINDOWLIST

WINDOWNTILIST

WINDOWS

WINDOWSTATE

WINDOWTYPE

WINDQUERY

WINDSCREEN

WINDSNIP

WINDSTPROC

WITH

WIZARDPROMPT

WK1

WK3

WKS

WLAST

WLCOL

WLROW

WMAXIMUM

WMINIMUM

WONTOP

WORDWRAP

WORKAREA

WOUTPUT

WP

WPARENT

WR1

WRAP

WRAPCHARINCDATA

WRAPINCDATA

WRAPMEMOINCDATA

WREAD

WRITEEXPRESSION

WRITEMETHOD

WRK

WROWS

WTITLE

WVISIBLE

X

XCMDFILE

XL5

XL8

XLS

XMLADAPTER

XMLCONSTRAINTS

XMLFIELD

XMLNAME

XMLNAMESPACE

XMLPREFIX

XMLSCHEMALOCATION

XMLTABLE

XMLTOCURSOR

XMLTYPE

XMLUPDATEGRAM

XSDFRACTIONDIGITS

XSDMAXLENGTH

XSDTOTALDIGITS

XSDTYPE

Y

YEAR

YRESOLUTION

Z

ZAP

ZOOM

ZOOMBOX

ZORDER

ZORDERSET

See Also

Language Reference A-Z | Error Messages A-Z


Special Terms for Configuration Files

The following table lists special terms you can use in configuration files.

Note You can also use the SET commands, system variables, and the _STARTUP setting in configuration files. For more information, see Creating a Configuration File under Configuring Visual FoxPro.

Special terms available in configuration files

Term Description
ALLOWEXTERNAL ON | OFF
 Specifies whether settings from an external configuration file as specified by the -C command-line switch (or located in path) are read in after those from an internal one. The ALLOWEXTERNAL term is ignored unless it is bound inside of an application.

Default is ALLOWEXTERNAL = OFF

BITMAP ON | OFF
 Specifies whether Visual FoxPro first writes screen or form updates to an off-screen bitmap, and then performs a bit block transfer (bitblt) to the screen. BITMAP = OFF can improve performance when application are accessed using Windows Terminal Server clients.

Default is BITMAP = ON

CODEPAGE
 Specifies a number that identifies the character set used for files. Setting CODEPAGE to AUTO selects the current operating system code page. A list of possible values can be found in Code Pages Supported by Visual FoxPro.

CODEPAGE = nValue | AUTO

COMMAND
 Specifies a Visual FoxPro command to execute when Visual FoxPro is started. The syntax to use is the following, where cVisualFoxProCommand is the command to execute:

COMMAND = cVisualFoxProCommand

EDITWORK path
 Specifies where the text editor should place its work files. Because work files can become large, specify a location with plenty of free space. Default is the startup directory.
ENGINEBEHAVIOR
 Enables SQL data engine compatibility with Visual FoxPro 7.0 or Visual FoxPro 8.0. For more information, see SET ENGINEBEHAVIOR Command.

ENGINEBEHAVIOR 70 | 80

INDEX extension
 Specifies the extension for Visual FoxPro index files. Default is .idx.
LABEL extension
 Specifies the extension for Visual FoxPro label definition files. Default is .lbx.
MVCOUNT
 Sets the maximum number of variables that Visual FoxPro can maintain. This value can range from 128 to 65,000. The default is 16,384.
OUTSHOW
 Disables the ability to hide all windows in front of the current output by pressing SHIFT+CTRL+ALT. Default is ON.

OUTSHOW = ON | OFF

PROGWORK path
 Specifies where Visual FoxPro keeps the program cache file. For faster performance, especially in a multiuser environment, specify a fast disk (such as a local disk or RAM disk, if available). Allow at least 256K for the cache (however, the file can grow larger). Default is the startup directory.
REPORT extension
 Specifies the extension for Visual FoxPro report definition files. Default is .frx.
RESOURCE path[\file]
 Specifies the location of the FoxUser resource file. The file argument is optional; if not included, Visual FoxPro looks for the FoxUser.dbf file. If the specified file does not exist, it is created. Default is the startup directory (path) and FoxUser.dbf (file).
SCREEN
 Specifies whether the main Visual FoxPro window appears when opening Visual FoxPro. The default for SCREEN is set to ON. Setting SCREEN to OFF is useful when an application consists of one or more top-level forms that are displayed in the Windows desktop, making the main Visual FoxPro window not required. For further information on top-level forms, see Defining Form Behavior.

SCREEN = ON | OFF

SORTWORK path
 Specifies where commands such as SORT and INDEX should place work files. Because work files can become up to twice as large as the tables being sorted, specify a location with plenty of free space. For faster performance, especially in a multiuser environment, specify a fast disk (such as a local disk). Default is the startup directory.
TEDIT [/N] editor
 Specifies the name of the text editor used when you edit program files with MODIFY COMMAND or MODIFY FILE. Include the optional clause /N with TEDIT to specify a Windows text editor (for example, Microsoft Word for Windows). Default is the Visual FoxPro editor.
TITLE title
 Specifies the title that appears in the caption bar of the main Visual FoxPro window. Default is "Microsoft Visual FoxPro."
TMPFILES drive:
 Specifies where temporary EDITWORK, SORTWORK, and PROGWORK work files are stored if they have not been specified with any of the other options. Because work files can become very large, specify a location with plenty of free space. For faster performance, especially in a multiuser environment, specify a fast disk (such as a local disk). Default is the startup directory.

For more details about optimizing performance, see Optimizing Applications.

See Also

Creating a Configuration File | Configuring Visual FoxPro | SET Command | Using SET Commands | Specifying the Configuration File to Use | Using a Configuration File


System Menu Names

The following tables list the internal names and user interface names for the Visual FoxPro system menu bar, menu titles, menus, and menu items. With these names you can use the Visual FoxPro system menu bar to create a menu system for your own application.

The SYS(2013) function returns a space-delimited string containing these names. You can also create a quick menu using the Menu Designer to see the internal system menu names.

For more information on the system menu bar, see Designing Menus and Toolbars.

System Menu Names in Visual FoxPro

The internal name for the system menu bar itself in Visual FoxPro is _MSYSMENU.

System Menus

Menu titles | Internal name
File | _MSM_FILE
Edit | _MSM_EDIT
View | _MSM_VIEW
Format | _MSM_TEXT
Tools | _MSM_TOOLS
Program | _MSM_PROG
Window | _MSM_WINDO
Help | _MSM_SYSTM

File Menu

Menu and items | Internal name
File menu | _MFILE
New | _MFI_NEW
Open | _MFI_OPEN
Close | _MFI_CLOSE
Close All | _MFI_CLALL
1st Separator | _MFI_SP100
Save | _MFI_SAVE
Save As | _MFI_SAVAS
Save As HTML | _MFI_SAVASHTML
Revert | _MFI_REVRT
2nd Separator | _MFI_SP200
Import | _MFI_IMPORT
Export | _MFI_EXPORT
3rd Separator | _MFI_SP300
Page Setup | _MFI_PGSET
Print Preview | _MFI_PREVU
Print | _MFI_SYSPRINT
Send | _MFI_SEND
4th Separator | _MFI_SP400
Exit | _MFI_QUIT

Edit Menu - Visual FoxPro

Menu and items | Internal name
Edit menu | _MEDIT
Undo | _MED_UNDO
Redo | _MED_REDO
1st Separator | _MED_SP100
Cut | _MED_CUT
Copy | _MED_COPY
Paste | _MED_PASTE
Paste Special | _MED_PSTLK
Clear | _MED_CLEAR
2nd Separator | _MED_SP200
Select All | _MED_SLCTA
3rd Separator | _MED_SP300
Find | _MED_FIND
Replace | _MED_REPL
Go To Line | _MED_GOTO
4th Separator | _MED_SP400
List Members | _MED_LISTMEMBERS
QuickInfo | _MED_QUICKINFO
5th Separator | _MED_SP500
Bookmarks | _MED_BKMKS
6th Separator | _MED_SP600
Insert Object | _MED_INSOB
Object | _MED_OBJ
Links | _MED_LINK
7th Separator | _MED_SP700
Properties | _MED_PREF

View Menu

Menu and items | Internal name
View menu | _MVIEW
Toolbars | _MVI_TOOLB

Tools Menu

Menu and items | Internal name
Tools menu | _MTOOLS
Wizards | _MTL_WZRDS
1st Separator | _MTL_SP100
Macros | _MST_MACRO
Class Browser | _MTL_BROWSER
Component Gallery | _MTL_GALLERY
Object Browser | _MTL_OBJECTBROWSER
IntelliSense Manager | _MTI_FOXCODE
2nd Separator | _MTL_SP200
Beautify | _MED_BEAUT
Task List | _MTI_TASKLIST
Document View | _MTI_DOCVIEW
3rd Separator | _MTL_SP300
Coverage Profiler | _MTL_COVERAGE
Breakpoints | _MTI_BREAKPOINT
Debugger | _MTL_DEBUGGER
4th Separator | _MTL_SP400
Trace | _MTI_TRACE
Locals | _MTI_LOCALS
Call Stack | _MTI_CALLSTACK
Output | _MTI_DBGOUT
Options | _MTL_OPTNS

Program Menu

Menu and items | Internal name
Program item | _MPROG
Do | _MPR_DO
Cancel | _MPR_CANCL
Resume | _MPR_RESUM
Suspend | _MPR_SUSPEND
1st Separator | _MPR_SP100
Compile | _MPR_COMPL

Window Menu

Menu and items | Internal name
Window menu | _MWINDOW
Cascade | _MWI_CASCADE
Arrange All | _MWI_ARRAN
1st Separator | _MWI_SP100
Dockable | _MWI_DOCKABLE
2nd Separator | _MWI_SP200
Hide | _MWI_HIDE
Clear | _MWI_CLEAR
Cycle | _MWI_ROTAT
3rd Separator | _MWI_SP300
Command Window | _MWI_CMD
Data Session _MWI_VIEW
(maintains compatibility with earlier versions of Visual FoxPro)
Properties | _MWI_PROPERTIES

Help Menu

Menu and items | Internal name
Help menu | _MSYSTEM
Microsoft Visual FoxPro Help | _MST_HPSCH
MSDN Search | _MST_MSDNS
1st Separator | _MST_SP100
Technical Support | _MST_TECHS
Visual FoxPro on the Web | _MST_VFPWEB
2nd Separator | _MST_SP200
About Microsoft Visual FoxPro | _MST_ABOUT

See Also

SYS(2013) - System Menu Name String | SYS(1500) - Activate a System Menu Item | Menu Designer | Designing Menus and Toolbars


Visual FoxPro and Other Programming Languages

Most programming languages have similar basic features. If you are familiar with one programming language, you can easily translate this knowledge to another language. Choose an item below to see a comparison of Visual FoxPro with BASIC, C/C++, and Pascal.

To compare | See
Whether the language is case-sensitive | Case Sensitivity
How variables are declared | Variable Declaration
How to insert comments in programs | Comments
How to store values to variables | Assignment Statements
The structure of IF statements | IF Statements
The structure of CASE statements | CASE Statements
The structure of FOR loops | FOR Loops
The structure of WHILE loops | WHILE Loops
How parameters are passed by value | Parameter Passing by Value
How parameters are passed by reference | Parameter Passing by Reference

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


Case Sensitivity

Neither Visual FoxPro nor BASIC are case-sensitive programming languages.

Visual FoxPro | BASIC
Not case-sensitive | Not case-sensitive
Pascal | C/C++
Case-sensitive | Case-sensitive

See Also

Assignment Statements | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


Variable Declaration

When you store a value to a variable and the variable does not exist, Visual FoxPro implicitly declares it with PRIVATE scope. Other languages that require explicit declaration of variables return an error. To create variables in Visual FoxPro with PUBLIC or LOCAL scope, you must explicitly declare them with the PUBLIC or LOCAL command.

In Visual FoxPro, you do not assign a data type to a variable (although it is recommended that you name your variable with a prefix suggesting the data type you will use it for). Other languages require that you assign a data type to a variable when you declare it.

Visual FoxPro | BASIC
Variables are implicitly declared; no data typing. | Variables can be implicitly declared; variable name dictates data type.
Pascal | C/C++
Variables must be explicitly declared and assigned a data type. | Variables must be explicitly declared and assigned a data type.

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | LanguageOptions Property | Parameter Passing by Reference | Parameter Passing by Value | WHILE Loops


Comments

Each language has its own format for adding comments to programs. Visual FoxPro, C, and C++ have different formats for whole line comments and comments on partial lines.

Visual FoxPro BASIC
* full line

USE  && end of line

NOTE multiline ;
   comment

' comment
Pascal C/C++
{ comment }

// comment

/* multiline
 comment */

See Also

Assignment Statements | Case Sensitivity | CASE Statements | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


Assignment Statements

Pascal requires a colon in the assignment statement.

Visual FoxPro BASIC
nVal = 7
–or–
STORE 7 to nVal

nVal = 7
Pascal C/C++
nVal := 7

nVal = 7
Note In Visual FoxPro, you can also assign values to fields in a table with the REPLACE command.

See Also

Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


CASE Statements

Only Pascal does not offer defaults in CASE statements.

Visual FoxPro BASIC
DO CASE
 CASE n = 0
  ? 'Zero'
 CASE n > 0
  ? 'Pos'
 OTHERWISE
  ? 'Neg'
ENDCASE

Select Case n
 Case 0
  Print 'Zero'
 Case Is > 0
  Print 'Pos'
 Case Else
  Print 'Neg'
End Select
Pascal C/C++
case n of
 0: writeln("Zero");
 1: writeln("One");
end

switch(n) {
 case 0:
  printf("Zero\n");
  break;
 case 1:
  printf("One\n");
  break;
 default:
  printf("?\n");}

See Also

Assignment Statements | Case Sensitivity | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


IF Statements

Each language offers equivalent IF functionality. The THEN clause is allowed only on the IF statement in Visual FoxPro.

Visual FoxPro BASIC
IF nCnt < nMax
 nTot = nTot * nCnt
 nCnt = nCnt + 1
ENDIF

If nCnt < nMax Then
 nTot = nTot * nCnt
 nCnt = nCnt + 1
End If
Pascal C/C++
if nCnt < nMax then
 begin
  nTot:=nTot * nCnt;
  nCnt:=nCnt + 1;
 end

if(nCnt < nMax) {
 nTot *= nCnt;
 nCnt++;
 }

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


FOR Loops

Each language offers a FOR statement; C/C++ has the most flexibility for expressions.

Visual FoxPro BASIC
FOR n = 1 TO 10
 ? n
ENDFOR

For n = 1 to 10
 Print n
Next n
Pascal C/C++
for n := 1 to 10 do
  writeln(n);

for(n=1; n<11; n++)
 printf("%d\n",n);

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration | WHILE Loops


WHILE Loops

Each language offers equivalent WHILE loop functionality.

Visual FoxPro BASIC
DO WHILE n < 100
 n = n + n
ENDDO

Do While n < 100
 n = n + n
Loop
Pascal C/C++
while n < 100 do
 n := n + n;

while(n < 100)
 n += n;

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Parameter Passing by Value | Variable Declaration


Parameter Passing by Reference

You can pass parameters by reference two ways in Visual FoxPro.

Visual FoxPro BASIC
=ABC(@X)
–or–
DO ABC WITH X

ABC X
Pascal C/C++
procedure ABC
var x:integer);

ABC(&VAR);

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Value | Variable Declaration | WHILE Loops | SET UDFPARMS Command


Parameter Passing by Value

Each language permits passing parameters by value.

Visual FoxPro BASIC
=ABC(X)

ABC ByVal X
Pascal C/C++
procedure ABC (x:integer);

ABC(X);

See Also

Assignment Statements | Case Sensitivity | CASE Statements | Comments | FOR Loops | IF Statements | Parameter Passing by Reference | Variable Declaration | WHILE Loops | SET UDFPARMS Command


Visual FoxPro System Capacities

Some capacities may be limited by available memory.

Category Feature Capacity

Table and Index Files

Maximum # of records per table file | 1 billion
Maximum size of a table file | 2 gigabytes
Maximum size of an FPT file | 2 gigabytes
Maximum # of characters per record | 65,500
Maximum # of fields per record1 | 255
Maximum # of tables open at one time2 | 65,535
Maximum # of characters per table field | 254
Maximum # of bytes per index key in a non-compact index3 | 100
Maximum # of bytes per index key in a compact index3 | 240
Maximum # of open index files per table2 | Unlimited
Maximum # of open indexes in all work areas2 | Unlimited
Maximum # of relations | Unlimited
Maximum length of relational expressions | Unlimited

Field Characteristics

Maximum size of character fields | 254
Maximum size of numeric and float fields | 20
Maximum number of characters in field names in a free table | 10
Maximum number of characters in field names for a table contained in a database | 128
Minimum value of an integer | -2,147,483,647
Maximum value of an integer | 2,147,483,647
Digits of precision in numeric computations. Visual FoxPro can handle numbers up to 9007199254740992 (2^53) in exact computations. | 16
Miscellaenous:
64 bits = 8 bytes
Largest number = 10 ^ 308 = 2 ^ 1023
-> 10 bits per exponent + 1 for exponent sign plus 1 for number sign => 12 bits
Leaving 52 bits for the mantissa + 1 for implied normalized bit -> 53 bits

LOG10(2^53) = 15.95 decimal digits accuracy

Variables and Arrays

Default # of variables | 1,024
Maximum # of variables | 65,000
Maximum # of arrays | 65,000
Maximum # of elements per array | 65,000

Program and Procedure Files

Maximum # of lines in source program files | Unlimited
Maximum size of compiled program modules4 | 64K
Maximum # of procedures per file | Unlimited
Maximum # of nested DO calls | 128
Maximum # of READ nesting levels | 5
Maximum # of nested structured programming commands | 384
Maximum # of passed parameters | 26
Maximum # of transactions | 5

Report Designer Capacities

Maximum # of objects in a report definition2 | Unlimited
Maximum length of a report definition | 20 inches
Maximum # of grouping levels | 128
Maximum length of character report variables | 255

Other Capacities

Maximum # of open windows (all types)2 | Unlimited
Maximum # of open Browse windows | 255
Maximum # of characters per character string or memory variable | 16,777,184
Maximum # of characters per command line | 8,192
Maximum # of characters per label control on a report | 252
Maximum # of characters per macro substituted line | 8,192
Maximum # of open files | System limit
Maximum keystrokes in keyboard macro | 1,024
Maximum fields that can be selected by a SQL SELECT statement | 255
Maximum length of a string literal | 255
Maximum # of pages in a report at runtime | 32767

1 If one or more fields allow null values, the limit is reduced by one to 254 fields.
2 Limited by memory and available file handles. .cdx files use only one file handle.
3 If the collating sequence is set to MACHINE, each character uses one byte. If the collating sequence is not set to MACHINE, each character uses two bytes. If the indexed field supports null values, one additional byte is used in the index key. Note that non-machine indexes are always compact.
4 A program module is one procedure. A program or application can contain an unlimited number of program modules.

See Also

Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx) | Setting Up an ODBC Data Source | Display System Information | Optimizing Your System | File Extensions and File Types | Optimizing Visual FoxPro Startup Speed | Special Terms for Configuration Files


XML Functionality Using XMLAdapters

With the XMLAdapter, XMLTable, and XMLField classes, Visual FoxPro enhances its existing XML features and its compatibility with XML DiffGram and .NET Framework ADO.NET DataSet formats. The XMLAdapter, XMLTable, and XMLField classes require Microsoft XML Core Services (MSXML) 4.0 Service Pack 1 (SP1).

For more details and download information, see Microsoft XML Core Services 4.0 SP1 on the MSDN Library Web site at http://msdn.microsoft.com/downloads/.

Visual FoxPro supports hierarchically formatted XML for the following:

  • XML files that have associated schema, either inline or external, as implemented by ADO.NET DataSets based on the .NET Framework
  • Microsoft XML Data Reduced Schema (XDR) as used by Microsoft SQL XML
  • ADO Recordset schemas that are produced when an ADO Recordset is saved as XML to a file or stream

Visual FoxPro can factor an XML file representing a collection of different and possibly related tables, such as an ADO.NET DataSet object, into separate Visual FoxPro cursors. Usually, this file contains data from a database management system (DBMS) with the structure of Parent > Child > Child. The XML can also have a nested format such as Parent > Child, Parent > Child, or a serial format such as Parent-Parent, Child-Child.

When you have hierarchical XML that represents a single table resulting from a multiple-table SQL JOIN command, Visual FoxPro creates only one cursor.

For more information about XML DiffGram and ADO.NET DataSet formats, see the .NET Framework SDK on the MSDN Library Web site at http://msdn.microsoft.com/library/.

ADO.NET DataSets

In the .NET Framework, ADO.NET is a set of classes that expose data access services to the programmer working with .NET. ADO.NET provides consistent access to data sources such as Microsoft SQL Server and other data sources exposed through OLE DB and XML.

The ADO.NET DataSet is used as the primary class for manipulating data and encapsulates data as XML. An ADO.NET DataSet object can produce XML in several ways:

  • By returning the entire ADO.NET DataSet to the calling application.

    This method returns all rows in the original query in XML DiffGram format with inline schema and update, insert, and delete operations as indicated. Rows that remain unchanged do not have the diffgr:hasChanges attribute.

    When a DataSet object returns to the calling application from a method in an application that uses the .NET Framework and returns ADO.NET DataSet objects, it is always serialized, or converted, into XML. Visual FoxPro can convert this XML into cursors, which you can then manipulate in a Visual FoxPro application.

  • By returning only changes to the ADO.NET DataSet to the .NET-based application.

    This method returns only those rows, in XML DiffGram format, that were modified, added, or deleted.

    If the ADO.NET DataSet object contains changes, they are marked with the attributes, DiffGram:hasChanges="modified" or DiffGram:hasChanges="inserted". For those records marked as "modified", the previous values appear in the section, diffgr:before. Records that are deleted appear only in the diffgr:before section and not in the main section of the DiffGram.

  • By using the ADO.NET DataSet GetXml and GetXMLSchema methods to return XML as a .CLR stream or string type.
  • By using the ADO.NET DataSet WriteXml and WriteXmlSchema methods write the ADO.NET DataSet as XML to a file with inline schema, without schema, or separate schema.

See Also

Objects, Collections, and Classes | XMLAdapter Class | XMLTable Class | XMLField Class | Visual FoxPro and XML Schema Data Type Mapping


XSource Folder

The XSource folder in your Visual FoxPro \Tools directory contains zip files that expand to the Solution Sample HTML Help files and to the folders containing other additions to Visual FoxPro. These additions include the Addlabel, Browser, Builder, Converter, Coverage, and Wizards source files.

See Also

Addlabel.app | Builders | Coverage Profiler Application


Language Reference

You can use the Visual FoxPro interface to perform many database tasks and develop applications for cataloging, tracking, and processing information. Knowing more about the Visual FoxPro programming language enhances your ability to access the power of Visual FoxPro.

Like other programming languages, the Visual FoxPro programming language makes it possible for you to work with various types of data, such as numbers and character strings. You can store data of these various types in tables, arrays, variables, and other data containers. To manipulate data, you can perform operations, such as addition and concatenation. In addition to operators, Visual FoxPro provides a rich set of commands and functions, so you can protect, display, and manage your data.

This section contains information about programming language elements in Visual FoxPro.

In This Section

Language Categories
Contains categories describing areas of functionality offered by Visual FoxPro.
Commands
Lists the commands available in Visual FoxPro.
Objects, Collections, and Classes
Lists the classes, collections, and objects available in Visual FoxPro.
Properties
Lists the properties of classes and objects in Visual FoxPro.
Methods
Lists the methods available in Visual FoxPro.
Events
Lists the events that occur in Visual FoxPro.
Functions
Lists the functions available in Visual FoxPro.
Operators
Lists the operators you can use to manipulate data in Visual FoxPro.
Preprocessor Directives
Lists the preprocessor directives you can include in your Visual FoxPro programs.
System Variables
Lists the Visual FoxPro system variables which you can use to store values.
API Library Construction
Describes API library routines, system events, and key codes.
SQL Commands and Functions
Describes Structured Query Lanaguage (SQL) commands and functions supported by Visual FoxPro.
Language Reference for OLE DB Development
Describes support in the OLE DB Provider for native Visual FoxPro language and syntax.
Backward-Compatible Language Elements
Lists obsolete language elements that are included for backwards compatibility.

Related Topics

Reference
Includes Visual FoxPro general, programming language, user interface, and error message reference topics.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and make it possible for you to access the full power of Visual FoxPro.
Samples and Walkthroughs
Contains Visual FoxPro code samples and step-by-step walkthroughs that you can use for experimenting with and learning Visual FoxPro features.


Language Categories

This section contains basic categories describing the functionality of the Visual FoxPro.

In This Section

Databases
Links to information on how you can manipulate databases, tables, records, and fields, as well as indexes and relations.
Input and Output
Contains links to information about controlling input and output from your applications.
Programming
Contains links to more programming information, including array manipulation, debugging and error handling, structured programming, and so on.
Shared Access to Data
Contains commands and functions that make it possible for you to manage multiple users.
Visual FoxPro Environment
Lists commands and functions that make it possible for you to access the Visual FoxPro environment.

Related Sections

Language Reference
Contains a list of language reference topics in alphabetical order.
Naming Conventions
Discusses how to choose names for exposed objects, properties, and methods that can be understood easily by users of the application.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.
Visual FoxPro and Other Programming Languages
Provides a comparison between Visual FoxPro and other programming languages.


Databases

You can manipulate databases, tables, records, and fields, as well as indexes and relations.

In This Section

Database Manipulation
Lists the commands and functions that manipulate databases.
Field Manipulation
Lists the commands and functions that make it possible for you to manipulate fields in a table.
Indexes
Lists the commands and functions that perform operations on and return information about index files.
Record Manipulation
Lists the commands and functions that make it possible for you to select records within a table or position the record pointer.
Relations
Lists the commands and functions that make it possible for you to establish or break relations between table files.
Table Manipulation
Lists the commands and functions that make it possible for you to create, manipulate, and monitor table files.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Database Manipulation

These commands and functions manipulate databases.

ADATABASES( ) Function

ADD TABLE Command

APPEND PROCEDURES Command

AUSED( ) Function

CLOSE Commands

COMPILE DATABASE Command

COPY PROCEDURES Command

CREATE CONNECTION Command

CREATE DATABASE Command

CREATE SQL VIEW Command

CREATE TRIGGER Command

CREATEOFFLINE( ) Function

DROPOFFLINE( ) Function

CURSORGETPROP( ) Function

CURSORSETPROP( ) Function

CURVAL( ) Function

DATETIME( ) Function

DBC( ) Function

DBGETPROP( ) Function

DBSETPROP( ) Function

DBUSED( ) Function

DELETE - SQL Command

DELETE CONNECTION Command

DELETE DATABASE Command

DELETE TRIGGER Command

DELETE VIEW Command

DISPLAY CONNECTIONS Command

DISPLAY DATABASE Command

DISPLAY PROCEDURES Command

DISPLAY TABLES Command

DISPLAY VIEWS Command

FREE TABLE Command

GETFLDSTATE( ) Function

GETNEXTMODIFIED( ) Function

INDBC( ) Function

ISEXCLUSIVE( ) Function

LIST CONNECTIONS Command

LIST DATABASE Command

LIST PROCEDURES Command

LIST TABLES Command

LIST VIEWS Command

MODIFY CONNECTION Command

MODIFY DATABASE Command

MODIFY PROCEDURE Command

MODIFY VIEW Command

OLDVAL( ) Function

OPEN DATABASE Command

PACK DATABASE Command

REFRESH( ) Function

REMOVE TABLE Command

RENAME CONNECTION Command

RENAME TABLE Command

RENAME VIEW Command

REQUERY( ) Function

SET DATABASE Command

SET DATASESSION Command

SETFLDSTATE( ) Function

SQLCANCEL( ) Function

SQLCOLUMNS( ) Function

SQLCOMMIT( ) Function

SQLCONNECT( ) Function

SQLDISCONNECT( ) Function

SQLEXEC( ) Function

SQLGETPROP( ) Function

SQLMORERESULTS( ) Function

SQLROLLBACK( ) Function

SQLSETPROP( ) Function

SQLSTRINGCONNECT( ) Function

SQLTABLES( ) Function

TABLEREVERT( ) Function

TABLEUPDATE( ) Function

_TRIGGERLEVEL System Variable

VALIDATE DATABASE Command


Field Manipulation

These commands and functions make it possible for you to manipulate fields in a table.

AFIELDS( ) Function

BLANK Command

DELETED( ) Function

FCOUNT( ) Function

FIELD( ) Function

FLDLIST( ) Function

FSIZE( ) Function

GATHER Command

ISBLANK( ) Function

LUPDATE( ) Function

NDX( ) Function

SCATTER Command

SET BLOCKSIZE Command

SET EXACT Command

SET NOCPTRANS Command

SET TEXTMERGE Command

SET TEXTMERGE DELIMITERS Command

SYS(14) - Index Expression


Indexes

These commands and functions perform operations on and return information about index files.

ATAGINFO( ) Function

CANDIDATE( ) Function

CDX( ) Function

CLOSE Commands

COPY INDEXES Command

COPY TAG Command

DESCENDING( ) Function

DELETE TAG Command

FOR( ) Function

IDXCOLLATE( ) Function

INDEX Command

INDEXSEEK( ) Function

KEY( ) Function

KEYMATCH( ) Function

MDX( ) Function

NDX( ) Function

ORDER( ) Function

PRIMARY( ) Function

REINDEX Command

SET COLLATE Command

SET INDEX Command

SET KEY Command

SET ORDER Command

SET UNIQUE Command

SYS(14) - Index Expression

SYS(21) - Controlling Index Number

SYS(2021) - Filtered Index Expression

TAG( ) Function

TAGCOUNT( ) Function

TAGNO( ) Function

UNIQUE( ) Function


Record Manipulation

These commands and functions make it possible for you to select records within a table or position the record pointer.

APPEND FROM Command

APPEND MEMO Command

BLANK Command

CONTINUE Command

DELETE - SQL Command

FILTER( ) Function

GO | GOTO Command

INDEXSEEK( ) Function

INSERT Command

INSERT – SQL Command

ISBLANK( ) Function

KEYMATCH( ) Function

LOCATE Command

LOOKUP( ) Function

REPLACE FROM ARRAY Command

SEEK Command

SEEK( ) Function

SET COLLATE Command

SET FILTER Command

SET KEY Command

SET NEAR Command

SET RELATION Command

SKIP Command

UPDATE - SQL Command


Relations

These commands and functions make it possible for you to establish or break relations between table files.

RELATION( ) Function

SELECT - SQL Command

SET RELATION Command

SET RELATION OFF Command

SET SKIP Command

TARGET( ) Function


Table Manipulation

These commands and functions make it possible for you to create, manipulate, and monitor table files.

ADD TABLE Command

ALINES( ) Function

ALTER TABLE - SQL Command

APPEND Command

AUSED( ) Function

AVERAGE Command

BEGIN TRANSACTION Command

BROWSE Command

CHANGE Command

CLOSE TABLES Command

COPY MEMO Command

COPY STRUCTURE Command

COPY STRUCTURE EXTENDED Command

COPY TO Command

COUNT Command

CPCURRENT( ) Function

CPDBF( ) Function

CREATE Command

CREATE FROM Command

CREATE QUERY Command

CREATE TABLE - SQL Command

CURVAL( ) Function

DELETE Command

DELETE - SQL Command

DELETED( ) Function

DISPLAY STRUCTURE Command

DISPLAY TABLES Command

EDIT Command

END TRANSACTION Command

EXPORT Command

FLUSH Command

GETFLDSTATE( ) Function

GETNEXTMODIFIED( ) Function

IMPORT Command

ISEXCLUSIVE( ) Function

ISREADONLY( ) Function

LIST TABLES Command

MEMLINES( ) Function

MLINE( ) Function

MODIFY GENERAL Command

MODIFY MEMO Command

MODIFY QUERY Command

MODIFY STRUCTURE Command

OLDVAL( ) Function

PACK Command

RECALL Command

REFRESH( ) Function

REMOVE TABLE Command

REPLACE Command

REPLACE FROM ARRAY Command

RENAME TABLE Command

ROLLBACK Command

SELECT Command

SELECT - SQL Command

SET ANSI Command

SET AUTOSAVE Command

SET DATASESSION Command

SET DELETED Command

SET FIELDS Command

SET NULL Command

SET OLEOBJECT Command

SET OPTIMIZE Command

SORT Command

SUM Command

SYS(2029) - Table Type

TABLEREVERT( ) Function

TABLEUPDATE( ) Function

TOTAL Command

TXNLEVEL( ) Function

UPDATE Command

UPDATE - SQL Command

USE Command

USED( ) Function

ZAP Command


Input and Output

To find out more about controlling input and output from your applications, choose one of the following sections.

In This Section

Data Formatting
Lists the commands and functions that make it possible for you to format and display data from records, fields, memory variables, or arrays.
Keyboard and Mouse Input
Lists the commands and functions that make it possible for you to control input with the keyboard or mouse.
Menus and Menu Bars
Lists the commands and functions that make it possible for you to develop, display, and activate user-defined menus and menu bars.
Printing
Lists the commands and functions that make it possible for you to print or display data from records or memory variables to the screen, a printer, or an output file.
Reports and Labels
Lists the commands that make it possible for you to create reports and control output.
Windows Commands and Functions
Lists the commands and functions that make it possible for you to create, display, and activate user-defined windows.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Data Formatting

These commands and functions make it possible for you to format and display data from records, fields, memory variables, or arrays. They also make it possible for you to manipulate general screen or window display features.

\ | \\ Command

? | ?? Command

@ ... BOX Command

@ ... CLEAR Command

@ ... EDIT - Edit Boxes Command

@ ... FILL Command

@ ... GET - Check Boxes Command

@ ... GET - Combo Boxes Command

@ ... GET - Command Buttons Command

@ ... GET - List Boxes Command

@ ... GET - Option Buttons Command

@ ... GET - Spinners Command

@ ... GET - Text Boxes Command

@ ... GET - Transparent Buttons Command

@ ... SAY Command

@ ... TO Command

ACTIVATE SCREEN Command

APPEND Command

BROWSE Command

CHANGE Command

CLEAR Commands

CLEAR READ Command

CLOSE FORMAT Command

COL( ) Function

COMPILE FORM Command

CREATE FORM Command

CREATE SCREEN Command

DISPLAY Command

DisplayPath( ) Function

EDIT Command

FUNCTION Command

INKEY( ) Function

LIST Commands

MESSAGEBOX( ) Function

MODIFY FORM Command

MODIFY SCREEN Command

OBJNUM( ) Function

OBJTOCLIENT( ) Function

OBJVAR( ) Function

RDLEVEL( ) Function

READ Command

READKEY( ) Function

RESTORE SCREEN Command

ROW( ) Function

SAVE SCREEN Command

SCOLS( ) Function

SCROLL Command

SET CARRY Command

SET CLEAR Command

SET COLOR OF Command

SET COLOR OF SCHEME Command

SET COLOR SET Command

SET COLOR TO Command

SET CONFIRM Command

SET CONSOLE Command

SET CURSOR Command

SET DECIMALS Command

SET DEVICE Command

SET FIXED Command

SET FORMAT Command

SET HEADINGS Command

SET MARK TO Command

SET MEMOWIDTH Command

SET MESSAGE Command

SET ODOMETER Command

SET SPACE Command

SET TEXTMERGE Command

SET TEXTMERGE DELIMITERS Command

SHOW GET Command

SHOW GETS Command

SHOW OBJECT Command

SROWS( ) Function

SYS(7) - Current Format File

SYS(100) - Console Setting

SYS(101) - Device Setting

SYS(2002) - Turn Insertion Point On or Off

TEXT ... ENDTEXT Command

TRANSFORM( ) Function

UPDATED( ) Function


Keyboard and Mouse Input

These commands and functions make it possible for you to control input with the keyboard or mouse.

AMOUSEOBJ( ) Function

CAPSLOCK( ) Function

CHRSAW( ) Function

CLEAR MACROS Command

CLEAR TYPEAHEAD Command

INSMODE( ) Function

KEYBOARD Command

LASTKEY( ) Function

MCOL( ) Function

MDOWN( ) Function

MOUSE Command

MROW( ) Function

NUMLOCK( ) Function

ON KEY Command

ON KEY LABEL Command

PLAY MACRO Command

POP KEY Command

PUSH KEY Command

RESTORE MACROS Command

SAVE MACROS Command

SET FUNCTION Command

SET KEYCOMP Command

SET MACKEY Command

SET TYPEAHEAD Command


Menus and Menu Bars

These commands and functions make it possible for you to develop, display, and activate user-defined menus and menu bars.

\ | \\ Command

ACTIVATE POPUP Command

BAR( ) Function

BARPROMPT( ) Function

CLEAR MENUS Command

CLEAR POPUPS Command

CNTBAR( ) Function

CNTPAD( ) Function

CREATE MENU Command

DEACTIVATE MENU Command

DEACTIVATE POPUP Command

DEFINE BAR Command

DEFINE MENU Command

DEFINE PAD Command

DEFINE POPUP Command

GETBAR( ) Function

GETPAD( ) Function

HIDE MENU Command

HIDE POPUP Command

MODIFY MENU Command

MOVE POPUP Command

MRKBAR( ) Function

MRKPAD( ) Function

ON BAR Command

ON EXIT BAR Command

ON EXIT MENU Command

ON EXIT PAD Command

ON EXIT POPUP Command

ON PAD Command

ON SELECTION BAR Command

ON SELECTION MENU Command

ON SELECTION PAD Command

ON SELECTION POPUP Command

PAD( ) Function

POP MENU Command

POP POPUP Command

POPUP( ) Function

PRMBAR( ) Function

PRMPAD( ) Function

PROMPT( ) Function

PUSH MENU Command

PUSH POPUP Command

RELEASE BAR Command

RELEASE MENUS Command

RELEASE PAD Command

RELEASE POPUPS Command

SET BORDER Command

SET MARK OF Command

SET SKIP OF Command

SIZE POPUP Command

SKPBAR( ) Function

SKPPAD( ) Function

SHOW MENU Command

SHOW POPUP Command

SYS(2013) - System Menu Name String


Printing

These commands and functions make it possible for you to print or display data from records or memory variables to the screen, a printer, or an output file.

_ASCIICOLS System Variable

_ASCIIROWS System Variable

\ | \\ Command

? | ?? Command

??? Command

@ ... SAY Command

APRINTERS( ) Function

CLOSE ALTERNATE Command

DEFINE BOX Command

DISPLAY Command

EJECT Command

EJECT PAGE Command

GETPRINTER( ) Function

LIST Commands

ON PAGE Command

PCOL( ) Function

PRINTJOB ... ENDPRINTJOB Command

PRINTSTATUS( ) Function

PROW( ) Function

PRTINFO( ) Function

SET MARGIN Command

SET PDSETUP Command

SET PRINTER Commands

SYS(6) - Current Printer Device

SYS(13) - Printer Status

SYS(102) - Printer Setting

SYS(1037) - Page Setup Dialog Box

TYPE Command


Reports and Labels

These commands make it possible for you to create reports and control output.

_ASCIICOLS System Variable

_ASCIIROWS System Variable

\ | \\ Command

CREATE LABEL Command

CREATE REPORT Command

LABEL Command

MODIFY LABEL Command

MODIFY REPORT Command

REPORT Command


Windows Commands and Functions

These commands and functions make it possible for you to create, display, and activate user-defined windows.

ACTIVATE WINDOW Command

CLEAR WINDOWS Command

CREATE SCREEN Command

DEACTIVATE WINDOW Command

DEFINE WINDOW Command

HIDE WINDOW Command

MODIFY SCREEN Command

MODIFY WINDOW Command

MOVE WINDOW Command

RELEASE WINDOWS Command

RESTORE WINDOW Command

SAVE WINDOWS Command

SET BORDER Command

SET WINDOW OF MEMO Command

SHOW WINDOW Command

SIZE WINDOW Command

SYS(2016) - SHOW GETS WINDOW Name

WBORDER( ) Function

WCHILD( ) Function

WCOLS( ) Function

WEXIST( ) Function

WFONT( ) Function

WLAST( ) Function

WLCOL( ) Function

WLROW( ) Function

WMAXIMUM( ) Function

WMINIMUM( ) Function

WONTOP( ) Function

WOUTPUT( ) Function

WPARENT( ) Function

WREAD( ) Function

WROWS( ) Function

WTITLE( ) Function

WVISIBLE( ) Function

ZOOM WINDOW Command


Programming

Find the programming information you want by choosing one of the following sections:

In This Section

Array Manipulation
Lists the commands and functions that make it possible for you to work with arrays of variables.
Debugging and Error Handling
Lists the commands and functions that make it possible for you to perform various debugging operations with Visual FoxPro programs.
Event Handlers
Lists the commands and functions that make it possible for you to specify the action a program takes when a given event occurs.
Low-Level File Functions
Lists the functions that make it possible for you to manipulate files and communication ports at a low level. Low-level file functions should be used carefully, especially when manipulating table files.
Object-Oriented Programming Commands and Functions
Lists the commands and functions that make it possible for you to create and manipulate classes and objects.
Program Execution
Lists the commands and functions that make it possible for you to control how Visual FoxPro programs are executed, suspended, and terminated.
Structured Programming
Lists the commands and functions that make it possible for you to control program execution and branching within a Visual FoxPro program.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Array Manipulation

These commands and functions make it possible for you to work with arrays of variables.

ACOPY( ) Function

ADEL( ) Function

ADIR( ) Function

AELEMENT( ) Function

AFIELDS( ) Function

AFONT( )

AINS( ) Function

ALEN( ) Function

APPEND FROM ARRAY Command

ASESSIONS( ) Function

ASCAN( ) Function

ASORT( ) Function

ASUBSCRIPT( ) Function

COPY TO ARRAY Command

DECLARE Command

DIMENSION Command

GATHER Command

SCATTER Command


Debugging and Error Handling

These commands and functions make it possible for you to perform various debugging operations with Microsoft Visual FoxPro programs.

* Command

&& Command

AERROR( ) Function

CLEAR EVENTS Command

COMRETURNERROR( ) Function

DEBUG Command

DEBUGOUT Command

ERROR Command

ERROR( ) Function

EXTERNAL Command

LINENO( ) Function

MESSAGE( ) Function

NOTE Command

ON ERROR Command

ON READERROR Command

ON( ) Function

PROGRAM( ) Function

RETRY Command

SET DEBUG Command

SET DEVELOPMENT Command

SET ECHO Command

SET TALK Command

SET TRBETWEEN Command

SYS(16) - Executing Program File Name

SYS(18) - Current Control

SYS(2018) - Error Message Parameter

VARREAD( ) Function

WAIT Command

See Also

Error Messages A-Z | Error Messages by Number


Event Handlers

These commands and functions make it possible for you to specify the action a program takes when a given event occurs.

EVENTHANDLER( ) Function

ON ERROR Command

ON ESCAPE Command

ON KEY Command

ON KEY LABEL Command

ON PAD Command

ON SELECTION PAD Command

ON SELECTION POPUP Command

ON SHUTDOWN Command

ON( ) Function

READ EVENTS Command


Low-Level File Functions

These functions make it possible for you to manipulate files and communication ports at a low level. Low-level file functions should be used carefully, especially when manipulating table files. Before using these functions, test them on sample files before using them on files that contain important data.

FCHSIZE( ) Function

FCLOSE( ) Function

FCREATE( ) Function

FEOF( ) Function

FERROR( ) Function

FFLUSH( ) Function

FGETS( ) Function

FOPEN( ) Function

FPUTS( ) Function

FREAD( ) Function

FSEEK( ) Function

FWRITE( ) Function

HEADER( ) Function


Object-Oriented Programming Commands and Functions

These commands and functions make it possible for you to create and manipulate classes and objects.

:: Scope Resolution Operator

@ ... CLASS Command

_WIZARD System Variable

ACLASS( ) Function

ADATABASES( ) Function

ADBOBJECTS( ) Function

ADD CLASS Command

AddProperty Method

AGETCLASS( ) Function

AINSTANCE( ) Function

AMEMBERS( ) Function

AMOUSEOBJ( ) Function

ASELOBJ( ) Function

AVCXCLASSES( ) Function

_BUILDER System Variable

COMCLASSINFO( ) Function

COMPOBJ( ) Function

CREATE CLASS Command

CREATE CLASSLIB Command

CREATEOBJECT( ) Function

DEFINE CLASS Command

DISPLAY OBJECTS Command

GETINTERFACE( ) Function

GETOBJECT( ) Function

LIST OBJECTS Command

LOADPICTURE( ) Function

MODIFY CLASS Command

NEWOBJECT( ) Function

NewObject Method

RELEASE CLASSLIB Command

REMOVE CLASS Command

RENAME CLASS Command

SAVEPICTURE( ) Function

_SCREEN System Variable

SET CLASSLIB Command

SET OLEOBJECT Command

WITH ... ENDWITH Command


Program Execution

These commands and functions make it possible for you to control how Microsoft Visual FoxPro programs are executed, suspended, and terminated.

BUILD APP Command

BUILD DLL Command

BUILD EXE Command

BUILD PROJECT Command

CALL Command

CANCEL Command

CLEAR PROGRAM Command

CLOSE ALL Command

CLOSE PROCEDURE Command

COMPILE Command

CREATE PROJECT Command

#DEFINE ... #UNDEF Preprocessor Directive

DO Command

DO FORM Command

EXECSCRIPT( ) Function

FUNCTION Command

#IF ... #ENDIF Preprocessor Directive

#INCLUDE Preprocessor Directive

_INCLUDE System Variable

LOAD Command

LPARAMETERS Command

MESSAGEBOX( ) Function

MODIFY PROJECT Command

PARAMETERS Command

PARAMETERS( ) Function

PROCEDURE Command

RELEASE PROCEDURE Command

RESUME Command

RETURN Command

RUN | ! Command

SET ESCAPE Command

SET LIBRARY Command

SET LOGERRORS Command

SET PROCEDURE Command

SET SYSMENU Command

SET UDFPARMS Command

SUSPEND Command

SYS(2015) - Unique Procedure Name

WAIT Command


Structured Programming

These commands and functions make it possible for you to control program execution and branching within a Visual FoxPro program.

DO CASE ... ENDCASE Command

DO WHILE ... ENDDO Command

EXIT Command

FOR ... EACH Command

FOR ... ENDFOR Command

#IF ... #ENDIF Preprocessor Directive

#IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive

IF ... ENDIF Command

IIF( ) Function

LOOP Command

SCAN ... ENDSCAN Command


Variable Manipulation

These commands and functions make it possible for you to assign values to variables or text.

& Command

= Command

ACOPY( ) Function

ADEL( ) Function

ADIR( ) Function

AELEMENT( ) Function

AFIELDS( ) Function

AINS( ) Function

LEN( ) Function

ASCAN( ) Function

ASORT( ) Function

ASUBSCRIPT( ) Function

AVERAGE Command

CLEAR ALL Command

CLEAR MEMORY Command

COUNT Command

DISPLAY MEMORY Command

GETEXPR Command

_GETEXPR System Variable

LIST MEMORY Command

LOCAL Command

PARAMETERS Command

PRIVATE Command

PUBLIC Command

RELEASE Command

RESTORE FROM Command

SAVE TO Command

STORE Command

SUM Command

TEXTMERGE( ) Function

WAIT Command


Shared Access to Data

The commands and functions listed in this section make it possible for you to manage multiple users.

In This Section

Shared Access to Data Commands and Functions
Lists the commands and functions that make it possible for multiple users on a network to share data from tables.
Commands that Scope to a Data Session
Lists the commands that affect only the data session in which they are issued.

Related Sections

Language Categories
Contains a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Shared Access to Data Commands and Functions

These commands and functions make it possible for multiple users on a network to share data from tables.

CURSORSETPROP( ) Function

CURVAL( ) Function

FLOCK( ) Function

LOCK( ) Function

OLDVAL( ) Function

RLOCK( ) Function

SET EXCLUSIVE Command

SET LOCK Command

SET MULTILOCKS Command

SET REFRESH Command

SET REPROCESS Command

SYS(3051) - Set Lock Retry Interval

SYS(3052) - Override SET REPROCESS Locking

TABLEREVERT( ) Function

TABLEUPDATE( ) Function

UNLOCK Command


Commands that Scope to a Data Session

These commands affect only the data session in which they are issued.

BEGIN TRANSACTION Command

END TRANSACTION Command

ROLLBACK Command

SET ANSI Command

SET AUTOSAVE Command

SET BLOCKSIZE Command

SET CARRY Command

SET CENTURY Command

SET COLLATE Command

SET CONFIRM Command

SET CURRENCY Command

SET DATABASE Command

SET DATE Command

SET DECIMALS Command

SET DELETED Command

SET DELIMITERS Command

SET EXACT Command

SET EXCLUSIVE Command

SET FIELDS Command

SET FIXED Command

SET LOCK Command

SET MARK TO Command

SET MEMOWIDTH Command

SET MULTILOCKS Command

SET NEAR Command

SET NULL Command

SET PATH Command

SET POINT Command

SET REFRESH Command

SET REPROCESS Command

SET SAFETY Command

SET SEPARATOR Command

SET TALK Command

SET UNIQUE Command


Visual FoxPro Environment

The commands and functions listed in this section make it possible for you to access the Microsoft Visual FoxPro environment.

In This Section

Environment
Contains commands and functions that make it possible for you to manage a wide range of Visual FoxPro system and environment parameters.
File Management
Contains commands and functions for managing and manipulating disk files.

Related Sections

Language Categories
Provides a list of language functionality and descriptions.
Using Visual FoxPro
Discusses how Visual FoxPro programming features are designed to improve developer productivity, including Access and Assign methods, support for more graphic file formats, and language to simplify programming tasks.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Environment

These commands and functions make it possible for you to manage a wide range of Microsoft Visual FoxPro system and environment parameters.

ADIR( ) Function

ADLLS( ) Function

ALANGUAGE( ) Function

APROCINFO( )

ASSIST Command

ASESSIONS( ) Function

ASTACKINFO( ) Function

_BROWSER System Variable

_BUILDER System Variable

CAPSLOCK( ) Function

COL( ) Function

CREATE COLOR SET Command

CREATE VIEW Command

DECLARE - DLL Command

DIR or DIRECTORY Command

DISKSPACE( ) Function

DISPLAY DLLS Command

DISPLAY STATUS Command

FKLABEL( ) Function

FKMAX( ) Function

FONTMETRIC( ) Function

_GALLERY System Memory Variable

_GENHTML System Memory Variable

GETCOLOR( ) Function

GETCP( ) Function

GETENV( ) Function

_GETEXPR System Memory Variable

GETFILE( ) Function

GETFONT( ) Function

GETPEM( ) Function

HOME( ) Function

HELP Command

IMESTATUS( ) Function

_INCLUDE System Memory Variable

INKEY( ) Function

INSMODE( ) Function

ISCOLOR( ) Function

ISMOUSE( ) Function

LIST DLLS Command

LIST STATUS Command

LOCFILE( ) Function

MEMORY( ) Function

MESSAGE( ) Function

NUMLOCK( ) Function

_OBJECTBROWSER System Variable

OBJTOCLIENT( ) Function

OS( ) Function

PCOL( ) Function

PEMSTATUS( ) Function

PROW( ) Function

PUTFILE( ) Function

QUIT Command

READKEY( ) Function

RGB( ) Function

ROW( ) Function

SCHEME( ) Function

_SCREEN System Variable

SET( ) Function

SET Command

SET ANSI Command

SET BELL Command

SET BLOCKSIZE Command

SET CENTURY Command

SET CLEAR Command

SET CLOCK Command

SET CPDIALOG Command

SET COLOR OF Command

SET COLOR OF SCHEME Command

SET COLOR SET Command

SET COMPATIBLE Command

SET CURRENCY Command

SET DATE Command

SET DEBUG Command

SET DEFAULT Command

SET DISPLAY Command

SET FDOW Command

SET FIXED Command

SET FUNCTION Command

SET FWEEK Command

SET HELP Command

SET INTENSITY Command

SET KEYCOMP Command

SET LIBRARY Command

SET MARK TO Command

SET NOTIFY Command

SET PATH Command

SET POINT Command

SET RESOURCE Command

SET SEPARATOR Command

SET STATUS BAR Command

SET SYSFORMATS Command

SET TALK Command

SET TEXTMERGE Command

SET TEXTMERGE DELIMITERS Command

SET TOPIC Command

SET TOPIC ID Command

SET TYPEAHEAD Command

SET VIEW Command

SYS(3) - Legal File Name

SYS(5) - Default Drive

SYS(6) - Current Printer Device

SYS(7) - Current Format File

SYS(9) - Visual FoxPro Serial Number

SYS(12) - Available Memory in Bytes

SYS(16) - Executing Program File Name

SYS(17) - Processor in Use

SYS(18) - Current Control

SYS(24) - EMS Memory Limit

SYS(100) - Console Setting

SYS(101) - Device Setting

SYS(102) - Printer Setting

SYS(103) - Talk Setting

SYS(1001) - Visual FoxPro Memory

SYS(1016) - User Object Memory Use

SYS(1023) - Enable Help Diagnostic Mode

SYS(1024) - Disable Help Diagnostic Mode

SYS(1269) - Property Information

SYS(1270) - Object Location

SYS(1271) - Object's .SCX File

SYS(1272) - Object Hierarchy

SYS(2001) - SET ... Command Status

SYS(2003) - Current Directory

SYS(2004) - Visual FoxPro Start Directory

SYS(2005) - Current Resource File

SYS(2006) - Current Graphics Card

SYS(2010) - CONFIG.SYS File Settings

SYS(2013) - System Menu Name String

SYS(2016) - SHOW GETS WINDOW Name

SYS(2019) - Configuration File Name and Location

SYS(2020) - Default Disk Size

SYS(2022) - Disk Cluster (Block) Size

SYS(2023) - Temporary File Drive

SYS(2334) – Automation Server Invocation Mode

SYS(2800) – Accesibility Support

SYS(3004) - Return Locale ID

SYS(3005) - Set Locale ID

SYS(3006) - Set Language and Locale IDs

SYS(3050) - Set Buffer Memory Size

SYS(3053) - ODBC Environment Handle

SYS(3056) – Read Registry Settings

SYS(3095) – IDispatch Pointer

SYSMETRIC( ) Function

_TASKLIST System Variable

TXTWIDTH( ) Function

VERSION( ) Function

WFONT( ) Function

_WIZARD System Variable


File Management

These commands and functions manage and manipulate disk files.

ADDBS( ) Function

ADIR( ) Function

ASSIST Command

CD | CHDIR Command

CLOSE ALL Command

CLOSE ALTERNATE Command

CLOSE DATABASES Command

CLOSE FORMAT Command

CLOSE INDEXES Command

CLOSE PROCEDURE Command

COPY FILE Command

CREATE VIEW Command

CURDIR( ) Function

DEFAULTEXT( ) Function

DELETE FILE Command

DIR or DIRECTORY Command

DISPLAY FILES Command

DISKSPACE( ) Function

DRIVETYPE( ) Function

EDITSOURCE( ) Function

ERASE Command

FDATE( ) Function

FTIME( ) Function

FILE( ) Function

FILETOSTR( ) Function

FLUSH Command

FORCEEXT( ) Function

FORCEPATH( ) Function

FULLPATH( ) Function

GETFILE( ) Function

GETPICT( ) Function

ISNULL( ) Function

JUSTDRIVE( ) Function

JUSTEXT( ) Function

JUSTFNAME( ) Function

JUSTPATH( ) Function

JUSTSTEM( ) Function

LIST FILES Command

LOCFILE( ) Function

MD | MKDIR Command

MODIFY COMMAND Command

MODIFY FILE Command

NVL( ) Function

OPEN DATABASE Command

PUTFILE( ) Function

RD | RMDIR Command

RENAME Command

SET ALTERNATE Commands

SET DEFAULT Command

SET FULLPATH Command

SET PATH Command

SET SAFETY Command

SET VIEW Command

STRTOFILE( ) Function

SYS(3) - Legal File Name

SYS(2000) - File Name Wildcard Match

SYS(2014) - Minimum Path

TYPE Command


Commands

Supported Visual FoxPro SET Commands in OLE DB Provider

Unsupported Visual FoxPro Commands and Functions in OLE DB Provider

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

Symbols

& Command

&& Command

* Command

#NAME?

? | ?? Command

??? Command

@ ... BOX Command

@ ... CLASS Command

@ ... CLEAR Command

@ ... EDIT - Edit Boxes Command

@ ... FILL Command

@ ... GET - Check Boxes Command

@ ... GET - Combo Boxes Command

@ ... GET - Command Buttons Command

@ ... GET - List Boxes Command

@ ... GET - Option Buttons Command

@ ... GET - Spinners Command

@ ... GET - Text Boxes Command

@ ... GET - Transparent Buttons Command

@ ... MENU Command

@ ... PROMPT Command

@ ... SAY - Pictures & OLE Objects Command

@ ... SAY Command

@ ... SCROLL Command

@ ... TO Command

\ | \\ Command

A

ACTIVATE MENU Command

ACTIVATE POPUP Command

ACTIVATE SCREEN Command

ACTIVATE WINDOW Command

ADD CLASS Command

ADD TABLE Command

ALTER TABLE – SQL Command

APPEND Command

APPEND FROM ARRAY Command

APPEND FROM Command

APPEND GENERAL Command

APPEND MEMO Command

APPEND PROCEDURES Command

ASSERT Command

ASSIST Command

AVERAGE Command

B

BEGIN TRANSACTION Command

BLANK Command

BROWSE Command

BUILD APP Command

BUILD DLL Command

BUILD EXE Command

BUILD MTDLL Command

BUILD PROJECT Command

C

CALCULATE Command

CALL Command

CANCEL Command

CD | CHDIR Command

CHANGE Command

CLEAR Commands

CLOSE Commands

CLOSE MEMO Command

COMPILE Command

COMPILE DATABASE Command

COMPILE FORM Command

CONTINUE Command

COPY FILE Command

COPY INDEXES Command

COPY MEMO Command

COPY PROCEDURES Command

COPY STRUCTURE Command

COPY STRUCTURE EXTENDED Command

COPY TAG Command

COPY TO ARRAY Command

COPY TO Command

COUNT Command

CREATE CLASS Command

CREATE CLASSLIB Command

CREATE COLOR SET Command

CREATE Command

CREATE CONNECTION Command

CREATE CURSOR – SQL Command

CREATE DATABASE Command

CREATE FORM Command

CREATE FROM Command

CREATE LABEL Command

CREATE MENU Command

CREATE PROJECT Command

CREATE QUERY Command

CREATE REPORT – Quick Report Command

CREATE REPORT Command

CREATE SCREEN – Quick Screen Command

CREATE SCREEN Command

CREATE SQL VIEW Command

CREATE TABLE – SQL Command

CREATE TRIGGER Command

CREATE VIEW Command

D

DEACTIVATE MENU Command

DEACTIVATE POPUP Command

DEACTIVATE WINDOW Command

DEBUG Command

DEBUGOUT Command

DECLARE - DLL Command

DECLARE Command

DEFINE BAR Command

DEFINE BOX Command

DEFINE CLASS Command

DEFINE MENU Command

DEFINE PAD Command

DEFINE POPUP Command

DEFINE WINDOW Command

DELETE - SQL Command

DELETE Command

DELETE CONNECTION Command

DELETE DATABASE Command

DELETE FILE Command

DELETE TAG Command

DELETE TRIGGER Command

DELETE VIEW Command

DIMENSION Command

DIR or DIRECTORY Command

DISPLAY Command

DISPLAY CONNECTIONS Command

DISPLAY DATABASE Command

DISPLAY DLLS Command

DISPLAY FILES Command

DISPLAY MEMORY Command

DISPLAY OBJECTS Command

DISPLAY PROCEDURES Command

DISPLAY STATUS Command

DISPLAY STRUCTURE Command

DISPLAY TABLES Command

DISPLAY VIEWS Command

DO CASE ... ENDCASE Command

DO Command

DO FORM Command

DO WHILE ... ENDDO Command

DOCK WINDOW Command

DOEVENTS Command

DROP TABLE Command

DROP VIEW Command

E

EDIT Command

EJECT Command

EJECT PAGE Command

END TRANSACTION Command

ERASE Command

ERROR Command

EXIT Command

EXPORT Command

EXTERNAL Command

F

FIND Command

FLUSH Command

FOR EACH ... ENDFOR Command

FOR ... ENDFOR Command

FREE TABLE Command

FUNCTION Command

G

GATHER Command

GETEXPR Command

GO | GOTO Command

H

HELP Command

HIDE MENU Command

HIDE POPUP Command

HIDE WINDOW Command

I

IF ... ENDIF Command

IMPORT Command

INDEX Command

INPUT Command

INSERT – SQL Command

INSERT Command

J

JOIN Command

K

KEYBOARD Command

L

LABEL Command

LIST Commands

LIST CONNECTIONS Command

LIST DATABASE Command

LIST DLLS Command

LIST OBJECTS Command

LIST PROCEDURES Command

LIST TABLES Command

LIST VIEWS Command

LOAD Command

LOCAL Command

LOCATE Command

LOOP Command

LPARAMETERS Command

M

MD | MKDIR Command

MENU Command

MENU TO Command

MODIFY CLASS Command

MODIFY COMMAND Command

MODIFY CONNECTION Command

MODIFY DATABASE Command

MODIFY FILE Command

MODIFY FORM Command

MODIFY GENERAL Command

MODIFY LABEL Command

MODIFY MEMO Command

MODIFY MENU Command

MODIFY PROCEDURE Command

MODIFY PROJECT Command

MODIFY QUERY Command

MODIFY REPORT Command

MODIFY SCREEN Command

MODIFY STRUCTURE Command

MODIFY VIEW Command

MODIFY WINDOW Command

MOUSE Command

MOVE POPUP Command

MOVE WINDOW Command

N

NOTE Command

O

ON BAR Command

ON ERROR Command

ON ESCAPE Command

ON EXIT BAR Command

ON EXIT MENU Command

ON EXIT PAD Command

ON EXIT POPUP Command

ON KEY = Command

ON KEY Command

ON KEY LABEL Command

ON PAD Command

ON PAGE Command

ON READERROR Command

ON SELECTION BAR Command

ON SELECTION MENU Command

ON SELECTION PAD Command

ON SELECTION POPUP Command

ON SHUTDOWN Command

OPEN DATABASE Command

P

PACK Command

PACK DATABASE Command

PARAMETERS Command

PLAY MACRO Command

POP KEY Command

POP MENU Command

POP POPUP Command

PRINTJOB ... ENDPRINTJOB Command

PRIVATE Command

PROCEDURE Command

PUBLIC Command

PUSH KEY Command

PUSH MENU Command

PUSH POPUP Command

Q

QUIT Command

R

RD | RMDIR Command

READ Command

READ EVENTS Command

READ MENU Command

RECALL Command

REINDEX Command

RELEASE BAR Command

RELEASE CLASSLIB Command

RELEASE Command

RELEASE LIBRARY Command

RELEASE MENUS Command

RELEASE PAD Command

RELEASE POPUPS Command

RELEASE PROCEDURE Command

RELEASE WINDOWS Command

REMOVE CLASS Command

REMOVE TABLE Command

RENAME CLASS Command

RENAME Command

RENAME CONNECTION Command

RENAME TABLE Command

RENAME VIEW Command

REPLACE Command

REPLACE FROM ARRAY Command

REPORT Command

RESTORE FROM Command

RESTORE MACROS Command

RESTORE SCREEN Command

RESTORE WINDOW Command

RESUME Command

RETRY Command

RETURN Command

ROLLBACK Command

RUN | Command

S

SAVE MACROS Command

SAVE SCREEN Command

SAVE TO Command

SAVE WINDOWS Command

SCAN ... ENDSCAN Command

SCATTER Command

SCROLL Command

SEEK Command

SELECT - SQL Command

SELECT Command

SET ALTERNATE Command

SET ANSI Command

SET ASSERTS Command

SET AUTOINCERROR Command

SET AUTOSAVE Command

SET BELL Command

SET BLOCKSIZE Command

SET BORDER Command

SET BROWSEIME Command

SET BRSTATUS Command

SET CARRY Command

SET CENTURY Command

SET CLASSLIB Command

SET CLEAR Command

SET CLOCK Command

SET COLLATE Command

SET COLOR OF Command

SET COLOR OF SCHEME Command

SET COLOR SET Command

SET COLOR TO Command

SET Command

SET COMPATIBLE Command

SET CONFIRM Command

SET CONSOLE Command

SET COVERAGE Command

SET CPCOMPILE Command

SET CPDIALOG Command

SET CURRENCY Command

SET CURSOR Command

SET DATABASE Command

SET DATASESSION Command

SET DATE Command

SET DEBUG Command

SET DEBUGOUT Command

SET DECIMALS Command

SET DEFAULT Command

SET DELETED Command

SET DELIMITERS Command

SET DEVELOPMENT Command

SET DEVICE Command

SET DISPLAY Command

SET DOHISTORY Command

SET ECHO Command

SET ENGINEBEHAVIOR Command

SET ESCAPE Command

SET EVENTLIST Command

SET EVENTTRACKING Command

SET EXACT Command

SET EXCLUSIVE Command

SET FDOW Command

SET FIELDS Command

SET FILTER Command

SET FIXED Command

SET FORMAT Command

SET FULLPATH Command

SET FUNCTION Command

SET FWEEK Command

SET HEADINGS Command

SET HELP Command

SET HOURS Command

SET INDEX Command

SET INTENSITY Command

SET KEY Command

SET KEYCOMP Command

SET LIBRARY Command

SET LOCK Command

SET LOGERRORS Command

SET MACKEY Command

SET MARGIN Command

SET MARK OF Command

SET MARK TO Command

SET MEMOWIDTH Command

SET MESSAGE Command

SET MULTILOCKS Command

SET NEAR Command

SET NOCPTRANS Command

SET NOTIFY Command

SET NULL Command

SET NULLDISPLAY Command

SET ODOMETER Command

SET OLEOBJECT Command

SET OPTIMIZE Command

SET ORDER Command

SET PALETTE Command

SET PATH Command

SET PDSETUP Command

SET POINT Command

SET PRINTER Command

SET PROCEDURE Command

SET READBORDER Command

SET REFRESH Command

SET RELATION Command

SET RELATION OFF Command

SET REPROCESS Command

SET RESOURCE Command

SET SAFETY Command

SET SECONDS Command

SET SEPARATOR Command

SET SKIP Command

SET SKIP OF Command

SET SPACE Command

SET STATUS BAR Command

SET STATUS Command

SET STEP Command

SET STRICTDATE Command

SET SYSFORMATS Command

SET SYSMENU Command

SET TABLEVALIDATE Command

SET TALK Command

SET TEXTMERGE Command

SET TEXTMERGE DELIMITERS Command

SET TOPIC Command

SET TOPIC ID Command

SET TRBETWEEN Command

SET TYPEAHEAD Command

SET UDFPARMS Command

SET UNIQUE Command

SET VIEW Command

SET WINDOW OF MEMO Command

SHOW GET Command

SHOW GETS Command

SHOW MENU Command

SHOW OBJECT Command

SHOW POPUP Command

SHOW WINDOW Command

SIZE POPUP Command

SIZE WINDOW Command

SKIP Command

SORT Command

STORE Command

SUM Command

SUSPEND Command

SYS(2001) – SET ... Command Status

T

TEXT ... ENDTEXT Command

TOTAL Command

TRY...CATCH...FINALLY Command

TYPE Command

U

UNLOCK Command

UPDATE - SQL Command

UPDATE Command

USE Command

V

VALIDATE DATABASE Command

W

WAIT Command

WITH ... ENDWITH Command

X

Y

Z

ZAP Command

ZOOM WINDOW Command


& Command

Performs macro substitution.

& VarName[.cExpression]

Parameters

& VarName
Specifies the name of the variable or array element to reference in the macro substitution. Do not include the M. prefix that distinguishes variables from fields. Such inclusion causes a syntax error. The macro should not exceed the maximum statement length permitted in Visual FoxPro.

A variable cannot reference itself recursively in macro substitution. For example, the following generates an error message:

STORE '&gcX' TO gcX
? &gcX

Macro substitution statements that appear in DO WHILE, FOR, and SCAN are evaluated only at the start of the loop and are not reevaluated on subsequent iterations. Any changes to the variable or array element that occur within the loop are not recognized.

.cExpression
The optional period (.) delimiter and .cExpression are used to append additional characters to a macro. cExpression appended to the macro with .cExpression can also be a macro. If cExpression is a property name, include an extra period (cExpression..PropertyName).

Remarks

Macro substitution treats the contents of a variable or array element as a character string literal. When an ampersand (&) precedes a character-type variable or array element, the contents of the variable or element replace the macro reference. You can use macro substitution in any command or function that accepts a character string literal.

Tip Whenever possible, use a name expression instead of macro substitution. A name expression operates like macro substitution. However, a name expression is limited to passing character strings as names. Use a name expression for significantly faster processing if a command or function accepts a name (a file name, window name, menu name, and so on). For additional information on name expressions, see Name Expression Creation.

While the following commands are acceptable:

STORE 'customer' TO gcTableName
STORE 'company'  TO gcTagName
USE &gcTableName ORDER &gcTagName

use a name expression instead:

USE (gcTableName) ORDER (gcTagName)

Macro substitution is useful for substituting a keyword in a command. In the following example, the TALK setting is saved to a variable so the setting can be restored later in the program. The original TALK setting is restored with macro substitution.

Example

STORE SET('TALK') TO gcSaveTalk
SET TALK OFF
*
*  Additional program code
*
SET TALK &gcSaveTalk  && Restore original TALK setting

See Also

Commands | STORE Command | && Command | Macro Substitution


&& Command

Indicates the beginning of a nonexecuting inline comment in a program file.

&& [Comments]

Parameters

Comments
Indicates that inline comments follow. For example:
STORE (20*12) TO gnPayments  && 20 years of monthly payments

Inserting inline comments to denote the end of the IF ... ENDIF, DO, and FOR ... ENDFOR structured programming commands greatly improves the readability of programs.

Remarks

Place a semicolon (;) at the end of each comment line that continues to a following line.

Note In earlier versions of Visual FoxPro, you cannot place && and a comment after the semicolon that is used to continue a command line to an additional line.

Example

NOTE  Initialize the page number;
   variable.
STORE 1 to gnPageNum
* Set up the loop
DO WHILE gnPageNum <= 25  && loop 25 times
   gnPageNum = gnPageNum + 1
ENDDO  && DO WHILE gnPageNum <= 25

See Also

* Command | MODIFY COMMAND Command | MODIFY FILE Command | NOTE Command | & Command


* Command

Indicates the beginning of a nonexecuting comment line in a program file.

* [Comments]

Parameters

Comments
Specifies the comment in the comment line. For example:
*   This is a comment

Remarks

Place a semicolon (;) at the end of each comment line that continues to a following line.

Example

* Initialize the page number;
   variable.
STORE 1 to gnPageNum
* Set up the loop
DO WHILE gnPageNum <= 25  && loop 25 times
   gnPageNum = gnPageNum + 1
ENDDO  && DO WHILE gnPageNum <= 25

See Also

&& Command | MODIFY COMMAND Command | MODIFY FILE Command | NOTE Command


? | ?? Command

Evaluates expressions and displays the results.

? | ?? Expression1 [PICTURE cFormatCodes] | [FUNCTION cFormatCodes] |
   [VnWidth] [AT nColumn]
   [FONT cFontName [, nFontSize] [STYLE cFontStyle | Expression2]]
   [, Expression3] ...

Parameters

? Expression1
Evaluates the expression specified by Expression1 and sends a carriage return and line feed before the expression results. The results are displayed on the next line of the main Visual FoxPro window or the active user-defined window and printed at the left margin of a page, unless a function code cFormatCodes or the _ALIGNMENT system variable specifies otherwise.

If you omit the expressions, a blank line is displayed or printed. A space is placed between expression results when multiple expressions are included.

If Expression1 is an object, ? returns the character string "(Object)".

?? Expression1
Evaluates the expression specified by Expression1 and displays the expression results on the current line at the current position of the main Visual FoxPro window, an active user-defined window, or the printer. A carriage return and line feed are not sent before the results.
PICTURE cFormatCodes
Specifies a picture format in which the result of Expression1 is displayed. cFormatCodes can consist of function codes, picture codes, or a combination of both. You can use the same codes available in the Format Property and InputMask Property.

Function codes affect the overall format of the result; picture codes act on individual characters in the result. If function codes are used in cFormatCodes, they must appear before the picture codes and they must be preceded by @. Multiple function codes with no embedded spaces can immediately follow @. The last function code must be followed by one or more spaces. The space or spaces signal the end of the function codes and the start of the picture codes.

FUNCTION cFormatCodes
Specifies a function code to include in ? and ?? output. If the function clause is included, do not precede the function codes with @. Function codes must be preceded by @ when included in PICTURE.
VnWidth
Specifies a special function code that enables the results of a character expression to stretch vertically within a limited number of columns. nWidth specifies the number of columns in the output.
? 'This is an example of how the V function code works.' ;
   FUNCTION 'V10'
AT nColumn
Specifies the column number where the output is displayed. This option makes it possible for you to align output in columns to create a table. The numeric expression nColumn can be a user-defined function that returns a numeric value.
FONT cFontName [, nFontSize]
Specifies a font for ? | ?? output. cFontName specifies the name of the font, and nFontSize specifies the point size. For example, the following command displays the system date in 16-point Courier font:
? DATE( ) FONT 'Courier',16

If you include the FONT clause but omit the point size nFontSize, a 10-point font is used.

If you omit the FONT clause and ? | ?? output is placed in the main Visual FoxPro window, the main Visual FoxPro window font is used for the output. If you omit the FONT clause and ? | ?? output is placed in a user-defined window, the user-defined window font is used for the output.

  • If the font you specify is not available, a font with similar font characteristics is substituted.
STYLE cFontStyle
Specifies a font style for ? | ?? output. If you omit the STYLE clause, the Normal font style is used. If the font style you specify is not available, a font style with similar characteristics is substituted.
Note You must include the FONT clause when you specify a font style with the STYLE clause.

The font styles you can specify with cFontStyle are as follows:

Character | Font style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command displays the system date in Courier Bold Italic:

? DATE( ) FONT 'COURIER' STYLE 'BI'

Remarks

? and ?? evaluate expressions and send the results to the main Visual FoxPro window, an active user-defined window, or the printer.

If SET PRINTER is ON, the expression results are directed to the printer and the main Visual FoxPro window or an active user-defined window. If SET PRINTER is ON and SET CONSOLE is OFF, the results are directed only to the printer.

Example

? 15 * (10+10)
? 'Welcome to ' PICTURE '@!'
?? 'Visual FoxPro'

See Also

??? Command |@ ... SAY Command | SET MEMOWIDTH Command | SET PRINTER Command | SET SPACE Command | Format Property | InputMask Property


??? Command

Sends output directly to the printer.

??? cExpression

Parameters

cExpression
Specifies the characters that are sent to the printer.

Remarks

A group of three question marks bypasses the printer driver and sends the contents of cExpression directly to the printer. cExpression must contain valid printer codes.

Printer control codes make it possible for you to reset the printer, change type styles and sizes, and enable or disable boldface printing. These codes can consist of any combination of printable or nonprintable characters that are specific to the printer you are using. You can direct control codes to the printer in several different ways:

  • Use combinations of CHR( ) and quoted strings concatenated with + to send ASCII characters directly to the printer.
  • Use quotation marks to send a string containing printer codes or ASCII characters.
  • Codes can be sent to the printer before printing begins and after printing ends with the _PSCODE and _PECODE system variables. For more information, see _PSCODE System Variable and _PECODE System Variable.

Printer control codes vary from printer to printer. The best source for information about printer control codes is the manual that came with your printer.

See Also

? | ?? Command? | @ ... SAY Command | CHR( ) Function | Print Dialog Box | _PSCODE System Variable | _PECODE System Variable


@ ... CLASS Command

Creates a control or object that can be activated with READ.

@ nRow, nColumn CLASS ClassName NAME ObjectName

Parameters

@ nRow, nColumn
Specifies the position of the control or object. The height and width of the control or object is determined by the class default height and width values.

Rows are numbered from top to bottom. The first row is number 0 in the main Visual FoxPro window or in a user-defined window. Row 0 is the row immediately beneath the Visual FoxPro system menu bar.

Columns are numbered from left to right. The first column is number 0 in the main Microsoft Visual FoxPro window or in a user-defined window. When a control or object is placed in a user-defined window, the row and column coordinates are relative to the user-defined window, not to the main Visual FoxPro window.

A position in the main Visual FoxPro window or in a user-defined window is determined by the font of the window. Most fonts can be displayed in a wide variety of sizes; some are proportionally spaced. A row corresponds to the height of the current font; a column corresponds to the average width of a letter in the current font.

You can position the control or object using decimal fractions for row and column coordinates.

CLASS ClassName
Specifies the class of the control or object. ClassName can be a Visual FoxPro base class or a user-defined class. The following table lists the Visual FoxPro base classes you can specify for ClassName.

Base class names

CheckBox Control | Line Control
Column Object | ListBox Control
ComboBox Control | OLE Container Control
CommandButton Control | OLE Bound Control
CommandGroup Control | OptionButton Control
Container Object | OptionGroup Control
Control Object | Page Object
Cursor Object | PageFrame Control
Custom Object | Relation Object
DataEnvironment Object | Separator Object
EditBox Control | Shape Control
Grid Control | Spinner Control
Header Object | TextBox Control
Image Control | Timer Control
Label Control |
NAME ObjectName
Specifies the name of the object reference variable to create. The object-oriented properties, events, and methods of the control or object can be manipulated by referencing this variable.

Remarks

@ ... CLASS provides an intermediate step for converting programs and applications created in earlier versions of FoxPro to the preferred object-oriented programming methods of Visual FoxPro. For additional information about backward compatibility with FoxPro 2.x controls, see Controls and Objects.

For information about object-oriented programming in Visual FoxPro, see Object-Oriented Programming.

Example

The following example demonstrates how @ ... CLASS can be used with programming techniques used in earlier FoxPro versions (in this example, use of READ to activate controls). @ ... CLASS is used to create a text box whose properties can be changed with the Visual FoxPro object-oriented programming techniques.

ON KEY LABEL is used to display the Windows Color dialog box when you press CTRL+I. The TextBox is placed on the main Visual FoxPro window using @ ... CLASS, and READ activates the text box.

CLEAR
ON KEY LABEL CTRL+I _SCREEN.PageFrame1.Page1.goFirstName.BackColor;
    = GETCOLOR( )
@ 2,2 SAY 'Press Ctrl+I to change the background color'

@ 4,2 CLASS TextBox NAME goFirstName
READ
CLEAR

See Also

CREATEOBJECT( ) Function | DEFINE CLASS Command | READ Command | _SCREEN System Variable


@ ... CLEAR Command

Clears a portion of the main Visual FoxPro window or a user-defined window.

@ nRow1, nColumn1 [CLEAR | CLEAR TO nRow2, nColumn2]

Parameters

@ nRow1, nColumn1 CLEAR
Clears a rectangular area whose upper-left corner begins at nRow1 and nColumn1 and continues to the lower-right corner of the main Visual FoxPro window or a user-defined window.
CLEAR TO nRow2, nColumn2
Clears a rectangular area whose upper-left corner is at nRow1 and nColumn1 and whose lower-right corner is at nRow2 and nColumn2.

Remarks

If you omit CLEAR or CLEAR TO, Visual FoxPro clears nRow1 from nColumn1 to the end of the row.

Example

The following example clears the screen, main Visual FoxPro window, or user-defined window from the second row to the bottom of the window.

@ 2,0 CLEAR

The following example clears a rectangular region. The area from row 10 and column 0 to row 20 and column 20 is cleared.

@ 10,0 CLEAR TO 20,20

See Also

CLEAR Commands | SET CLEAR Command | _WClear( ) API Library Routine


@ ... FILL Command

Changes the colors of existing text within an area of the screen.

@ nRow1, nColumn1 FILL TO nRow2,
 nColumn2[COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

@ nRow1, nColumn1
Specifies the upper-left corner of the area to change.
FILL TO nRow2, nColumn2
Specifies the lower-right corner of the area to change.
COLOR SCHEME nSchemeNumber
Specifies the color of the area. Only the first color pair in the specified color scheme determines the color of the area.
COLOR ColorPairList
Specifies the color of the area. Only the first color pair in the specified color pair list determines the color of the area.

If you omit the COLOR SCHEME or COLOR clauses, the rectangular portion is cleared. An area can also be cleared with @ ... CLEAR.

Remarks

This command changes the colors of text within a rectangular area of the main Visual FoxPro window or the active user-defined window. You can set the foreground and background color attributes for existing text only. Any text output to the same area after you issue @ ... FILL appears in the default screen or window colors.

Example

The following example clears the main Visual FoxPro window and fills an area with color.

ACTIVATE SCREEN
CLEAR
@ 4,1 FILL TO 10, 8 COLOR GR+/B

See Also

@ ... SAY Command | ColorScheme Property | FillColor Property


@ ... SCROLL Command

Moves an area of the main Microsoft Visual FoxPro window or a user-defined window up, down, left, or right.

@ nRow1, nColumn1 TO nRow2, nColumn2 SCROLL
[UP | DOWN | LEFT | RIGHT]   [BY nMoveAmount]

Parameters

@ nRow1, nColumn1 TO nRow2, nColumn2 SCROLL
Moves a rectangular area whose upper-left corner is at nRow1, nColumn1 and lower-right corner is at nRow2, nColumn2.
UP | DOWN | LEFT | RIGHT
Specifies the direction in which rectangular area is moved. If you omit a direction clause, the area is moved upward.
BY nMoveAmount
Specifies the number of rows or columns the rectangular area is moved. If you omit BY nMoveAmount, the region is moved by one row or column.

See Also

SCROLL Command | Scrolled Event


\ | \\ Command

Prints or displays lines of text.

\TextLine

-Or-

\\TextLine

Parameters

\TextLine
When you use \, the text line is preceded by a carriage return and a line feed.
\\TextLine
When you use \\, the text line is not preceded by a carriage return and a line feed.

Any spaces preceding \ and \\ are not included in the output line, but spaces following \ and \\ are included.

You can embed an expression in the text line. If the expression is enclosed in the text merge delimiters (<< >> by default) and SET TEXTMERGE is ON, the expression is evaluated and its value is output as text.

Remarks

The \ and \\ commands facilitate text merge in Visual FoxPro. Text merge makes it possible for you to output text to a file to create form letters or programs.

Use \ and \\ to output a text line to the current text-merge output file and the screen. SET TEXTMERGE is used to specify the text merge output file. If text merge is not directed to a file, the text line is output only to the main Visual FoxPro window or the active user-defined output window. SET TEXTMERGE NOSHOW suppresses output to the main Visual FoxPro window or the active user-defined window.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
SET TEXTMERGE ON
SET TEXTMERGE TO letter.txt
\<<CDOW(DATE( ))>>, <<CMONTH(DATE( ))>>
\\ <<DAY(DATE( ))>>, <<YEAR(DATE( ))>>
\
\
\Dear <<contact>>
\Additional text
\
\Thank you,
\
\XYZ Corporation
CLOSE ALL
MODIFY FILE letter.txt NOEDIT

See Also

_PRETEXT System Variable | SET TEXTMERGE Command | SET TEXTMERGE DELIMITERS Command | _TEXT System Variable | TEXT ... ENDTEXT Command


= Command

Evaluates one or more expressions.

= Expression1 [, Expression2 ...]

Parameters

Expression1 [, Expression2 ...]
Specifies the expression or expressions that the = command evaluates.

Remarks

The = command evaluates one or more expressions, Expression1, Expression2 ..., and discards the return values. This option is particularly useful when a Visual FoxPro function or a user-defined function has a desired effect, but there is no need to assign the function's return value to a variable, array element, or field.

For example, to turn insert mode on, you can issue the following command:

= INSMODE(.T.)

INSMODE normally returns a True (.T.) or False (.F.) value. In the example above, the function is executed but the return value is discarded.

If only one expression (Expression1) is included, the equal sign is optional.

Note There are two unrelated uses for the equal sign (=). It can be used as an operator in logical expressions to make a comparison, or to assign values to variables and array elements. In these two cases, the equal sign (=) is an operator and not a command. See Relational Operators for more information about using the equal sign (=) as an operator in logical expressions. See STORE Command for more information about using the equal sign (=) to assign values to variables and array elements.

See Also

EVALUATE( ) Function | INSMODE( ) Function | Relational Operators | STORE Command | ON KEY = Command


ACTIVATE MENU Command

Displays and activates a menu bar.

ACTIVATE MENU MenuBarName   [NOWAIT]   [PAD MenuTitleName]

Parameters

MenuBarName
Specifies the name of the menu bar to activate.
NOWAIT
Specifies that at run time the program should not wait for the user to choose a menu from the active menu bar or to press ESC. Instead, the program continues to execute. A menu activated with the NOWAIT option does not return program execution to the line following the ACTIVATE MENU command when DEACTIVATE MENU is issued.
PAD MenuTitleName
Specifies the menu title name that is automatically selected when the menu bar is activated. If you don't specify a menu title name, the first menu title name in the activated menu bar is activated by default.

Remarks

Displays and activates the menu bar specified with MenuBarName. This command works in conjunction with DEFINE MENU and DEFINE PAD.

Note When you include the Visual FoxPro system menu bar (_MSYSMENU) in an application, there is no need to activate the menu. Instead, issue SET SYSMENU AUTOMATIC.

Example

The following example uses ACTIVATE MENU to display and activate a user-defined menu system. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Two menu titles are created with DEFINE PAD; DEFINE POPUP is used to create a drop-down menu for each menu title. DEFINE BAR is used to create menu items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu. ACTIVATE MENU displays and activates the menu bar.

When a menu item is chosen from a menu, the CHOICE procedure is executed. CHOICE displays the name of the chosen item and the name of the menu containing the item.

*** Name this program ACTIMENU.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
ON KEY LABEL ESC KEYBOARD CHR(13)
DEFINE MENU example BAR AT LINE 1
DEFINE PAD convpad OF example PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD cardpad OF example PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD convpad OF example ACTIVATE POPUP conversion
ON PAD cardpad OF example ACTIVATE POPUP cardinfo
DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' ;
   KEY CTRL+E, '^E'
DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
ON SELECTION POPUP conversion DO choice IN actimenu;
   WITH PROMPT( ), POPUP( )
DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF cardinfo PROMPT '\-'
DEFINE BAR 5 OF cardinfo PROMPT '\<Charges ' ;
   KEY ALT+C, ''
ON SELECTION POPUP cardinfo;
   DO choice IN actimenu WITH PROMPT( ), POPUP( )

ACTIVATE MENU example
DEACTIVATE MENU example
RELEASE MENU example EXTENDED
SET SYSMENU TO DEFAULT
ON KEY LABEL ESC
PROCEDURE choice
PARAMETERS mprompt, mpopup
WAIT WINDOW 'You chose ' + mprompt + ' from popup ' + mpopup NOWAIT

See Also

CLEAR Commands | CREATE MENU Command | DEACTIVATE MENU Command | DEFINE MENU Command | DEFINE PAD | HIDE MENU Command | SET SYSMENU | SHOW MENU


ACTIVATE POPUP Command

Displays and activates a menu.

ACTIVATE POPUP MenuName   [AT nRow, nColumn]
[BAR nMenuItemNumber]   [NOWAIT]   [REST]

Parameters

MenuName
Specifies the name of the menu to activate.
AT nRow, nColumn
Specifies the position of the menu on the screen or in a user-defined window. The row and column coordinate applies to the upper-left corner of the menu. The position you specify with this argument takes precedence over a position you specify with the FROM argument in DEFINE POPUP.
BAR nMenuItemNumber
Specifies the item in the menu that is selected when the menu is activated. For example, if nMenuItemNumber is 2, the second item is selected. The first item is selected if you omit BAR nMenuItemNumber or if nMenuItemNumber is greater than the number of items in the menu.
NOWAIT
Specifies that, at run time, a program does not wait for the user to choose an item from the menu before continuing program execution. Instead, the program continues to execute.
REST
A menu created with the PROMPT FIELD clause of DEFINE POPUP places records from a field into the menu. When the menu is activated, the first item in the menu is initially selected, even if the record pointer in the table containing the field is positioned on a record other than the first record.

Include REST to specify that the item selected when the menu is activated corresponds to the current record pointer position in the table.

Remarks

ACTIVATE POPUP works in conjunction with DEFINE POPUP, used to create the menu, and DEFINE BAR, used to create the items on the menu.

Example

This example uses ACTIVATE POPUP with ON PAD to activate a menu when a menu title is chosen. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Two new system menu titles are created with DEFINE PAD; DEFINE POPUP is used to create a menu for each menu title. DEFINE BAR is used to create menu items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu.

When an item is chosen from a menu, the CHOICE procedure is executed. CHOICE displays the name of the chosen item and the name of the menu containing the item. If the Exit item is chosen from the Card Info menu, the original Visual FoxPro system menu is restored.

*** Name this program ACTIPOP.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD convpad OF _MSYSMENU PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD cardpad OF _MSYSMENU PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD convpad OF _MSYSMENU ACTIVATE POPUP conversion
ON PAD cardpad OF _MSYSMENU ACTIVATE POPUP cardinfo
DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' KEY CTRL+E, '^E'
DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
ON SELECTION POPUP conversion;
   DO choice IN actipop WITH PROMPT(), POPUP()
DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF cardinfo PROMPT '\-'
DEFINE BAR 5 OF cardinfo PROMPT '\<Charges' ;
   KEY ALT+C, ''
DEFINE BAR 6 OF cardinfo PROMPT '\-'
DEFINE BAR 7 OF cardinfo PROMPT 'E\<xit';
   KEY ALT+X, ''
ON SELECTION POPUP cardinfo;
DO choice IN actipop WITH PROMPT(),POPUP()

PROCEDURE choice
PARAMETERS mprompt, mpopup
WAIT WINDOW 'You chose ' + mprompt + ;
   ' from popup ' + mpopup NOWAIT
IF mprompt = 'Exit'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

CLEAR Commands | CREATE MENU | DEACTIVATE POPUP | DEFINE BAR | DEFINE POPUP | HIDE POPUP | MOVE POPUP | ON SELECTION POPUP | POP POPUP | POPUP( ) | PROMPT( ) | PUSH POPUP | SHOW POPUP


ACTIVATE SCREEN Command

Sends all subsequent output to the main Visual FoxPro window instead of to the active user-defined window.

ACTIVATE SCREEN

Remarks

Use ACTIVATE WINDOW to direct output to a user-defined window.

See Also

ACTIVATE WINDOW | DEACTIVATE WINDOW | DEFINE WINDOW | HIDE WINDOW | SHOW WINDOW


ACTIVATE WINDOW Command

Displays and activates one or more user-defined windows or Visual FoxPro system windows.

ACTIVATE WINDOW WindowName1 [, WindowName2 ...]
| ALL   [IN [WINDOW] WindowName3 | IN SCREEN
[BOTTOM | TOP | SAME]    [NOSHOW]

Parameters

WindowName1 [, WindowName2 ...]
Specifies the name of each window to activate. Separate the window names with commas. In Visual FoxPro, you can specify the name of a toolbar to activate. See SHOW WINDOW for a list of Visual FoxPro toolbar names.
ALL
Specifies that all windows are activated. The last window activated is the active output window.
IN [WINDOW] WindowName3
Specifies the name of the parent window within which the window is placed and activated. The activated window becomes a child window. A parent window can have multiple child windows. A child window activated inside a parent window cannot be moved outside the parent window. If the parent window is moved, the child window moves with it.
Note The parent window must be visible for any of its child windows to be visible.
IN SCREEN
Places and activates a window in the main Visual FoxPro window. A window can be placed in a parent window by including IN WINDOW in DEFINE WINDOW when the window is created. Including the IN SCREEN clause in ACTIVATE WINDOW overrides the IN WINDOW clause in DEFINE WINDOW.
BOTTOM | TOP | SAME
Specifies where windows are activated with respect to other previously activated windows. By default, a window becomes the window on top when it is activated. Including BOTTOM places a window behind all other windows. TOP places it in front of all other windows. SAME activates a window without affecting its front-to-back placement.
NOSHOW
Activates and directs output to a window without displaying the window.

Remarks

To successfully use this command on user-defined windows, any target user-defined window must have been created using the DEFINE WINDOW command.

Activating a window makes it the window on top and directs all output to that window. Output can be directed to only one window at a time. A window remains the active output window until it is deactivated or released, or until another window or the main Visual FoxPro window is activated.

The names of user-defined windows appear in the bottom section of the Window menu. The name of the active user-defined window is marked with a check mark.

More than one window can be placed in the main Visual FoxPro window at one time, but output is directed only to the last window activated. When more than one window is open, deactivating the active output window removes it from the main Visual FoxPro window and sends subsequent output to another window. If there is no active output window, output is directed to the main Visual FoxPro window.

Note To ensure output is directed to a specific window when you deactivate the active output window, you must explicitly activate the window you want to send output to with ACTIVATE WINDOW.

All activated windows are displayed until DEACTIVATE WINDOW or HIDE WINDOW is issued to remove them from view. Issuing either command removes windows from view but not from memory. Windows can be redisplayed by issuing ACTIVATE WINDOW or SHOW WINDOW.

To remove windows from view and from memory, use CLEAR WINDOWS, RELEASE WINDOWS, or CLEAR ALL. Windows that are removed from memory must be redefined to place them back in the main Visual FoxPro window.

You can use ACTIVATE WINDOW to place Visual FoxPro system windows in the main Visual FoxPro window or in a parent window.

The following system windows can be opened with ACTIVATE WINDOW:

  • Command
  • Call Stack
  • Debug
  • Debug Output
  • Document View
  • Locals
  • Trace
  • Watch
  • View

To activate a system window and or a toolbar, enclose the entire system window or toolbar name in quotation marks. For example, to activate the Call Stack debugging window in Visual FoxPro, issue the following command:

ACTIVATE WINDOW "Call Stack"

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the ACTIVATE WINDOW command.

Use HIDE WINDOW or RELEASE WINDOW to remove a system window from the main Visual FoxPro window or a parent window.

Example

The following example defines a window named output and activates it, placing it in the main Visual FoxPro window. The WAIT command pauses execution, the window is hidden, and then redisplayed.

CLEAR
DEFINE WINDOW output FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
ACTIVATE WINDOW output
WAIT WINDOW 'Press any key to hide window output'
HIDE WINDOW output
WAIT WINDOW 'Press any key to show window output'
SHOW WINDOW output
WAIT WINDOW 'Press any key to release window output'
RELEASE WINDOW output

See Also

CLEAR WINDOWS | DEACTIVATE WINDOW | DEFINE WINDOW | HIDE WINDOW | RELEASE WINDOWS | SHOW WINDOW


ADD CLASS Command

Adds a class definition to a .vcx visual class library.

ADD CLASS ClassName [OF ClassLibraryName1] TO ClassLibraryName2
   [OVERWRITE]

Parameters

ClassName
Specifies the name of the class definition added to the .vcx visual class library ClassLibraryName2.

If you omit the optional OF ClassLibraryName1 clause, Visual FoxPro searches for the class definition in any .vcx visual class libraries opened with SET CLASSLIB.

Visual FoxPro generates an error if the class definition cannot be located or a class definition with the name you specify already exists in ClassLibraryName2.

OF ClassLibraryName1
Specifies a .VCX visual class library from which the class definition is copied.
TO ClassLibraryName2
Specifies the .vcx visual class library to which the class definition is added. If you specify a .vcx visual class library that does not exist, Visual FoxPro creates the visual class library and adds the class definition to the library.
OVERWRITE
Specifies that a class definition with the same name as the class definition you specify with ClassName is overwritten. An error message is generated if you omit OVERWRITE and a class definition with the same name as ClassName already exists in the .vcx visual class library.

Remarks

Use ADD CLASS to add a class definition to a class library, or to copy a class definition from one .vcx visual class library to another. A class definition cannot be added from a Visual FoxPro program or application (.prg or .app), or a procedure file.

See Also

ACLASS( ) | AMEMBERS( ) | CREATE CLASS | CREATE CLASSLIB | DEFINE CLASS | MODIFY CLASS | RELEASE CLASSLIB | REMOVE CLASS | RENAME CLASS | SET CLASSLIB


ADD TABLE Command

Adds a free table to the current database.

ADD TABLE TableName | ?   [NAME LongTableName]

Parameters

TableName
Specifies the name of the table added to the database.
?
Displays the Open dialog box from which you can choose a table to add to the database.
NAME LongTableName
Specifies a long name for the table. Long names can contain up to 128 characters and can be used in place of short file names that have a .DBF extension.

Remarks

After the table is added to the database, you can perform the same operations on it as you can on any other table.

Once the table is added to the database, it is no longer free. However, any table in the database can be made free by issuing REMOVE TABLE.

The table you are adding:

  • Must be a valid .DBF file.
  • Cannot have the same name as an existing table in the open database, unless you assign the table a unique long name.
  • Cannot exist in another database. Use REMOVE TABLE to remove the table from another database.

The database to which you are adding a table cannot be involved in a transaction.

Example

The following example creates two databases named mydbc1 and mydbc2, and a table named table1. The table is added to mydbc1 when it is created. The table is then closed and removed from mydbc1. ADD TABLE is then used to add the table to mydbc2. RENAME TABLE is used to change the name of the table from table1 to table2.

CREATE DATABASE mydbc1
CREATE DATABASE mydbc2
SET DATABASE TO mydbc1
CREATE TABLE table1 (cField1 C(10), n N(10))  && Adds table to mydbc1
CLOSE TABLES     && A table must be closed to remove it from a database
REMOVE TABLE table1
SET DATABASE TO mydbc2
ADD TABLE table1
RENAME TABLE table1 TO table2

See Also

CLOSE Commands | CREATE DATABASE | DISPLAY TABLES | FREE TABLE | OPEN DATABASE | REMOVE TABLE


ALTER TABLE - SQL Command

Programmatically modifies the structure of a table.

ALTER TABLE TableName1 ADD | ALTER [COLUMN] FieldName1
   FieldType [( nFieldWidth [, nPrecision])] [NULL | NOT NULL] [CHECK lExpression1 [ERROR cMessageText1]]
   [AUTOINC [NEXTVALUE NextValue [STEP StepValue]]] [DEFAULT eExpression1]
   [PRIMARY KEY | UNIQUE [COLLATE cCollateSequence]]
   [REFERENCES TableName2 [TAG TagName1]] [NOCPTRANS] [NOVALIDATE]

-or-

ALTER TABLE TableName1 ALTER [COLUMN] FieldName2 [NULL | NOT NULL] [SET DEFAULT eExpression2]
   [SET CHECK lExpression2 [ERROR cMessageText2]] [ DROP DEFAULT ] [ DROP CHECK ] [ NOVALIDATE ]

-or-

ALTER TABLE TableName1 [DROP [COLUMN] FieldName3]
   [SET CHECK lExpression3 [ERRORcMessageText3]] [DROP CHECK]
   [ADD PRIMARY KEY eExpression3 [FOR lExpression4] TAG TagName2
   [COLLATE cCollateSequence]] [DROP PRIMARY KEY]
   [ADD UNIQUE eExpression4 [[FOR lExpression5] TAG TagName3
   [COLLATE cCollateSequence]]] [DROP UNIQUE TAG TagName4]
   [ADD FOREIGN KEY [eExpression5] [FOR lExpression6] TAG TagName4
   [COLLATE cCollateSequence] REFERENCES TableName2 [TAG TagName5]]
   [DROP FOREIGN KEY TAG TagName6 [SAVE]] [RENAME COLUMN FieldName4 TO FieldName5] [NOVALIDATE]

Parameters

ALTER TABLE TableName1
Modifies the structure of a table. The TableName1 parameter specifies the name of the table to be modified.
ADD | ALTER [COLUMN] FieldName1
Specifies the name of the field to add or modify.

A single table can contain up to 255 fields. If one or more fields allow null values, the limit decreases by one field to 254 fields.

Using ALTER COLUMN resets the collating sequence to the default. You should index the table again with the desired collating sequence after performing ALTER COLUMN. You can also use the COLLATE clause in the ALTER TABLE command when appropriate (primary key or foreign key).

FieldType [(nFieldWidth [, nPrecision])]
Specifies the field type, field width, and field precision (number of decimal places) for the new or modified field.

FieldType is a single letter indicating the field's data type. Some field data types require that you specify nFieldWidth or nPrecision, or both. The following table lists the values for FieldType and whether nFieldWidth and nPrecision are required:

FieldType | nFieldWidth | nPrecision | Data type
C N – Character field of width n
D – – Date
T – – DateTime
N | N | D | Numeric field of width n with d decimal places
F | N | D | Floating numeric field of width n with d decimal places
I – – Integer
B – D Double
Y – – Currency
L – – Logical
M – – Memo
G – – General
P – – Picture

The nFieldWidth and nPrecision parameters are ignored for D, T, I, Y, L, M, G, and P types. The nPrecision parameter defaults to zero (no decimal places) if nPrecision is not included for the N, F, or B types.

NULL | NOT NULL
Specifies whether null values are allowed in the field. NULL permits null values, while NOT NULL does not allow null values. If one or more fields can contain null values, the maximum number of fields the table can contain is reduced from 255 to 254.
CHECK lExpression1
Specifies a validation rule for the field. The lExpression1 parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure. Visual FoxPro checks the validation rule specified in the CHECK clause when a blank record is appended.
ERROR cMessageText1
Specifies an error message. Visual FoxPro displays this message when the validation rule specified with the CHECK clause generates an error. The message displays only when data is changed within a Browse window or Edit window.
AUTOINC [NEXTVALUE NextValue [STEP StepValue]]
Enables automatic incrementing for the field. NextValue specifies the start value and can be a positive or a negative integer value ranging from 2,147,483,647 to -2,147,483,647. The default value is 1. You can set NextValue using the Next Value spin box in Fields tab of the Table Designer.

StepValue specifies the increment value for the field and can be a positive, nonzero integer value ranging from 1 to 255. The default value is 1. You can set StepValue using the Step spin box in the Fields tab of the Table Designer.

Autoincrementing values cannot be NULL.

Note Tables containing automatically incrementing field values append table-buffered records approximately 35% slower than tables without automatically incrementing field values, which might affect performance. When using table buffering, the table header is locked when the record is appended.
DEFAULT eExpression1
Specifies a default value for the field specified in FieldName1. The data type of eExpression1 must be the same as the data type for the field.

You cannot specify a default value if you use the AUTOINC clause to turn on autoincrementing for a field. Visual FoxPro generates an error message if you specify values for both the AUTOINC and DEFAULT clauses.

PRIMARY KEY | UNIQUE
PRIMARY KEY creates a primary index for the field specified in FieldName1. UNIQUE creates a candidate index for the field specified in FieldName1. The primary index tag or candidate index tag has the same name as the field. For more information about primary and candidate indexes, see Setting a Primary or Candidate Index.
COLLATE cCollateSequence
Specifies a collation sequence other than the default setting, MACHINE. The cCollateSequence parameter must be a valid Visual FoxPro collation sequence. For more information about setting collation sequences, see Optimization of International Applications and SET COLLATE Command.
REFERENCES TableName2 [TAG TagName1]
Specifies the parent table to which a persistent relationship is established. The parent table cannot be a free table.

The TagName1 parameter clause specifies an index tag name for the parent table in TableName2. Index tag names can contain up to 10 characters. If you omit the TAG clause, the relationship is established using the primary index key of the parent table. If the parent table does not have a primary index, Visual FoxPro generates an error.

NOCPTRANS
Prevents translation to a different code page for character and memo fields. You can specify NOCPTRANS only for character and memo fields. This creates what appears to be Character (binary) and Memo (binary) data types in the Table Designer.
NOVALIDATE
Specifies that Visual FoxPro allows changes to the table structure that can violate the data integrity of the table. By default, Visual FoxPro prevents ALTER TABLE from making such changes to the table structure. To override the default behavior, include the NOVALIDATE option.
ALTER [COLUMN] FieldName2
Specifies the name of a field to modify. You need to include multiple ALTER COLUMN clauses to change more than one property of a field in a single ALTER TABLE command. For more information about how ALTER COLUMN clauses are structured, see the examples in this topic.
SET DEFAULT eExpression2
Specifies a new default value for an existing field. The data type of eExpression2 must be the same as the data type for the field.

You cannot specify a default value if you use the AUTOINC clause to turn on autoincrementing for a field. Visual FoxPro generates an error message if you specify values for both the AUTOINC and SET DEFAULT clauses.

SET CHECK lExpression2
Specifies a new validation rule for an existing field. The lExpression2 parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure.
ERROR cMessageText2
Specifies an error message for the field validation rule in lExpression2. Visual FoxPro displays this message when the field validation rule generates an error. The message displays only when data is changed within a Browse window or Edit window.
DROP DEFAULT
Removes the default value for an existing field.
DROP CHECK
Removes the validation rule for an existing field.
DROP [COLUMN] FieldName3
Specifies a field to remove from the table. Removing a field from the table also removes the field's default value setting and field validation rule.

If index key or trigger expressions reference the field, the expressions become invalid when the field is removed. In this case, an error is not generated when the field is removed, but the invalid index key or trigger expressions generate errors at run time.

SET CHECK lExpression3
Specifies the table validation rule. The lExpression3 parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure.
ERROR cMessageText3
Specifies an error message for the table validation rule in lExpression3. Visual FoxPro displays this message when the table validation rule generates an error. The message displays only when data is changed within a Browse window or Edit window.
DROP CHECK
Removes the table validation rule.
ADD PRIMARY KEY eExpression3 [FOR lExpression4] TAG TagName2
Adds a primary index to the table. The eExpression3 specifies the primary index key expression.

You can use lExpression4 to specify a filter expression where only records that satisfy the condition are available for display and access. Primary index keys are created in the index file just for those records that match the filter expression. You should avoid using the FOR clause to create a primary index; the uniqueness of a primary key is enforced only for those records that match the condition specified in the FOR clause. Instead, use the INDEX command with a FOR clause to create a filtered index.

Rushmore Query Optimization optimizes an ALTER TABLE ... FOR lExpression4 command if the lExpression4 expression can be optimized. For the best performance, use an optimizable expression in the FOR clause. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

The TagName2 parameter specifies the name of the primary index tag. Index tag names can contain up to 10 characters. If you omit TAG TagName2, and eExpression3 is a single field, the primary index tag has the same name as the field specified in eExpression3.

DROP PRIMARY KEY
Removes the primary index and its index tag. A table can have only one primary key, so you do not need to specify the name of the primary key. Removing the primary index also deletes any persistent relations based on the primary key.
ADD UNIQUE eExpression4 [TAG TagName3 [FOR lExpression5]]
Adds a candidate index to the table. The eExpression4 parameter specifies the candidate index key expression. The TagName3 parameter specifies the name of the candidate index tag. Index tag names can contain up to 10 characters. If you omit TAG TagName3, and if eExpression4 is a single field, the candidate index tag has the same name as the field specified in eExpression4.

You can use the lExpression5 parameter to specify a filter expression where only records that satisfy the condition are available for display and access. Candidate index keys are created in the index file just for those records that match the filter expression.

Rushmore optimizes an ALTER TABLE ... FOR lExpression5 command if the lExpression5 expression can be optimized. For the best performance, use an optimizable expression in the FOR clause. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

DROP UNIQUE TAG TagName4
Removes the candidate index and its index tag. A table can have multiple candidate keys, so you must specify the name of the candidate index tag.
ADD FOREIGN KEY [eExpression5] TAG TagName4 [FOR lExpression6]
Adds a foreign (non-primary) index to the table. The eExpression5 parameter specifies the foreign index key expression. The TagName4 parameter specifies the name of the foreign index tag. Index tag names can contain up to 10 characters.

You can use the lExpression6 parameter to specify a filter expression where only records that satisfy the condition are available for display and access. Foreign index keys are created in the index file just for those records that match the filter expression.

Rushmore optimizes an ALTER TABLE ... FOR lExpression6 command if the lExpression6 expression can be optimized. For the best performance, use an optimizable expression in the FOR clause. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

REFERENCES TableName2 [TAG TagName5]
Specifies the parent table to which a persistent relationship is established. You can use the TAG TagName5 clause to establish a relationship based on an existing index tag for the parent table. Index tag names can contain up to 10 characters. If you omit the TAG clause, Visual FoxPro establishes the relationship using the parent table's primary index tag.
DROP FOREIGN KEY TAG TagName6 [SAVE]
Deletes a foreign key whose index tag is TagName6. You can use SAVE to keep the index tag in the structural index. If you omit SAVE, the index tag is deleted from the structural index.
RENAME COLUMN FieldName4 TO FieldName5
Makes it possible for you to change the name of a field in the table. The FieldName4 parameter specifies the name of the field to be renamed. The FieldName5 paramter specifies the new name of the field.
Caution Exercise care when renaming table fields because index expressions, field and table validation rules, commands, functions, and so on might refer to the original field names.

Remarks

You can use ALTER TABLE to modify the structure of a table that has not been added to a database. However, Visual FoxPro generates an error if you include the DEFAULT, FOREIGN KEY, PRIMARY KEY, REFERENCES, or SET clauses when modifying a free table.

ALTER TABLE might rebuild the table by creating a new table header and appending records to the table header. For example, changing the type or width of a field can cause the table to rebuild.

After a table is rebuilt, field validation rules are executed for any fields whose type or width is changed. If you change the type or width of any field in the table, the table rule is executed.

If you modify field or table validation rules for a table that has records, Visual FoxPro tests the new field or table validation rules against the existing data and issues a warning on the first occurrence of a field or table validation rule or of a trigger violation.

You cannot specify a value or expression in the DEFAULT clause if you turn on autoincrementing for a field.

To remove autoincrementing, use ALTER TABLE - SQL to change COLUMN but do not include the AUTOINC clause.

Field validation should remain enabled for autoincrementing fields. You might want to use validation to return a new autoincrementing value.

When you change a table that does not contain an autoincrementing field to include one, either by using ALTER TABLE or the Table Designer, autoincrementing begins with the next added row. Previous rows in the table are not updated with autoincrementing values starting with the first record. You need to make sure that no conflicts occur as a result.

ALTER TABLE might not produce consistent results when used with Visual FoxPro cursors created by the CREATE CURSOR command. In particular, you can create a Visual FoxPro cursor with features, such as long field names, that are normally available only with tables that are part of a database container. ALTER TABLE saves a temporary copy of the cursor, so the rules that apply to free tables also apply, and any features requiring database support are lost or changed in an unpredictable manner. Therefore, you should generally avoid using ALTER TABLE with Visual FoxPro cursors unless you have tested and understood the outcome.

If you omit NULL and NOT NULL, the current setting of the SET NULL command determines if null values are allowed in the field. However, if you omit NULL and NOT NULL but include the PRIMARY KEY or UNIQUE clause, Visual FoxPro disregards the current setting of SET NULL, and the field defaults to NOT NULL.

Visual FoxPro generates an error if the validation rule specified in the CHECK clause does not allow for a blank field value in an appended record.

Null values and duplicate records are not permitted in a field used for a primary or candidate index. If you are creating a new field using ADD COLUMN, Visual FoxPro does not generate an error if you create a primary or candidate index for a field that supports null values. However, Visual FoxPro generates an error if you attempt to enter a null or duplicate value into a field used for a primary or candidate index.

Note Candidate indexes, created by including the UNIQUE option (provided for ANSI compatibility) in CREATE TABLE – SQL or ALTER TABLE – SQL commands, are not the same as indexes created in the INDEX command with the UNIQUE option. An index created in the INDEX command using the UNIQUE option allows duplicate index keys; candidate indexes do not allow duplicate index keys. For more information about the UNIQUE option in the INDEX command, see INDEX Command.

If you modify an existing field, and the primary index expression or candidate index expression consists of fields in the table, Visual FoxPro checks the fields to see if they contain null values or duplicate records. If they do, Visual FoxPro generates an error and the table is not altered.

If the table is converted to another code page, the fields for which NOCPTRANS has been specified are not translated.

Example

Example 1 adds a field called Fax to a Customer table and allows the field to have null values.

Example 2 makes the Cust_id field the primary key of the Customer table.

Example 3 adds a field validation rule to the Quantity field of the Orders table so that values in the Quantity field must be non-negative.

Example 4 adds a one-to-many persistent relation between the Customer and Orders tables based on the primary key Cust_id in the Customer table and a new foreign key index Cust_id in the Orders table.

Example 5 removes the field validation rule from the Quantity field in the Orders table.

Example 6 removes the persistent relation between the Customer and Orders tables, but keeps the Cust_id index tag in the Orders table.

Example 7 adds a field called Fax2 to the Customer table and prevents the field from containing null values. The new structure of the table is displayed. Two ALTER COLUMN clauses are used to allow the field to have null values and set the default value for the field to the null value. Note that multiple ALTER COLUMN clauses are required to change more than one property of a field in a single ALTER TABLE command. The new field is then removed from the table to restore the table to its original state.

* Example 1
SET PATH TO (HOME(2) + 'Data\')     && Sets path to table.
ALTER TABLE Customer ADD COLUMN Fax c(20) NULL

* Example 2
ALTER TABLE Customer ADD PRIMARY KEY Cust_id TAG Cust_id
ALTER TABLE Customer ALTER COLUMN Cust_id c(5) PRIMARY KEY

* Example 3
ALTER TABLE Orders;
    ALTER COLUMN Quantity SET CHECK Quantity >= 0;
    ERROR "Quantities must be non-negative"

* Example 4
ALTER TABLE Orders;
   ADD FOREIGN KEY Cust_id TAG Cust_id REFERENCES Customer

* Example 5
ALTER TABLE Orders ALTER COLUMN Quantity DROP CHECK

* Example 6
ALTER TABLE Orders DROP FOREIGN KEY TAG Cust_id SAVE

* Example 7
CLEAR
ALTER TABLE Customer ADD COLUMN Fax2 c(20) NOT NULL
DISPLAY STRUCTURE
ALTER TABLE Customer;
   ALTER COLUMN Fax2 NULL;
   ALTER COLUMN Fax2 SET DEFAULT .NULL.
ALTER TABLE Customer DROP COLUMN Fax2

The following example uses NOCPTRANS to prevent translation to a different code page. The example creates a table named "mytable" that contains two character fields and two memo fields. The second character field, "char2", and the second memo field, "memo2", include NOCPTRANS to prevent translation.

CREATE TABLE mytable (char1 C(10), char2 C(10) NOCPTRANS,;
   memo1 M, memo2 M NOCPTRANS)

See Also

Commands | Autoincrementing Field Values in Tables | AFIELDS( ) Function | CREATE TABLE - SQL | INDEX | MODIFY STRUCTURE | OPEN DATABASE | SET OPTIMIZE | Using Rushmore Query Optimization to Speed Data Access


APPEND Command

Adds one or more new records to the end of a table.

APPEND [BLANK] [IN nWorkArea | cTableAlias] [NOMENU]

Parameters

BLANK
Adds one blank record to the end of the current table. Visual FoxPro does not open an editing window when you issue APPEND BLANK.

You can edit the new record with BROWSE, CHANGE, or EDIT.

IN nWorkArea
Specifies the work area of the table to which a new record is appended.
IN cTableAlias
Specifies the alias of the table to which a new record is appended.

If you omit nWorkArea and cTableAlias, a new record is appended to the table in the currently selected work area. If you issue APPEND, a blank record is added to the table you specify with nWorkArea or cTableAlias and the table is automatically selected. If you issue APPEND BLANK, a blank record is added to the table you specify with nWorkArea or cTableAlias and the table is not selected.

NOMENU
Specifies that the Table menu title is removed from the system menu bar, preventing changes to the format of the editing window.

Remarks

When you issue APPEND or APPEND BLANK and a table isn't open in the currently selected work area, the Open dialog appears so that you can choose a table to which you can append records.

APPEND opens an editing window so you can enter data into one or more new records. When you add a new record, Visual FoxPro updates any indexes that are open.

Example

The following example uses APPEND BLANK to create a table with 10 records containing random values, then displays the maximum and minimum values in the table.

CLOSE DATABASES
CREATE TABLE Random (cValue N(3))
FOR nItem = 1 TO 10  && Append 10 records
   APPEND BLANK
   REPLACE cValue WITH 1 + 100 * RAND( )  && Insert random values
ENDFOR

CLEAR
LIST  && Display the values
gnMaximum = 1  && Initialize minimum value
gnMinimum = 100  && Initialize maximum value
SCAN
   gnMinimum = MIN(gnMinimum, cValue)
   gnMaximum = MAX(gnMaximum, cValue)
ENDSCAN
? 'The minimum value is: ', gnMinimum  && Display minimum value
? 'The maximum value is: ', gnMaximum  && Display maximum value

See Also

APPEND FROM ARRAY | BROWSE | CHANGE | EDIT | INSERT - SQL | REPLACE


APPEND FROM ARRAY Command

Adds one record to the currently selected table for each row in an array and fills each record with data from the corresponding array row.

APPEND FROM ARRAY ArrayName [FOR lExpression]
   [FIELDS FieldList | FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton]

Parameters

ArrayName
Specifies the name of the array that contains the data to be copied to the new records. New records are added to the table until all rows in the array are appended.
FOR lExpression
Specifies a condition for appending records from the array. lExpression must contain the name of a target field in its conditional expression.

Before a row of the array is appended to a record in the table, the array element corresponding to the target field specified in lExpression is checked to determine whether that array element meets the condition in lExpression. If the array element satisfies the condition, a record is appended.

If the array element does not satisfy the condition, the array row is not appended and the next row in the array is checked to determine whether it meets the condition.

FIELDS FieldList
Specifies that only the fields in FieldList are updated from the array. The first field in the list is updated with the contents of the first element in the array, the second field is updated from the second element, and so on.
FIELDS LIKE Skeleton
Specifies that fields that match the field skeleton Skeleton are updated from the array.
FIELDS EXCEPT Skeleton
Specifies that all fields except those that match the field skeleton Skeleton are updated from the array.

The field skeleton Skeleton supports wildcards. For example, to specify that all fields that begin with the letters A and P are updated from the array, use the following:

APPEND FROM ARRAY aMyArray FIELDS LIKE A*,P*

The LIKE clause can be combined with the EXCEPT clause:

APPEND FROM ARRAY aMyArray FIELDS LIKE A*,P* EXCEPT PARTNO*

Remarks

Memo and general fields are ignored in APPEND FROM ARRAY. When a table is open for shared use, APPEND FROM ARRAY locks the table header while records are being added.

If the array is one-dimensional, APPEND FROM ARRAY adds one record to the table. The contents of the first array element fill the first field of the newly added record, the contents of the second element of the array fill the second field of the record, and so on.

If the one-dimensional array has more elements than the table has fields, the additional elements are ignored. If the table has more fields than the array has elements, the additional fields are initialized to the default empty value. Here are the default empty values for each field type:

Field type | Default value
Character | Spaces
Numeric | 0
Currency | 0
Float | 0
Integer | 0
Double | 0
Date | Empty Date (e.g. CTOD(""))
DateTime | Empty DateTime (e.g. CTOT(""))
Logical | False (.F.)
Memo | Empty (no contents)

If the array is two-dimensional, APPEND FROM ARRAY adds a new record to the table for each row in the array. For example, if the array has four rows, four new records are appended to the table.

The contents of the first array column fill the first field of the newly added records, the second array column fills the second field of the new records, and so on. For example, if the array has four rows and three columns, elements from the first array column fill the first field in each of the four new records appended to the table.

If the two-dimensional array has more columns than the table has fields, the additional columns are ignored. If the table has more fields than the array has columns, the additional fields are initialized to empty values.

APPEND FROM ARRAY can fill a field even if the data type of the corresponding array element doesn't match the data type of the field, provided that the array element data is compatible with the data type of the corresponding field. If the data isn't compatible, the field is initialized to an empty value.

Example

This example creates a table and then uses APPEND FROM ARRAY to append a record to the new table.

LOCAL ARRAY aNewRec(3)

* Create the table
CREATE TABLE Test FREE  (Object C(10), Color C(16), SqFt n(6,2))
SCATTER TO aNewRec BLANK  && Create a new array from the table
aNewRec[1]="Box"         && Fill the array
aNewRec[2]="Red"
aNewRec[3]=12.5
APPEND FROM ARRAY aNewRec   && Add record containing array contents
          && to the table

See Also

APPEND | COPY TO ARRAY | DIMENSION | GATHER | SCATTER


APPEND FROM Command

Adds records to the end of the currently selected table from another file.

APPEND FROM FileName | ?   [FIELDS FieldList] [FOR lExpression]
   [[TYPE] [DELIMITED [WITH Delimiter | WITH BLANK | WITH TAB
      | WITH CHARACTER Delimiter] | DIF | FW2 | MOD | PDOX | RPD |
      SDF | SYLK | WK1 | WK3 | WKS | WR1 | WRK | CSV | XLS | XL5
      [SHEET cSheetName] | XL8 [SHEET cSheetName]]] [AS nCodePage]

Parameters

FileName
Specifies the name of the file to append from. If you don't include a file name extension, a Visual FoxPro table and a default extension .dbf is assumed. If you are appending from a Visual FoxPro table, records in the table that are marked for deletion are appended if the current SET DELETED setting is OFF.
?
Displays the Open dialog box, from which you can choose a table to append from.
FIELDS FieldList
Specifies to which fields data is appended.
FOR lExpression
Appends a new record for each record in the currently selected table for which lExpression evaluates to True (.T.). Records are appended until the end of the currently selected table is reached. If you omit FOR, the entire source file is appended to the currently selected table.
TYPE
Specifies the source file type of the file you are appending from. Although you must specify a file type if the file you are appending from isn't a Visual FoxPro table, you need not include the TYPE key word. You can append from a wide variety of different file types including delimited ASCII text files, in which you can specify a field delimiter.

If the source file you are appending from doesn't have the usual default file extension for that type of file, the source file name must include the file's extension. For example, Microsoft Excel worksheets normally have an .xls extension. If the Microsoft Excel worksheet you append from has an extension other than the expected .xls, be sure to specify the extension.

Note When you are appending from a worksheet, the data in the worksheet must be stored in a row-major order rather than a column-major order. This allows the appended worksheet data to match the table structure.
DELIMITED
Specifies that the source file from which data is appended to the current Visual FoxPro table is a delimited file. A delimited file is an ASCII text file in which each record ends with a carriage return and line feed. Field contents are by default assumed to be separated from each other by commas (do not include extra spaces before or after the commas), and character field values to be additionally delimited by double quotation marks. For example:
"Smith",9999999,"TELEPHONE"

The file extension is assumed to be .txt for all delimited files.

You can import dates from delimited files if the dates are in proper date format. The date format defaults to mm/dd/yy. Including the century portion of a date is optional. Visual FoxPro will import a date, such as 12/25/95, that doesn't include the century and assumes the date is in the twentieth century. Date delimiters can be any non-numeric character except the delimiter that separates the fields in the delimited file.

Dates in other formats can be imported if their formats match date formats available in SET DATE. To import dates that are not in the default format, issue SET DATE with the proper date format before using APPEND FROM. To test whether a date format can be successfully imported, use it with CTOD( ). If the date is acceptable to CTOD( ), the date will import properly.

DELIMITED WITH Delimiter
Indicates that character fields are separated by a character other than the quotation mark.
DELIMITED WITH BLANK
Specifies files that contain fields separated by spaces instead of commas.
DELIMITED WITH TAB
Specifies files that contain fields separated by tabs rather than commas.
DELIMITED WITH CHARACTER Delimiter
Specifies files that contain fields all enclosed by the character specified with Delimiter. If Delimiter is a semicolon (the character used in Visual FoxPro to indicate command line continuation), enclose the semicolon in quotation marks. You can also specify the BLANK and TAB keywords for Delimiter.

The WITH Delimiter clause can be combined with the WITH CHARACTER clause. For example, the following command adds records from a text file with character fields enclosed by underscores and all fields delimited from each other with asterisks:

APPEND FROM mytxt.txt DELIMITED WITH _ WITH CHARACTER *
DIF
Include DIF to import data from a VisiCalc .dif (Data Interchange Format) file. Vectors (columns) become fields in the currently selected table and tuples (rows) become records. DIF file names are assumed to have a .dif extension.
FW2
Include FW2 to import data from a file created by Framework II. FW2 file names are assumed to have a .fw2 extension.
MOD
Include MOD to import data from a Microsoft Multiplan version 4.01 file. MOD files are created by Microsoft Multiplan version 4.01, and are assumed to have a .mod extension.
PDOX
Include PDOX to import data from a Paradox version 3.5 or 4.0 database file. Paradox file names are assumed to have a .db extension.
RPD
Include RPD to import data from a file created by RapidFile version 1.2. RapidFile file names are assumed to have an .rpd extension.
SDF
Include SDF to import data from a System Data Format file. An SDF file is an ASCII text file in which records have a fixed length and end with a carriage return and line feed. Fields are not delimited. The file name extension is assumed to be .txt for SDF files.

Effective conversion of date data from SDF files to Visual FoxPro tables requires data to be stored in YYYYMMDD format.

If date information is stored in ambiguous formats, you should map the date column to a character column of appropriate width so you can inspect the value then apply the correct conversion routine to create correctly formatted date data.

SYLK
Include SYLK to import data from a SYLK (Symbolic Link) interchange format file. SYLK files are used in Microsoft MultiPlan. Columns in the SYLK file become fields in the Visual FoxPro table and rows become records. SYLK file names have no extension.
WK1
Include WK1 to import data from a Lotus 1-2-3 version 2.x spreadsheet. Each column from the spreadsheet becomes a field in the table; each spreadsheet row becomes a record in the table. A .WK1 file name extension is assigned to a spreadsheet created in Lotus 1-2-3 revision 2.x.
WK3
Include WK3 to import data from a Lotus 1-2-3 spreadsheet. Each column from the spreadsheet becomes a field in the table; each spreadsheet row becomes a record in the table. A .wk3 file name extension is assigned to a spreadsheet created in Lotus 1-2-3 revision 3.x.
WKS
Include WKS to import data from a Lotus 1-2-3 revision 1-A spreadsheet. Each column from the spreadsheet becomes a field in the table; each spreadsheet row becomes a record in the table. A .wks file name extension is assigned to a spreadsheet created in Lotus 1-2-3 revision 1-A.
WR1
Include WR1 to import data from a Lotus Symphony version 1.1 or 1.2 spreadsheet. Each column from the spreadsheet becomes a field in the table and each spreadsheet row becomes a record in the table. A .wr1 file name extension is assigned to a spreadsheet created in Symphony versions 1.1 or 1.2.
WRK
Include WRK to import data from a Lotus Symphony version 1.0 spreadsheet. Each column from the spreadsheet becomes a field in the table and each spreadsheet row becomes a record in the table. A .wrk file name extension is assigned to a spreadsheet created in Symphony version 1.0.
CSV
Include CSV to import data from a comma separated value file. A CSV file has field names as the first line in the file; the field names are ignored when the file is imported.
XLS
Include XLS to import data from a Microsoft Excel worksheet. Each column from the worksheet becomes a field in the table and each worksheet row becomes a record in the table. Worksheet files created in Microsoft Excel are given an .xls file name extension.
XL5
Include XL5 to import data from Microsoft Excel version 5.0. Columns from the worksheet become fields in the table; the worksheet rows become records in the table. Worksheet files created in Microsoft Excel have an .xls extension.

If you omit the SHEET clause, the data in Sheet1 is imported. To import data from a specific sheet, include the SHEET keyword and specify the sheet name with cSheetName.

XL8
Include XL8 to import data from Microsoft Excel 97. Columns from the worksheet become fields in the table; the worksheet rows become records in the table. Worksheet files created in Microsoft Excel have an .xls extension.

If you omit the SHEET clause, the data in Sheet1 is imported. To import data from a specific sheet, include the SHEET keyword and specify the sheet name with cSheetName.

AS nCodePage
Specifies the code page of the source table or file. Visual FoxPro copies the contents of the source table or file and, as it copies the data, automatically converts the data to the code page of the current table.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, making it possible for you to specify a code page for the appended table or file.

If you omit AS nCodePage and Visual FoxPro cannot determine the code page of the source table or file, Visual FoxPro copies the contents of the source table or file. As it copies the data, it automatically converts the data to the current Visual FoxPro code page. If SET CPDIALOG is ON, the table in the currently selected work area is marked with a code page. If you're appending from a table not marked with a code page, the Code Page dialog is displayed, making it possible for you to choose the code page of the table from which you're appending. The current Visual FoxPro code page can be determined with CPCURRENT( ).

If you omit AS nCodePage and Visual FoxPro can determine the code page of the table or file being appended, Visual FoxPro copies the contents of the appended table or file. As it copies the data, it automatically converts the data to the code page of the currently selected table.

If nCodePage is 0, Visual FoxPro assumes that the code page of the table or file being appended is the same as the code page of the currently selected table. No conversion to the current Visual FoxPro code page occurs.

Remarks

If the file from which you append is a Visual FoxPro table or a table created in an earlier version of FoxPro, a .dbf extension is assumed. If the Visual FoxPro table or the table created in an earlier version of FoxPro doesn't have a .dbf extension, you must specify its extension. If the file is not a Visual FoxPro table or a table created in an earlier version of FoxPro, you must specify the type of file from which you append.

Before you can append from a table created in dBASE IV or dBASE V that contains a memo field, you must first open the table in Visual FoxPro with USE. When you are prompted to convert the file, choose Yes.

If you append from a Visual FoxPro table or a table created in an earlier version of FoxPro, the table you append from can be open in another work area. Records marked for deletion in the table you are appending from are unmarked once the records are appended.

Use the DBF( ) function to append from a temporary read-only cursor created by a SELECT - SQL command. Include the name of the cursor in the DBF( ) function as in the following example:

APPEND FROM DBF('<Cursor Name>')

If the target table uses autoincrementing, APPEND FROM fails if AUTOINCERROR is set to ON, unless the FIELDS option is used to omit the AUTOINC column. Setting AUTOINCERROR to OFF or turning off autoincrementing in the target table by using CURSORSETPROP( ) allows the APPEND FROM to succeed. The target table's autoincrementing field or fields are incremented according to the values specified, and the values in source table are not applied.

Example

In the following example, the customer table is opened, its structure is copied to a table called backup, and backup is then opened. Visual FoxPro then appends all records from Finland from the customer table. These records are then copied to a new delimited file called TEMP.TXT.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Open customer table
COPY STRUCTURE TO backup
USE backup
APPEND FROM customer FOR country = 'Finland'
COPY TO temp TYPE DELIMITED
MODIFY FILE temp.txt
USE
DELETE FILE backup.dbf
DELETE FILE temp.txt

See Also

COPY FILE | COPY TO | EXPORT | GETCP( ) | IMPORT | SET DELETED


APPEND GENERAL Command

Imports an OLE object from a file and places it into a general field.

APPEND GENERAL GeneralFieldName [FROM FileName]
   [DATA cExpression] [LINK] [CLASS OLEClassName]

Parameters

GeneralFieldName
Specifies the name of the general field in which the OLE object is placed. You can specify a general field in a table open in a noncurrent work area by including the table alias with the field name.
FROM FileName
Specifies the file containing the OLE object. You must include the entire file name, including its extension. If the file is located in a directory other than the current default directory, include the path with the file name.
DATA cExpression
Specifies a character expression that is evaluated and passed as a character string to the OLE object in the general field. The OLE object must be capable of receiving and processing the string. For example, you cannot send a character string to a graphics object such as one created using Paintbrush.
LINK
Creates a link between the OLE object and the file that contains the object. The OLE object appears in the general field but the object's definition remains in the file. If you omit LINK, the OLE object is embedded in the general field.
CLASS OLEClassName
Specifies an OLE class for an OLE object other than the default class.

You can specify a class name when the file extension for the file containing the OLE object is different from the default extension and you want to force the behavior for the class. If the default extension can be used by multiple Automation servers, include the class to specify a particular server.

Remarks

If an OLE object already exists in the general field, it is replaced with the OLE object from the file. To remove an OLE object from a general field, issue APPEND GENERAL GeneralFieldName (GeneralFieldName is the name of the general field to clear) without any additional arguments.

For additional information about OLE objects in Visual FoxPro, see Adding OLE.

Example

The following example imports a Microsoft Excel chart in the Excel directory to a general field named mygenfield.

CREATE TABLE MyGenTbl (mygenfield G)
APPEND BLANK  && Add a blank record
APPEND GENERAL mygenfield FROM C:\EXCEL\BOOK1.XLS CLASS EXCELCHART

See Also

@ ... SAY - Pictures & OLE Objects | MODIFY GENERAL | OLE Bound Control


APPEND MEMO Command

Copies the contents of a text file to a memo field.

APPEND MEMO MemoFieldName FROM FileName[OVERWRITE] [AS nCodePage]

Parameters

MemoFieldName
Specifies the name of the memo field to which the file is appended.
FROM FileName
Specifies the text file whose contents are copied to the memo field. You must include the entire text file name, including its extension.
OVERWRITE
Replaces the current contents of the memo field with the contents of the file.
AS nCodePage
Specifies the code page of the text file copied to the memo field. Microsoft Visual FoxPro copies the contents of the text file and, as it copies the data to the memo field, automatically converts the data from the code page you specify to the code page of the table containing the memo field. If the table containing the memo field is not marked with a code page, Visual FoxPro automatically converts the data from the code page you specify to the current Visual FoxPro code page.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the appended table or file.

If you omit the AS nCodePage clause or specify 0 for nCodePage, no code page conversion occurs for the text file.

Remarks

The entire text file is appended to the contents of the specified memo field in the current record if overwrite is omitted.

Example

In the following example, the contents of the memo field notes are copied to a file called Test.txt. Test.txt is then appended to the contents of the memo field. Finally, the contents of Test.txt replace the current contents of the memo field.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee  && Open Employee table
WAIT WINDOW 'Employee notes memo field - press ESC' NOWAIT
MODIFY MEMO notes NOEDIT  && Open the notes memo field
COPY MEMO notes TO test.txt  && Create test file from memo field
WAIT WINDOW 'TEST.TXT text file - press ESC' NOWAIT
MODIFY FILE test.txt NOEDIT && Open the text file
WAIT WINDOW 'Employee notes now appended - press ESC' NOWAIT
APPEND MEMO notes FROM test.txt  && Add contents of text file
MODIFY MEMO notes NOEDIT  && Display memo field again
WAIT WINDOW 'Overwrite Employee notes- press ESC' NOWAIT
APPEND MEMO notes FROM test.txt OVERWRITE  && Replace notes
MODIFY MEMO notes NOEDIT NOWAIT
DELETE FILE test.txt

See Also

COPY MEMO | GETCP( ) | CLOSE MEMO | SET WINDOW OF MEMO


APPEND PROCEDURES Command

Appends stored procedures in a text file to the stored procedures in the current database.

APPEND PROCEDURES FROM FileName   [AS nCodePage] [OVERWRITE]

Parameters

FileName
Specifies the name of a text file from which the stored procedures are appended.
AS nCodePage
Specifies the code page of the text file from which the stored procedures are appended. Visual FoxPro copies the contents of the text file and, as it does, automatically convert the contents of the text file to the code page you specify.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the text file from which the stored procedures are appended.

If you omit AS nCodePage, Visual FoxPro copies the contents of the text file from which the stored procedures are appended and, as it does so, automatically converts the contents of the text file to the current Visual FoxPro code page. The current Visual FoxPro code page can be determined with CPCURRENT( ).

If nCodePage is 0, Visual FoxPro assumes that the code page of the text file from which the stored procedures are appended is the same as the code page of the current database, and that no conversion to the current Visual FoxPro code page occurs.

OVERWRITE
Specifies that the current stored procedures in the database be overwritten by those in the text file. If you omit OVERWRITE, the current stored procedures in the database are not overwritten, and the stored procedures in the text file are appended to the current stored procedures.

Remarks

APPEND PROCEDURES is not available in a distributed executable file. If your application uses this command, it will generate the error, "Feature is not available." For more information about restricted and distributable Visual FoxPro files, see Distributable and Restricted Visual FoxPro Features and Files

Use APPEND PROCEDURES to programmatically modify stored procedures in a database. A database must be open and current when APPEND PROCEDURES is issued; otherwise Visual FoxPro generates an error message.

Note To view or edit stored procedures through the user interface, use the Database Designer.
CLOSE DATABASES
* Open the testdata database
OPEN DATABASE (HOME(2) + 'Data\testdata')

* Create a free, temporary table with one memo field called mProcedure
CREATE TABLE mytable FREE (mProcedure M)
APPEND BLANK          && Add a blank record to mytable

* Add PROCEDURE command, name, and carriage return/linefeed to
* memo field
REPLACE mProcedure WITH "PROCEDURE MyProcedure" + CHR(13) + CHR(10)

* Copy contents of memo field to temporary file
COPY MEMO mProcedure TO mytemp.txt
USE             && Close the temporary table

APPEND PROCEDURES FROM mytemp.txt   && Copy procedure to the database
CLEAR

* Display the procedures associated with the current database
DISPLAY PROCEDURES
DELETE FILE mytable.dbf     && Erase temporary table
DELETE FILE mytable.fpt     && Erase temporary table memo file
DELETE FILE mytemp.txt      && Erase temporary text file

Example

The following example opens the testdata database. A temporary table named mytable with a single memo field is created, and REPLACE is used to place a stored procedure named MyProcedure in the memo field. COPY MEMO is used to create a temporary text file named Mytemp.txt that contains the contents of the memo field.

APPEND PROCEDURES is used to append the stored procedure from the temporary text file to the database. DISPLAY PROCEDURES displays the stored procedures in the database and then the temporary table and text file are erased.

See Also

COPY PROCEDURES | CREATE TRIGGER | DISPLAY PROCEDURES | MODIFY PROCEDURE | OPEN DATABASE | PROCEDURE | SET DATABASE


ASSERT Command

Displays a message box when a logical expression evaluates to False (.F.).

ASSERT lExpression [MESSAGE cMessageText]

Parameters

lExpression
Specifies the logical expression that is evaluated. If lExpression evaluates to a logical False (.F.), a debugging dialog box is displayed. If lExpression evaluates to a logical True (.T.), the dialog box is not displayed.
cMessageText
Specifies the text displayed in the debugging dialog box. If you omit cMessageText, the default text is displayed, indicating the line number on which the assertion failed and procedure containing the assertion.

Remarks

This command is ignored if the SET ASSERTS command is set to OFF.

The message box contains Cancel, Debug, Ignore and Ignore All buttons. The following table describes the action performed when each button is chosen.

Button | Action
Debug | Program execution is suspended and the Debugger window is displayed with the Trace window active.
Cancel | Program execution is ended.
Ignore | Program execution continues with the line following the ASSERT command.
Ignore All | Program execution continues with the line following the ASSERT command and ASSERTS is set to OFF. Subsequent ASSERT commands are ignored until ASSERTS is set to ON.

ASSERT is disregarded in applications you distribute.

See Also

Debugger Window, | SET ASSERTS | Setting Asserts


AVERAGE Command

Computes the arithmetic mean of numeric expressions or fields.

AVERAGE [ExpressionList]   [Scope] [FOR lExpression1] [WHILElExpression2]
   [TO VarList | TO ARRAY ArrayName]   [NOOPTIMIZE]

Parameters

ExpressionList
Specifies the expressions to average. ExpressionList can be a list of fields from the table separated by commas, or numeric expressions involving fields from the table.
Scope
Specifies the record or range of records to include in the average. Only the records that fall within the range of records specified by the scope are averaged. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. The default scope for AVERAGE is ALL records.

Commands that include Scope operate only on the table in the active work area.

FOR lExpression1
Specifies a condition whereby only the records that satisfy the logical condition lExpression are included. This argument allows you to filter out undesired records.

Rushmore Query Optimization optimizes an AVERAGE FOR query if lExpression is an optimizable expression. For best performance, use an optimizable expression in the FOR clause. For information on Rushmore optimizable expressions, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies that as long as the logical expression lExpression2 evaluates to true (.T.), records are included in the average.
TO VarList
Specifies the list of variables or array elements to which the results of the average are stored.
TO ARRAY ArrayName
Specifies the one-dimensional array to which the results of the average are stored. The one-dimensional array can be created before the execution of AVERAGE.

If the array you include in AVERAGE doesn't exist, Visual FoxPro automatically creates it. If the array exists and isn't large enough to contain all the results, Visual FoxPro increases the size of the array automatically to accommodate the information.

NOOPTIMIZE
Disables Rushmore optimization of AVERAGE. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

All numeric fields in the selected table are averaged unless you include an optional expression list. The result is displayed on the screen if SET TALK is ON. If SET HEADINGS is ON, the field names or expression involving the field names are displayed above the results.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE orders  && Open order table

CLEAR
AVERAGE Order_Amt  && Calcuate averages of all orders
AVERAGE Order_Amt TO gnAvg  && Store average to memory variable
? 'Average order amount: '
?? gnAvg  && Display the average again

See Also

CALCULATE | DIMENSION | SET HEADINGS | SUM | Using Rushmore Query Optimization to Speed Data Access | SET OPTIMIZE


BEGIN TRANSACTION Command

Begins a transaction. Transactions are supported only for tables in a database. See CREATE DATABASE and ADD TABLE for information on how to create and add tables to a database.

BEGIN TRANSACTION

Remarks

To save any modifications you made and end the transaction, issue END TRANSACTION. If the transaction fails (the server fails, the workstation fails, or you exit Visual FoxPro without committing the transaction) or if you issue ROLLBACK, the file or files in the transaction are restored to their original state.

Transactions can be nested five levels deep. An error is generated if you attempt a sixth level of nesting.

When you modify records in a table that is part of a transaction, other users on the network do not have access (read or write) to the records until you end the transaction.

When other users on the network try to access records you have modified, they must wait until you end your transaction. They receive the message "Record not available ... please wait" until the records become available. Because of this, it is important to keep the length of the transaction to a minimum or conduct the transaction during times when others do not need access.

All IDX index files (non-structural, or non-CDX based, indexes) must be closed during transactions. Only structural indexes are supported within transactions.

The following commands and functions are not supported during a transaction:

Commands and functions |
ADD TABLE | DELETE CONNECTION
APPEND PROCEDURES | DELETE DATABASE
CLEAR ALL | DELETE TRIGGER
CLOSE ALL1 | DELETE VIEW
CLOSE DATABASES1 | MODIFY CONNECTION
COPY INDEXES | MODIFY DATABASE
COPY PROCEDURES | MODIFY PROCEDURE
CREATE CONNECTION | MODIFY VIEW
CREATE DATABASE | REMOVE TABLE
CREATE TRIGGER | RENAME TABLE
CREATE VIEW | REQUERY( )
CREATE SQL VIEW |

1 If CLOSE ALL is issued while a transaction is in progress, all tables in all open databases are closed. However, the databases remain open. Issuing CLOSE DATABASES within a transaction closes all tables in the current database, but the database remains open.

Also, the following commands and functions cannot be issued for a specific table participating in a transaction:

Commands and functions |
ALTER TABLE | MODIFY STRUCTURE
CREATE TABLE | PACK
CURSORSETPROP( ) | REINDEX
DELETE TAG | TABLEREVERT( )
INDEX | ZAP
INSERT |

Example

In the following example, the customer table in the testdata database is opened. Optimistic table buffering is set for the customer table. The contents of the cust_id and company fields are displayed, and then the contents of the company field are replaced within the buffered data.

BEGIN TRANSACTION is issued to start a transaction. The TABLEUPDATE( ) function is used to write the changes to the table. The new contents are displayed, and ROLLBACK is issued to restore the original contents of the company field. The cust_id and company fields are displayed again with the company field containing its original values.

CLEAR
CLOSE DATABASES

* Transactions are only supported within a DBC
OPEN DATABASE (HOME(2) + 'Data\testdata')

SET MULTILOCKS ON      && Required for buffering

USE customer
=CURSORSETPROP("Buffering",5)
? 'The original company field'
LIST FIELDS cust_id, company NEXT 5
REPLACE ALL company WITH "***" && Change field contents

BEGIN TRANSACTION
   =TABLEUPDATE(.T.)
   GO TOP
   ? 'The modified company field'
   LIST FIELDS cust_id, company NEXT 5
   ROLLBACK           && Restore original field contents

=TABLEREVERT(.T.)
GO TOP
? 'The restored company field'
LIST FIELDS cust_id, company NEXT 5

See Also

END TRANSACTION | ROLLBACK | TXNLEVEL( ) Function


BLANK Command

Clears data from all fields in the current record when issued without additional arguments.

BLANK [FIELDS FieldList] [Scope] [FOR lExpression1] [WHILE lExpression2]
   [NOOPTIMIZE] [IN nWorkArea | cTableAlias]

Parameters

FIELDS FieldList
Clears only the fields you specify with FieldList. If you omit the FIELDS clause, all fields in a record are cleared by default. Any field you specify in an unselected work area must be prefaced with the alias of the work area.
Note BLANK does not clear field data of a record in another related work area if the record pointer is at the end of the file in the current work area. The record pointer must be on a record in the current work area in order for BLANK to act on the fields in the related record.
Scope
Specifies a range of records to clear. The default scope for BLANK is the current record (NEXT 1). Only the records that fall within the range are cleared.

The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

Commands that include the Scope parameter operate only on the table in the active work area.

For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Clears field data in records for which lExpression1 evaluates to true (.T.). Rushmore Query Optimization optimizes BLANK FOR if lExpression1 is an optimizable expression. A discussion of Rushmore Query Optimization appears in Using Rushmore Query Optimization to Speed Data Access.
WHILE lExpression2
Specifies a condition whereby field data in records is cleared as long as the logical expression lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Prevents Rushmore optimization of BLANK. For more information see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.
IN nWorkArea | cTableAlias
Specifies the workarea or table alias affected by the BLANK command. Use this clause to specify a workarea or a table outside the current work area.

Remarks

Use APPEND BLANK to add a new blank record to the end of a table. Use ISBLANK( ) to determine if a field in a record is blank.

Example

The following example opens the customer table in the testdata database. The contents of the first record are displayed. SCATTER is used to save the contents of the record to an array. The record is cleared with BLANK, and the contents of the record are displayed again. GATHER is used to restore the original record contents, and the restored record contents are displayed again.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table

CLEAR
DISPLAY  && Displays the current record
SCATTER TO gaCustomer  && Create array with record contents
BLANK  && Clear the record
DISPLAY  && Displays the blank record
GATHER FROM gaCustomer  && Restore original record contents
DISPLAY  && Display the restored record

See Also

APPEND | EMPTY( ) | ISBLANK( ) | REPLACE | SET OPTIMIZE | Using Rushmore Query Optimization to Speed Data Access


BROWSE Command

Opens the Browse window and displays records from the current or selected table.

BROWSE [FIELDS FieldList] [FONT cFontName [, nFontSize]]
   [STYLE cFontStyle] [FOR lExpression1 [REST]] [FORMAT]
   [FREEZE FieldName] [KEY eExpression1 [, eExpression2]] [LAST | NOINIT]
   [LOCK nNumberOfFields] [LPARTITION] [NAME ObjectName] [NOAPPEND]
   [NOCAPTIONS] [NODELETE] [NOEDIT | NOMODIFY] [NOLGRID] [NORGRID]
   [NOLINK] [NOMENU] [NOOPTIMIZE] [NOREFRESH] [NORMAL] [NOWAIT]
   [PARTITION nColumnNumber [LEDIT] [REDIT]]
   [PREFERENCE PreferenceName] [SAVE] [TIMEOUT nSeconds]
   [TITLE cTitleText] [VALID [:F] lExpression2 [ERROR cMessageText]]
   [WHEN lExpression3] [WIDTH nFieldWidth] [WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN] [COLOR SCHEME nSchemeNumber]

Parameters

FIELDS FieldList
Specifies the fields that appear in the Browse window. The fields are displayed in the order specified in FieldList. You can include fields from other related tables in the field list. When you include a field from a related table, preface the field name with its table alias and a period.

If you omit FIELDS, all the fields in the table are displayed in the order they appear in the table structure.

FONT cFontName [, nFontSize]
Specifies the Browse window's font and font size. The character expression cFontName specifies the name of the font, and the numeric expression nFontSize specifies the font size. For example, the following clause specifies 16-point Courier font for the fields displayed in a Browse window:
FONT 'Courier',16

If you include the FONT clause but omit the font size nFontSize, a 10-point font is used in the Browse window. If you omit the FONT clause, 8-point MS Sans Serif is used.

If the font you specify is not available, a font with similar font characteristics is substituted.

STYLE cFontStyle
Specifies the Browse window's font style. If you omit the STYLE clause, the Normal font style is used

If the font style you specify is not available, a font style with similar characteristics is substituted or the Normal font style is used.

Character | Font style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
– Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. The following example opens a Browse window and uses an underlined font:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
IF _WINDOWS
   BROWSE FIELDS contact FONT 'System', 15  STYLE 'NU'
ENDIF
IF _MAC
   BROWSE FIELDS contact FONT 'Geneva', 14  STYLE 'NU'
ENDIF
FOR lExpression1
Specifies a condition whereby only records for which lExpression1 is true are displayed in the Browse window.

Rushmore Query Optimization optimizes a query specified with a BROWSE FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause. For information on Rushmore optimizable expressions, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Include FOR to move the record pointer to the first record meeting the condition. Include REST to keep the record pointer at its current position.

REST
Prevents the record pointer from being moved from its current position to the top of the table when a Browse window is opened with the FOR clause. Otherwise, BROWSE positions the record pointer at the top of the table by default.
FORMAT
Specifies the use of a format file to control the display and data-entry format in a Browse window. The format file must first be opened with SET FORMAT. The following information is extracted from the format file and applied to the Browse window:
  • The list of fields to browse
  • All VALID clauses
  • All WHEN clauses
  • All RANGE clauses
  • Field sizes (as specified in PICTURE clauses)
  • All SAY expressions (included as calculated BROWSE fields)

The following example uses a format file to validate data entered into a Browse window. Positions specified with @ ... GET are ignored.

The first line creates a BROWSE field (cust_id) that is 5 characters wide and allows the entry of letters and digits only. The second line creates a BROWSE field (company) that cannot contain a blank value and can contain a maximum of 20 alphabetic characters.

The third line creates a BROWSE field (contact) into which you enter data only when the field is blank.

Here are the contents of the Custentr.fmt format file, which is used to validate data entered into the customer table:

@ 3,0 GET cust_id PICTURE 'NNNNN'
@ 3,0 GET company VALID company != SPACE(40) ;
   PICTURE 'AAAAAAAAAAAAAAAAAAAA'
@ 3,0 GET contact WHEN contact = SPACE(40)

* This is the program that uses the format file
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
SET FORMAT TO custentr.fmt
BROWSE FORMAT
FREEZE FieldName
Permits changes to be made to only one field in the Browse window. You specify this field with FieldName. The remaining fields are displayed but cannot be edited.
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE FIELDS phone :H = 'Phone Number:' , ;
   company :H = 'Company:' ;
   FREEZE phone
KEY eExpression1 [, eExpression2]
Limits the scope of records that are displayed in the Browse window. With KEY you can specify an index key value (eExpression1) or a range of key values (eExpression1, eExpression2) for the records that are displayed in the Browse window. The table you browse must be indexed, and the index key value or values included in the KEY clause must be the same data type as the index expression of the master index file or tag.

For example, the customer table includes a character field containing postal codes. If the table is indexed on the postal code field, you can specify a range of postal codes in the KEY clause.

In the following example, only records with postal codes falling within the range of 10,000 to 30,000 are displayed in the Browse window:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
SET ORDER TO postalcode
BROWSE KEY '10000', '30000'
LAST | NOINIT
Saves any configuration changes made to the appearance of a Browse window. The changes are saved in the FoxUser.dbf file and can include changes to the field list, the size of each field, and the location and size of the Browse window.

If you issue BROWSE with the LAST or NOINIT clause, the Browse window opens in the same configuration that was last saved in the FoxUser.dbf file if SET RESOURCE is ON. This restores the Browse window configuration created with the last BROWSE command. If the last BROWSE issued in the Command window included a long list of clauses, issue BROWSE with the LAST or NOINIT option to avoid having to retype the command. For more information on the FoxUser resource file, see SET RESOURCE.

If the last Browse window was opened with a BROWSE that included a PREFERENCE clause, BROWSE LAST won't restore the preference.

Any Browse window configuration changes you make in the current session aren't saved if you exit BROWSE by pressing CTRL+Q.

The LAST and NOINIT clauses are identical; NOINIT provides dBASE compatibility.

LOCK nNumberOfFields
Specifies either a positive number, which indicates the number of fields that you can see in the left partition of the Browse window without tabbing or scrolling, or a negative number, which indicates the number of fields that remain locked in the Browse window when tabbing to the right.

The left partition sizes automatically to display the number of fields you specify with nNumberOfFields. A column separator line, which appears 1 pixel wider than the line separating the other columns, indicates the area where the locked columns end and the normal columns begin.

LPARTITION
Specifies that the cursor is placed in the first field in the left Browse window partition. By default, the cursor is placed in the first field in the right partition when the Browse window is opened.
NAME ObjectName
Creates an object reference for the Browse window, allowing you to manipulate the Browse window with object-oriented properties available for the Grid control. For additional information about object-oriented programming in Visual FoxPro, see, Object-Oriented Programming. For additional information about the Grid control properties that you can specify for a Browse window created with the NAME clause, see Grid Control.
NOAPPEND
Prevents the user from adding records to the table by pressing CTRL+Y or by choosing Append Record from the Table menu.
Note Including NOAPPEND doesn't prevent you from appending a record from within a routine (created with VALID, WHEN, or ON KEY LABEL) while in the Browse window.
NOCAPTIONS
Specifies to always use the field name of a table or view for the column headers, even when the database contains a friendly caption for the table field. This clause applies only to tables or views in a database.
NODELETE
Prevents records from being marked for deletion from within a Browse window. By default, a record can be marked for deletion by pressing CTRL+T, choosing Toggle Delete from the Table menu, or by clicking in the leftmost column of the record to be deleted.
NOEDIT | NOMODIFY
Prevents a user from modifying the table. NOEDIT and NOMODIFY are identical. If you include either clause, you can browse or search the table, but you cannot edit it. However, you can append and delete records.
NOLGRID
Removes the field gridlines in the left partition of the Browse window.
NORGRID
Removes the field gridlines in the right partition of the Browse window.
NOLINK
Unlinks the partitions in a Browse window. By default, the left and right partitions of the Browse window are linked together so that when you scroll through one partition, the other partition scrolls.
NOMENU
Removes the Table menu title from the system menu bar, preventing access to the Browse menu.
NOOPTIMIZE
Disables Rushmore Query Optimization of BROWSE. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.
NOREFRESH
Prevents the Browse window from being refreshed. Browse windows are refreshed at the rate determined by SET REFRESH. NOREFRESH is useful with read-only files and improves performance.
NORMAL
Opens the Browse window with its normal default settings, such as its colors, size, position, title, and control options (GROW, FLOAT, ZOOM, and so on). If you omit NORMAL, and the current output window is a user-defined window with its own settings, the Browse window assumes those user-defined settings also.
NOWAIT
Continues program execution immediately after the Browse window is opened. The program doesn't wait for the Browse window to be closed but continues executing on the program line immediately following the program line containing BROWSE NOWAIT. If you omit NOWAIT when BROWSE is issued from within a program, a Browse window is opened and program execution pauses until the Browse window is closed.

NOWAIT is available only from within a program. Including NOWAIT when issuing BROWSE from the Command window has no effect.

PARTITION nColumnNumber
Splits a Browse window into left and right partitions with nColumnNumber specifying the column number of the split bar. For example, if nColumnNumber is 20, the split bar is placed in column 20 of the Browse window.
LEDIT
Specifies that the left partition of the Browse window appear in Edit mode.
REDIT
Specifies that the right partition of the Browse window appear in Edit mode. This example opens a Browse window with the split bar placed in column 20 and the right partition open in Edit mode.

Include both keywords to open both partitions in Edit mode.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE PARTITION 20 REDIT
PREFERENCE PreferenceName
Saves a Browse window's attributes and options for later use. Unlike LAST, which restores the Browse window as it appeared in the previous session, PREFERENCE saves a Browse window's attributes indefinitely in the FoxUser.dbf resource file. Preferences can be retrieved at any time.

Issuing BROWSE with the specified preference name for the first time creates an entry in the FoxUser.dbf file that saves the Browse window configuration. Issuing BROWSE later with the same preference name restores the Browse window to that preference state. When the Browse window is closed, the preference is updated.

Preference names can be up to 10 characters long, must begin with a letter or an underscore, and can contain any combination of letters, numbers and underscores.

Once you have a preference the way you like it, you can prevent it from being changed. Close the Browse window, issue SET RESOURCE OFF, open the FoxUser.dbf file as a table, and change the record containing the preference to read-only by changing the value of the logical field READONLY to true (.T.).

For more information about the FoxUser.dbf resource file, see SET RESOURCE.

If you exit a Browse window by pressing CTRL+Q, no Browse window changes are saved to the resource file.

SAVE
Keeps the Browse window and any of its memo field text-editing windows active and visible (open). You can then return to the Browse window after cycling through other open windows with the keyboard or the mouse.

SAVE is available only from within a program. SAVE has no effect when included with BROWSE in the Command window because BROWSE SAVE is always the default in the interactive mode.

TIMEOUT nSeconds
Specifies how long a Browse window waits for input. The numeric expression nSeconds specifies how many seconds can elapse without any input before the Browse window automatically closes.

TIMEOUT is available only from within a program; it has no effect when you issue BROWSE from the Command window. In the following example, the Browse window is closed if no input occurs in 10 seconds.

DEFINE WINDOW wBrowse FROM 1,1 TO 24,40 ;
   CLOSE ;
   GROW ;
   COLOR SCHEME 10
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE WINDOW wBrowse ;
   FIELDS phone :H = 'Phone Number:' , ;
   company :H = 'Company:' ;
   TIMEOUT 10
RELEASE WINDOW wBrowse
TITLE cTitleText
Overrides the default table name or alias that appears in the Browse window title bar with the title you specify with cTitleText. Otherwise, the name or alias of the table being browsed appears in the title bar.

If you issue BROWSE WINDOW to place the Browse window in a user-defined window, the Browse window's title replaces the user-defined window's title.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE;
   TITLE 'My Browse Window' ;
   FIELDS phone :H = 'Phone Number' , ;
   company :H = 'Company:'
VALID lExpression2
Performs record-level validation in a Browse window. The VALID clause is executed only if a change is made to the record and you attempt to move the cursor to another record. The VALID clause is not executed if the only change is to a memo field.

If VALID returns a value that is true (.T.), the user can move the cursor to another record. If VALID returns a false value (.F.), the cursor remains in the current field and Visual FoxPro generates an error message. If VALID returns 0, the cursor remains in the current field, and an error message isn't displayed.

The VALID clause shouldn't be confused with the verify option (:V), which enables field-level validation.

:F
Forces the VALID clause to execute before the user moves the cursor to the next record. In this case, VALID is executed even if the record isn't changed.
ERROR cMessageText
Specifies an error message that overrides the system default error message. Visual FoxPro displays cMessageText when VALID returns false (.F.).
WHEN lExpression3
Evaluates a condition when the user moves the cursor to another record. If lExpression3 evaluates to true (.T.), the user can modify the record moved to. If lExpression3 evaluates to false (.F.) or 0, the record the user moves to becomes read-only and cannot be modified.

The WHEN clause isn't executed when another window is activated.

WIDTH nFieldWidth
Limits the number of characters displayed for all fields in a Browse window to nFieldWidth. The contents of a field can be scrolled horizontally using the LEFT ARROW and RIGHT ARROW keys or the horizontal scroll bar. Including the WIDTH clause doesn't change the size of fields in the table; it alters only the way the fields are displayed in the Browse window. If a width has been specified for an individual field with the FIELDS clause, it overrides the width specified with the WIDTH clause for that field.
WINDOW WindowName1
Specifies a user-defined window whose characteristics the Browse window assumes. For example, if the user-defined window is created with the FLOAT clause, the Browse window can be moved. The specified window doesn't have to be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies the parent window within which the Browse window is opened. The Browse window doesn't assume the characteristics of the parent window. A Browse window activated inside a parent window cannot be moved outside the parent window. If the parent window is moved, the Browse window moves with it.

To access the Browse window, the parent window must first be defined with DEFINE WINDOW and must be active and visible.

IN SCREEN
Explicitly places a Browse window on the main Visual FoxPro window when a user-defined window is active.
COLOR SCHEME nSchemeNumber
Specifies the number of a color scheme used for the Browse window's colors.

The Browse window assumes the color scheme established using the Windows Color Control Panel.

Remarks

A Browse window allows you to view records in a table, edit those records, and append additional records. Visual FoxPro allows you to have several Browse windows open at the same time.

If you press ESC to exit a Browse window, changes made to the last field you modified are discarded. However, if you move to another record after modifying a field, your changes to the field are saved.

The field list can specify any combination of fields or calculated fields. The syntax of the field list is:

FieldName1
   [:R]
   [:nColumnWidth]
   [:V = lExpression1 [:F] [:E = cMessageText]]
   [:P = cFormatCodes]
   [:B = eLowerBound, eUpperBound [:F]]
   [:H = cHeadingText]
   [:W = lExpression2]
   [, FieldName2 [:R]...]

Calculated Fields... The field list can contain statements for creating calculated fields. A calculated field contains read-only data created with an expression. The expression can take any form, but it must be a valid Visual FoxPro expression.

The format of the statement you use to create a calculated field is:

CalculatedFieldName = eExpression

The following example creates a calculated field called location:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE FIELDS location = ALLTRIM(city) + ', ' + country

city and country are the names of fields from the currently selected table.

The FIELDS clause field list includes options that enable special handling of fields displayed in a Browse window:

:R
Specifies that the field is read-only. The data it contains can be viewed but not edited.

In the following example, a Browse window is opened with the cust_id and company fields. The cust_id field is read-only and cannot be changed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
BROWSE FIELDS cust_id:R, company
:nColumnWidth
Specifies the display size for a field in columns. The value of :nColumnWidth doesn't affect the size of the field in the table; it only alters the way the field appears in the Browse window.
:V = lExpression1 [:F] [:E = cMessageText]
Lets you perform field-level data validation within the Browse window. If lExpression1 evaluates to true (.T.) when you move the cursor from a field, the data input into the field is considered correct and the cursor moves to the next field.

If lExpression1 evaluates to false (.F.), the data input is considered incorrect, the cursor remains in the field and an error or exception is raised. If lExpression1 evaluates to 0, the data input is considered incorrect and the cursor remains in the field but no error message appears.

The verify option is not executed for memo fields.

By default, lExpression1 is evaluated only when the field is modified. To force verification, include the :F option.

You can display your own error message by including the :E option described below.

:F
Determines whether the expression in the verify option is evaluated when you move the cursor out of a field or another window is activated. If :F is not included, lExpression1 is evaluated only if changes are made to the field. If :F is included, lExpression1 is evaluated even if the field isn't modified.
:E = cMessageText
If the validation expression :V = lExpression1 evaluates to true (.T), the cursor leaves the field normally. If the expression evaluates to false (.F.), the cursor remains in the field, and Visual FoxPro generates an error message.

If the error option (:E) is included, cMessageText appears instead of the system error message. cMessageText appears only if SET NOTIFY is ON. The bell is sounded if SET BELL is ON.

If :V = lExpression1 evaluates to 0, no message appears and the cursor remains in the field being validated. This option lets you display your own error messages in validation routines.

The following example opens the products table and displays the product_id and prod_name fields. The product_id field is a numeric field that will accept up to five numbers. For purposes of this example, we consider a product_id greater than 100 to be invalid.

:V specifies the validation criteria. :F forces the validation check to be performed whether the data is changed or not. :E replaces the Visual FoxPro system error message with a user-defined error message. In Visual FoxPro, the error message appears in the status bar at the bottom of the main Visual FoxPro window.

Press ESC to close the Browse window.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
IF _WINDOWS OR _MAC
   SET STATUS BAR ON
ENDIF
USE products
BROWSE FIELDS in_stock :V = in_stock < 100 ;
   :F ;
   :E = 'The stock amount must be less than 100'
:P = cFormatCodes
If you include a FIELDS clause, you can also specify a picture option (:P) for each field in the list. The picture option lets you create a list of codes that controls the display and input of data for each field in a Browse window. cFormatCodes is the list of codes.

The following example uses the picture option to allow only numeric data in a specific format to be entered in the unit_price field:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
BROWSE FIELDS unit_price :P = '99,999.99'

See the Format Property and InputMask Property properties for more information about picture option codes.

:B = eLowerBound, eUpperBound [:F]
Specifies a set of boundaries between which data in a field must fall. The boundary expressions eLowerBound and eUpperBound must match the data type of the field. They cannot be user-defined functions. If the data entered doesn't fall between eLowerBound and eUpperBound, a system error message appears indicating the range within which the data must fall.

By default, the data you enter is checked against the boundary values only if you make a change to the contents of the field. To force checking against the boundary values, include the forced validation option (:F).

The following example ensures that the value in the in_stock field falls between 1 and 100. Press ESC to close the Browse window.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
BROWSE FIELDS in_stock :B = 1, 100    :F
:H = cHeadingText
Replaces the default field names with your own headings, which you specify with cHeadingText. By default, field names are used as the column headings in the Browse window.

The following example provides user-defined headings for the displayed fields.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
BROWSE FIELDS prod_name :H = 'Product Name:', ;
   unit_price :H = 'Price per Unit:'
:W = lExpression2
Determines whether the cursor can be moved to a field. If lExpression2 evaluates to false (.F.), moving the cursor to the field is prohibited. If lExpression2 evaluates to true (.T.), the cursor can be moved to the field. User-defined functions are supported in lExpression2.

If moving the cursor to all fields is prohibited, the current record is marked read-only. This occurs only when every field contains a WHEN clause that evaluates to false.

SET SKIP Support... SET SKIP lets you establish a one-to-many relationship between two tables. For each record in the parent table, there can be multiple related records in the child table. If you create a one-to-many relationship, you may use BROWSE to view records from both the parent and child tables.

The parent record appears once, along with the first matching record from the child table. Any subsequent matching records are displayed in the rows following the parent record and first matching child record. The fill character for repeated parent information depends on the current Browse window font.

If the record pointer is positioned on a parent record, you can move the pointer through the parent records in the Browse window by pressing CTRL+DOWN ARROW to move to the next parent record or CTRL+UP ARROW to move to the previous parent record. For more information on creating one-to-many relationships, see SET SKIP.

The FIELDS clause field list contains records from both the parent and child tables. The names of fields are prefaced with their table alias (orders or customer) and a period.

CLEAR
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer ORDER cust_id IN 0   && Parent table
USE orders ORDER cust_id IN 0  && Child table
SELECT customer     && Back to parent work area
SET RELATION TO cust_id INTO orders     && Establish relationship
SET SKIP TO orders  && One-to-many relationship
WAIT WINDOW 'Scroll to see shipping dates for each customer' NOWAIT
BROWSE FIELDS customer.cust_id :H='Customer Number', ;
   customer.city :H='Customer City', orders.shipped_on

Useful Functions... Several Visual FoxPro functions return useful information about a Browse window.

Function | Description
VARREAD( ) | Returns the name of the field the cursor is in for the active Browse window.
RECNO( ) | Returns the record number of the selected record in the active Browse window.

See Also

CHANGE | EDIT | Grid Control | SET SKIP | WTITLE( ) | Adding Records


BUILD APP Command

Creates an application file with an .app file name extension using information from a project file.

BUILD APP APPFileName FROM ProjectName [RECOMPILE]

Parameters

APPFileName
Specifies the file name of the application to build. The default file name extension is .app.
FROM ProjectName
Specifies the name of the project from which the application is built.
RECOMPILE
Specifies that the project be compiled before the application file is built. All program and format files; form, label, report, and visual class library source code; and stored procedures in databases in the project are compiled.

Remarks

You create a project file with CREATE PROJECT or MODIFY PROJECT. A project file is a table that uses the file extensions .pjx (table file) and .pjt (memo file).

Before using BUILD APP, be sure that the project file contains all of the files needed in the application. If required files are missing during the build, Visual FoxPro generates an error. These and other compile-time errors are stored in an error file with an .ERR file extension. The first eight characters of the error file name are the same as the first eight characters of your project name.

For more information on building projects, see Compiling an Application.

See Also

BUILD EXE | Build Method | BUILD PROJECT | CREATE PROJECT | MODIFY PROJECT


BUILD DLL Command

Creates a dynamic-link library (DLL) with a .dll file name extension using class information from a project file.

BUILD DLL DLLFileName FROM ProjectName [RECOMPILE]

Parameters

DLLFileName
Specifies the file name of the dynamic-link library to build. The default file name extension is .dll.
FROM ProjectName
Specifies the name of the project from which the dynamic-link library is built.

The project must contain a class designated as OLEPUBLIC or an error message is displayed. To designate a class as OLEPUBLIC in program code, include the OLEPUBLIC keyword in DEFINE CLASS. To designate a class as OLEPUBLIC in the Class Designer, choose Class Info from the Class Menu and select the OLE Public check box.

RECOMPILE
Specifies that the project be compiled before the dynamic-link library is built. All program and format files; form, label, report, and visual class library source code; and stored procedures in databases in the project are compiled.

Remarks

BUILD DLL automatically registers the servers in the Server Classes list box on the Servers tab of the Project Information dialog box.

For information about creating custom Automation servers, see Creating Automation Servers.

See Also

BUILD EXE | Build Method | BUILD PROJECT | CREATE PROJECT | MODIFY PROJECT


BUILD EXE Command

Creates an executable file from a project.

BUILD EXE EXEFileName FROM ProjectName [RECOMPILE]

Parameters

EXEFileName
Specifies the name of the executable file to create. If an .app application file with the same root file name as the stand-alone executable file exists, it is deleted. If an executable file exists and you create an .app file with the same name, the executable file is deleted.
FROM ProjectName
Specifies the name of the project from which the executable file is built.
RECOMPILE
Specifies that the project be compiled before the executable file is built. All program and format files; form, label, report, and visual class library source code; and stored procedures in databases in the project are compiled.

Remarks

An executable file created with BUILD EXE requires two support files: Vfp8r.dll and Vfp8renu.dll (enu denotes the English version). These files must be placed in the same directory as the executable file or along the MS-DOS path.

If the executable file contains OLEPUBLIC class definitions, BUILD EXE automatically registers the OLEPUBLIC class definitions in the system registry. OLEPUBLIC class definitions appear in the Server Classes list box on the Servers tab of the Project Information dialog box.

BUILD EXE also creates .vbr (registration) and .tlb (type library) files with the same name as the executable file. The .vbr file allows you to register the class definitions in the system registry when the executable file is moved to a different computer. The .tlb file is for use with object browsers.

For more information about registering OLEPUBLIC class definitions in an executable file, see Adding OLE.

See Also

BUILD DLL | BUILD APP | Build Method | BUILD MTDLL | BUILD PROJECT


BUILD MTDLL Command

Creates a multithreaded dynamic-link library (DLL) with a .dll file name extension using class information from a project file.

BUILD MTDLL MTDLLFileName FROM ProjectName [RECOMPILE]

Parameters

MTDLLFileName
Specifies the file name of the dynamic-link library to build. The default file name extension is .dll.
FROM ProjectName
Specifies the name of the project from which the dynamic-link library is built.

The project must contain a class designated as OLEPUBLIC or an error message is displayed. To designate a class as OLEPUBLIC in program code, include the OLEPUBLIC keyword in DEFINE CLASS. To designate a class as OLEPUBLIC in the Class Designer, choose Class Info from the Class Menu and select the OLE Public check box.

RECOMPILE
Specifies that the project be compiled before the dynamic-link library is built. All program and format files; form, label, report, and visual class library source code; and stored procedures in databases in the project are compiled.

Remarks

For information about creating custom Automation servers see Creating Automation Servers.

The Visual FoxPro run time that creates multithreaded .dll files is designed to create only in-process servers. Many user input commands and functions are not supported. For details see, Interoperability and the Internet.

BUILD MTDLL automatically registers the servers in the Server Classes list box on the Servers tab of the Project Information dialog box.

See Also

BUILD DLL | BUILD EXE | Build Method | BUILD PROJECT | CREATE PROJECT | MODIFY PROJECT


BUILD PROJECT Command

Creates and builds a project file.

BUILD PROJECT ProjectFileName [RECOMPILE]   [FROM ProgramName1 |
MenuName1 | ReportName1 | LabelName1      | FormName1 | LibraryName1
[, ProgramName2 | MenuName2 | ReportName2 | LabelName2      | FormName2
 | LibraryName2 ...]]

Parameters

ProjectFileName
Specifies the name of the project table to be created.
RECOMPILE
Compiles all files in the project. If RECOMPILE is omitted, only the files that have been modified are compiled when the project is built.
FROM ProgramName1 | MenuName1 | ReportName1 | LabelName1| FormName1 | LibraryName1
Specifies the files to include in the project. You can specify one or more program, menu, report, label, form, or library files and the project will keep track of these files, as well as the dependencies, references, and connections among them.

The first executable program or menu file in the FROM clause is the master program file in the project by default.

Remarks

BUILD PROJECT automatically creates a project table with a .pjx file name extension by opening and processing one or more program, menu, report, label, form, or library files that you specify. You can use the project file to create one of two program types: an application file with an .app extension or an executable file with an .exe extension. The project table keeps track of all the files required to create an application, as well as the dependencies, references, and connections among the files. Once you specify the pieces in the project, Visual FoxPro makes sure that the application is based on the latest source files.

For more information on building projects, see Compiling an Application.

When Visual FoxPro encounters a program, menu, or form file while creating a project file from BUILD PROJECT, it finds its compiled file and compares the time and date stamp of the two files. If the time and date stamp of the source file is later than that of the compiled file, Visual FoxPro recompiles the source file.

Each project file contains a time and date stamp so you can refresh the project file when you make changes to files in the project or when dependencies change. This practice helps to guarantee that any applications created from a project file will always use the most recent source files. To refresh a project file, issue BUILD PROJECT without the optional FROM clause. Visual FoxPro then updates the specified project.

When you issue BUILD PROJECT, unresolved references and other errors are reported but do not prevent the project file from being created. This enables you to build a project even when all the necessary pieces aren't actually created or available at the time the project is built. Unresolved references or other problems can be corrected by refreshing the project file at a later date, or by manually modifying the information stored in the project file with MODIFY PROJECT.

See Also

BUILD APP | BUILD EXE | Build Method | BuildDateTime Property | CREATE PROJECT | EXTERNAL | MODIFY PROJECT


CALCULATE Command

Performs financial and statistical operations on fields in a table or on expressions involving fields.

CALCULATE eExpressionList [Scope] [FOR lExpression1] [WHILE lExpression2]
   [TO VarList | TO ARRAY ArrayName] [NOOPTIMIZE]
   [IN nWorkArea | cTableAlias]

Parameters

eExpressionList
Specifies the expressions that can contain any combination of the following functions:

AVG(nExpression)

CNT( )

MAX(eExpression)

MIN(eExpression)

NPV(nExpression1, nExpression2 [, nExpression3])

STD(nExpression)

SUM(nExpression)

VAR(nExpression)

Functions in the expression list eExpressionList are separated by commas. These functions are specific to CALCULATE and are described in detail later in this section. They should not be confused with similarly named independent functions. For example, CALCULATE MIN( ) is not the same as MIN( ).

Scope
Specifies a range of records used in the calculation. Only the records that fall within the range of records are included in the calculation. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see the Scope Clauses topic. Commands that include Scope operate only on the table in the active work area.

The default scope for CALCULATE is ALL records.

FOR lExpression1
Specifies that only the records that satisfy the logical condition lExpression1 are included in the calculation. Including a FOR clause conditionally includes records in the calculation, filtering out undesired records.

Rushmore Query Optimization optimizes a CALCULATE ... FOR query if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause. For information on Rushmore optimizable expressions, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are included in the calculation as long as the logical expression lExpression2 evaluates to true (.T.).
TO VarList
Specifies one or more variables to which the results of the calculation are stored. If a variable you specify does not exist, Visual FoxPro automatically creates the variable with the name you specify.
TO ARRAY ArrayName
Specifies an array name to which the results of the calculation can be stored. If the array name you specify does not exist, Visual FoxPro automatically creates an array with the name you specify. If the array exists and is not large enough to contain all the results of the calculation, Visual FoxPro automatically increases the size of the array to accommodate the information. If an existing array is larger than necessary, additional elements are left unchanged. Results are stored to the array elements in the order they are specified in the CALCULATE command.
NOOPTIMIZE
Disables Rushmore optimization of CALCULATE. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.
AVG(nExpression)
Computes the arithmetic mean of nExpression. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
CNT( )
Returns the number of records in the table. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
MAX(eExpression)
Returns the highest or latest value of eExpression. Within the MAX( ) clause, you can specify any character, date, datetime, numeric, float, integer, double, or currency field, or any expression using fields of these types. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
MIN(eExpression)
Returns the lowest or earliest value of eExpression. Any character, date, datetime, numeric, float, integer, double, or currency field, or any valid expression using fields of these types, can be included in eExpression. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
NPV(nExpression1, nExpression2 [, nExpression3])
Computes the net present value of a series of future cash flows discounted at a constant periodic interest rate.

nExpression1 specifies the interest rate expressed as a decimal value.

nExpression2 specifies a field, field expression, or a numeric expression representing a series of cash flows. Each cash flow can be either positive or negative. In cases where nExpression2 is a field, the value for each record in the field is considered a cash flow.

nExpression3 specifies an optional initial investment. If the initial investment is not included, then the initial investment is assumed to occur at the end of the first period. This initial investment is the first record in the field and is negative to represent a cash outflow.

Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.

STD(nExpression)
Computes the standard deviation of nExpression. The standard deviation measures the degree to which the values of fields or expressions involving fields differ from the average of all the values. The smaller the standard deviation, the less the values vary from the average. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
SUM(nExpression)
Totals the values of nExpression. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
VAR(nExpression)
Computes the variance from the average of nExpression. The variance is the standard deviation squared. The smaller the variance, the less the values vary from the average. Only records meeting the Scope and/or optional FOR or WHILE conditions are included in the result.
IN nWorkArea | cTableAlias
Specifies the workarea or table alias affected by the CALCULATE command. Use this clause to specify a workarea or a table outside the current work area.

Remarks

Records containing the null value are not included in the operations that CALCULATE performs.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE orders  && Open Orders table

SET TALK ON
CLEAR
CALCULATE AVG(order_amt), MIN(order_amt), MAX(order_amt)
CALCULATE STD(order_amt), VAR(order_amt) TO gnStd, gnVar

See Also

AVERAGE | COUNT | DIMENSION | FV( ) | MAX( ) | MIN( ) | PAYMENT( ) | PV( ) | SUM


CANCEL Command

Ends execution of the current Visual FoxPro program file.

CANCEL

Remarks

Control returns to the Command window when Visual FoxPro is being used interactively. If a distributed run-time application is running, CANCEL terminates the application and control returns to Windows. If a program is executing in Visual FoxPro during design time, CANCEL terminates the program and control returns to the Command window.

Executing CANCEL releases all private variables.

Example

The following example simulates a program execution loop. Each time through the loop you are asked if you want to continue. If you press the Cancel button, CANCEL stops program execution.

DO WHILE .T.
   IF MESSAGEBOX("Do you want to continue?",36) <> 6
      CANCEL
   ENDIF
ENDDO

See Also

QUIT | RESUME | RETURN | SUSPEND | Cancel Property | SQLCANCEL( )


CD | CHDIR Command

Changes the default Visual FoxPro directory to the directory you specify.

CD cPath | CHDIR cPath

Parameters

cPath
Specifies one of the following:
  • A drive designator
  • A drive designator with a directory
  • A child directory
  • Any of the above using MS-DOS shorthand notation ( \ or ..). When you include .. to change to the parent directory, you must include a space between CD or CHDIR and the two periods.

Remarks

Use CD or CHDIR to specify the default Visual FoxPro directory. Visual FoxPro searches for files in the default Visual FoxPro directory. If Visual FoxPro cannot find a file in the default directory, it then searches the Visual FoxPro path if one has been specified. Use SET PATH to specify the Visual FoxPro path.

If you create a file and do not specify where to place it, the file is placed in the default Visual FoxPro directory.

You can locate hidden or system directories using CD and CHDIR. For more information, see FILE( ) Function and DIRECTORY( ) Function.

The CD and CHDIR commands are not supported in either single or multithreaded DLL servers. These commands change the default directory of the entire process, so all threads which are part of the process are affected. Use the SET PATH command in DLL servers, in place of SET DEFAULT.

Example

The following example uses SET DEFAULT to change the default Visual FoxPro directory to the startup directory. It uses MKDIR to create a new directory named mytestdir, and CHDIR changes to the mytestdir directory. GETDIR( ) shows you the directory structure in the Select Directory dialog box. You can then use SET DEFAULT to move your position back to the startup directory, RMDIR to remove the newly created directory, and GETDIR( ) to display the original directory structure.

SET DEFAULT TO HOME()
MKDIR mytestdir
CHDIR mytestdir  = GETDIR()
SET DEFAULT TO HOME()
RMDIR mytestdir  = GETDIR()

See Also

DIR or DIRECTORY Command | DIRECTORY( ) | GETDIR( ) | HOME( ) | MD | MKDIR | RD | RMDIR | SET DEFAULT | SET PATH | SYS(5) - Default Drive | SYS(2003) - Current Directory | SYS(2004) - Visual FoxPro Start Directory


CHANGE Command

Displays fields for editing.

CHANGE [FIELDS FieldList] [Scope] [FOR lExpression1] [WHILE lExpression2] [FONT cFontName [, nFontSize]] [STYLE cFontStyle] [FREEZE FieldName]
[KEY eExpression1 [, eExpression2]] [LAST | NOINIT] [LPARTITION]
[NAME ObjectName] [NOAPPEND] [NOCAPTION] [NOCLEAR] [NODELETE]
[NOEDIT | NOMODIFY] [NOLINK] [NOMENU] [NOOPTIMIZE] [NORMAL] [NOWAIT]
[PARTITION nColumnNumber [LEDIT] [REDIT]] [PREFERENCE PreferenceName]
[REST] [SAVE] [TIMEOUT nSeconds] [TITLE cTitleText]
[VALID [:F] lExpression3 [ERROR cMessageText]] [WHEN lExpression4]
[WIDTH nFieldWidth] [WINDOW WindowName1]
[IN [WINDOW] WindowNam2 | IN SCREEN | IN MACDESKTOP]]
[COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

The arguments for CHANGE are the same as those for EDIT. See EDIT.

Remarks

CHANGE works just like EDIT.

See Also

BROWSE | EDIT | WTITLE( )


CLEAR Commands

Releases the specified item or items from memory.

CLEAR [ALL | CLASS ClassName | CLASSLIB ClassLibraryName | DEBUG | DLLS
   [cAliasNameList]| EVENTS | FIELDS | GETS | MACROS | MEMORY
   | MENUS | POPUPS | PROGRAM | PROMPT | READ [ALL] | RESOURCES
   [FileName] | TYPEAHEAD | WINDOWS]

Parameters

ALL
Releases from memory all variables and arrays and the definitions of all user-defined menu bars, menus, and windows. CLOSE ALL also closes any tables, including all associated index, format and memo files, and selects work area 1. CLEAR ALL also releases from memory all external shared library functions registered with DECLARE - DLL.

CLEAR ALL does not release system variables, and does not clear the compiled program buffer. Use CLEAR PROGRAM to clear the compiled program buffer.

Issuing CLEAR ALL within an event or method for an active control or object generates a Visual FoxPro error message. An object type variable cannot be released from memory when its associated control or object is active.

CLASS ClassName
Clears a class definition from memory. When an instance of a class is created, Visual FoxPro keeps the class definition in memory after the instance is released. Use CLEAR CLASS to clear a class definition from memory after its instance is released.
CLASSLIB ClassLibraryName
Clears from memory all class definitions contained in a visual class library. If instances of classes in the class library exist, the class definitions are not cleared from memory. However, all class definitions that do not have instances are cleared from memory.
DEBUG
Clears all breakpoints in the Debugger and restores the Debugger windows (Call Stack, Trace, Watch, etc.) to their default positions.

If Clear Debug is issued when the Debugger is closed, the Debugger is opened with the Debugger windows in their default positions.

Works in either fox or debugger frame mode.

DLLS cAliasNameList
Clears from memory external shared libraries registered with DECLARE - DLL. cAliasNameList is a comma separated list of function aliases to remove from memory as in the following example:
CLEAR DLLS  "RegCloseKey","RegOpenKey"

If you used no alias in the declaration, cAliasNameList is the same as the function name. If you specify no cAliasNameList, all DLLS are removed from memory. You can use the ADLLS( ) Function to determine which DLLs are loaded.

See DECLARE - DLL Command for more information about registering external shared library functions.

EVENTS
Stops event processing started with READ EVENTS. When CLEAR EVENTS is executed, program execution continues on the program line immediately following READ EVENTS.
FIELDS
Releases a list created with SET FIELDS and executes SET FIELDS OFF. CLEAR FIELDS differs from SET FIELDS TO in that it releases all field lists for all work areas, not just the field list for the current work area. Also, SET FIELDS TO does not implicitly issue a SET FIELDS OFF.
GETS
Releases all pending @ ... GET controls. Issuing CLEAR also releases all pending @ ... GET controls.
Note GETS is included for backward compatibility.
MACROS
Releases from memory all keyboard macros, including any SET FUNCTION key assignments. Macros can be saved to a macro file or to a memo field with SAVE MACROS and restored later with RESTORE MACROS. You can also restore the default macros with RESTORE MACROS.
MEMORY
Releases from memory all public and private memory variables and arrays. System variables aren't released.
MENUS
Releases all menu bar definitions from memory.
POPUPS
Releases from memory all menu definitions created with DEFINE POPUP.
PROGRAM
Clears the compiled program buffer. Visual FoxPro keeps a buffer of the most recently executed programs. In rare cases, Visual FoxPro might not recognize changes made to program files on disk. CLEAR PROGRAM forces Visual FoxPro to read the programs from disk, rather than from the program buffer. The most common reason Visual FoxPro might not recognize changes made to program files is your using an external or terminate-and-stay-resident (TSR) editor to modify a program file. With this exception, you should not have to use CLEAR PROGRAM.
PROMPT
Releases menu items created with @ ... PROMPT.
READ [ALL]
Included for backward compatibility. Use CLEAR EVENTS instead.
RESOURCES [FileName]
Specifies the name of a cached bitmap, picture, font, cursor, or icon file to be cleared from memory. If no file name is specified, all bitmap, picture, font, cursor and icon files are removed from memory.

When Visual FoxPro displays a bitmap, picture, cursor, icon, or font resource, the resource is cached to optimized performance. If a resource of the same name is used (for example, a different bitmap with the same name as one already cached), Visual FoxPro does not reload the resource.

Clearing a resource file is therefore particularly useful for removing a graphic image from memory and forcing Visual FoxPro to reload an image of the same name from disk. For example, a report might display graphic images from a database, all of which are named TEMP; however, because they all have the same name, Visual FoxPro will not reload each new graphic unless the existing one has been cleared from memory using the CLEAR RESOURCES command.

TYPEAHEAD
Clears the keyboard type-ahead buffer. CLEAR TYPEAHEAD is useful when you want to prevent input into a field or prevent a response to a prompt before the field or prompt is displayed.
WINDOWS
Releases from memory all user-defined window definitions and clears the windows from the main Visual FoxPro window or the active user-defined window. Use SAVE WINDOW to save window definitions in a file or memo field for later use.

Issuing CLEAR WINDOWS releases any system variable references to forms. For example, the following commands create a system variable reference for a form, and then display information about the variable:

goMyForm = CREATEOBJECT('FORM')
DISPLAY MEMORY LIKE goMyForm  && Displays GOMYFORM  O  FORM

Issuing CLEAR WINDOWS releases the system variable reference and the variable now contains the null value:

CLEAR WINDOWS
DISPLAY MEMORY LIKE goMyForm  && Displays GOMYFORM  O  .NULL.

Remarks

CLEAR erases the main Visual FoxPro window or the current user-defined window, and releases from memory all pending @ ... GET controls. You can include CLEAR in format files.

See Also

@ ... CLEAR | CLOSE | DECLARE -DLL | READ | READ EVENTS | RELEASE | RELEASE CLASSLIB | RELEASE WINDOWS


CLOSE Commands

Closes various file types.

CLOSE [ALL | ALTERNATE | DATABASES [ALL] | DEBUGGER | FORMAT | INDEXES
   | PROCEDURE | TABLES [ALL]]

Parameters

ALL
Closes all open databases, tables, and indexes in the current and any inactive data sessions and selects work area 1. CLOSE ALL also closes any files opened with the FCREATE( ) and FOPEN( ) low-level file functions. CLOSE ALL does not close a file opened with SET PRINT.

CLOSE ALL also closes the following:

  • Form Designer
  • Project Manager
  • Label Designer
  • Report Designer
  • Query Designer

CLOSE ALL does not close these:

  • Command window
  • Debug window
  • Help
  • Trace window
CLOSE ALTERNATE
Closes an alternate file opened with SET ALTERNATE.
CLOSE DATABASES [ALL]
Closes the current database in the current data session and its tables. If there is no current database, all open free tables, indexes, and format files in all work areas in the current data session are closed, and work area 1 is selected.

The ALL keyword specifies that the following are closed in the current and all inactive data sessions:

  • All open databases and their tables, except for currently selected databases in other data sessions or databases and their tables that are open in other data sessions.
  • All open free tables.
  • All indexes and format files in all work areas.
  • Work area 1 is selected.
CLOSE DEBUGGER
Closes the Visual FoxPro debugger.
CLOSE FORMAT
Closes a format file in the current work area opened with SET FORMAT.
CLOSE INDEXES
Closes all open index files (both single-entry .idx and independent compound .cdx files) in the current work area. A structural compound index (a .cdx file automatically opened with the table) is not closed.
CLOSE PROCEDURE
Closes a procedure file opened with SET PROCEDURE.
CLOSE TABLES [ALL]
Closes all tables in the currently selected database. CLOSE TABLES closes all free tables in all work areas if a database isn't open.

Include ALL to close all tables in all databases, and all free tables. All databases remain open.

CLOSE TABLES should not be issued when a transaction is in progress; Visual FoxPro will generate an error message.

See Also

ADD TABLE | CLOSE MEMO | CREATE DATABASE | Close Method


CLOSE MEMO Command

Closes one or more memo editing windows.

CLOSE MEMO MemoFieldName1 [, MemoFieldName2 ...] | ALL

Parameters

MemoFieldName1 [, MemoFieldName2 ...]
Specifies the name of the memo field whose memo editing window you want to close. To close a set of memo editing windows, include a list of memo field names with the field names separated by commas. You can close the memo editing window of a memo field in a table open in another work area by including the table alias.
ALL
Closes all memo editing windows for all memo fields in any open tables.

Remarks

CLOSE MEMO closes memo editing windows opened with MODIFY MEMO, or opened from a Browse window or Edit window. CLOSE MEMO saves any changes you made to the memo fields.

Closing a table containing the memo field or fields also saves any changes you made and closes the memo windows.

See Also

BROWSE | MODIFY MEMO | APPEND MEMO | COPY MEMO


COMPILE Command

Compiles one or more source files and creates an object file for each source file.

COMPILE FileName | FileSkeleton | ? [ENCRYPT] [NODEBUG] [AS nCodePage]

Parameters

LABEL
Specifies that the file to compile is a label definition file (.lbx). Source code for the data environment saved with the label definition file is compiled and stored in an additional memo field.
REPORT
Specifies that the file to compile is a report definition file (.frx). Source code for the data environment saved with the report definition file is compiled and stored in an additional memo field.
FileName | FileSkeleton
Specifies for compilation a single file FileName or a set of files that match a file skeleton FileSkeleton containing wildcards such as * and ?. For example, to compile all program files with the extension .prg in the current directory or folder, issue COMPILE *.PRG.
?
Displays the Compile dialog box, allowing you to choose a file to compile.
ENCRYPT
Encrypts your compiled Visual FoxPro programs. Cannot be used with the CLASSLIB, LABEL, and REPORT keywords. This prevents any access to your original source programs. For additional source code protection, always include this option when compiling programs intended for distribution.
NODEBUG
Reduces the size of your compiled file by two bytes per source file line. Cannot be used with the CLASSLIB, LABEL, and REPORT keywords. These two bytes in the compiled file are a reference to the corresponding line in the source file. Removing these two bytes doesn't affect the program's performance, but it does reduce your compiled file size, and conserves disk space.

When you include NODEBUG, you cannot view a program's execution in the Trace window or use MESSAGE(1) to return the source code for a line that causes an error.

AS nCodePage
Specifies the code page for which the program is compiled. Cannot be used with the CLASSLIB, LABEL, and REPORT keywords. The compilation code page you specify with this clause overrides the global compilation code page specified with SET CPCOMPILE.

Remarks

Visual FoxPro executes only object files, so if a source file hasn't been compiled it is automatically compiled when you run the program. The source file remains unchanged. A separate compiled file is created with the same root name as the source file, but with a different extension. The following table lists the source and compiled file extensions for each file type:

File type | Source extension | Compiled extension
Program file | PRG | FXP
Form code | SPR | SPX
Menu code | MPR | MPX
Query | QPR | QPX
Format | FMT | PRX

The compiler detects any syntax errors in the source file. Compilation error messages are saved to a text file if SET LOGERRORS is ON when the file is compiled. The error log file has the same root name as the compiled file, and has an .err extension. If SET LOGERRORS is OFF, the error log file isn't created.

See Also

#DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | #IFDEF|#IFNDEF ... #ENDIF Preprocessor Directive | #INCLUDE | BUILD PROJECT | COMPILE DATABASE Command | COMPILE FORM Command BUILD APP | MODIFY COMMAND | MODIFY PROJECT | SET CPCOMPILE | SET LOGERRORS


COMPILE DATABASE Command

Compiles stored procedures in a database.

COMPILE DATABASE cDatabaseName | cFileSkeleton | ?

Parameters

DATABASE
Specifies that the file to compile is a database file (.dbc). Source code for stored procedures saved with the database is compiled and stored in an additional memo field.
cDatabaseName
Specifies the name of the database containing the stored procedures to compile. You can compile stored procedures in a database that is not open.
cFileSkeleton
Specifies a subset of database files to compile. cFileSkeleton is a file specification skeleton that supports wildcards such as * and ?. For example, to compile all database files that begin with A, use the following command:
COMPILE DATABASE A*

Remarks

Use COMPILE DATABASE to compile stored procedures outside the Database Designer. Stored procedures can be created and modified interactively with MODIFY PROCEDURES, or programmatically with APPEND PROCEDURES.

COMPILE DATABASE packs memo fields in the .dct memo file for the database to remove unused space from the memo file. Records marked for deletion in the database table aren't removed from the table.

Example

The following example compiles all stored procedures in the testdata database.

CLOSE DATABASES
COMPILE DATABASE (HOME(2) + 'data\testdata')

See Also

APPEND PROCEDURES | COPY PROCEDURES | CREATE TRIGGER | DISPLAY PROCEDURES | MODIFY PROCEDURE | OPEN DATABASE


COMPILE FORM/CLASSLIB Command

Compiles one or more Form objects.

COMPILE FORM | CLASSLIB cFileName | cFileSkeleton | ? [ALL]

Parameters

FORM
Specifies that the file to compile is a form definition file (.scx). Source code for the data environment saved with the form definition file is compiled and stored in an additional memo field.
CLASSLIB
Specifies that the file to compile is a visual class library (.vcx). Visual class library source code is stored in memo fields in the visual class library table. COMPILE CLASSLIB compiles these memo fields into object code that is stored in an additional memo field.
cFileName
Specifies the name of the form to compile.
cFileSkeleton
Specifies a subset of form files to compile. cFileSkeleton is a file specification skeleton that supports wildcards such as * and ?. For example, to compile all Form objects that begin with A, use the following command:
COMPILE FORM A*
?
Displays the Compile dialog box, allowing you to choose a file to compile.
ALL
Compiles all records for all Visual FoxPro platforms in the Form table. If you omit ALL, only records for the current Visual FoxPro platform are compiled.

Remarks

Forms are automatically compiled when they are saved in the Form Designer. Use COMPILE FORM to compile a form outside the Form Designer.

Form source code is stored in memo fields in the Form table. COMPILE FORM compiles these memo fields into object code that is stored in an additional memo field. The object code in this additional field is executed when you issue DO FORM.

Note that if a form has an include (.H) file and the include file is moved from its original directory, a compilation error occurs and is listed in the .err error log file. The form can be run, but cannot be saved if modified until you correct the path to the include file. To correct the path to the include file, open the form with MODIFY FORM, choose Include File from the Form menu, and specify the include file with its new path in the Include File dialog box.

See Also

CREATE FORM | DO FORM | MODIFY FORM


COMPILE REPORT/LABEL Command

Compiles one or more Report or Label objects.

COMPILE  REPORT | LABEL cFileName | cFileSkeleton [ALL]

Parameters

REPORT
Specifies that the file to compile is a report definition file (.frx). Source code for the data environment saved with the report definition file is compiled and stored in an additional memo field.
LABEL
Specifies that the file to compile is a label definition file (.lbx). Source code for the data environment saved with the label definition file is compiled and stored in an additional memo field.
cFileName
Specifies the name of the report or label to compile.
cFileSkeleton
Specifies a subset of form files to compile. cFileSkeleton is a file specification skeleton that supports wildcards such as * and ?. For example, to compile all Form objects that begin with A, use the following command:
ALL
Compiles all records for all Visual FoxPro platforms in the Form table. If you omit ALL, only records for the current Visual FoxPro platform are compiled.

See Also

COMPILE Command


CONTINUE Command

Continues the previous LOCATE.

CONTINUE

Remarks

CONTINUE is used after LOCATE succeeds in finding a record, to continue the LOCATE operation. CONTINUE moves the record pointer to the next record for which the logical expression specified in the previous LOCATE evaluates to True (.T.).

CONTINUE can be repeated until the end of the file is encountered, or until the end of the scope you specified with LOCATE is reached.

If CONTINUE succeeds in finding a record, RECNO( ) returns the record number of the record, FOUND( ) returns a value of True (.T.), and EOF( ) returns a value of False (.F.).

If CONTINUE doesn't succeed in finding a record, RECNO( ) returns the number of records in the table plus one, FOUND( ) returns False (.F.), and EOF( ) returns True (.T.).

Example

In the following example, all customers from France are counted and the total is displayed. All records are found using one LOCATE command followed by a CONTINUE command within a loop.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
SET TALK OFF
STORE 0 TO gnCount

LOCATE FOR ALLTRIM(UPPER(country)) = 'FRANCE'
DO WHILE FOUND( )
   gnCount = gnCount + 1
   CONTINUE
ENDDO
? 'Total customers from France: '+ LTRIM(STR(gnCount))

See Also

EOF( ) | FOUND( ) | LOCATE | SEEK


COPY FILE Command

Duplicates any type of file.

COPY FILE FileName1 TO FileName2

Remarks

COPY FILE creates a duplicate of the file whose name is specified in FileName1. You can use COPY FILE to copy any type of file. The file to be copied cannot be open. You must include the extensions for both the source file name FileName1 and destination file name FileName2.

FileName1 and FileName2 can contain wildcard characters such as * and ?. For example, to create backup copies of all program files with the extension .prg in the current directory, issue COPY FILE *.PRG TO *.BAK.

If you use COPY FILE to create a backup of a table that has a memo field, a structural index or both, be sure to copy the .fpt and .cdx files as well.

See Also

DELETE FILE | RENAME | RENAME TABLE


COPY INDEXES Command

Creates compound index tags from single-entry .idx index files.

COPY INDEXES IndexFileList | ALL   [TO CDXFileName]

Parameters

IndexFileList
Specifies the single-entry .idx index files whose index expressions are used to create the tags. Separate the index file names with commas. The name assigned to each tag is the root name of the corresponding single-entry index file. If you create a tag from an index file that has the same name as an existing tag, a dialog is displayed (if SAFETY is ON) asking if you would like to overwrite the tag.
ALL
Specifies to create index tags from all open single-entry index files.
TO CDXFileName
Creates tags in a non-structural compound index file. Specify the name of the non-structural compound index file with CDXFileName. If a non-structural compound index file with the specified name doesn't exist, Visual FoxPro automatically creates it.

Remarks

A compound index file is an index file containing separate index entries called tags. Each tag is identified by its unique tag name. The default extension for a compound index file is .cdx.

You must first open the table and single-entry index files before using COPY INDEXES. The index expressions from the single-entry index files are used to create the new tags.

If you omit the TO clause, the new tags are added to the structural compound index file that is automatically opened with the table. If a structural compound index file doesn't exist for the table, COPY INDEXES creates one.

Use COPY TAG to create a single-entry index file from compound index file tags.

See Also

CDX( ) | COPY TAG | DELETE TAG | INDEX | TAG( ) | USE


COPY MEMO Command

Copies the contents of the specified memo field in the current record to a text file.

COPY MEMO MemoFieldName TO FileName   [ADDITIVE]   [AS nCodePage]

Parameters

MemoFieldName
Specifies the name of the memo field copied to the text file.
TO FileName
Specifies the name of a new or existing text file to which the memo field is copied. If you do not provide an extension in FileName, a .txt extension is assigned. You can also include a path with the file name.
ADDITIVE
Appends the contents of the memo field to the end of the specified text file. If you omit ADDITIVE, the memo field contents replace the contents of the text file.
AS nCodePage
Specifies the code page for the text file COPY MEMO creates. Visual FoxPro copies the contents of the specified memo field, and, as it copies the data, automatically converts the data to the code page you specify for the text file.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the file Visual FoxPro creates.

If AS nCodePage is omitted or is 0, no code page conversion occurs.

Example

In the following example, the contents of the memo field named notes are copied to a file called Test.txt. The memo field is then copied again and appended to the end of the text file.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee && Opens Employee table
COPY MEMO notes TO test.txt
WAIT WINDOW 'Memo contents now in test.txt' NOWAIT
MODIFY FILE test.txt
COPY MEMO notes TO test.txt ADDITIVE
WAIT WINDOW 'Memo contents added again to test.txt' NOWAIT
MODIFY FILE test.txt
DELETE FILE test.txt

See Also

APPEND MEMO | COPY FILE | COPY TO | MODIFY MEMO


COPY PROCEDURES Command

Copies stored procedures in the current database to a text file.

COPY PROCEDURES TO FileName   [AS nCodePage] [ADDITIVE]

Parameters

FileName
Specifies the name of a text file to which the stored procedures are copied. If the file doesn't exist, Visual FoxPro automatically creates it.
AS nCodePage
Specifies the code page for the text file to which the stored procedures are copied. Visual FoxPro copies the stored procedures, and, as it does so, automatically converts the stored procedures to the code page you specify.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the text file to which the stored procedures are copied.

If you omit AS nCodePage or if AS nCodePage is 0, no code page conversion occurs.

ADDITIVE
Appends the stored procedures to the end of the specified text file. If you omit ADDITIVE, the stored procedures replace the contents of the text file.

Remarks

Use COPY PROCEDURES with APPEND PROCEDURES to programmatically modify stored procedures in a database. A database must be open and current when COPY PROCEDURES is issued; otherwise Visual FoxPro generates an error message.

Example

The following example opens the testdata database, and uses COPY PROCEDURES to copy the procedures to a temporary text file named Myproc.txt. MODIFY FILE is used to open the temporary text file, which will be empty if there are no stored procedures in the database.

If there are no stored procedures in the database, you can run the example for APPEND PROCEDURES to add a procedure to database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')

COPY PROCEDURES TO myproc.txt && Copy stored procedures to a file
MODIFY FILE myproc.txt  && Open the file
DELETE FILE myproc.txt  && Erase the file

See Also

APPEND PROCEDURES | CREATE TRIGGER | DISPLAY PROCEDURES | MODIFY PROCEDURE | SET DATABASE


COPY STRUCTURE Command

Creates a new, empty table with the same structure as the currently selected table.

COPY STRUCTURE TO TableName   [FIELDS FieldList]
[[WITH] CDX | [WITH] PRODUCTION]
[DATABASE cDatabaseName [NAME cTableName]]

Parameters

TableName
Specifies the name of the new, empty table to create.

In Visual FoxPro, null value support and the code page for the new, free table are identical to the currently selected table.

FIELDS FieldList
Specifies that only the fields whose names are specified in the FieldList are copied to the new table. If you omit FIELDS FieldList, all fields are copied to the new table.
[WITH] CDX | [WITH] PRODUCTION
Creates a structural index file for the new table that is identical to the structural index file of the existing table. The tags and index expressions from the original structural index file are copied to the new structural index file.

The CDX and PRODUCTION clauses are identical.

In Visual FoxPro, a primary index for the currently selected table is converted to a candidate index for the new empty table.

DATABASE cDatabaseName
Specifies the name of an existing database to which the new table is added. Note that the table and field properties are not copied to the database.
NAME cTableName
Specifies the name of the table as it appears in the database.

Example

In the following example, the customer table is opened, its structure is copied to a table called backup and backup is opened. APPEND FROM then appends records to the backup table from the customer table, and a Browse window is opened for the backup table.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

COPY STRUCTURE TO backup
USE backup
APPEND FROM customer FOR country = 'UK'
BROWSE FIELDS contact, country
USE
DELETE FILE backup.dbf

See Also

COPY STRUCTURE EXTENDED | CREATE | DISPLAY STRUCTURE


COPY STRUCTURE EXTENDED Command

Creates a new table with fields containing the structure of the currently selected table.

COPY STRUCTURE EXTENDED TO FileName
   [DATABASE DatabaseName [NAME LongTableName]] [FIELDS FieldList]

Parameters

FileName
Specifies the new table to create.
DATABASE DatabaseName
Specifies a database to which the new table is added.
NAME LongTableName
Specifies a long name for the new table. Long names can contain up to 128 characters and can be used instead of short file names in the database.
FIELDS FieldList
Specifies that only the fields in FieldList are included in a record in the new table. If you omit FIELDS FieldList, all fields have a record in the new table.

Remarks

Information about each field in the currently selected table is copied to a record in the new table. The structure of the new table has a fixed format and consists of 18 fields. The following table lists the names of the fields and their contents.

Field | Field type | Contents
FIELD_NAME | Character | Field names from selected table (128 characters wide)
FIELD_TYPE | Character | Field types:C = CharacterY = CurrencyN = NumericF = FloatI = IntegerB = DoubleD = DateT = DateTimeL = LogicalM = MemoG = General
FIELD_LEN | Numeric | Field widths
FIELD_DEC | Numeric | Number of decimal places in numeric fields
FIELD_NULL | Logical | Field null value support
FIELD_NOCP | Logical | Code page translation not allowed (character and memo fields only)
FIELD_DEFA | Memo | Field default values
FIELD_RULE | Memo | Field validation rules
FIELD_ERR | Memo | Field validation text
TABLE_RULE | Memo | Table validation rule
TABLE_ERR | Memo | Table validation text
TABLE_NAME | Character | Long table name (first record only)
INS_TRIG | Memo | Insert trigger expression (first record only)
UPD_TRIG | Memo | Update trigger expression (first record only)
DEL_TRIG | Memo | Delete trigger expression (first record only)
TABLE_CMT | Memo | Table comment (first record only)
FIELD_NEXT | Numeric | Next value for AUTOINC field, if enabled.
FIELD_STEP | Numeric | Step value for AUTOINC field. If value is 0, autoincrementing is not enabled for the field.

The width of the FIELD_NAME field is 10 characters in previous versions of Visual FoxPro, FoxPro for Windows, and FoxPro for MS-DOS. To use CREATE FROM with a table created by COPY STRUCTURE EXTENDED in Visual FoxPro 5.0 and earlier, you must change the width of the FIELD_NAME field to 10 characters. Some field types are not supported in Visual FoxPro 3.0 and earlier versions.

If fields in the source table use autoincrementing, FIELD_STEP is a nonzero value.

You can modify the newly created table and use the CREATE FROM command to create a new table with a different structure. The COPY STRUCTURE and CREATE FROM commands allow you to programmatically change the structure of a table.

Example

The following example displays the structure of the Orders table, copies the structure extended to a Temp table, browses Temp, creates a table called Backup from Temp, and displays the structure of Backup.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Orders  && Opens Orders table.
CLEAR
DISPLAY STRUCTURE

WAIT WINDOW 'Structure of the Orders table' NOWAIT
COPY STRUCTURE EXTENDED TO Temp
USE Temp
WAIT WINDOW 'The Temp table - 1 row per field in orders' NOWAIT
BROWSE
CREATE Backup FROM Temp
USE Backup
DISPLAY STRUCTURE
WAIT WINDOW 'Backup.dbf has the same structure as Orders' NOWAIT
USE
DELETE FILE Temp.dbf
DELETE FILE Backup.dbf

See Also

AFIELDS( ) | Autoincrementing Field Values in Tables | CREATE FROM | COPY STRUCTURE Command


COPY TAG Command

Creates a single-entry index (.idx) file from a tag in a compound index file.

COPY TAG TagName [OF CDXFileName]   TO IndexFileName

Parameters

TagName
Specifies the tag used to create the single-entry .idx file.
OF CDXFileName
Specifies the compound index file containing the tag. Include this clause if there are tags with the same names in the open compound index files. If you omit OF CDXFileName, Visual FoxPro looks for the tag first in the structural index file. If it isn't found there, Visual FoxPro searches all the open non-structural compound index files.
TO IndexFileName
Specifies the name of the single-entry .idx file to create.

Remarks

Use COPY TAG to create a new single-entry .idx file from a tag in a .cdx compound index file.

The compound index file from which you create the single-entry .idx file must be open. Structural compound index files are automatically opened when you open a table. Non-structural compound indexes must be explicitly opened with USE ... INDEX or SET INDEX. For more information about compound index files, see INDEX.

Use COPY INDEX to create tags in compound index files from single-entry .idx files.

See Also

CDX( ) | COPY INDEXES | DELETE TAG | INDEX | TAG( ) | USE


COPY TO ARRAY Command

Copies data from the currently selected table to an array.

COPY TO ARRAY ArrayName
   [FIELDS FieldList | FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton]
   [Scope] [FOR lExpression1] [WHILE lExpression2] [NOOPTIMIZE]

Parameters

ArrayName
Specifies the array to which data from the table is copied.
FIELDS FieldList
Specifies that only the fields specified in FieldList are copied to the array. If you omit FIELDS FieldList, all fields are copied to the array if the array has enough columns.
FIELDS LIKE Skeleton
Specifies that fields that match the field skeleton Skeleton are copied to the array.
FIELDS EXCEPT Skeleton
Specifies that all fields except those that match the field skeleton Skeleton are copied to the array.
Scope
Specifies a range of records copied to the array. Only the records within the range are copied. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see the Scope Clauses online topic.
FOR lExpression1
Specifies that only the records that satisfy the logical condition lExpression1 are copied to the array. To conditionally copy records to the array, include the FOR clause to filter out undesired records.
WHILE lExpression2
Specifies a condition where records are copied to the array while the logical expression lExpression2 evaluates to True (.T.).
NOOPTIMIZE
Disables Rushmore Query Optimization of COPY TO ARRAY. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

Rushmore optimizes a COPY TO ARRAY query that includes FOR lExpression1 if lExpression1 is an optimizable expression. For the best performance, use an optimizable expression in the FOR clause. For information on Rushmore optimizable expressions, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

COPY TO ARRAY and SCATTER are similar. COPY TO ARRAY copies multiple records to an array, while SCATTER copies just one record into an array or a set of memory variables. Both COPY TO ARRAY and SCATTER create a new array if an array with the name you specify does not exist.

To copy a single record to an array, you can specify a one-dimensional array. The one-dimensional array you specify should have the same number of elements as fields in the table, not counting memo fields. Memo fields are ignored in COPY TO ARRAY.

If you specify a one-dimensional array, the first field of a record is stored to the first element of the array, the second field is stored to the second element of the array, and so on. If the one-dimensional array has more elements than the table has fields, any remaining elements remain unchanged. If the array has fewer elements than the table has fields, any remaining fields are ignored.

To copy multiple records or an entire table to an array, specify a two-dimensional array. The number of rows in the array is the number of records the array can hold, and the number of columns in the array is the number of fields the array can hold.

Each record is stored in one row of the array, and each field of the record is stored in one column of the array. For each record, the first field is stored to the first column of the array, the second field is stored to the second column of the array, and so on. If the array has more columns than the table has fields, any remaining columns aren't changed. If the array has fewer columns than the table has fields, any remaining fields aren't stored to the array.

Each successive row in the array is filled with the contents of the next record in the table. If the array has more rows than the table has records, any remaining rows aren't changed. If the array has fewer rows than the table has records, any remaining records aren't stored to the array.

Data can be copied from arrays to new table records with APPEND FROM ARRAY. Data can also be copied from either an array or a set of memory variables to records in a table with GATHER.

The field skeleton Skeleton supports wildcards. For example, to specify that all fields that begin with the letters A and P are copied to the array, use the following:

COPY TO ARRAY aMyArray FIELDS LIKE A*,P*

The LIKE clause can be combined with the EXCEPT clause:

COPY TO ARRAY aMyArray FIELDS LIKE A*,P* EXCEPT PARTNO*

Turning on autoincrementing has no effect on the COPY TO ARRAY command. Only the record values are copied to the array.

Example

In the following example, the Customer table is opened. A two-dimensional array is then created and the first three records from Customer are copied to the array. DISPLAY MEMORY shows the data stored in the array.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer  && Opens Customer table.

DIMENSION gaTemp(3,10)
COPY NEXT 3 TO ARRAY gaTemp
DISPLAY MEMORY LIKE gaTemp

See Also

APPEND FROM ARRAY | DECLARE | DIMENSION | GATHER | PUBLIC | SCATTER | STORE


COPY TO Command

Creates a new file from the contents of the currently selected table.

COPY TO FileName [DATABASE DatabaseName [NAME LongTableName]]
   [FIELDS FieldList | FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton]
   [Scope] [FOR lExpression1] [WHILE lExpression2]
   [ [WITH] CDX ] | [ [WITH] PRODUCTION ] [NOOPTIMIZE]
   [ [TYPE] [ FOXPLUS | FOX2X | DIF | MOD | SDF | SYLK | WK1 | WKS | WR1
   | WRK | CSV | XLS | XL5 | DELIMITED [ WITH Delimiter | WITH BLANK
   | WITH TAB | WITH CHARACTER Delimiter ] ] ] [AS nCodePage]

Parameters

FileName
Specifies the name of the new file to create. If you do not include a file extension, COPY TO assigns the default extension for the specified file type. If you do not specify a file type, COPY TO creates a new Visual FoxPro table and assigns the default .dbf extension to the table file name.
DATABASE DatabaseName
Specifies a database to which the new table is added.
NAME LongTableName
Specifies a long name for the new table. Long names can contain up to 128 characters and can be used instead of short file names in the database.
FIELDS FieldList
Specifies which fields are copied to the new file. If you omit FIELDS FieldList, all fields are copied to the file. If the file you are creating is not a table, memo fields are not copied to the new file, even if memo field names are included in the field list.
FIELDS LIKE Skeleton
Specifies that fields from the original table that match the field skeleton Skeleton are included in the new file that COPY TO creates.
FIELDS EXCEPT Skeleton
Specifies that all fields except those that match the field skeleton Skeleton are included in the new file that COPY TO creates.
Scope
Specifies a range of records to copy to a file. Only the records within the range are copied. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see Scope Clauses.
FOR lExpression1
Specifies that COPY TO copies only the records for which the logical condition lExpression1 evaluates to True (.T.) to the file. To conditionally copy records, include the FOR lExpression1 clause to filter out undesired records.
WHILE lExpression2
Specifies a condition where records are copied while the logical expression lExpression2 evaluates to True (.T.).
[WITH] CDX | [WITH] PRODUCTION
Creates a structural index file for the new table that is identical to the structural index file of the existing table. The tags and index expressions from the original structural index file are copied to the new structural index file. The CDX and PRODUCTION clauses are identical. However, do not include CDX or PRODUCTION if you are copying to a file other than a new Visual FoxPro table.
NOOPTIMIZE
Disables Rushmore Query Optimization for COPY TO. For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.
TYPE
Specifies the file type if the file you create is not a Visual FoxPro table. Although you must specify a file type, you do not need to include the TYPE keyword.
FOXPLUS
Visual FoxPro memo files have a different structure than Microsoft FoxBASE+™ memo files. If your source Visual FoxPro table contains a memo field, include the FOXPLUS clause to create a table that can be used in FoxBASE+. The Visual FoxPro memo field cannot contain binary data because FoxBASE+ does not support binary data in memo fields.
FOX2X
Creates a new table that can be opened in earlier versions of FoxPro (versions 2.0, 2.5, and 2.6).

For Numeric, Float, Integer, Double, and Currency type fields, null values in the source table are converted to zero in the new table. For other field types, null values in the source table are converted to blanks in the new table. For further information about blank values, see ISBLANK( ).

The following table lists the Visual FoxPro field types that are converted to different field types in the new table when the FOX2X argument is included.

Visual FoxPro field type | FoxPro 2.x field type
Currency | Float
DateTime | Date
Double | Float
Integer | Numeric
DIF
Creates a VisiCalc® .dif (Data Interchange Format) file. Fields from the Visual FoxPro table become vectors (columns) and records become tuples (rows). The new file name is assigned a .dif extension if you do not include an extension in FileName.
MOD
Creates a Microsoft Multiplan® version 4.01 file. The new Microsoft Multiplan file name is assigned a .mod extension if an extension is not included.
SDF
Creates an SDF (System Data Format) file. An SDF file is an ASCII text file in which records have a fixed length and end with a carriage return and line feed. Fields are not delimited. The SDF file name is assigned a .txt file extension if you do not include an extension. The SET CENTURY setting is ignored when creating SDF files with COPY TO.

If SDF files include date data, it should be in YYYYMMDD format to allow effective reconversion into Visual FoxPro tables.

If date information is stored in ambiguous formats, you should make sure that the dates are in YYYYMMDD format before you perform the COPY TO operation.

SYLK
Creates a SYLK (Symbolic Link) interchange file. SYLK files are used in Microsoft MultiPlan. Each field from the currently selected table becomes a column in the spreadsheet, and each record becomes a row. SYLK file names have no extension.
WK1
Creates a Lotus® 1-2-3® version 2.x spreadsheet file. Each field from the currently selected table becomes a column in the spreadsheet and each record becomes a row. A .wk1 file name extension is assigned to the new spreadsheet.
WKS
Creates a Lotus 1-2-3 version 1a spreadsheet file. Each field from the currently selected table becomes a column in the spreadsheet and each record becomes a row. A .wks file name extension is assigned to the new spreadsheet.
WR1
Creates a Lotus Symphony® version 1.1 or 1.2 spreadsheet file. Each field from the currently selected table becomes a column in the spreadsheet and each record becomes a row. A .wr1 file name extension is assigned to the new spreadsheet.
WRK
Creates a Lotus Symphony version 1.0 spreadsheet file. Each field from the currently selected table becomes a column in the spreadsheet and each record becomes a row. A .wr1 file name extension is assigned to the new spreadsheet.
CSV
Creates a comma separated value file. A CSV file has the field names as the first line in the file, and the field values in the remainder of the file are separated with commas.
XLS
Creates a Microsoft Excel version 2.0 worksheet file. Each field from the currently selected table becomes a column in the spreadsheet, and each record becomes a row. If you do not include a file extension, an .xls extension is assigned to the new worksheet.
Note Though you can export a maximum of 65,535 rows, which includes one row reserved for the field header, versions of Excel earlier than 8.0 (Excel 97) display only the first 16,384 rows and cannot import files containing more than 32,767 rows.
XL5
Creates a Microsoft Excel version 5.0 workbook file. Each field from the currently selected table becomes a column in the spreadsheet, and each record becomes a row. If you do not include a file extension, an .xls extension is assigned to the new workbook.
Note Though you can export a maximum of 65,535 rows, which includes one row reserved for the field header, versions of Excel earlier than 8.0 (Excel 97) display only the first 16,384 rows and cannot import files containing more than 32,767 rows.
DELIMITED
Creates a delimited file. A delimited file is an ASCII text file in which each record ends with a carriage return and line feed. The default field separator is a comma. Because character data can include commas, character fields are additionally delimited with double quotation marks.

Unless you specify otherwise, a .txt extension is assigned to all newly created DELIMITED files.

DELIMITED WITH Delimiter
Creates a delimited file with character fields delimited by a character other than a quotation mark. The character that delimits character fields is specified with Delimiter.
DELIMITED WITH BLANK
Creates a delimited file with fields separated by spaces instead of commas.
DELIMITED WITH TAB
Creates a delimited file with fields separated by tabs instead of commas.
DELIMITED WITH CHARACTER Delimiter
Creates a delimited file with all fields enclosed by the character specified with Delimiter. If Delimiter is a semicolon (;), used in Visual FoxPro to indicate command line continuation, enclose the semicolon in quotation marks. You can also specify the BLANK and TAB keywords for Delimiter.

You can combine the WITH Delimiter clause with the WITH CHARACTER clause. For example, the following command creates a text file with character fields enclosed by underscores and all fields delimited from each other with semicolons:

COPY TO mytxt.txt DELIMITED WITH _ WITH CHARACTER ';'
AS nCodePage
Specifies the code page for the table or file that COPY TO creates. Visual FoxPro copies the contents of the currently selected table, and, as it copies the data, automatically converts the data to the code page you specify for the new table or file. If possible, Visual FoxPro marks the newly created table or file with the code page you specify.

If you omit AS nCodePage, the newly created table or file is converted to the current Visual FoxPro code page.

Remarks

The field skeleton Skeleton supports wildcards. For example, to specify that all fields that begin with the letters A and P are included in the new file, use the following:

COPY TO mytable FIELDS LIKE A*,P*

The LIKE clause can be combined with the EXCEPT clause:

COPY TO mytable FIELDS LIKE A*,P* EXCEPT PARTNO*

Rushmore Query Optimization optimizes COPY TO with a FOR lExpression1 clause if lExpression1 is an optimizable expression. For the best performance, use an optimizable expression in the FOR lExpression1 clause. For information on Rushmore optimizable expressions, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

If an index order is set, records are copied in master index order.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use the GETCP( ) function for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the table or file Visual FoxPro creates.

The COPY TO command preserves autoincrementing settings except under the following conditions:

  • When the field list specified using COPY TO...FIELDS does not include the field that uses autoincrementing.
  • When using the TYPE clause in the COPY TO command, regardless of the type specified by the clause.

The target table begins autoincrementing starting with the NextValue of the source table. For example, suppose the NextValue in the source table is 1000 with a Step value of 1. The first row of the target table then has an autoincrementing field value of 1001; the second row has a value of 1002, and so on.

Example

In the following example, the "Customer" table is opened and the next three records are copied to a new DELIMITED data file called "temp.txt".

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer  && Opens Customer table.

COPY NEXT 3 TO temp TYPE DELIMITED
WAIT WINDOW 'This is the delimited text file' NOWAIT
MODIFY FILE temp.txt
DELETE FILE temp.txt

See Also

APPEND FROM | COPY FILE | GETCP( ) | EXPORT | IMPORT | RENAME TABLE


COUNT Command

Counts table records.

COUNT   [Scope] [FOR lExpression1] [WHILE lExpression2]   [TO VarName]
   [NOOPTIMIZE]

Parameters

Scope
Specifies a range of records to be included in the count. The default scope for COUNT is ALL records.

The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. Commands that include Scope operate only on the table in the active work area.

For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies that only the records that satisfy the logical condition lExpression1 are counted. Including FOR lets you conditionally count records, filtering out undesired records.

Rushmore Query Optimization will optimize a COUNT FOR query if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information on optimizable expressions, see SET OPTIMIZE Command and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are counted for as long as the logical expression lExpression2 evaluates to True (.T.).
TO VarName
Specifies the variable or array to which the record count is stored. If the variable you specify doesn't exist, Visual FoxPro creates it.
NOOPTIMIZE
Disables Rushmore optimization of COUNT. For more information see SET OPTIMIZE Command and Using Rushmore Query Optimization to Speed Data Access.

Remarks

COUNT counts the records within a scope of records for which the FOR or WHILE conditions are true. If SET TALK is ON, the record count is displayed.

Records marked for deletion are included in the count if SET DELETE is OFF.

For a discussion of how null values affect COUNT, see the Behavior of Null Values in Commands and Functions topic.

Example

The following example counts and displays the number of customers in Paris.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

CLEAR
COUNT FOR UPPER(city) = 'PARIS'
DISPLAY FIELDS company, contact FOR UPPER(city) = 'PARIS'

See Also

CALCULATE Command | SET DELETED Command | SET TALK Command


CREATE CLASS Command

Opens the Class Designer, allowing you to create a new class definition.

CREATE CLASS ClassName | ? [OF ClassLibraryName1 | ?]
[AS cBaseClassName [FROM ClassLibraryName2]] [NOWAIT]

Parameters

ClassName
Specifies the name of the class definition to create.
?
Displays the New Class dialog box, from which you can specify the name of the class definition to create.
OF ClassLibraryName1
Specifies the name of the .vcx visual class library to create. If the .vcx visual class library already exists, the class definition is added to it.

A .vcx file extension is assumed for the visual class library. Be sure to include the file extension if the visual class library you specify has a file extension other than .vcx.

?
Displays the New Class dialog box, from which you can specify the name of a new or existing .vcx visual class library to which the class definition is added.
AS cBaseClassName
Specifies the class on which the class definition is based. You can specify any Visual FoxPro base class except Column and Header. You can also specify a user-defined class if you include the FROM ClassLibraryName2 clause that specifies the name of the visual class library (.vcx) file containing the user-defined class.

If you omit AS cBaseClassName, the class definition is based on the Visual FoxPro FormSet base class.

FROM ClassLibraryName2
Specifies the name of the .vcx visual class library containing the user-defined class specified with cBaseClassName.
NOWAIT
Continues program execution after the Class Designer has been opened. The program doesn't wait for the Class Designer to be closed, but continues execution on the program line immediately following the line that contains CREATE CLASS NOWAIT. If you omit NOWAIT, when CREATE CLASS is issued in a program, the Class Designer is opened and program execution pauses until the Class Designer is closed.

Including NOWAIT has no effect on CREATE CLASS when it is issued in the Command window.

Remarks

Use CREATE CLASS to create a class definition and save it in a .vcx visual class library. You can open the .vcx visual class library with SET CLASSLIB, allowing you to access the class definitions within the .vcx visual class library.

See Also

ADD CLASS Command | _BROWSER System Variable | CREATE CLASSLIB Command | DEFINE CLASS Command | _INCLUDE System Variable | MODIFY CLASS Command | RELEASE CLASSLIB Command | Session Object | SET CLASSLIB Command


CREATE CLASSLIB Command

Creates a new, empty visual class library (.vcx) file.

CREATE CLASSLIB ClassLibraryName

Parameters

ClassLibraryName
Specifies the name of the visual class library to create. If a visual class library with the name you specify already exists and SET SAFETY is ON, Visual FoxPro asks if you'd like to overwrite the existing visual class library. If SET SAFETY is OFF, the existing file is automatically overwritten.

If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .vcx extension.

Remarks

Class definitions can be added to a visual class library with ADD CLASS and CREATE CLASS.

Example

The following example uses CREATE CLASSLIB to create a visual class library named myclslib. A class named myform based on the Visual FoxPro Form base class is created and is stored in the myclslib visual class library. SET CLASSLIB is used to open the myclslib visual class library so that classes within it can be used.

CREATE CLASSLIB myclslib     && Creates a new .VCX visual class library
CREATE CLASS myform OF myclslib AS "Form"  && Creates new class
SET CLASSLIB TO myclslib ADDITIVE     && Opens MyClsLib.VCX

See Also

ADD CLASS Command | _BROWSER System Variable | CREATE CLASS Command | DEFINE CLASS Command | MODIFY CLASS Command | RELEASE CLASSLIB Command | SET CLASSLIB Command


CREATE COLOR SET Command

Creates a color set from the current color settings.

CREATE COLOR SET ColorSetName

Parameters

ColorSetName
Specifies the name of the color set to create.

Remarks

Every color pair in every color scheme is saved in the color set you create. A color set name can be up to 24 characters long in Visual FoxPro, (10 characters in earlier FoxPro versions) and can contain numbers and underscores, but it cannot begin with a number.

Once you have created a color set, you can load it with SET COLOR SET.

Color sets are saved in the Visual FoxPro resource file. If a color set exists with the same name you specify, it is overwritten.

See Also

SET COLOR OF SCHEME Command | SET COLOR SET Command | SET COLOR TO Command


CREATE Command

Builds a new Visual FoxPro table.

CREATE [FileName | ?]

Parameters

FileName
Specifies the name of the table to create.
?
Displays the Create dialog box that prompts you to name the table being created.

Remarks

In Visual FoxPro, if a database is open when you create a table, the table is automatically added to the database.

When running on the Windows operating system, you cannot create a table with the name of an MS-DOS device, such as CON, NUL, PRN, and COM1. You should avoid using hyphens in a table name because hyphenated table names don't appear in the Data Session window, and can cause confusion with the alias pointer (->).

A table is created by defining the name, type, and size of each field. Once the structure of the table is created, you can then add records to the table. For more information on tables, see Table Creation.

See Also

ADD TABLE Command | ALTER TABLE SQL Command | CREATE DATABASE Command | CREATE TABLE - SQL Command | MODIFY STRUCTURE Command


CREATE CONNECTION Command

Creates a named connection and stores it in the current database.

CREATE CONNECTION [ConnectionName | ?]   [DATASOURCE cDataSourceName]
   [USERID cUserID] [PASSWORD cPassWord]   [DATABASE cDatabaseName]
| CONNSTRING cConnectionString]

Parameters

ConnectionName
Specifies the name of the connection to create.
?
Displays the Connection Designer from which you can create and save a connection.
DATASOURCE cDataSourceName
Specifies the name of the ODBC data source for the connection.
USERID cUserID
Specifies your user identification for the ODBC data source.
PASSWORD cPassWord
Specifies your password for the ODBC data source.
DATABASE cDatabaseName
Specifies a database on the server to which the connection is made.
CONNSTRING cConnectionString
Specifies a connection string for the ODBC data source. The connection string can be used instead of explicitly including the ODBC data source, the user identification, and the password.

Remarks

If you omit the optional arguments, the Connection Designer appears, allowing you to interactively create a connection.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn is created. DISPLAY CONNECTIONS is used to display the named connections in the database. The connection is then removed from the database with DELETE CONNECTION.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
CREATE CONNECTION Myconn DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"

CLEAR
DISPLAY CONNECTIONS  && Displays named connections in the database
DELETE CONNECTION Myconn  && Removes the connection just created

See Also

DELETE CONNECTION Command | DBGETPROP( ) Function | DISPLAY CONNECTIONS Command | LIST CONNECTIONS Command | MODIFY CONNECTION Command | OPEN DATABASE Command | RENAME CONNECTION Command


CREATE CURSOR - SQL Command

Creates a temporary table.

CREATE CURSOR alias_name
   (fname1 type [(precision [, scale])] [NULL | NOT NULL]
   [CHECK lExpression [ERROR cMessageText]]
   [AUTOINC [NEXTVALUE NextValue [STEP StepValue]]]
   [DEFAULT eExpression] [UNIQUE [COLLATE cCollateSequence]]
   [NOCPTRANS] [, fname2 ...])
   | FROM ARRAY ArrayName

Parameters

alias_name
Specifies the name of the temporary table to create. The alias_name parameter can be a name expression.
fname
Specifies the name of a field in the temporary table. Each fname can be a name expression.
type
Specifies a single letter indicating the data type for the field.
precision
Specifies the width of the field specified with fname. Some data types require that you specify a value for precision.
scale
Specifies the number of decimal places for the specified data type. Some data types require that you specify a value for scale.

The following table shows what type, precision, and scale can be.

FieldType | nFieldWidth | nPrecision | Description
C n – Character field of width n
D – – Date
T – – Datetime
N | n | d | Numeric field of width n with d decimal places
F | n | d | Floating numeric field of width n with d decimal places
I – – Integer
B – d Double
Y – – Currency
L – – Logical
M – – Memo
G – – General
P – – Picture

The nFieldWidth and nPrecision parameters are ignored for D, T, Y, L, M, G, and P types. The nPrecision parameter defaults to zero (no decimal places) if nPrecision is not included for the N, F, or B types.

NULL | NOT NULL
Specifies whether null values are allowed in the field. NULL permits null values, while NOT NULL does not allow null values.
CHECK lExpression
Specifies a validation rule for the field. The lExpression parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure.
ERROR cMessageText
Specifies an error message. Visual FoxPro displays this message when the validation rule specified in the CHECK clause generates an error. The message displays only when data is changed within a Browse window or Edit window.
AUTOINC [NEXTVALUE NextValue [STEP StepValue]]
Enables autoincrementing for the field.

NextValue specifies the start value and can be a positive or a negative integer value ranging from 2,147,483,647 to -2,147,483,647. The default value is 1. You can set NextValue using the Next Value box on the Fields tab in the Table Designer.

StepValue specifies the increment value for the field and can be a positive, nonzero integer value ranging from 1 to 255. The default value is 1. You can set StepValue using the Step box on the Fields tab in the Table Designer.

Autoincrementing values cannot be null (.NULL.).

Note Tables containing automatically incrementing field values append table-buffered records approximately 35% slower than tables without automatically incrementing field values, which might affect performance. When using table buffering, the table header is locked when the record is appended.
DEFAULT eExpression
Specifies a default value for the field. The data type of eExpression must be the same as the specified field's data type.

If you use the AUTOINC clause to turn on autoincrementing for a field and specify a default value, Visual FoxPro stores the default value in the table but does not use it. Visual FoxPro uses the default value if you use the ALTER TABLE - SQL command to remove autoincrementing for the field.

UNIQUE
Creates a candidate index for the field. The candidate index tag has the same name as the field. For more information about candidate indexes, see Index Information Display and Setting a Primary or Candidate Index.
COLLATE cCollateSequence
Specifies a collation sequence other than the default setting, MACHINE. The cCollateSequence parameter must be a valid Visual FoxPro collation sequence. For more information about setting collation sequences, see Optimization of International Applications and SET COLLATE Command.
NOCPTRANS
Prevents translation to a different code page for character and memo fields. You can specify NOCPTRANS only for character and memo fields.
FROM ARRAY ArrayName
Specifies the name of an existing array whose contents are the name, type, precision, and scale for each field in the temporary table. You can use the FROM ARRAY clause instead of specifying individual fields. For the proper format of the contents of the array, see AFIELDS( ) Function.

Autoincrementing is turned on when the step value is greater than 0.

Remarks

CREATE CURSOR creates a temporary table that exists until it is closed. You can manipulate a temporary table created with CREATE CURSOR like any other table — you can browse and index it, and you can append and modify records.

The temporary table opens in the lowest numbered available (unused) work area and can be accessed by its alias. Each field in the temporary table is defined with a name, type, precision, and scale. These definitions can be obtained from the command itself or from an array. The temporary table opens exclusively, regardless of the setting of SET EXCLUSIVE.

If you omit NULL and NOT NULL, the current setting of SET NULL determines if null values are allowed in the field. However, if you omit NULL and NOT NULL and include the PRIMARY KEY or UNIQUE clause, Visual FoxPro disregards the current setting of SET NULL, and the field defaults to NOT NULL.

Null values and duplicate records are not permitted in a field used for a candidate index. However, Visual FoxPro does not generate an error if you create a candidate index for a field that supports null values. Visual FoxPro generates an error if you attempt to enter a null or duplicate value into a field used for a candidate index.

Note Candidate indexes, created by including the UNIQUE option (provided for ANSI compatibility) in CREATE TABLE – SQL or ALTER TABLE – SQL commands, are not the same as indexes created in the INDEX command with the UNIQUE option. An index created in the INDEX command using the UNIQUE option allows duplicate index keys; candidate indexes do not allow duplicate index keys. For more information about the UNIQUE option in the INDEX command, see INDEX Command.

If the table is converted to another code page, the fields for which NOCPTRANS has been specified are not translated.

CREATE CURSOR...FROM ARRAY recognizes all the fields available in the AFIELDS( ) function and turns on autoincrementing in the cursor when the Step value is greater than zero.

Example

The following example creates a cursor with the alias "employee". A blank record is appended, filled, and displayed with the BROWSE command.

CLOSE DATABASES
CLEAR
CREATE CURSOR employee ;
 (EmpID N(5), Name C(20), Address C(30), City C(30), ;
  PostalCode C(10), OfficeNo C(8) NULL, Specialty M)
DISPLAY STRUCTURE
WAIT WINDOW "Press a key to add a record."

INSERT INTO employee (EmpId, Name, Address, City, PostalCode, ;
   OfficeNo, Specialty);
   VALUES (1002, "Dr. Bonnie Doren", "University of Oregon", "Eugene", ;
   "98403", "", "Secondary Special Education")
BROWSE

* At this point you can copy this record to a permanent table.
CLOSE ALL   && Once the cursor closes, all data is flushed from memory.
CLEAR

The following example uses NOCPTRANS to prevent translation to a different code page. The example creates a cursor named "mycursor" that contains two character fields and two memo fields. The second character field, "char2", and the second memo field, "memo2", include NOCPTRANS to prevent translation.

CREATE CURSOR mycursor (char1 C(10), char2 C(10) NOCPTRANS,;
   memo1 M, memo2 M NOCPTRANS)

See Also

AFIELDS( ) | CREATE | CREATE QUERY | CREATE TABLE - SQL | INSERT - SQL | MODIFY QUERY | SELECT - SQL


CREATE DATABASE Command

Creates a database and opens it.

CREATE DATABASE [DatabaseName | ?]

Parameters

DatabaseName
Specifies the name of the database to create.

If SAFETY is set to ON and the database name you specify has the same path and name as an existing database, Visual FoxPro displays a warning dialog box that prompts you to specify a new path or name for the database.

?
Displays the Create dialog box from which you can specify the name of the database to create.

Remarks

A database file has a .dbc extension. The associated database memo files have a .dct extension, and the associated index files have a .dcx extension.

The database is opened exclusively, regardless of the setting of SET EXCLUSIVE. Because CREATE DATABASE opens the database after it has been created, you do not have to issue a subsequent OPEN DATABASE command.

If CREATE DATABASE is issued without any of its optional arguments, the Create dialog box is displayed, allowing you to specify a name for the database.

Example

This example creates a database named people. A table named friends is created and is automatically added to the database. DISPLAY TABLES is used to display the tables in the database, and DISPLAY DATABASES is used to display information about the tables in the database.

CREATE DATABASE people
CREATE TABLE friends (FirstName C(20), LastName C(20))
CLEAR
DISPLAY TABLES  && Displays tables in the database
DISPLAY DATABASES  && Displays table information

See Also

ADD TABLE | CLOSE DATABASES | DBC( ) | DBGETPROP( ) | DBSETPROP( ) | DELETE DATABASE | DISPLAY TABLES | FREE TABLE | INDBC( ) | MODIFY DATABASE | OPEN DATABASE | PACK DATABASE | REMOVE TABLE | SET DATABASE | VALIDATE DATABASE | ADBOBJECTS( ) | ADATABASES( )


CREATE FORM Command

Opens the Form designer.

CREATE FORM [FormName | ?] [AS cClassName FROM cClassLibraryName | ?]
   [NOWAIT] [SAVE] [DEFAULT] [[WINDOW WindowName1] [IN [WINDOW]
      WindowName2 | IN SCREEN]]

Parameters

FormName
Specifies the file name for the form. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .scx extension. If a form file with the name you specify already exists, you are asked if you want to overwrite the existing file (if SET SAFETY is set to ON).
?
Displays the Create dialog box from which you can choose a form or enter the name of a new form to create.
AS cClassName FROM cClassLibraryName | ?
Creates a new form from a form class in a .vcx visual class library. cClassName specifies the name of the user-defined form class from which the new form is created. An error is generated if cClassName isn't based on a form. cClassLibraryName specifies the name of the .vcx visual class library containing the form class specified with cClassName. Include ? to display the Open dialog box, allowing you to specify the visual class library.
NOWAIT
Continues program execution after the Form designer has been opened. The program doesn't wait for the Form designer to be closed, but continues execution on the program line immediately following the line that contains CREATE FORM NOWAIT. If you omit NOWAIT, when CREATE FORM is issued in a program, the Form designer is opened and program execution pauses until the Form designer is closed.

Including NOWAIT has no effect on CREATE FORM when it is issued in the Command window.

SAVE
When issued in a program, leaves the Form designer open after another window is brought forward. Including the SAVE option has no effect when issued from the Command window.
DEFAULT
Specifies that the Form designer is opened with the default Visual FoxPro form template, overriding a default form template specified on the Forms tab of the Options dialog.

For additional information about form templates, see Creating Forms .

WINDOW WindowName1
Specifies a window whose characteristics the Form designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Form designer can be moved. The window need not be active or visible, but it must be defined.

The Form designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Form designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Form designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Form designer is opened. The Form designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Form designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Form designer.

IN SCREEN
Specifies that the Form designer is explicitly opened in the main Visual FoxPro window, after the Form designer has been placed in a parent window. The Form designer is placed in a parent window by including the IN WINDOW clause.

Remarks

Issuing CREATE FORM without any additional arguments opens a new form in the Form designer. When you exit the Form designer, you are prompted to save the form with a different name.

See Also

_BROWSER | COMPILE FORM | DO FORM | GETPEM( ) | _INCLUDE | MODIFY FORM | PEMSTATUS( ) | Session Object | SYS(1269) - Property Information | SYS(1270) - Object Location | SYS(1271) - Object's .SCX File | SYS(1272) - Object Hierarchy


CREATE FROM Command

Creates a table from a table created by the COPY STRUCTURE EXTENDED command.

CREATE [FileName1 [DATABASE DatabaseName [NAME LongTableName]]]
   FROM [FileName2]

Parameters

FileName1
Specifies the name of the new table to create.
DATABASE DatabaseName
Specifies a database to which the new table is added.
NAME LongTableName
Specifies a long name for the new table. Long names can contain up to 128 characters and can be used in place of short file names in the database.
FROM [FileName2]
Specifies the table, created either manually or with COPY STRUCTURE EXTENDED, from which the new table is created.

Remarks

This variation of CREATE assumes that the table specified in FileName2 has been created either manually with COPY STRUCTURE EXTENDED. A new table FileName1 is created with the structure described in FileName2. The newly created table becomes the active table.

If you do not include either FileName1 or FileName2, or both, a dialog box appears. In this dialog box, you can specify the file to create or the FROM file, or both.

Note All records in FileName2, including those marked for deletion, are used to create FileName1.

CREATE FROM turns on autoincrementing for fields when the FIELD_STEP field in the table created by COPY STRUCTURE EXTENDED contains a valid value. The autoincrementing value and step values are retained from the original table.

Example

The following example displays the structure of the "Orders" table, copies the structure extended file to the "Temp" table, browses "Temp", creates a table called "Backup" from "Temp", and displays the structure of "Backup".

CLOSE DATABASES
CLEAR
SET PATH TO (HOME(2) + 'Data\')     && Sets path to database.
USE Orders
DISPLAY STRUCTURE
WAIT WINDOW 'Structure of the Orders table' NOWAIT
COPY STRUCTURE EXTENDED TO Temp
USE Temp
WAIT WINDOW 'Temp table has 1 row per field in Orders' NOWAIT
BROWSE
CREATE Backup FROM Temp
USE Backup
DISPLAY STRUCTURE
WAIT WINDOW 'Backup.dbf has the same structure as Orders' NOWAIT
USE
DELETE FILE Temp.dbf
DELETE FILE Backup.dbf

See Also

COPY STRUCTURE EXTENDED | COPY STRUCTURE | CREATE


CREATE LABEL Command

Opens the Label designer so you can create a label.

CREATE LABEL [FileName | ?] [NOWAIT] [SAVE] [WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN

Parameters

FileName
Specifies the file name for the label. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .lbx extension.
?
Displays the Create dialog box that prompts you to name the label being created.
NOWAIT
Continues program execution after the Label designer is opened. The program doesn't wait for the Label designer to be closed, but continues execution on the program line immediately following the line that contains CREATE LABEL NOWAIT. If you omit NOWAIT when CREATE LABEL is issued in a program, the Label designer is opened and program execution pauses until the Label designer is closed.

Including the NOWAIT option has no effect on the CREATE LABEL command when issued from the Command window.

SAVE
Leaves the Label designer open after another window is activated. If you omit SAVE, the Label designer is closed when another window is activated.

Including SAVE has no effect when issued from the Command window.

WINDOW WindowName1
Specifies a window whose characteristics the Label designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Label designer can be moved. The window doesn't have to be active or visible, but it must be defined.

The Label designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Label designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Label designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Label designer is opened. The Label designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Label designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible to access the Label designer.

IN SCREEN
Specifies that the Label designer is explicitly opened in the main Visual FoxPro window, after the Label designer has been placed in a parent window. A Label designer is placed in a parent window by including the IN WINDOW clause.

Remarks

CREATE LABEL lets you create labels in standard label formats or design your own custom labels. You can also use the Label Wizard to create labels.

See Also

LABEL | MODIFY LABEL | Label Wizard | Label Designer | Creating Reports and Labels | Creating a Mailing Label Layout


CREATE MENU Command

Opens the Menu designer in Visual FoxPro.

CREATE MENU [FileName | ?] [NOWAIT] [SAVE] [WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN

Parameters

FileName
Specifies the file name for the menu table. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .mnx extension.
?
Displays the Create dialog box that prompts you to name the menu being created.
NOWAIT
Continues program execution after the Menu designer is opened. The program doesn't wait for the Menu designer to be closed, but continues execution on the program line immediately following the line that contains CREATE MENU NOWAIT. If you omit NOWAIT, when CREATE MENU is issued in a program, the Menu designer is opened and program execution pauses until the Menu designer is closed.

If you issue CREATE MENU from the Command window and include NOWAIT, the New Menu dialog is not displayed. The New Menu dialog lets you specify the type of menu (standard or shortcut) created.

SAVE
Leaves the Menu designer open after another window is activated. If you omit SAVE, the Menu designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.
WINDOW WindowName1
Specifies a window whose characteristics the Menu designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Menu designer can be moved. The window need not be active or visible, but it must be defined.

The Menu designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Menu designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Menu designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Menu designer is opened. The Menu designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Menu designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Menu designer.

IN SCREEN
Specifies that the Menu designer is opened explicitly in the main Visual FoxPro window, after the Menu designer has been placed in a parent window. The Menu designer is placed in a parent window by including the IN WINDOW clause.

Remarks

Issuing CREATE MENU without any additional arguments opens the Menu designer within which you can define a menu system. The name MENU1 is temporarily assigned to the menu definition table. When you exit the Menu designer, you can save the menu definition under a different name.

See Also

DEFINE MENU | MODIFY MENU | Menu Designer | Designing Menus and Toolbars


CREATE PROJECT Command

Opens the Project Manager so you can create a project.

CREATE PROJECT [FileName | ?] [NOWAIT] [SAVE] [WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN [NOSHOW] [NOPROJECTHOOK]

Parameters

FileName
Specifies the file name for the project table. If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .pjx extension.
?
Displays the Create dialog box that prompts you to name the project being created.
NOWAIT
Continues program execution after the Project Manager is opened. The program doesn't wait for the Project Manager to be closed, but continues execution on the program line immediately following the line that contains CREATE PROJECT NOWAIT. If you omit NOWAIT when CREATE PROJECT is issued in a program, the Project Manager is opened and program execution pauses until the Project Manager is closed.

Including NOWAIT has no effect on CREATE PROJECT when it is issued in the Command window.

SAVE
Leaves the Project Manager open after another window is activated. If you omit SAVE, the Project Manager is closed when another window is activated.

Including SAVE has no effect when issued from the Command window.

WINDOW WindowName1
Specifies a window whose characteristics the Project Manager takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Project Manager can be moved. The window need not be active or visible, but it must be defined.

The Project Manager has a default size that can be larger than the window from which it takes its characteristics. In this case, the Project Manager still assumes the characteristics of the window in which it is placed. The upper-left corner of the Project Manager is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Project Manager is opened. The Project Manager doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Project Manager moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Project Manager.

IN SCREEN
Specifies that the Project Manager is explicitly opened in the main Visual FoxPro window, after the Project Manager has been placed in a parent window. The Project Manager is placed in a parent window by including the IN WINDOW clause.
NOSHOW
Specifies that the Project Manager is hidden (its Visible property is set to False (.F.)) when it is opened. To display the Project Manager, set the Project Manager's Visible property to True (.T.). NOSHOW allows you to manipulate a project before displaying it in the Project Manager. Note that to avoid confusion with the NOSHADOW keyword, you cannot abbreviate NOSHOW to less than five characters.
NOPROJECTHOOK
Specifies that a ProjectHook object not be created when the Project Manager is opened. Include NOPROJECTHOOK for projects that will not be manipulated programmatically through the Project Manager hooks. Note that a Project object is still created whenever a project file (.pjx) is opened.

Remarks

A project is a table that keeps track of all files that are required to create an application, as well as all dependencies, references, and connections among the files. A project table has a .pjx extension and an associated memo file with a .pjt extension. In a project, you specify all the pieces that are required for an application, and Visual FoxPro ensures that compiled files are based on the latest source files.

A project table can be opened with USE and manipulated like any other Visual FoxPro table.

Issuing the command CREATE PROJECT without any additional arguments displays the Create dialog, allowing you to specify a name for the project.

See Also

BUILD APP | BUILD PROJECT | MODIFY PROJECT | Compiling an Application


CREATE QUERY Command

Opens the Query designer.

CREATE QUERY [FileName | ?] [NOWAIT]

Parameters

FileName
Specifies the file name for the query. If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .qpr extension.
?
Displays the Create dialog box that prompts you to name the query being created.
NOWAIT
Continues program execution after the Query designer is opened. The program doesn't wait for the Query designer to be closed, but continues execution on the program line immediately following the line that contains CREATE QUERY NOWAIT. If you omit NOWAIT when CREATE QUERY is issued in a program, the Query designer is opened and program execution pauses until the Query designer is closed.

NOWAIT is effective only from within a program. It has no effect on CREATE QUERY when issued from the Command window.

Remarks

CREATE QUERY opens the Query designer so you can interactively create a query.

A SQL SELECT command is used to retrieve data from tables. SELECT is very powerful and can replace a series of Visual FoxPro commands. Because one SQL SELECT performs the function of a series of Visual FoxPro commands, SELECT optimizes program performance.

Think of SELECT as a way to pose a query to Visual FoxPro to obtain information from tables. SELECT allows you to specify the information you want without telling Visual FoxPro how to retrieve the information. Visual FoxPro determines the best way to retrieve the information.

After you create a query, the query is stored as a Visual FoxPro program file with a .qpr extension. A query program can be executed with DO. You must include the query file extension when executing a query with DO, as shown in the following example.

DO my_query.qpr

Issuing the command CREATE QUERY without any additional arguments opens a new query window. The name QUERY1 is assigned to the query. When you exit the Query window, you can save the query with a different name.

See Also

MODIFY QUERY | SELECT - SQL | Query Designer


CREATE REPORT – Quick Report Command

Programmatically creates a report.

CREATE REPORT FileName1 | ? FROM FileName2 [FORM | COLUMN]
 [FIELDS FieldList] [ALIAS] [NOOVERWRITE] [WIDTH nColumns]

Parameters

FileName1
Specifies the file name for the report. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .frx extension.
?
Displays the Create dialog box that prompts you to name the report being created.
FROM FileName2
Specifies the name of the table from which the report is created. The table doesn't have to be open.
FORM
Specifies that the report is created with the fields and their names arranged from top to bottom in the Detail band.
COLUMN
Specifies that the report is created with the fields arranged from left to right across the page in the Detail band. The field names are placed in the Page Header band. If you omit FORM and COLUMN, the report defaults to the COLUMN format.
FIELDS FieldList
Specifies the fields from the table that appear in the report. Separate the fields in FieldList with commas.
ALIAS
Specifies that the table alias is added to the field names in the report.
NOOVERWRITE
Specifies that an existing report isn't overwritten. If a report already exists with the name specified with FileName1, the report isn't created.
WIDTH nColumns
Specifies the width of the report page in columns.

Remarks

This form of CREATE REPORT creates a quick report without opening the Report designer. The report is created as if you chose Quick Report from the Report menu.

Another form of CREATE REPORT, discussed in the previous topic, opens the Report designer to let you interactively create a report.

See Also

CREATE REPORT | MODIFY REPORT | REPORT | Creating Reports and Labels | Report Designer


CREATE REPORT Command

Opens a report in a Report designer.

CREATE REPORT [FileName | ?] [NOWAIT] [SAVE] [WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN

Parameters

FileName
Specifies the file name for the report. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .frx extension. If a report file with the name you specify already exists, you are asked if you want to overwrite the existing file (if SET SAFETY is ON).
?
Displays the Create dialog box that prompts you to name the report being created.
NOWAIT
Continues program execution after the Report designer is opened. The program doesn't wait for the Report designer to be closed, but continues execution on the program line immediately following the line that contains CREATE REPORT NOWAIT. If you omit NOWAIT when CREATE REPORT is issued in a program, the Report designer is opened and program execution pauses until the Report designer is closed.

Including NOWAIT has no effect on CREATE REPORT when it is issued in the Command window.

SAVE
Leaves the Report designer open after another window is activated. If you omit SAVE, the Report designer is closed when another window is activated.

Including SAVE has no effect when issued from the Command window.

WINDOW WindowName1
Specifies a window whose characteristics the Report designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Report designer can be moved. The window need not be active or visible, but it must be defined.

The Report designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Report designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Report designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Report designer is opened. The Report designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Report designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Report designer.

IN SCREEN
Specifies that the Report designer is opened explicitly in the main Visual FoxPro window, after the Report designer has been placed in a parent window. The Report designer is placed in a parent window by including the IN WINDOW clause.

Remarks

Issuing CREATE REPORT without any additional arguments opens a new Report designer. The name REPORT1 is assigned to the report definition. When you exit the Report designer, you are prompted to save the report definition with a different name.

CREATE REPORT can also be used to generate a quick report without opening the Report designer.

See Also

ASCIICOLS | _ASCIIROWS | CREATE REPORT - Quick Report | MODIFY REPORT | REPORT | Report Designer | Creating Reports and Labels


CREATE SQL VIEW Command

Displays the View Designer, allowing you to create a SQL view. Views are a powerful means of providing customized access to selected portions of your database, combining the flexibility of a query with the ability to update data.

A SQL view allows you to extract specific fields and records from one or more related tables and treat the resulting data set as a table that you can update.

CREATE [SQL] VIEW [ViewName ] [REMOTE]
[CONNECTION ConnectionName [SHARE] | CONNECTION DataSourceName]
   [AS SQLSELECTStatement]

Parameters

SQL
Creates a SQL view.
VIEW ViewName
Specifies the name of the view to create.
REMOTE
Specifies that a remote view using remote tables is created. If you omit REMOTE, you can create a view using local tables.
CONNECTION ConnectionName [SHARE]
Specifies a named connection to establish when the view is opened.

If you include the SHARE keyword, Visual FoxPro uses new statement handle for the shared connection, if one is available. If a shared connection is not available, Visual FoxPro creates a shared connection when the view opens, which you might be able to share with other views.

CONNECTION DataSourceName
Specifies an existing data source to which a connection is established.
AS SQLSELECTStatement
Specifies the view definition. SQLSELECTStatement must be a valid SQL SELECT statement and should not be enclosed in quotation marks ("").

For local views, preface the view or table name with the name of the database and an exclamation point (!). For example, the following command creates a SQL view called mysqlview that selects all fields in the orders table in the customer database:

CREATE SQL VIEW mysqlview AS SELECT * FROM customer!orders

For additional information about SQL SELECT statements, see SELECT – SQL.

You can limit the scope of a view without creating a separate view for each subset of records by creating a parameterized view. A parameterized view uses a WHERE clause that limits the records downloaded to only those records by supplying a value as a parameter.

For example, you can create a SQL view that allows you to download records for any country, simply by supplying the country's name when you use the view.

The parameter you supply is evaluated as a Visual FoxPro expression. If the evaluation fails, Visual FoxPro prompts for the parameter value. For example, if the customer table from the Testdata database is located on a remote server, the following example creates a parameterized remote view that limits the view to those customers whose country matches the value supplied for the ?cCountry parameter:

OPEN DATABASE Testdata
CREATE SQL VIEW customer_remote_view CONNECTION remote_01 ;
   AS SELECT * FROM customer WHERE customer.country = ?cCountry

For additional information about parameterized views, see Creating Views.

Example

The following example opens the testdata database. CREATE SQL VIEW is used to create a local SQL view named myview which is created from a SELECT – SQL statement that selects all records from the customer table. The View Designer is displayed, allowing you to modify the SQL view. After the View Designer is closed, the SQL view is erased.

CLOSE DATABASES
* Open testdata database
OPEN DATABASE (HOME(2) + 'data\testdata')

* Create view with initial select criteria from customer table
CREATE SQL VIEW myview AS SELECT * FROM testdata!customer;
   WHERE country="Mexico"

* Activate View Designer to modify or run query
MODIFY VIEW myview  &&Activates View Designer

* Delete view after View Designer closes
DELETE VIEW myview

See Also

CREATE DATABASE | CREATE VIEW | DELETE VIEW | DISPLAY VIEWS | LIST VIEWS | MODIFY VIEW | OPEN DATABASE | RENAME VIEW | SELECT – SQL | USE | DBSETPROP( ) Function | DBGETPROP( ) Function


CREATE TABLE - SQL Command

Creates a table using the specified fields or from an array.

CREATE TABLE | DBF TableName1 [NAME LongTableName] [FREE]
    ( FieldName1 FieldType [( nFieldWidth [, nPrecision] )] [NULL | NOT NULL]
    [CHECK lExpression1 [ERROR cMessageText1]]
    [AUTOINC [NEXTVALUE NextValue [STEP StepValue]]] [DEFAULT eExpression1]
    [PRIMARY KEY | UNIQUE [COLLATE cCollateSequence]]
    [REFERENCES TableName2 [TAG TagName1]] [NOCPTRANS]
    [, FieldName2 ... ]
    [, PRIMARY KEY eExpression2 TAG TagName2 |, UNIQUE eExpression3 TAG TagName3
    [COLLATE cCollateSequence]]
    [, FOREIGN KEY eExpression4 TAG TagName4 [NODUP]
    [COLLATE cCollateSequence]
    REFERENCES TableName3 [TAG TagName5]] [, CHECK lExpression2 [ERROR cMessageText2]] )
    | FROM ARRAY ArrayName

Parameters

CREATE TABLE | DBF TableName1
Creates a table or .dbf. The TableName1 parameter specifies the name of the table. The TABLE and DBF options are identical.
NAME LongTableName
Specifies a long name for the table. You can specify a long table name only when a database is open because long table names are stored in databases. Long names can contain up to 128 characters and can be used in place of short file names in the database.
FREE
Specifies that the table is not be added to an open database. You do not need to use FREE if a database is not open.
FieldName1, FieldType, nFieldWidth, nPrecision
Specifies the field name, field type, field width, and field precision (number of decimal places) respectively. A single table can contain up to 255 fields. If one or more fields allow null values, the limit decreases by one field to 254 fields.

The FieldType parameter is a single letter indicating the field's data type. Some field data types require that you specify nFieldWidth or nPrecision, or both. The following table lists the values for FieldType and whether nFieldWidth and nPrecision are required.

FieldType | nFieldWidth | nPrecision | Data type
C n – Character field of width n
D – – Date
T – – DateTime
N | n | d | Numeric field of width n with d decimal places
F | n | d | Floating numeric field of width n with d decimal places
I – – Integer
B – d Double
Y – – Currency
L – – Logical
M – – Memo
G – – General

The nFieldWidth and nPrecision parameters are ignored for D, T, I, Y, L, M, G, and P data types. The nPrecision parameter defaults to zero (no decimal places) if nPrecision is not included for the N or F types. The nPrecision parameter defaults to the number of decimal places specified by the setting of the SET DECIMALS command if nPrecision is not included for the B type.

NULL | NOT NULL
Specifies whether null values are allowed in the field. NULL permits null values, while NOT NULL does not allow null values. If one or more fields can contain null values, the maximum number of fields the table can contain is reduced from 255 to 254.
CHECK lExpression1
Specifies a validation rule for the field. The lExpression1 parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure. Visual FoxPro checks the validation rule specified in the CHECK clause when a blank record is appended.
ERROR cMessageText1
Specifies an error message. Visual FoxPro displays this message when the validation rule specified with the CHECK clause generates an error. The message displays only when data is changed within a Browse window or Edit window.
AUTOINC [NEXTVALUE NextValue [STEP StepValue]]
Enables autoincrementing for the field. NextValue specifies the start value and can be a positive or a negative integer value ranging from 2,147,483,647 to -2,147,483,647. The default value is 1. You can set NextValue using the Next Value spin box in Fields tab of the Table Designer.

StepValue specifies the increment value for the field and can be a positive, nonzero integer value ranging from 1 to 255. The default value is 1. You can set StepValue using the Step spin box in the Fields tab of the Table Designer.

Autoincrementing values cannot be NULL.

Note Tables containing automatically incrementing field values append table-buffered records approximately 35% slower than tables without automatically incrementing field values, which might affect performance. When using table buffering, the table header is locked when the record is appended.
DEFAULT eExpression1
Specifies a default value for the field specified in FieldName1. The data type of eExpression1 must be the same as the specified field's data type.

If you use the AUTOINC clause to turn on autoincrementing for a field and specify a default value, Visual FoxPro stores the default value in the table but does not use it. Visual FoxPro uses the default value if you use the ALTER TABLE - SQL command to remove autoincrementing for the field.

PRIMARY KEY | UNIQUE
PRIMARY KEY creates a primary index for the field specified in FieldName1. UNIQUE creates a candidate index for the field specified in FieldName1. The primary index tag or candidate index tag have the same name as the field. For more information about primary and candidate indexes, see Setting a Primary or Candidate Index.
COLLATE cCollateSequence
Specifies a collation sequence other than the default setting, MACHINE. The cCollateSequence parameter must be a valid Visual FoxPro collation sequence. For more information about setting collation sequences, see Optimization of International Applications and SET COLLATE Command.
REFERENCES TableName2 [ TAG TagName1 ]
Specifies the parent table to which a persistent relationship is established. The parent table cannot be a free table.

The TagName1 parameter clause specifies an index tag name for the parent table in TableName2. Index tag names can contain up to 10 characters. If you omit the TAG clause, the relationship is established using the primary index key of the parent table. If the parent table does not have a primary index, Visual FoxPro generates an error.

NOCPTRANS
Prevents translation to a different code page for character and memo fields. You can specify NOCPTRANS only for character and memo fields. This creates what appears to be Character (binary) and Memo (binary) data types in the Table Designer.
FieldName2 ...
Specifies one or more additional fields and attributes.
PRIMARY KEY eExpression2 TAG TagName2
Specifies any field or combination of fields in the table for creating a primary index. You cannot use this PRIMARY KEY clause if you previously created a primary index for a field because a table can have only one primary index. If you include more than one PRIMARY KEY clause in a CREATE TABLE statement, Visual FoxPro generates an error.

The TagName2 parameter specifies a name for the primary index tag in eExpression2. Index tag names can contain up to 10 characters.

UNIQUE eExpression3 TAG TagName3
Specifies any field or combination of fields in the table for creating a candidate index. A table can have multiple candidate indexes. However, if you previously created a primary index with one of the PRIMARY KEY options, you cannot include the field that was specified for the primary index.

The TagName3 parameter specifies a name for the candidate index tag in eExpression3. Index tag names can contain up to 10 characters.

FOREIGN KEY eExpression4 TAG TagName4 [ NODUP ]
Creates a foreign (non-primary) index, specifies the index key expression, and establishes a relationship to a parent table. You can create multiple foreign indexes for the table, but foreign index expressions must specify different fields in the table.

The TagName4 parameter specifies the name for the foreign index key tag. Index tag names can contain up to 10 characters.

NODUP creates a candidate foreign index.

REFERENCES TableName3 TAG TagName5
Specifies the parent table to which a persistent relationship is established.

The TagName5 parameter specifies the name of the index tag for the parent table in TableName3 and establishes a relation based on the index tag. Index tag names can contain up to 10 characters. If you omit the TAG clause, the relationship is established by default using the primary index key of the parent table.

CHECK lExpression2
Specifies the table validation rule. The lExpression2 parameter must evaluate to a logical expression and can be a user-defined function or a stored procedure.
ERROR cMessageText2
Specifies an error message for the table validation rule in lExpression2. Visual FoxPro displays this message when the table validation rule generates an error. The message displays only when data is changed within a Browse window or Edit window.
FROM ARRAY ArrayName
Specifies the name of an existing array whose contents are the name, type, precision, and scale for each field in the table. You can use the FROM ARRAY clause instead of specifying individual fields in the CREATE TABLE - SQL statement. For the proper format of the contents of the array, see AFIELDS( ) Function.

Autoincrementing is turned on when StepValue is greater than 0.

Remarks

The new table opens in the lowest numbered available (unused) work area and can be accessed by its alias. The new table opens exclusively, regardless of the current setting of the SET EXCLUSIVE command.

If a database is open and you do not include the FREE clause, the new table is added to the database. You cannot create a new table with the same name as a table in the database.

If the table is converted to another code page, the fields for which NOCPTRANS has been specified are not translated.

If a database is not open when you create the new table, including the NAME, CHECK, DEFAULT, FOREIGN KEY, PRIMARY KEY, or REFERENCES clauses generates an error.

Tables created in the Visual FoxPro OLE DB Provider using CREATE TABLE are placed in the default folder of the calling application, unless you specify another location.

Note The CREATE TABLE syntax uses commas to separate certain CREATE TABLE options. You must place the NULL, NOT NULL, CHECK, DEFAULT, PRIMARY KEY, and UNIQUE clauses within the parentheses containing the column definitions.

If you omit NULL and NOT NULL, the current setting of the SET NULL command determines if null values are allowed in the field. However, if you omit NULL and NOT NULL but include the PRIMARY KEY or UNIQUE clause, Visual FoxPro disregards the current setting of SET NULL, and the field defaults to NOT NULL.

Visual FoxPro generates an error if the validation rule specified in the CHECK clause does not allow for a blank field value in an appended record.

Null values and duplicate records are not permitted in a field used for a primary or candidate index. However, Visual FoxPro does not generate an error if you create a primary or candidate index for a field that supports null values. Visual FoxPro generates an error if you attempt to enter a null or duplicate value into a field used for a primary or candidate index.

Note Candidate indexes, created by including the UNIQUE option (provided for ANSI compatibility) in CREATE TABLE – SQL or ALTER TABLE – SQL commands, are not the same as indexes created in the INDEX command with the UNIQUE option. An index created in the INDEX command using the UNIQUE option allows duplicate index keys; candidate indexes do not allow duplicate index keys. For more information about the UNIQUE option in the INDEX command, see INDEX Command.

For NextValue, an empty value is interpreted as 0 and causes incrementing to begin with 0 + StepValue.

The StepValue incremental value is always positively added. If you want to use a negative automatically incrementing series, you should begin with a negative NextValue and step towards 0 using the StepValue increment value. For example, if NextValue equals -2147483647, the first step produces a value of -2147483646.

CREATE TABLE recognizes all the fields available in the AFIELDS( ) function and turns on autoincrementing in the table when StepValue is greater than zero.

Examples

Example 1

The following example creates a new database named mydata1 and uses CREATE TABLE to create three tables: Salesman, Customer, and Orders. The FOREIGN KEY and REFERENCES clauses in the second CREATE TABLE command create a persistent one-to-many relationship between the Salesman and Customer tables. The DEFAULT clauses in the third CREATE TABLE command establish default values, and the CHECK and ERROR clauses establish business rules for entering data into specific fields. The MODIFY DATABASE command displays the relationship between the three tables.

CLOSE DATABASES
CLEAR
CREATE DATABASE mydata1

* Create a Salesman table with a primary key.
CREATE TABLE Salesman ;
   (SalesID c(6) PRIMARY KEY, ;
   SaleName C(20))

* Create a Customer table and relate it to the Salesman table.
CREATE TABLE Customer ;
   (SalesID c(6), ;
   CustId i PRIMARY KEY, ;
   CustName c(20) UNIQUE,   ;
   SalesBranch c(3), ;
   FOREIGN KEY SalesId TAG SalesId REFERENCES Salesman)

* Create an Orders table related to Customer with its own primary
* key and some business rules such as defaults and checks.
CREATE TABLE Orders ;
   (OrderId i PRIMARY KEY, ;
      CustId i REFERENCES customer TAG CustId, ;
      OrderAmt y(4), ;
      OrderQty i ;
      DEFAULT 10 ;
      CHECK (OrderQty > 9) ;
      ERROR "Order Quantity must be at least 10", ;
         DiscPercent n(6,2) NULL ;
      DEFAULT .NULL., ;
      CHECK (OrderAmt > 0) ERROR "Order Amount must be > 0" )

* Display new database, tables, and relationships.
MODIFY DATABASE

* Delete example files.
SET SAFETY OFF && Suppress verification message.
CLOSE DATABASES     && Close database before deleting.
DELETE DATABASE mydata1 DELETETABLES

Example 2

The following example uses NOCPTRANS to prevent translation to a different code page. The example creates a table named "mytable" that contains two character fields and two memo fields. The second character field, "char2", and the second memo field, "memo2", include NOCPTRANS to prevent translation.

CREATE TABLE mytable (char1 C(10), char2 C(10) NOCPTRANS,;
   memo1 M, memo2 M NOCPTRANS)

Example 3

The following example creates a Customer table with a field called myField that has Integer data type and uses automatically incrementing field values:

CREATE TABLE Customer (myField i AUTOINC NEXTVALUE 1 STEP 1, name c(40) )

See Also

AFIELDS( ) Function | ALTER TABLE – SQL Command | Autoincrementing Field Values in Tables | CREATE Command | CREATE QUERY | INSERT – SQL Command | MODIFY QUERY Command | MODIFY STRUCTURE Command | OPEN DATABASE Command | SELECT – SQL Command | SET NOCPTRANS Command | SQL Commands Overview


CREATE TRIGGER Command

Creates a Delete, Insert, or Update trigger for a table.

CREATE TRIGGER ON TableName   FOR DELETE | INSERT |
UPDATE AS lExpression

Parameters

TableName
Specifies the table in the current database for which a trigger is created.
FOR DELETE | INSERT | UPDATE
Specifies the type of trigger Visual FoxPro creates.

If a trigger of the type you specify already exists and SET SAFETY is ON, Visual FoxPro asks you if you would like to overwrite the existing trigger. If SET SAFETY is OFF, the existing trigger is automatically overwritten.

AS lExpression
Specifies the logical expression evaluated when the trigger occurs. lExpression can be a user-defined function or a stored procedure that returns a logical value. Stored procedures are created for a table with MODIFY PROCEDURE.

A user-defined function or a stored procedure can use AERROR( ) to determine the name of the table for which the trigger occurred and the trigger type.

If lExpression evaluates to true (.T.), the command or event that caused the trigger to occur is executed.

If lExpression evaluates to false (.F.), the command or event that caused the trigger to occur is not executed. If an ON ERROR procedure is in effect, the ON ERROR procedure is executed instead of the command or event. If an ON ERROR procedure is not in effect, the command or event is not executed and Visual FoxPro generates an error message.

Remarks

Use CREATE TRIGGER to trap for events that cause records in a table to be deleted, added, or changed. Delete, Insert, or Update triggers can be created only for a table that has been added to a database. Use CREATE DATABASE to create a database, and ADD TABLE to add a table to a database.

The following lists describe the events that cause a Delete, Insert, or Update trigger to occur.

Delete Trigger

  • DELETE is issued.
  • A record is marked for deletion from the Table Menu in a Browse window or Edit window.
  • Note that issuing ZAP does not cause the Delete trigger to occur.

Insert Trigger

  • APPEND FROM is issued.
  • APPEND FROM ARRAY is issued.
  • APPEND BLANK is issued.
  • A record is appended from the Table Menu in a Browse window or Edit window.
  • IMPORT is issued.
  • INSERT – SQL is issued.
  • RECALL is issued.
  • A record is recalled from the Table Menu in a Browse window or Edit window.

Update Trigger

  • GATHER is issued.
  • REPLACE is issued.
  • REPLACE FROM ARRAY is issued.
  • UPDATE – SQL is issued.
  • Other event that causes a record to be modified, such as when a Form changes the contents of a field.

The following rules apply to triggers created with CREATE TRIGGER:

  • INSERT cannot be issued for a table with a trigger. However, INSERT – SQL can be used.
  • Issuing PACK does not cause any triggers to occur.
  • Issuing ZAP does not cause a Delete trigger to occur.
  • No trigger occurs if you update a record marked for deletion.
  • A trigger may not occur immediately, depending on the current buffering mode:

If table buffering is in effect, the Update trigger occurs when TABLEUPDATE( ) is issued and each buffered record is updated in the table.

Example

The following example creates an Update trigger which prevents values greater than 50 from being entered in the maxordamt field in the customer table. An error message is generated when the first REPLACE command is executed because the value for the maxordamt field is greater than 50. The second REPLACE command does not generate an error because the value for the maxordamt field is less than or equal to 50.

CLOSE DATABASES

OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table

* Set trigger on maxordamt field to fail with values <= 50
CREATE TRIGGER ON customer FOR UPDATE AS maxordamt <= 50

ON ERROR  && Restore the system error handler

WAIT WINDOW "Press a key to test trigger with value of 60"+CHR(13);
 +"When you get the error message, press Ignore."
REPLACE maxordamt WITH 60    && Displays an error message
? maxordamt

WAIT WINDOW "Press a key to test with value of 50."
REPLACE maxordamt WITH 50    && Value is accepted
? maxordamt
DELETE TRIGGER ON customer FOR UPDATE  && Remove the trigger

See Also

ADD TABLE | AERROR( ) | CREATE DATABASE | DELETE TRIGGER | DISPLAY DATABASE | LIST DATABASE | OPEN DATABASE


CREATE VIEW Command

Creates a view file from the Visual FoxPro environment.

CREATE VIEW FileName

Parameters

FileName
Specifies the name of the view file to create.

Remarks

CREATE VIEW builds a new view file containing information about the Visual FoxPro environment. SET VIEW restores the environment saved to a view file by CREATE VIEW. View files created with CREATE VIEW are assigned a .vue extension.

The information saved in a view file includes:

  • All tables, index, alternate files, and format files currently open in all work areas
  • All fields contained in the SET FIELDS list
  • All established relations between open tables
  • All filters in effect for open tables
  • The DEFAULT and PATH settings
  • The procedure file setting
  • The current Help file
  • The current resource file
  • The SET SKIP status
  • The status bar state (ON or OFF)

View files are useful both in programs and while debugging. Only one command, SET VIEW TO FileName, needs to be executed to restore the entire environment. While debugging, the environment settings can be saved in a view file, testing can be performed, and the environment can be restored to continue program execution.

See Also

CREATE SQL VIEW | SET VIEW | SET SKIP | SET FIELDS


DEACTIVATE MENU Command

Deactivates a user-defined menu bar and removes it from the screen; but does not remove the menu-bar definition from memory.

DEACTIVATE MENU MenuName1 [, MenuName2 ...] | ALL

Parameters

MenuName1 [, MenuName2 ...]
Specifies the names of the menu bars to deactivate. You can deactivate a set of menu bars by including a list of menu bar names separated by commas.
ALL
Deactivates all active menus.

Remarks

DEACTIVATE MENU removes an active menu bar or set of menu bars from the main Visual FoxPro window or a user-defined window without removing the menu bar definition from memory. A menu bar can be reactivated with ACTIVATE MENU and the menu bar name.

Tip When you include the system menu bar (_MSYSMENU) in an application, you do not need to define, activate, or deactivate the menu bar. Instead, issue SET SYSMENU AUTOMATIC.

To release a specific menu bar or a set of menu bars from memory, use RELEASE MENUS. You can release all menu bars from memory with CLEAR MENUS or CLEAR ALL.

Program control is returned to the program line immediately following the line that activated the menu bar unless DEFINE MENU BAR is used to create the menu bar or ACTIVATE MENU NOWAIT is used to activate the menu bar.

Example

The following example uses DEACTIVATE MENU to deactivate a menu and remove it from the screen. The current system menu bar is saved to memory with SET SYSMENU SAVE, and all the system menu titles are removed with SET SYSMENU TO.

Two menu titles are created with DEFINE PAD, and DEFINE POPUP creates a menu for each menu title. DEFINE BAR creates menu items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu. ACTIVATE MENU displays and activates the menu bar.

When an item is chosen from a menu, the CHOICE procedure is executed. CHOICE displays the name of the chosen item and the name of the menu containing the item. Program control continues on the line after ACTIVATE MENU.

Finally, the menu is deactivated and removed from the screen and is then released from memory with RELEASE MENUS EXTENDED.

*** Name this program DEACMENU.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
ON KEY LABEL ESC KEYBOARD CHR(13)
DEFINE MENU example BAR AT LINE 1
DEFINE PAD convpad OF example PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD cardpad OF example PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD convpad OF example ACTIVATE POPUP conversion
ON PAD cardpad OF example ACTIVATE POPUP cardinfo
DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' ;
   KEY CTRL+E, '^E'
DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
ON SELECTION POPUP conversion DO choice IN deacmenu WITH PROMPT( ), POPUP( )
DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF cardinfo PROMPT '\-'
DEFINE BAR 5 OF cardinfo PROMPT '\<Charges '
ON SELECTION POPUP cardinfo;
   DO choice IN deacmenu WITH PROMPT( ), POPUP( )

ACTIVATE MENU example
DEACTIVATE MENU example
RELEASE MENU example EXTENDED
SET SYSMENU NOSAVE
SET SYSMENU TO DEFAULT
ON KEY LABEL ESC

PROCEDURE choice
PARAMETERS mprompt, mpopup
WAIT WINDOW 'You chose ' + mprompt + ;
   ' from popup ' + mpopup NOWAIT

See Also

ACTIVATE MENU | CLEAR ALL | CLEAR MENUS | CREATE MENU | DEFINE MENU | HIDE MENU | RELEASE | SHOW MENU


DEACTIVATE POPUP Command

Deactivates a menu created with DEFINE POPUP.

DEACTIVATE POPUP MenuName1 [, MenuName2 ...] | ALL

Parameters

MenuName1 [, MenuName2 ...]
Specifies the names of the menu or menus to deactivate. You can deactivate a set of menus by including a list of menu names separated by commas.
ALL
Deactivates all active menus.

Remarks

DEACTIVATE POPUP removes an active menu or set of menus from the main Visual FoxPro window or a user-defined window without removing the menu definition from memory. A menu can be reactivated using ACTIVATE POPUP and the menu name.

Use RELEASE POPUPS with the menu name to release a specific menu or a set of menus from memory. You can release all menus from memory with CLEAR POPUPS or CLEAR ALL.

Program control is returned to the line immediately following the line that activated the menu unless ACTIVATE POPUP NOWAIT is used to activate the menu.

See Also

ACTIVATE POPUP | CLEAR ALL | CLEAR POPUPS | CREATE MENU | DEFINE POPUP | HIDE POPUP | RELEASE POPUPS | SHOW POPUP


DEACTIVATE WINDOW Command

Deactivates user-defined windows or Visual FoxPro system windows and removes them from the screen, but not from memory.

DEACTIVATE WINDOW WindowName1 [, WindowName2 ...] | ALL

Parameters

WindowName1 [, WindowName2 ...]
Specifies one or more windows to deactivate. You can specify Visual FoxPro system windows such as the Command window or a Browse window.
ALL
Deactivates all active windows.

To display the main FoxPro window again, choose Visual FoxPro Screen from the Window menu or issue ACTIVATE WINDOW SCREEN or SHOW WINDOW SCREEN.

Remarks

More than one user-defined window can be placed in the main Visual FoxPro window at the same time, but output is directed only to the most recently activated user-defined window. When more than one user-defined window is present, deactivating the current user-defined output window clears the contents of the window, removes the window from the screen and sends subsequent output to the previously activated user-defined window. If there is no output window, output is directed to the main Visual FoxPro window.

Use CLEAR WINDOWS or RELEASE WINDOWS to remove windows from both the screen and memory.

To deactivate a system window and or a toolbar (in Visual FoxPro), enclose the entire system window or toolbar name in quotation marks. For example, to deactivate the Report Controls toolbar in Visual FoxPro, issue the following command:

DEACTIVATE WINDOW "Report Controls"

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the DEACTIVATE WINDOW command.

Example

In the following example, a window named wOutput1 is defined and activated. After a record from the customer table is displayed, the program waits for the user to press a key and then deactivates the window.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

CLEAR
DEFINE WINDOW wOutput1 FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
ACTIVATE WINDOW wOutput1

DISPLAY
WAIT WINDOW 'Press a key to deactivate the window'
DEACTIVATE WINDOW wOutput1
RELEASE WINDOW wOutput1

See Also

ACTIVATE WINDOW | CLEAR WINDOWS | DEFINE WINDOW | HIDE WINDOW | RELEASE WINDOWS | SHOW WINDOW


DEBUG Command

Opens the Visual FoxPro debugger.

DEBUG

Remarks

The debugger Environment setting (FoxPro Frame or Debugger Frame) determines if the debugger is placed on the Visual FoxPro desktop or in a separate window. Toggle this setting in the Debugging tab of the Options dialog box.

If you issue DEBUG when the debugger is open, the debugger becomes the active window.

See Also

CLOSE DEBUGGER | Debugging Tab, Options Dialog Box | DEBUGOUT | SET DEBUG


DEBUGOUT Command

Directs the result of one or more expressions to the Debug Output window.

DEBUGOUT eExpression1 [, eExpression2] ...

Parameters

eExpression1 [, eExpression2] ...
Specifies one or more expressions to evaluate and display in the Debug Output window. You can specify multiple expressions of different types.

If the expression you specify is an object or object reference, Visual FoxPro automatically converts it to the string, "(Object)", to provide the character equivalent. In the following example, the _VFP system variable is returned as "(Object)" and passed to DEBUGOUT:

DEBUGOUT 123, _VFP, "Hello"

Remarks

Use DEBUGOUT to identify when a procedure or function is executed. For example, you can place DEBUGOUT at the beginning of a procedure to display a message in the Debug Output window, indicating that the procedure has begun executing.

Note You can abbreviate DEBUGOUT to a minimum of only six characters, which distinguishes it from the DEBUG command.

When you pass multiple expressions, a comma appears as a space. A carriage return line feed (CRLF) is added at the end of the line.

DEBUGOUT is disregarded in applications you distribute.

Example

The following example illustrates how DEBUGOUT can accept multiple expressions:

DEBUGOUT "test", 1, 2, 3, 4, DATE( ), _VFP

See Also

DEBUG | Debug Output Window | SET DEBUG


DECLARE - DLL Command

Registers a function in an external shared library. Libraries are 32-bit dynamic link library (.DLL) files.

DECLARE [cFunctionType] FunctionName IN LibraryName [AS AliasName]
   [cParamType1 [@] ParamName1, cParamType2 [@] ParamName2, ...]

Parameters

cFunctionType
Indicates the data type of the return value from the shared library, if any. If the function does not return a value, omit cFunctionType.

cFunctionType can assume the following values:

cFunctionType | Description
SHORT | 16-bit integer
INTEGER | 32-bit integer
SINGLE | 32-bit floating point
DOUBLE | 64-bit floating point
LONG | 32-bit long integer
STRING | Character string
OBJECT | IDispatch object type
FunctionName
Specifies the name of the shared library function to register in Visual FoxPro. Function names passed in this parameter are case-sensitive.
Note A DLL function name may not be the same as stated in the Win32 API manual. For example, the MessageBox function should be named MessageBoxA (for single-byte character), and MessageBoxW (for UNICODE). If Visual FoxPro cannot locate the DLL function you specify with FunctionName, the letter A is appended to the end of the function name and Visual FoxPro searches again for the function with the new name.

If the shared library function you specify has the same name as a Visual FoxPro function or is not a legal Visual FoxPro name, use the AS clause to assign an alias to the function when you register it, as described later in this topic.

You can also use OBJECT as a return value, such as "DECLARE OBJECT myfunc IN some DLL ..." although COM conventionally does not have any APIs of this form. For example:

DECLARE INTEGER AccessibleObjectFromWindow IN oleacc.dll ;
integer, integer, string , object @
IN LibraryName
Specifies the name of the external shared library containing the function specified with FunctionName.

If you specify WIN32API for the LibraryName, Visual FoxPro searches for the 32-bit Windows .dll function in Kernel32.dll, Gdi32.dll, User32.dll, Mpr.dll, and Advapi32.dll.

AS AliasName
Specifies an alias name for a shared library function name that has the same name as a Visual FoxPro function or is not a legal Visual FoxPro name. AliasName should not be a Visual FoxPro reserved word or the name of a shared library function already registered with Visual FoxPro.

If you assign alias to the function, use the alias when calling the shared library function. AliasName is not case-sensitive.

cParameterType1 [@] ParamName1, cParameterType2 [@] ParamName2, ...
Specifies the parameter types passed to the shared library function.

cParameterType is required and specifies the data type of any parameters that the shared library function expects to have passed to it. cParameterType may be one of the following:

cParameterType | Description
INTEGER | 32-bit integer
SINGLE | 32-bit floating point
DOUBLE | 64-bit floating point
LONG | 32-bit long integer
STRING | Character string

Visual FoxPro generates an error if the parameters are not of the type the shared library function expects. Null values can be passed as empty character strings.

To pass a parameter by reference when you call the function, you must include the at sign (@) after the parameter cParameterType in this command, and before the corresponding variable in the calling function. If you do not include @ in DECLARE, in the calling function, or in both, the parameter is passed by value. For information about shared library functions that require @ to pass parameters by reference, see the programmer's guide for your operating system or environment (for example, refer to the Microsoft Win32 Programmer's Guide for information on passing parameters to Windows DLLs).

Note The parameter names ParamName1, ParamName2, and so on, are optional, and are not used by Visual FoxPro or the shared library function. You can include them as a reminder of the names and types of parameters the function receives.

Remarks

Before you can call a shared library function from within Visual FoxPro, you must issue DECLARE with the name of the function, the name of the shared library containing the function, and the parameter types the function expects to receive.

For backward compatibility, Visual FoxPro allows calls to external API libraries using the SET LIBRARY command. (Using SET LIBRARY, you can access functions in Foxtools.fll.) However, using DECLARE is the preferred method to register shared library functions.

Though Visual FoxPro adds the OBJECT cFunctionType to this command primarily to support some ActiveX Accessibility API routines, you can use it generically with other Windows API routines.

For further information about calling shared library functions, see the programmer's guide for your operating system or environment (for example, refer to the Microsoft Win32 Programmer's Guide for information on calling DLLs).

Issue DISPLAY STATUS or LIST STATUS to display the names of registered functions. Issue CLEAR ALL or CLEAR DLLS to remove registered functions from memory.

Example

This example for Windows returns the window handle for Visual FoxPro or zero if you switch to another Windows application. When the WAIT window is displayed, you have 5 seconds to press ALT+TAB to switch to a different Windows application, or you can leave Visual FoxPro as the active application.

CLEAR
DECLARE INTEGER GetActiveWindow IN win32api
WAIT WINDOW "You can switch to another application now" TIMEOUT 5
? GetActiveWindow( )

See Also

CALL | CLEAR | DISPLAY DLLS | DISPLAY STATUS | LIST DLLS | LOAD | SET LIBRARY


DECLARE Command

Creates a one- or two-dimensional array.

DECLARE ArrayName1 (nRows1 [, nColumns1])
   [, ArrayName2 (nRows2 [, nColumns2])] ...

Remarks

DECLARE is identical in operation and syntax to DIMENSION. For more information, see DIMENSION.

When the size of an array is increased or decreased when SET COMPATIBLE is set to ON or DB4, the value of each element in the array is reinitialized to .F.

See Also

APPEND FROM ARRAY | COPY TO ARRAY | DIMENSION | GATHER | PRIVATE | PUBLIC | SCATTER | SET COMPATIBLE | STORE


DEFINE BAR Command

Creates a menu item on a menu created with DEFINE POPUP.

DEFINE BAR nMenuItemNumber1 | SystemItemName OF MenuName
   PROMPT cMenuItemText [PICTURE cFileName] [PICTRES cMenubarName]
   [BEFORE nMenuItemNumber2 | AFTER nMenuItemNumber3]
   [FONT cFontName [, nFontSize]] [STYLE cFontStyle]
   [KEY KeyLabel [, cKeyText]] [MARK cMarkCharacter]
   [MESSAGE cMessageText] [SKIP [FOR lExpression]]
   [COLOR SCHEME nSchemeNumber | COLOR ColorPairList]
   [MRU] [INVERT]

Parameters

nMenuItemNumber1
Specifies the menu item number. The menu item number makes it possible for you to reference the menu item in other commands and functions.
SystemItemName
Specifies a menu item on the Visual FoxPro system menu. For example, to provide access to the Print menu item, issue the following:
DEFINE BAR _MFI_PRINT OF popMyPopup PROMPT "Print..."

Not all Visual FoxPro system menu items are available. Use SYS(2013) to return a list of the Visual FoxPro system menu names that are available.

OF MenuName
Specifies the name of the menu on which the menu items are placed.
PROMPT cMenuItemText
Specifies the caption that appears on the menu item.

You can create a separator bar by specifying a backslash and a dash (\-) for cMenuItemText. A separator bar is used to separate item groups on a menu. For example, including the following command in a menu definition creates a separator bar between the third and fifth menu items:

DEFINE BAR 4 OF popMyPopup PROMPT '\-'

You can create multi-column menus by specifying a backslash and a vertical bar (\|) at the beginning of cMenuItemText. The menu item starts a new column, and subsequent menu items are placed in the same column until another menu item beginning with \| is encountered. For example, including the following command in a menu definition creates a new column in the menu:

DEFINE BAR 4 OF popMyPopup PROMPT '\|Start a new column'

You can create an access key for a menu item by placing a backslash and a less-than sign (\<) before the character to be the access key. For example:

DEFINE POPUP popReceive
DEFINE BAR 1 OF popReceive PROMPT '\<Invoices'
DEFINE BAR 2 OF popReceive PROMPT 'In\<quiry'
ACTIVATE POPUP popReceive

The user can press the I key to choose Invoices from the Receive menu and press the Q key to choose Inquiry from the same menu.

PICTURE cPictureName
Enables you to use an existing image with the menu bar. You can specify cPictureName in a relative path.
PICTRES cMenubarName
Specifies a system menu bar name as a resource for a menu. If cPictureName = "", then contents of Resname field of the .mnx table structure is treated as filename for use in DEFINE BAR...PICTURE. This functionality was introduced in Visual FoxPro version 7.
Note You must include a MARGIN clause in the appropriate DEFINE POPUP command in order for the PICTURE or PICTRES clauses to function properly.
BEFORE nMenuItemNumber2
Places a menu item before the menu item specified with nMenuItemNumber2.
AFTER nMenuItemNumber3
Places a menu item after the menu item specified with nMenuItemNumber3.
Note In order for BEFORE or AFTER to have an effect, you must include the RELATIVE clause when you create the menu with DEFINE POPUP.

You can also include _MFIRST and _MLAST in the BEFORE and AFTER clauses. If you include_MFIRST in the BEFORE clause, the menu item is the first item on the menu. If you include_MFIRST in the AFTER clause, the menu item is the second item on the menu. If you include_MLAST in the AFTER clause, the menu item is the last item on the menu. If you include_MLAST in the BEFORE clause, the menu item is the next-to-last item on the menu.

Menus created with DEFINE POPUP RELATIVE do not reserve space for undefined menu items. For example, if you define items 1, 2, 4, and 5 on a menu, a space for item 3 is not reserved. You can later insert item 3. The menu expands to accommodate it.

The following program displays the differences in the order and placement of the items on each type of menu:

   * DEFINE POPUP... relative example
   DEFINE POPUP popRelatYes RELATIVE FROM 1,1
   DEFINE BAR 4  OF popRelatYes PROMPT '4444'
   DEFINE BAR 3  OF popRelatYes PROMPT '3333'
   DEFINE BAR 2  OF popRelatYes PROMPT '2222'
   DEFINE BAR 1  OF popRelatYes PROMPT '1111'
   DEFINE BAR 6  OF popRelatYes PROMPT '6666' BEFORE 4

   * DEFINE POPUP... non-relative example
   DEFINE POPUP popRelatNo FROM 1,10
   DEFINE BAR 4 OF popRelatNo PROMPT '4444'
   DEFINE BAR 3 OF popRelatNo PROMPT '3333'
   DEFINE BAR 2 OF popRelatNo PROMPT '2222'
   DEFINE BAR 1 OF popRelatNo PROMPT '1111'
   DEFINE BAR 6 OF popRelatNo PROMPT '6666'
   ACTIVATE POPUP popRelatYes NOWAIT
             && Display "relative" poup
   ACTIVATE POPUP popRelatNo
             && Display "non-relative" popup
FONT cFontName [, nFontSize]
Specifies a font for the menu item. cFontName specifies the name of the font, and nFontSize specifies the point size. For example, the following command creates a menu item in 12-point Courier font:
DEFINE BAR 1 OF popReceive PROMPT '\<Invoices' FONT 'Courier', 12

If the font you specify is not available, a font with similar font characteristics is substituted. If you include the FONT clause but omit the point size nFontSize, a 10-point font is used.

STYLE cFontStyle
Specifies a font style for the menu item. If you omit the STYLE clause, the normal font style is used. If the font style you specify is not available, the normal font style is used.

The font styles you can specify with cFontStyle are as follows:

Character | Font style
B | Bold
I | Italic
N | Normal
Q | Opaque
– Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command specifies Bold Italic:

   DEFINE BAR 1 OF popReceive PROMPT '\<Invoices' STYLE 'BI'
KEY KeyLabel [, cKeyText]
Specifies an access key or key combination for a menu item. The menu does not have to be activated in order for the menu item to be chosen, unlike when you assign an access key using a backslash and a less-than sign (\<).

For a list of available keys and key combinations and their key label names, see ON KEY LABEL.

Note If a keyboard macro is already defined with the same key label, the keyboard macro takes precedence, and the menu item cannot be chosen with the specified key or key combination.

Include cKeyText to replace the key label with your own text. You can use any character in the cKeyText parameter; for example, you can use the text "^B" to indicate a key label of CTRL+B. For example, including KEY CTRL+B places the text CTRL+B on the menu to the right of the menu item name, but specifying KEY CTRL+B, "^B" places the text ^+B on the menu. You can suppress the display of a key label by specifying an empty string for cKeyText.

MARK cMarkCharacter
Specifies a mark character that appears to the left of the menu item. MARK can be included to change the default mark character to a character specified with cMarkCharacter. If cMarkCharacter includes more than one character, only the first character is used as the mark character.

The default mark character is a check.

The MARK clause is ignored and the default mark character is used if the menu containing the menu item is integrated into the Visual FoxPro system menu. Also, the MARK clause is ignored if FoxFont is not the font for the main Visual FoxPro window or the user-defined window in which the menu containing the menu item is placed.

Note Specifying a mark character does not mark a menu item. Use SET MARK OF to mark a menu item.

Mark characters specified in DEFINE BAR take precedence over mark characters specified with MARK in DEFINE POPUP. SET MARK OF is used to toggle mark characters on or off, and can also be used to specify a mark character for an individual menu item or for all menu items.

MESSAGE cMessageText
Displays a message when the user selects a menu item. The message is placed in the graphical status bar. If the graphical status bar is turned off with SET STATUS BAR OFF, the message is centered on the last line of the main Visual FoxPro window.
SKIP [FOR lExpression]
Specifies a condition whereby if lExpression evaluates to true (.T.), the menu item is disabled, preventing the user from choosing it; if false (.F.), the menu item is enabled. A disabled menu item appears in the disabled colors.

You can also disable a menu item by placing a backslash (\) before the text of the prompt. For example:

DEFINE BAR 1 OF popReceive PROMPT '\Invoices'

A menu item disabled with SKIP or \ cannot be selected. Menus you create that include SKIP FOR expressions may not behave properly when the spelling checker or wizards are active.

SKIP FOR expressions typically depend on the value of skip variables, but the skip variables are not visible to your menus when the spelling checker or wizards are active. In the initialization code of the spelling checker and wizard applications (SPELLCHK.APP and GENGRAPH.APP respectively), PRIVATE ALL is intentionally issued. This hides skip variables from user-defined menus and causes an error message when you choose a menu.

To correct this situation, the following code is placed at the beginning of the spelling checker and wizard applications:

   IF TYPE("_memvarmask") = "C" and !EMPTY(_memvarmask)
      PRIVATE ALL EXCEPT &_memvarmask
   ELSE
      PRIVATE ALL
   ENDIF

Suppose a certain menu item should be skipped when the variable named "skipvar" evaluates to true. You should include the following lines in your menu startup code to take advantage of the _MEMVARMASK variable:

   PUBLIC _memvarmask
   _memvarmask = "skipvar"
   STORE .T. TO skipvar     && Skip initially.

To create a set of skip variables, include the following lines in your menu startup code:

   PUBLIC _memvarmask
   _memvarmask = "skip*"
   STORE .T. TO skipthis, skipthat  && Skip initially.

When you run the spelling checker and wizards, they do not hide variables in SKIP FOR expressions, preventing the error messages you may experience when the spelling checker or wizards are active.

Note that _MEMVARMASK is not a system variable.

COLOR SCHEME nSchemeNumber
Specifies the colors for an individual menu item, overriding the default colors or the colors specified with DEFINE POPUP.
COLOR ColorPairList
Specifies the colors for an individual menu item, overriding the default colors or the colors specified with DEFINE POPUP. You can specify the colors of all menu items, mark characters, and messages.

By default, the colors of menu items are determined by color scheme 2 of the current color set.

MRU
Specifies that the menu displays vertical chevrons indicating a Most Recently Used type menu. You must provide script that dynamically handles the menus and adds any new menu bars. For menus invoked with the MRU keyword, Visual FoxPro imposes a 1-2 second delay before triggering the ON SELECTION BAR command. A user can click on the menu bar to immediately trigger the ON SELECTION BAR command.

If you use the MRU keyword, Visual FoxPro ignores PROMPT and other keywords associated with the bar.

DEFINE BAR 4 OF popMyPopup MRU
INVERT
Specifies that the menu displays with a sunken effect.
DEFINE BAR 4 OF popMyPopup PROMPT '\|Start a new column' ;
   PICTRES _med_copy INVERT

Remarks

DEFINE BAR is used with DEFINE POPUP to create menus. A menu is created and assigned a name with DEFINE POPUP. Menu items are placed on the menu with a series of DEFINE BAR commands.

If you use the Menu Designer to create your menu, you may not have to use these commands at all. The Menu Designer automatically creates the commands for your menu. The Menu Designer uses the Visual FoxPro system menu, which you can then modify by adding your own menu items. For more information on creating menus, see Designing Menus and Toolbars.

You can also create a menu that contains records or fields from a table or a list of files available on disk. For more information, see the PROMPT FIELD, PROMPT STRUCTURE and PROMPT FILES clauses in DEFINE POPUP.

Use ON BAR to create a cascading submenu for a menu item.

Example

The following example uses DEFINE BAR to create items on menus. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Two new system menu titles are created with DEFINE PAD, and DEFINE POPUP is used to create a drop-down menu for each menu title. DEFINE BAR is used to create items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu.

When an item is chosen from a menu, ON SELECTION POPUP uses PROMPT( ) and POPUP( ) to pass the item number and menu name to the CHOICE procedure. CHOICE displays the prompt of the chosen item and the name of the menu containing the item. If Exit is chosen from the Card Info menu, the original Visual FoxPro system menu is restored.

   *** Name this program DEFINBAR.PRG ***
   CLEAR
   SET SYSMENU SAVE
   SET SYSMENU TO
   DEFINE PAD convpad OF _MSYSMENU PROMPT '\<Conversions' COLOR SCHEME 3 ;
      KEY ALT+C, ''
   DEFINE PAD cardpad OF _MSYSMENU PROMPT 'Card \<Info' COLOR SCHEME 3 ;
      KEY ALT+I, ''
   ON PAD convpad OF _MSYSMENU ACTIVATE POPUP conversion
   ON PAD cardpad OF _MSYSMENU ACTIVATE POPUP cardinfo
   DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
   DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' KEY CTRL+E, '^E'
   DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
      KEY CTRL+L, '^L'
   DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
      KEY CTRL+S, '^S'
   DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
      KEY CTRL+D, '^D'
   DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
      KEY CTRL+T, '^T'
   DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
      KEY CTRL+I, '^I'
   DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
      KEY CTRL+M, '^M'
   ON SELECTION POPUP conversion;
      DO choice IN definbar WITH PROMPT( ), POPUP( )
   DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
   DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
      KEY ALT+V, ''
   DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
      KEY ALT+P, ''
   DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' KEY ALT+W, ''
   DEFINE BAR 4 OF cardinfo PROMPT '\-'
   DEFINE BAR 5 OF cardinfo PROMPT '\<Charges '
   DEFINE BAR 6 OF cardinfo PROMPT '\-'
   DEFINE BAR 7 OF cardinfo PROMPT 'E\<xit '
   ON SELECTION POPUP cardinfo;
      DO choice IN definbar WITH PROMPT( ), POPUP( )
   PROCEDURE choice
   PARAMETERS mprompt, mpopup
   WAIT WINDOW 'You chose ' + mprompt + ;
      ' from popup ' + mpopup NOWAIT
   IF mprompt = 'Exit'
      SET SYSMENU TO DEFAULT
   ENDIF

See Also

ACTIVATE POPUP | DEACTIVATE POPUP | DEFINE POPUP | HIDE POPUP | RELEASE BAR | SET MESSAGE | SHOW POPUP


DEFINE CLASS Command

Creates a user-defined class or subclass and specifies the properties, events, and methods for the class or subclass.

Caution Modifying read-only properties from base classes generates an error message. However, when creating a user-defined class or subclass from a base class that has read-only properties, modifying read-only properties does not generate the appropriate message. This might break existing code.
DEFINE CLASS ClassName1 AS ParentClass [OF ClassLibrary] [OLEPUBLIC]
   [IMPLEMENTS cInterfaceName [EXCLUDE]
      IN TypeLib | TypeLibGUID | ProgID ]
   [[PROTECTED | HIDDEN PropertyName1, PropertyName2 ...]
   [[.]Object.]PropertyName = eExpression ...]
   [ADD OBJECT [PROTECTED] ObjectName AS ClassName2 [NOINIT]
      [WITH cPropertylist]]
   [[PROTECTED | HIDDEN] FUNCTION | PROCEDURE Name[_ACCESS |_ASSIGN]
      ([cParamName | cArrayName[] [AS Type][@]]) [AS Type]
      [HELPSTRING cHelpString] |
      THIS_ACCESS(cMemberName)
      [NODEFAULT]
      cStatements
   [ENDFUNC | ENDPROC]]
   [PEMName_COMATTRIB = nFlags | DIMENSION PEMName_COMATTRIB[5]
      [PEMName_COMATTRIB[1] = nFlags
       PEMName_COMATTRIB[2] = cHelpString
       PEMName_COMATTRIB[3] = cPropertyCapitalization
       PEMName_COMATTRIB[4] = cPropertyType
       PEMName_COMATTRIB[5] = nOptionalParams]]
ENDDEFINE

Parameters

ClassName1
Specifies the name of the class to create.
AS ParentClass
Specifies the parent class on which a class or subclass is based. The parent class can be a Visual FoxPro base class, such as the Form class, or another user-defined class or subclass. The following table lists the Visual FoxPro base classes:

Base class names

CheckBox Collection Column
ComboBox CommandButton CommandGroup
Container Control Cursor
CursorAdapter Custom DataEnvironment
EditBox Exception Form
FormSet Grid Header
Hyperlink Image Label
Line ListBox OLEControl
OLEBoundControl OptionButton OptionGroup
Page PageFrame ProjectHook
Relation Separator Shape
Session Spinner TextBox
Timer ToolBar XMLAdapter
XMLTable XMLField

If you specify Custom as ParentClass, Visual FoxPro creates a non-visual user-defined class.

The following example code creates a subclass named MyForm based on the Form base class. The form contains a Click method that displays a dialog box when MyForm is clicked.

DEFINE CLASS MyForm AS Form
   PROCEDURE Click
      = MESSAGEBOX('MyForm has been clicked!')
   ENDPROC
ENDDEFINE

If you specify Session as ParentClass, Visual FoxPro creates a non-visual user defined class that maintains its own private Data Session. Since the Session Object is not a container, the AddObject clause is not available when you specify the Session ParentClass. The following Session properties have new default settings when used in a private Data Session (Visual FoxPro 7 and later versions):

  • EXCLUSIVE = OFF
  • TALK = OFF
  • SAFETY = OFF

If you specify OLEPUBLIC for a class whose BaseClass is Session, the type library generated for an EXE or DLL will only contain your custom properties and methods. All intrinsic properties, methods, and events of the Session BaseClass are excluded from the type library. The behavior is supported in Visual FoxPro 7 and later.

OF ClassLibrary
Enables you to identify the class library for AS ParentClass without explicitly specifying the path to the class library containing it, such as through SET CLASSLIB or SET PROCEDURE. ClassLibrary can be a class library (.vcx), program (.prg), or compiled program (.fxp) file.

If the specified ClassLibrary cannot be found when one attempts to instantiate an instance of the class, an error will occur saying, "Class definition ... is not found."

If an OF <programfile> reference is used in a program that is bound inside of an executable application, the <programfile> name should have an .fxp file name extension and not a .prg extension.

The specified ClassLibrary setting can contain a relative path as long as Visual FoxPro can locate the library along its usual class library searching paths.

Visual FoxPro will automatically add the ClassLibrary to the project during build if the program containing the class is included in the project.

OLEPUBLIC
Specifies that the class in an Automation server can be accessed by an Automation client.

If you add a program containing an OLEPUBLIC class definition to a project, an executable (.exe) file or a dynamic link library (.dll) containing the class can be created interactively in the Project Manager or with BUILD EXE, BUILD DLL, or BUILD MTDLL, The EXE or DLL is automatically registered with the operating system, and becomes available to any Automation client.

For information about creating custom Automation servers, see Creating Automation Servers.

[PROTECTED | HIDDEN PropertyName1, PropertyName2 ...][Object.]PropertyName = eExpression ... Creates a class or subclass property and assigns a default value to the property. Properties are named attributes of the class and define characteristics and behaviors for the class. Classes and subclasses can have multiple properties.

Use = to assign a value to the property. The following example creates a user-defined class named MyClass and creates two properties called Name and Version. The Name property is initialized to the empty string and the Version property is initialized to the character string 1.0.

   DEFINE CLASS MyClass AS Custom
      Name = ''
      Version = '1.0'
   ENDDEFINE

A property can be accessed outside the class or subclass definition after the object is created with CREATEOBJECT( ):

   MyObject = CREATEOBJECT('MyClass')

Properties are accessed with the following syntax:

   ObjectName.Property

The .Object keyword indicates to Visual FoxPro that the property value should be applied when the ActiveX control is created.

The following example adds the Outline ActiveX control to a form. The Object keyword is used to specify a property for the Outline control before it is created.

   PUBLIC frmOLETest
   frmOLETest = CREATEOBJECT('Form')
   frmOLETest.Visible = .T.

   frmOLETest.ADDOBJECT('OCXTest', 'BlueOLEControl', ;
      'MSOutl.Outline')
   frmOLETest.OCXTest.AddItem('Item One')
   frmOLETest.OCXTest.AddItem('Item Two')

   DEFINE CLASS BlueOLEControl AS OLEControl

      * Set a property of the ActiveX control
      .Object.Backcolor = 16776960

      * Set properties of the OLE Container Control
      Visible = .T.
      Height = 100
      Width = 200
   ENDDEFINE

Include PROTECTED and a list of property names to prevent access and changes to the properties from outside of the class or subclass definition. Methods and events within the class or subclass definition can access the protected properties.

In the following example, the Version property is protected, preventing it from being accessed and changed outside of the class definition. However, the Name property is not protected and can be accessed and changed.

   DEFINE CLASS MyClass AS Custom
      PROTECTED Version
      Name = ''
      Version = '1.0'
   ENDDEFINE

Include HIDDEN and a list of property names to prevent access and changes to the properties from outside of the class definition. Only methods and events within the class definition can access the hidden properties. While protected properties can be accessed by subclasses of the class definition, hidden properties can only be accessed from within the class definition.

Note If you don't include the HIDDEN keyword, you can subclass Access and Assign methods.

ADD OBJECT
Adds an object to a class or subclass definition from a Visual FoxPro base class, user-defined class or subclass, or ActiveX custom control.
PROTECTED
Prevents access and changes to the object's properties from outside the class or subclass definition. The PROTECTED keyword must be placed immediately before ObjectName or FoxPro generates a syntax error.
ObjectName
Specifies the name of the object and is used to reference the object from within the class or subclass definition after an object is created from the class or subclass definition.
AS ClassName2
Specifies the name of the class or subclass containing the object you add to the class definition. For example, the following class definition adds a command button from the CommandButton base class and a list box from the ListBox base class.
   DEFINE CLASS MyClass AS Custom
   ADD OBJECT CB1 AS CommandButton
   ADD OBJECT LIST1 AS ListBox
   ENDDEFINE
NOINIT
Specifies that an object's Init method is not executed when the object is added.
WITH cPropertyList
Specifies a list of properties and property values for the object you add to the class or subclass definition. For example, the following class definition creates a class called MyClass, adds a command button to the class definition, and specifies the Caption and BackColor properties for the command button.
   DEFINE CLASS MyClass AS CUSTOM
   ADD OBJECT CB1 AS CommandButton;
      WITH Caption = 'Cancel', BackColor = 2
   ENDDEFINE
FUNCTION | PROCEDURE Name[_ACCESS | _ASSIGN] | THIS_ACCESS
Create events and methods for the class or subclass. Events and methods are created as a set of functions or procedures.

You can create an event function or procedure within a class or subclass definition to respond to an event. An event is an action such as a mouse click that is recognized by an object created with a class or subclass definition. For additional information about Visual FoxPro event processing, see Understanding the Event Model.

Events are called with the following syntax:

ObjectName.Event

You can also create a method function or procedure within a class or subclass definition. A method is a procedure that acts upon the object created with the class or subclass definition. Methods are called with this syntax:

ObjectName.Method

You can add _ACCESS and _ASSIGN suffixes to a procedure or function name to create an Access or Assign method for a property of the same name. The code in an Access method is executed whenever the property is queried. The code in an Assign method is executed whenever you attempt to change the value of the property.

In addition, you can create a THIS_ACCESS procedure or function that is executed whenever a value change or query is made on a member of an object.

The following code creates an object whose internal procedures, MyProperty_ACCESS and MyProperty_ASSIGN, respond to queries (Access method) and to property changes (Assign method).

Note the use of an LPARAMETERS statement to accept the value passed to the Assign method. This example also demonstrates creation of read-only properties.

   DEFINE CLASS MyClass AS Custom
   MyProperty = 100 && A user-defined property

   PROCEDURE MyProperty_ACCESS && Access method
      WAIT WINDOW 'This is the Access method';
         +  ' ' + PROGRAM( )
      RETURN THIS.MyProperty
   ENDPROC

   PROCEDURE MyProperty_ASSIGN && Assign method
      LPARAMETERS tAssign  && Required to accept value
      WAIT WINDOW 'This is the Assign method';
          + ' ' + PROGRAM( )
   ENDPROC
   ENDDEFINE

The following code adds an Assign method to a native Visual FoxPro property that performs simple validation on the property the value.

DEFINE CLASS is used to create a Form class, frmMyForm. An Assign method, Left_ASSIGN, created by a PROCEDURE statement, runs whenever an attempt is made to assign a value to the form's Left property.

   DEFINE CLASS frmMyForm AS Form

   PROCEDURE Left_ASSIGN && Assign method
      LPARAMETERS tAssign  && Required to accept value

      DO CASE
         CASE tAssign < 0 && Left value negative
            WAIT WINDOW 'Value must be greater than 0'
         OTHERWISE  && Left value not negative
            THIS.Left = tAssign
      ENDCASE
   ENDPROC
   ENDDEFINE

If you attempt to change the Left property value to a negative value, the method displays a message and the value is left unchanged. If you attempt to change the Left property value to a non-negative value, the method sets the property to the specified value.

Access and Assign methods are not supported for native properties, events, or methods of ActiveX controls. However, Access and Assign methods are supported for properties, events, and methods of the Visual FoxPro OLE Container in which an ActiveX control is contained.

For more information about creating Access and Assign methods with DEFINE CLASS, see Access and Assign Methods.

cParamName [AS Type][@]
Specifies the parameter and its type passed to the procedure or function of the defined class. By using the at sign (@) token, you can specify that the parameter be passed by reference. Here, the AS Type clause specifies the data type of the named parameter.
Note The AS Type clause is used only for IntelliSense and class definition information stored in a type library (OLEPUBLIC). Visual FoxPro does not enforce type checking during compilation or code execution. Strict typing is also recommended for use with the interface methods specified by IMPLEMENTS.

For the parameters and their types to appear in the type library, you must use the inline parameter syntax instead of using LPARAMETERS to declare the parameters: ex. FUNCTION Publisher_ShowPrice(Bookid As Integer, Bookprice As String).

DEFINE CLASS f1 AS custom OLEPUBLIC
   PROTECTED myprop
   FUNCTION mymethod (parm1 AS integer @, parm2 AS string) ;
       AS integer
       RETURN parm1
   ENDFUNC
ENDDEFINE

Use AS VOID for the return value of a method if the method does not return anything (oneway procedure). This is required for certain technologies such as Microsoft COM+ Services Queued Components.

Visual FoxPro will automatically convert AS Type values when used by other COM servers. Visual FoxPro also displays type info for COM servers in IntelliSense Quick Info tips according to the following table:

VFP Defined Type | COM Typelib Conversion | IntelliSense Quick Info
Array | SAFEARRAY(type) | Array
BinaryMemo VARIANT —
Boolean | VARIANT_BOOL | Logical
Byte | unsigned char | Number
Character * | BSTR | String
Currency * | CURRENCY | Currency
Date | DATE | Date
DateTime | DATE | Date
Decimal * | wchar_t | Number
Double | double | Number
Float VARIANT —
Integer | long | Number
Logical | VARIANT_BOOL | Logical
Long | long | Number
Memo VARIANT —
Number | double | Number
Object | IDispatch* | Object
Short | long | Number
Single * | single | Number
String | BSTR | String
Variant VARIANT —
Void | void | VOID
cArrayName[] [AS Type ][@][AS Type]
Specifies the name of the array used in the creation of a type library using the first AS Type clause. Using the cArrayName[] [AS Type][@] clause, you can specify strong typing for arrays so they can be correctly written as safe arrays to a type library. For example:
DEFINE CLASS foo AS Session OLEPUBLIC
    PROCEDURE GetWidgets1(aWidgets[])
    ENDPROC
    PROCEDURE GetWidgets2(aWidgets[] AS Integer)
    ENDPROC
    PROCEDURE GetWidgets3(aWidgets[] AS Integer @)
    ENDPROC
    PROCEDURE GetRS(oRS[] AS ADODB.RECORDSET @)
    ENDPROC
ENDDEFINE
Note Strong typing for arrays is used primarily for type library creation and is not enforced at run time.

The type that you specify must be a valid COM data type (see the previous table). The type can also be a reference to a COM CoClass ProgID such as ADODB.Recordset.

If you specify an argument for the first AS Type clause, Visual FoxPro creates a SAFEARRAY with the specified type. If you do not specify an argument for the first AS Type clause, Visual FoxPro creates a SAFEARRAY of Variant data types. If the type specified is invalid, Visual FoxPro defaults to using the Variant data type.

Note When specifying an array, you must use square brackets ([]); DEFINE CLASS does not recognize parentheses (()) notation.

A safe array is a one or multidimensional array of a single data type, which can be of type VARIANT, allowing you to create arrays of mixed types. The safe array stores its lower bound, which does not have to be zero, and its size. Safe arrays allow locking and unlocking so you can be sure that the pointer you receive to the data is valid.

You cannot specify arrays as return types. The following code, while valid, only writes out the return type of the type library as VARIANT and not a SAFEARRAY.

PROCEDURE GetWidgets() AS aWidgets[]
ENDPROC

Using the cArrayName[] [AS Type][@][AS Type] clause, you can specify complex strong typing by defining a type based on a COM class. For example:

DEFINE CLASS foo AS Session OLEPUBLIC
   REFERENCE "ADODB.Recordset"
   PROCEDURE GetRS() AS ADODB.Recordset
      x=CREATEOBJECT("ADODB.Recordset")
      RETURN X
   ENDPROC
   PROCEDURE SetRS(oRS AS ADODB.Recordset @)
      oRS=CREATEOBJECT("ADODB.Recordset")
   ENDPROC
ENDDEFINE

If you pass a valid COM CoClass ProgID as an argument to an AS Type clause, Visual FoxPro includes it in the type library. For example, the following method:

PROCEDURE Test(oRS AS ADODB.Recordset @) AS ADODB.Recordset

Creates an entry in the type library:

Recordset Test([in, out] Recordset** oRS);

You cannot specify a reference to a ProgID that is generated from the type library itself. For example, you cannot reference a class that is contained within the same COM server.

You can specify ProgID' names with or without quotation marks (""). For example:

PROCEDURE Test(oRS AS "ADODB.Recordset" @) AS ADODB.Recordset
HELPSTRING cHelpString
Specifies the string added to the type library, for display in an object browser or IntelliSense, as a description of the functionality of a method.
IMPLEMENTS InterfaceName
Specifies that this class definition inherits the interface (class definition) of another COM component. One class can include several IMPLEMENTS statements.
DEFINE CLASS myClass AS custom olepublic
   IMPLEMENTS Publisher IN "mybookstore.dll"
   PROCEDURE Publisher_ShowPrice(cGetID AS Long) AS Short
   ENDPROC
ENDDEFINE
EXCLUDE
Excludes the implemented interface from type library.
IN TypeLib | TypeLibGUID | ProgID
Specifies the location of the interface.

You can specify the COM object by TypeLib, the type library of the COM object, TypeLibGUID, the GUID of the type library, or by specifying the ProgID of the program that initializes the COM object.

DEFINE CLASS MyBooks AS Custom olepublic
   IMPLEMENTS Publisher IN "c:\sample4\Publisher.VB\BooksPub.dll"
   FUNCTION Publisher_ShowPrice(Bookid As Integer, Bookprice As String)
   ACTIVATE SCREEN
   ? TRANS(Bookid)+"-"+TRANS(Bookprice),Sys(1011),Sys(1016)
   ENDFUNC
ENDDEFINE

When you use the TypeLibGUID option, pass the option with the major and minor version designation as in the following example:

IMPLEMENTS IDict1 IN {04BCEF93-7A77-11D0-9AED-CE3E5F000000}#1.0

The Typelib option is the least recommended way to specify the typelib since this requires a file name whose path may differ from computer to computer. If your DLL is being distributed, consider using TypeLibGUID or ProgID.

When you implement an interface, you must include in the class definition all methods of that interface. Use the interface name as preface to the method name (for example, Publisher_ShowPrice). This also avoids conflict between two interfaces that contain methods of the same name since you can have multiple IMPLEMENTS statements in a class definition. You must use the interface name exactly as it appears in the type library. For interface names preceded by an underscore, "_", such as the ADODB Recordset class, the underscore is optional.

Since properties are essentially stored as two methods inside a type library (put and get), the class definition must include both methods.

Tip Use the Visual FoxPro Object Browser to drag and drop an interface definition to your code to save time. The IMPLEMENTS statement, along with all the implemented methods with their proper parameter signatures, will be automatically written out for you.

Certain technologies, such as Microsoft COM+ Events, require the COM component to implement the interface of the event class being bound to.

NODEFAULT
Prevents Visual FoxPro from performing its default event or method processing for Visual FoxPro events and methods. For example, if the KeyPress event occurs, including NODEFAULT in the KeyPress procedure or function prevents Visual FoxPro from placing the key press into the Visual FoxPro keyboard buffer. This makes it possible for you to create a KeyPress procedure so you can test which key is pressed before the key is sent to the keyboard buffer.

You can place NODEFAULT anywhere within the event or method procedure. Note that NODEFAULT may also be placed within an event or method procedure in the Form Designer.

cStatements
[ENDFUNC | ENDPROC]]
...
ENDDEFINE

cStatements are the Visual FoxPro commands that are executed when an event or method is executed.

Event and method functions and procedures can accept values by including a PARAMETERS or LPARAMETERS statement as the first executable line of the function or procedure.

Unlike most Visual FoxPro keywords, you cannot abbreviate ENDFUNC and ENDPROC. This prevents conflicts with the ENDFOR and ENDPRINTJOB keywords.

The following example demonstrates how to create an event procedure that displays a message when the command button is clicked. This event procedure overrides the default command button Click event.

DEFINE CLASS MyClass AS Custom
   ADD OBJECT MyButton AS CommandButton
   ADD OBJECT MyList AS ListBox
   PROCEDURE MyButton.Click
      = MESSAGEBOX('This is my click event procedure')
   ENDPROC
ENDDEFINE
PEMName_COMATTRIB
Creates an array that specifies type library attributes for the PEMName property or method. This feature applies only to OLEPUBLIC classes. Use this option to specify additional information about the property or method that you want written to the type library such as a description or read-only attribute.

The PEMName_COMATTRIB setting can either be a property or property array. If a property is specified, then the value assigned is that of nFlags (first element of the array). Visual FoxPro generates an error for invalid values or types in the PEMName_COMATTRIB array. Empty elements will use default values.

COMATTRIB element | Description | Type
1 | Attribute flags | Number
2 | Help string | String
3 | Capitalization | String
4 | Property type | String
5 Number of parameters
If you specify fewer than the actual number of parameters, the number greater than those declared are optional.
 Number
Note Unlike Access and Assign method, the _COMATTRIB properties described here are automatically marked hidden and are not accessible in Visual FoxPro. They are strictly for use by Visual FoxPro during the Build process when writing out a COM type library.
nFlags
Specifies a set of attribute flags for PEMName as it appears in the type library. The following table describes the valid flags.
nFlag Value | #DEFINE | Description
0x1 (1) | COMATTRIB_RESTRICTED | The property/method should not be accessible from macro languages. This flag is intended for system-level functions or functions that type browsers should not display.
0x40 (64) | COMATTRIB_HIDDEN | The property/method should not be displayed to the user, although it exists and is bindable.
0x400 (1024) | COMATTRIB_NONBROWSABLE | The property/method appears in an object browser, but not in a properties browser.

You can also use either one of the following as valid flag values. Using both properties is the same as using neither.

#DEFINE | Value | Description
COMATTRIB_READONLY | 0x100000 | The property is read-only (applies only to Properties). Equivalent to a PropertyGet.
COMATTRIB_WRITEONLY | 0x200000 | The property is write-only (applies only to Properties). Equivalent to a PropertyLet.
cHelpString
Specifies a string value to be stored in the type library for the PEMName property. For methods, use the HELPSTRING cHelpString clause.
cPropertyCapitalization
Specifies the property name, a string value, as it will appear in the type library. All capitalization is preserved. Without this setting, Visual FoxPro will write out the property to the type library in all uppercase.
cPropertyType
This string value is property data type as it appears in the type library (same as AS Type clause). Applies to Properties only.
nOptionalParms
Specifies the number of optional parameters in a method. If this value is 2 for a method with 5 parameters, then the last 3 are optional. With late-binding clients, default values for optional parameters will still be .F. and PCOUNT() will accurately reflect the true number of parameters passed in. For early-bound clients, default values for optional parameters will always be set to "" and PCOUNT() will always be total number of parameters for the method (not number passed in). Applies to Methods only.
Note COMATTRIB_RESRICTED means that macro-oriented programmers should not be allowed to access this member. These members are usually treated as _HIDDEN by tools such as Visual Basic, with the main difference being that code cannot bind to those members. COMATTRIB_HIDDEN means that the property should never be shown in object browsers, property browsers, and so on. This function is useful for removing items from an object model. Code can bind to the member, but the user will never know that the member exists. COMATTRIB _NONBROWSABLE means that the property should not be displayed in a properties browser. It is used in circumstances in which an error would occur if the property were shown in a properties browser. Early and late binding impose differing access restrictions. Early binding clients will not be able to write to a read-only property, nor read from a write-only property because there will not be an entry in the vtable. Late binding clients can still access a propertyget on a write-only or a propertyput on a read-only PEMName.

Remarks

User-defined classes are a set of commands placed in a program file, similar to a procedure. The commands that follow the class or subclass definition define the properties, events, and methods for the class or subclass.

Note You cannot include normal executable program code after procedures in a program file; only class definitions, procedures, and user-defined functions can follow the first DEFINE CLASS, PROCEDURE or FUNCTION command in the file.

Class and subclass definitions created with DEFINE CLASS cannot be placed within structured programming commands, such as IF ... ENDIF or DO CASE ... ENDCASE. Nor can they be placed in loops, such as DO WHILE ... ENDDO or FOR ... ENDFOR.

To create an object from a class or subclass definition, issue CREATEOBJECT( ) with the class or subclass name.

If you use the IMPLEMENTS clause, you must include all the methods of the specified interface. Visual FoxPro does not enforce strong typing so you must ensure that you use valid data types. Because properties are stored as two methods, PUT and GET, you must include both methods in the class definition.

Access and Assign methods are protected by default - you cannot access or make changes to an Access or Assign method from outside of the class in which the Access or Assign method is created.

You can view the code for Access and Assign methods in the Trace window of the Debugger window. However, Access and Assign methods cannot be executed from within the Watch and Local windows of the Debugger window.

Arrays are passed to Access and Assign methods in the same manner as standard Visual FoxPro procedures.

The entire array is passed to an Access or Assign method if you issue SET UDFPARMS TO REFERENCE or preface the array name with @. The first element of the array is passed by value if you issue SET UDFPARMS TO VALUE or enclose the array name by parentheses. Array elements are always passed by value. See SET UDFPARMS for more information about passing values and arrays.

Example

The following example uses DEFINE CLASS and CREATEOBJECT( ) to create two custom classes named FormChild and FormGrandChild from the Visual FoxPro Form base class. ACLASS( ) is used to create an array named gaNewarray containing the class names, which are then displayed.

CLEAR
frmMyForm = CREATEOBJECT("FormGrandChild")
FOR nCount = 1 TO ACLASS(gaNewarray, frmMyForm)    && Creates an array
   ? gaNewarray(nCount)  && Displays the names of the classes
ENDFOR
RELEASE frmMyForm

DEFINE CLASS FormChild AS FORM
ENDDEFINE

DEFINE CLASS FormGrandChild AS FormChild
ENDDEFINE

The following code defines an array of typelib attributes using the _COMATTRIB parameter.

#INCLUDE foxpro.h
DEFINE CLASS myclass AS CUSTOM olepublic
   * Define property
   MyProperty = 5.2
   * Set the COM attributes for MyProperty
   DIMENSION MyProperty_COMATTRIB[4]
   myproperty_COMATTRIB[1] = COMATTRIB_READONLY
   myproperty_COMATTRIB[2] = "Helptext displayed in object browser"
   myproperty_COMATTRIB[3] =  "MyProperty"&& Proper capitalization.
   myproperty_COMATTRIB[4] = "Float"&& Data type
ENDDEFINE

If you want to only set the nFlags element, you do not need to dimension the _COMATTRIB property as an array.

#INCLUDE foxpro.h
DEFINE CLASS myclass AS SESSION olepublic
   * Define property
   MyProperty = "Test"
   * Only set the nFlags attribute for MyProperty
   myproperty_comattrib = COMATTRIB_READONLY
ENDDEFINE

See Also

:: Scope Resolution Operator | ADD CLASS | _BROWSER | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | DODEFAULT( ) Function | EVENTHANDLER( ) | GETOBJECT( ) | MODIFY CLASS | OBJECT BROWSER | RELEASE CLASSLIB | Session Object | SET CLASSLIB | WITH ... ENDWITH | NODEFAULT Command


DEFINE MENU Command

Creates a menu bar.

DEFINE MENU MenuBarName [BAR [AT LINE nRow]]
   [IN [WINDOW] WindowName | IN SCREEN] [FONT cFontName [, nFontSize]]
   [STYLE cFontStyle] [KEY KeyLabel] [MARK cMarkCharacter]
   [MESSAGE cMessageText] [NOMARGIN]
   [COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

MenuBarName
Specifies the name of the menu bar to create. The menu bar name allows you to reference the menu bar in other commands and functions.
BAR [AT LINE nRow]
Creates a menu bar that behaves like the Visual FoxPro system menu bar. The menu bar has these characteristics:
  • A horizontal menu bar one line high is drawn across the width of the main Visual FoxPro window or the user-defined window it is placed in.
  • The placement of the menu titles on the menu bar is handled automatically.
  • If the size or number of menu titles you define exceeds the size of the screen or a window in which the menu bar is placed, the menu bar scrolls.

The row number is specified with nRow.

IN [WINDOW] WindowName
Places a menu bar in a user-defined window. Specify the name of the window in which you want to place the menu bar with WindowName. If you omit IN WINDOW, the menu bar is placed in the main Visual FoxPro window by default unless there is an active user-defined window. If there is an active user-defined window, the menu bar is placed in the active window. This clause is supported only in top-level forms which can be set with ShowWindow=2 or Desktop=.T.
IN SCREEN
Explicitly places the menu bar in the main Visual FoxPro window.
FONT cFontName [, nFontSize]
Specifies a default font for all menu titles in the menu bar. You can override the default font for an individual menu title by including the FONT clause in DEFINE PAD.

cFontName specifies the name of the font, and nFontSize specifies the point size. For example, the following command creates a menu bar with menu titles in 12-point Courier font:

DEFINE MENU mnuExample FONT 'Courier', 12

If the font you specify is not available, a font with similar font characteristics is substituted. If you include the FONT clause but omit the point size nFontSize, a 10-point font is used.

The FONT clause is ignored for menu titles added to the Visual FoxPro system menu _MSYSMENU. Note that the Menu Designer uses the Visual FoxPro system menu.

STYLE cFontStyle
Specifies a default font style for all the menu titles in the menu bar. You can override the default style for individual menu titles by including the STYLE clause in DEFINE PAD.

If you omit the STYLE clause, or if the font style you specify is not available, the Normal font style is used.

The font styles you can specify with cFontStyle are as follows:

Character | Font style
B | Bold
I | Italic
N | Normal
Q | Opaque
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command specifies Bold Italic:

DEFINE MENU mnuExample STYLE 'BI'

The STYLE clause is ignored for menu titles added to the Visual FoxPro system menu _MSYSMENU. The Menu Designer uses the Visual FoxPro system menu.

KEY KeyLabel
Specifies the key or key combination used to activate the menu bar. For a list of available keys and key combinations and their key label names, see ON KEY LABEL.

Including the KEY clause is equivalent to issuing the following command:

ON KEY LABEL KeyLabel ACTIVATE MENU MenuName
Note If a keyboard macro is already defined with the same key label, the keyboard macro takes precedence, and the menu bar cannot be activated with the specified key or key combination.
MARK cMarkCharacter
Specifies a mark character that appears to the left of the menu titles on the menu bar. MARK can be included to change the default mark character to a character specified with cMarkCharacter. If cMarkCharacter includes more than one character, only the first character is used as the mark character.

The default mark character is a check. The MARK clause is ignored and the default mark character is used if the menu bar is the Visual FoxPro system menu. Also, the MARK clause is ignored if FoxFont isn't the font for the main Visual FoxPro window or the user-defined window in which the menu bar is placed.

Note Specifying a mark character doesn't mark the menu names on a menu bar. Use SET MARK OF to mark the menu titles on a menu bar with the character you specify.

Mark characters specified with DEFINE PAD take precedence over mark characters specified with the MARK clause in DEFINE MENU. SET MARK OF is used to toggle mark characters on or off, and can also be used to specify a mark character for an individual menu item or for all menu items.

MESSAGE cMessageText
Displays a message when the user selects a menu title. The message is placed in the graphical status bar. If the graphical status bar is turned off with SET STATUS BAR OFF, the message is centered on the last line of the main Visual FoxPro window.
NOMARGIN
Removes the spaces that are placed to the left and right of each menu name by default.
COLOR SCHEME nSchemeNumber
Specifies the colors for an individual menu bar.
COLOR ColorPairList
Specifies the colors for an individual menu bar. By default, the colors of menu items are determined by color scheme 2 of the current color set.

Remarks

Use DEFINE MENU to create the menu bar for your application's menu system. Use DEFINE PAD to create each of the menu titles (pads) on the menu bar. Use ON PAD ... ACTIVATE to specify which menu is displayed under each menu title. Use DEFINE POPUP to create the menus under each menu title. Use ACTIVATE MENU to activate the entire menu system.

If you use the Menu Designer to create your menu, you may not have to use these commands at all. The Menu Designer automatically creates the commands for your menu. The Menu Designer uses the Visual FoxPro system menu, which you can then modify by adding your own menu items.

For more information on creating menus, see Menu System Creation.

Example

The following example uses DEFINE MENU to create a user-defined menu system. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then the system menu titles are cleared with SET SYSMENU TO.

DEFINE MENU creates the menu bar, and two menu titles are created with DEFINE PAD. DEFINE POPUP creates a menu for each menu title. DEFINE BAR creates items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu. ACTIVATE MENU displays and activates the menu bar.

When an item is chosen from a menu, the CHOICE procedure is executed. CHOICE displays the name of the chosen item and the name of the menu containing the item.

*** Name this program DEFIMENU.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
ON KEY LABEL ESC KEYBOARD CHR(13)
DEFINE MENU example BAR AT LINE 1
DEFINE PAD convpad OF example PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD cardpad OF example PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD convpad OF example ACTIVATE POPUP conversion
ON PAD cardpad OF example ACTIVATE POPUP cardinfo
DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' ;
   KEY CTRL+E, '^E'
DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
ON SELECTION POPUP conversion DO choice IN defimenu WITH PROMPT( ), POPUP( )
DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF cardinfo PROMPT '\-'
DEFINE BAR 5 OF cardinfo PROMPT '\<Charges '
ON SELECTION POPUP cardinfo;
   DO choice IN defimenu WITH PROMPT( ), POPUP( )

ACTIVATE MENU example
DEACTIVATE MENU example
RELEASE MENU example EXTENDED
SET SYSMENU TO DEFAULT
ON KEY LABEL ESC
PROCEDURE choice
PARAMETERS mprompt, mpopup
WAIT WINDOW 'You chose ' + mprompt + ;
    ' from popup ' + mpopup NOWAIT

See Also

ACTIVATE MENU | CNTPAD( ) | CREATE MENU | DEACTIVATE MENU | DEFINE PAD | GETPAD( ) | HIDE MENU | MRKPAD( ) | ON PAD | ON SELECTION PAD | PRMPAD( ) | RELEASE MENUS | RELEASE PAD | SET MARK OF | SET SYSMENU | SHOW MENU


DEFINE PAD Command

Creates a menu title (pad) on a user-defined menu bar or the Visual FoxPro system menu bar.

DEFINE PAD MenuTitle1 OF MenuBarName PROMPT cMenuTitleText
   [AT nRow, nColumn] [BEFORE MenuName2 | AFTER MenuName3]
   [NEGOTIATE cContainerPosition [, cObjectPosition]]
   [FONT cFontName [, nFontSize]] [STYLE cFontStyle]
   [KEY KeyLabel [, cKeyText]] [MARK cMarkCharacter]
   [SKIP [FOR lExpression]] [MESSAGE cMessageText]
   [COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

MenuTitle1
Specifies the menu title to create. The menu title allows you to reference the menu title in other commands and functions.
OF MenuBarName
Specifies the name of the menu bar in which the menu title is placed.
PROMPT cMenuTitleText
Specifies the text that appears in the menu title.

You can create an access key for a menu title by placing a backslash and a less-than sign (\<) before the character you would like to be the access key. In the following example, the user can press the I key to choose Invoices from the Receive menu and press the Q key to choose Inquiry from the same menu:

DEFINE MENU mnuReceive
DEFINE PAD padInvoice OF mnureceive PROMPT "\<Invoices"
DEFINE PAD padInquire OF mnureceive PROMPT "In\<quiry"
ACTIVATE MENU mnuReceive
AT nRow, nColumn
Specifies where the menu title appears on the menu bar. nRow, nColumn are the coordinates of the left side of the menu title in the main Visual FoxPro window or in a user-defined window.

If you omit the AT clause, the left side of the first menu title is placed in row 0 of the main Visual FoxPro window or user-defined window. The next menu title is placed to the right of the first name on row 0, and so on.

Note You cannot include AT to specify a location for menu titles in menu bars created with the BAR clause in DEFINE MENU.
BEFORE MenuName2
Places the menu title on the menu bar to the left of the menu title specified with MenuName2. The order the menu titles are accessed from the keyboard corresponds to the location of the menu titles in the menu bar.
AFTER MenuName3
Places the menu title on the menu bar to the right of the menu title specified with MenuName3. The order the menu titles are accessed from the keyboard corresponds to the location of the menu titles in the menu bar.

You must first create the menu title you specify in a BEFORE or AFTER clause. If you don't create the menu title first, the placement of the menu title on the menu bar is determined by the order in which it is created or by a location specified with the AT clause.

For menu bars created without BAR, BEFORE or AFTER determines the order the menu titles are accessed from the keyboard. The location of a menu title is determined by the location specified with the AT clause.

Run the following two examples and note the differences in menu title placement and access order when menu titles are defined with and without the AT clause:

*** Program Example 1 without ATs ***
DEFINE MENU mnuBefAft
DEFINE PAD padOne OF mnuBefAft PROMPT '1111'
DEFINE PAD padTwo OF mnuBefAft PROMPT '2222'
DEFINE PAD padThree OF mnuBefAft PROMPT '3333'
DEFINE PAD padFour  OF mnuBefAft PROMPT '4444' BEFORE padTwo
ACTIVATE MENU mnuBefAft

*** Program Example 2 with ATs ***
DEFINE MENU mnuBefAft
DEFINE PAD padOne OF mnuBefAft PROMPT '1111' AT 1,5
DEFINE PAD padTwo OF mnuBefAft PROMPT '2222' AT 1,15
DEFINE PAD padThree OF mnuBefAft PROMPT '3333' AT 1,25
DEFINE PAD padFour  OF mnuBefAft PROMPT '4444' BEFORE padTwo AT 1,35
WAIT WINDOW 'Press ESC to erase menu' NOWAIT
ACTIVATE MENU mnuBefAft
NEGOTIATE cContainerPosition [, cObjectPosition]
cContainerPosition specifies the location of the menu title in the Visual FoxPro menu bar when OLE visual editing occurs for an ActiveX control contained in a Visual FoxPro form.

'The settings for cContainerPosition are:

Setting | Description
NONE | The menu title is not displayed.
LEFT | The menu title is placed to the left of the File Group.
MIDDLE | The menu title is placed to the left of the Container Group, after the Edit menu.
RIGHT | The menu title is placed to the left of the Window Group.

The settings for cObjectPosition are:

Setting | Description
NONE | The menu title is not displayed.
LEFT | The menu title is placed to the right of the File Group.
MIDDLE | The menu title is placed to the right of the Container Group, after the Edit menu.
RIGHT | The menu title is placed on the Help menu.

If you omit the NEGOTIATE clause, the menu title is removed from the menu bar when OLE visual editing occurs; NONE is the default for both cContainerPosition and cObjectPosition.

FONT cFontName [, nFontSize]
Specifies a font for the menu title. cFontName specifies the name of the font, and nFontSize specifies the point size. For example, the following command creates a menu title in 12-point Courier font:
DEFINE PAD padPageAccts OF mnuReceive FONT 'Courier', 12

If the font you specify is not available, a font with similar font characteristics is substituted. If you include the FONT clause but omit the point size nFontSize, a 10-point font is used.

The FONT clause is ignored for menu titles added to the Visual FoxPro system menu _MSYSMENU. Note that the Menu Designer uses the Visual FoxPro system menu.

STYLE cFontStyle
Specifies a font style for the menu title. If you omit the STYLE clause, or if the font style you specify is not available, the Normal font style is used.

The font styles you can specify with cFontStyle are as follows:

Character | Font style
B | Bold
I | Italic
N | Normal
Q | Opaque
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command specifies Bold Italic:

DEFINE PAD padPageAccts OF mnuReceive STYLE 'BI'

The STYLE clause is ignored for menu titles added to the Visual FoxPro system menu _MSYSMENU. Note that the Menu Designer uses the Visual FoxPro system menu.

KEY KeyLabel [, cKeyText]
Specifies an access key or key combination for a menu title. For a list of available keys and key combinations and their key label names, see ON KEY LABEL.
Note If a keyboard macro is already defined with the same key label, the keyboard macro takes precedence, and the menu title cannot be chosen with the specified key or key combination.

The key label is placed to the right of menu titles in menu bars created without the BAR clause. The key label isn't displayed in menu bars created with the BAR clause or for menu titles in the Visual FoxPro system menu bar.

Include cKeyText to replace the key label with your own text. You can use any character in the cKeyText parameter; for example, you can use the text "^B" to indicate a key label of CTRL+B. For example, including KEY CTRL+B places the text CTRL+B on the menu to the right of the menu item name, but specifying KEY CTRL+B, "^B" places the text ^+B on the menu. You can suppress the display of a key label by specifying an empty string for cKeyText.

MARK cMarkCharacter
Specifies a mark character that appears to the left of the menu title. MARK can be included to change the default mark character to a character specified with cMarkCharacter. If cMarkCharacter includes more than one character, only the first character is used as the mark character.

The default mark character is a check. The MARK clause is ignored and the default mark character is used if the menu bar containing the menu title is the Visual FoxPro system menu. Also, the MARK clause is ignored if FoxFont isn't the font for the main Visual FoxPro window or the user-defined window in which the menu bar containing the menu title is placed.

Mark characters specified with DEFINE PAD take precedence over mark characters specified with the MARK clause in DEFINE MENU. SET MARK OF is used to toggle marks on or off and can also be used to specify a mark character for an individual menu title or for all menu titles.

Note Specifying a mark character doesn't mark the menu title. Use SET MARK OF to mark a menu title with the character you specify.
SKIP [FOR lExpression]
Specifies a condition whereby if lExpression evaluates to true (.T.), the menu title is disabled, preventing the user form choosing it. If lExpression evaluates to false (.F.), the menu title is enabled.

You can also disable a menu item by placing a backslash (\) before the text of the menu title text. For example:

DEFINE PAD padPageAccts OF mnuReceive PROMPT '\Age Accounts'

The menu title padPageAccts is displayed dimmed, indicating that it cannot be chosen.

A disabled menu title can be displayed but can't be selected. However, a message specified with the MESSAGE clause is displayed.

MESSAGE cMessageText
Displays a message when the user selects a menu title. The message is placed in the graphical status bar. If the graphical status bar is turned off with SET STATUS BAR OFF, the message is centered on the last line of the main Visual FoxPro window.
COLOR SCHEME nSchemeNumber
Specifies the colors for an individual menu title, overriding the default colors or the colors specified with DEFINE MENU.
COLOR ColorPairList
Specifies the colors for an individual menu title, overriding the default colors or the colors specified with DEFINE MENU.

By default, the colors of menu titles in menu bars are determined by color scheme 2 of the current color set.

Remarks

You must create each menu title placed on the menu bar with its own DEFINE PAD command. A menu bar must be defined with DEFINE MENU before you can place menu titles on it, and you must include the menu bar name in DEFINE PAD.

If you use the Menu Designer to create your menu, you may not have to use these commands at all. The Menu Designer automatically creates the commands for your menu. The Menu Designer uses the Visual FoxPro system menu, which you can then modify by adding your own menu items. For more information on creating menus, see Menu System Creation.

Example

The following example uses DEFINE PAD to place menu titles in the Visual FoxPro system menu bar. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Several system menu titles are created with DEFINE PAD. When a menu title is chosen, the CHOICE procedure is executed. CHOICE displays the name of the chosen menu title and the name of the menu bar, and toggles the menu titles' mark character on and off. If the Exit menu title is chosen, the original Visual FoxPro system menu is restored.

*** Name this program DEFINPAD.PRG ***
CLEAR
SET TALK OFF
SET SYSMENU SAVE
SET SYSMENU TO
PUBLIC markpad
markpad = .T.
DEFINE PAD syspad  OF _MSYSMENU PROMPT '\<System'  COLOR SCHEME 3 ;
   KEY ALT+S, ''
DEFINE PAD editpad OF _MSYSMENU PROMPT '\<Edit'  COLOR SCHEME 3 ;
   KEY ALT+E, ''
DEFINE PAD recordpad OF _MSYSMENU PROMPT '\<Record'  COLOR SCHEME 3 KEY ALT+R, ''
DEFINE PAD windowpad OF _MSYSMENU PROMPT '\<Window'  COLOR SCHEME 3 ;
   KEY ALT+W, ''
DEFINE PAD reportpad OF _MSYSMENU PROMPT 'Re\<ports' COLOR SCHEME 3 ;
   KEY ALT+P, ''
DEFINE PAD exitpad OF _MSYSMENU PROMPT 'E\<xit'  COLOR SCHEME 3 ;
   KEY ALT+X, ''
ON SELECTION MENU _MSYSMENU ;
   DO choice IN definpad WITH PAD( ), MENU( )
PROCEDURE choice
PARAMETER mpad, mmenu
WAIT WINDOW 'You chose ' + mpad + ;
   ' from menu ' + mmenu NOWAIT
SET MARK OF PAD (mpad) OF _MSYSMENU TO ;
   ! MRKPAD('_MSYSMENU', mpad)
markpad = ! markpad
IF mpad = 'EXITPAD'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

ACTIVATE MENU | CREATE MENU | DEACTIVATE MENU | DEFINE MENU | GETPAD( ) | HIDE MENU | MRKPAD( ) | ON PAD | ON SELECTION PAD | PRMPAD( ) | RELEASE PAD | SET MARK OF | SET MESSAGE | SET SYSMENU | SHOW MENU


DEFINE POPUP Command

Creates a menu.

DEFINE POPUP MenuName [FROM nRow1, nColumn1] [TO nRow2, nColumn2]
   [IN [WINDOW] WindowName | IN SCREEN] [FONT cFontName [, nFontSize]]
   [STYLE cFontStyle] [FOOTER cFooterText] [KEY KeyLabel] [MARGIN]
   [MARK cMarkCharacter] [MESSAGE cMessageText] [MOVER] [MULTISELECT]
   [PROMPT FIELD FieldName | PROMPT FILES [LIKE FileSkeleton]
      | PROMPT STRUCTURE] [RELATIVE] [SCROLL] [SHORTCUT]
   [TITLE cMenuTitleText]
   [COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

MenuName
Specifies the name of the menu to create.
FROM nRow1, nColumn1 TO nRow2, nColumn2
Specifies where the menu is placed. nRow1, nColumn1 specifies coordinates for the upper-left corner of the menu. If you omit the FROM clause, Visual FoxPro places the upper-left corner of the menu in the first row and first column of the main Visual FoxPro window or a user-defined window.

To create a menu with a specific size, you can also include TO nRow2, nColumn2 to specify the location of the lower-right corner of the menu. If you include FROM nRow1, nColumn1 and omit TO nRow2, nColumn2, Visual FoxPro automatically sizes the menu. The menu is as wide as the longest menu item in it (if the items are created with DEFINE BAR) and as long as needed to display all of the menu items. The menu length is limited by the size of the main Visual FoxPro window or user-defined window in which the menu is placed. If a menu isn't large enough to contain all of the menu items, a scroll bar appears so that you can scroll through the menu items.

IN [WINDOW] WindowName
Places a menu in a user-defined window you specify with WindowName. If you omit this clause, the menu is placed on the main Visual FoxPro window by default unless there is an active user-defined window. If there is an active user-defined window, the menu is placed in the active window.
IN SCREEN
Explicitly places a menu in the main Visual FoxPro window.
FONT cFontName [, nFontSize]
Specifies a default font for the menu. You can override the default font for an individual menu item by including the FONT clause in DEFINE BAR.

cFontName specifies the name of the font, and nFontSize specifies the point size. For example, the following command creates a menu in 12-point Courier font:

DEFINE POPUP popMyPopup FONT 'Courier', 12

If the font you specify is not available, a font with similar font characteristics is substituted. If you include the FONT clause but omit the point size nFontSize, a 10-point font is used.

STYLE cFontStyle
Specifies a default font style for the menu. You can override the default style for an individual menu item by including the FONT clause in DEFINE BAR.

If you omit the STYLE clause, or if the font style you specify is not available, the Normal font style is used.

The font styles you can specify with cFontStyle are listed in the following table:

Character | Font style
B | Bold
I | Italic
N | Normal
Q | Opaque
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command specifies Bold Italic:

DEFINE MENU popMyPopup STYLE 'BI'
FOOTER cFooterText
Creates a footer with the text specified with cFooterText centered in the bottom border of the menu.
KEY KeyLabel
Specifies an access key or key combination for a menu. For a list of available keys and key combinations and their key label names, see ON KEY LABEL.

Including KEY is equivalent to issuing the following command:

ON KEY LABEL KeyLabel ACTIVATE POPUP MenuName
Note If a keyboard macro is already defined with the same key label, the keyboard macro takes precedence, and the menu cannot be activated with the specified key or key combination.
MARGIN
Places an extra space to the left and right of each menu item. Mark characters are displayed in the space to the left of an item, and arrows indicating additional cascading submenus are available and are displayed to the right of menu items. If you omit MARGIN, the mark characters overwrite the first character of the menu item names; hierarchical arrows overwrite the last character of the menu items.
Note You must include this clause if you want to use the DEFINE BAR ... PICTURE or PICTRES clauses.
MARK cMarkCharacter
Specifies a character that appears to the left of an item on the menu. The default mark character is a check mark. The MARK clause is ignored and the default mark character is used if the menu is integrated into the Visual FoxPro system menu. Also, the MARK clause is ignored if FoxFont isn't the font for the main FoxPro window or the user-defined window in which the menu is placed.

MARK can be included to change the default mark character to a character specified with cMarkCharacter. If cMarkCharacter includes more than one character, only the first character is used as the mark character.

Note Specifying a mark character doesn't mark a menu item. Use SET MARK OF to mark a menu item.

The MARK clause sets the mark character for all items on the menu. Mark characters specified with DEFINE BAR commands take precedence over mark characters specified with the MARK clause in DEFINE POPUP. SET MARK OF is used to toggle mark characters on or off and can also be used to specify a mark character for an individual menu item or for all menu items.

MESSAGE cMessageText
Displays a message when you select a menu item. The message is placed in the graphical status bar. If the character-based status bar is turned on with SET STATUS ON, the message is centered on the last line of the main Visual FoxPro window.
MOVER
Places a double-headed arrow [image] in the Mover box to the left of the selected item in the menu. You can drag the double-headed arrow to move an item to another position on the menu. GETBAR( ) can be used to determine where each item is positioned on the menu.

You cannot rearrange items in a menu created with a PROMPT clause.

MULTISELECT
Allows the user to select multiple items from a menu at the same time. When the user chooses an item from a menu, the mark character is placed to the left of the item.

You cannot make multiple selections from a menu created with a PROMPT clause.

MRKBAR( ) can be used to determine which items are chosen from the menu.

If you include MULTISELECT in DEFINE POPUP, you can include MARGIN to reserve space in each item for the mark character.

In the following example, a menu named popFruits is created. MULTISELECT is included to create a menu that allows multiple items to be chosen.

Each of the four items has a different mark character. When a user chooses items from the menu, the items are marked and a routine named yourchoice displays the chosen items.

CLEAR
IF NOT _DOS
   MODIFY WINDOW SCREEN FONT 'foxfont', 12
ENDIF
ACTIVATE SCREEN
DEFINE POPUP popFruits FROM 5,5 ;
   MULTISELECT MARGIN            && Create multi-choice menu
DEFINE BAR 1 OF popFruits ;
   PROMPT '\<Apples'  MARK CHR(3)    && First item
DEFINE BAR 2 OF popFruits ;
   PROMPT '\<Bananas' MARK CHR(4)    && Second item
DEFINE BAR 3 OF popFruits ;
   PROMPT '\<Grapes'  MARK CHR(5) && Third item
DEFINE BAR 4 OF popFruits ;
   PROMPT '\<Lemons'  MARK CHR(6)    && Fourth item
@ 12,5 SAY 'Your choices:'
ON SELECTION POPUP popFruits DO yourchoice    && Choice routine
ACTIVATE POPUP popFruits
PROCEDURE yourchoice            && Executed when choice is made
@ 13,5 CLEAR
FOR gnCount = 1 TO CNTBAR('popFruits')      && Loop for # of items
   IF MRKBAR('popFruits', gnCount) = .T.      && Option is marked,
      ? PRMBAR('popFruits', gnCount) AT 5      && display caption
   ENDIF
NEXT
PROMPT FIELD FieldName
Specifies the field name from an open table whose records become the items on the menu. The menu contains an item for each record in the table. When the menu is activated, the tables' work area is selected.
Tip You can take advantage of Rushmore Query Optimization if you set a filter on the field specified with PROMPT FIELD used in the menu. For more information on Rushmore Query Optimization, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access in Optimizing Applications.

FieldName can also contain multiple field names and expressions concatenated with the addition operator (+). FieldName can also be the name of the field in a table open in another work area or a user-defined function.

There is no limit to the number of entries that can appear in a menu created with PROMPT FIELD.

PROMPT FILES [LIKE FileSkeleton]
Creates a menu that displays the names of files available in the current directory.

LIKE FileSkeleton allows you to specify the files that are displayed in the menu using wildcards. For example, to create a menu that displays the names of tables in the default drive and directory, include the following command:

PROMPT FILES LIKE *.DBF

You can create a menu that displays the names of files on other drives and in other directories or folders by including a drive or volume specification, a directory specification, or both. For example, to create a menu that displays the names of program files in a directory called PROGRAMS on drive C, include the following command:

PROMPT FILES LIKE C:\PROGRAMS\*.PRG
PROMPT STRUCTURE
Displays the names of the fields in the current table on the menu according to the table's field structure. When the menu is activated, the table's work area is selected.
RELATIVE
Specifies the order in which items are placed on a menu. If you create a menu without the RELATIVE clause, an item is positioned on a menu in an order dictated by the item's bar number. Space on the menu is reserved for undefined items. For example, if the first and third items are defined and the menu is activated, a blank line reserved for the second item is placed on the menu.

If you create a menu with RELATIVE, the items appear on the menu in the order in which they are defined. Space in the menu isn't reserved for undefined items.

Defining a menu with RELATIVE also lets you make use of BEFORE and AFTER clauses in DEFINE BAR to position items on a menu relative to other items. If a menu is created without RELATIVE, including BEFORE or AFTER in DEFINE BAR generates an error.

Run the following two program examples and compare the placement of the items on each menu.

*** RELATIVE Example  ***
DEFINE POPUP popRelatYes RELATIVE FROM 1,1
DEFINE BAR 4  OF popRelatYes PROMPT '4444'
DEFINE BAR 3  OF popRelatYes PROMPT '3333'
DEFINE BAR 2  OF popRelatYes PROMPT '2222'
DEFINE BAR 1  OF popRelatYes PROMPT '1111'
DEFINE BAR 6  OF popRelatYes PROMPT '6666' BEFORE 4
ACTIVATE POPUP popRelatYes
*** NON-RELATIVE Example ***
DEFINE POPUP popRelatNo FROM 1,1
DEFINE BAR 4  OF popRelatNo PROMPT '4444'
DEFINE BAR 3  OF popRelatNo PROMPT '3333'
DEFINE BAR 2  OF popRelatNo PROMPT '2222'
DEFINE BAR 1  OF popRelatNo PROMPT '1111'
DEFINE BAR 6  OF popRelatNo PROMPT '6666'
ACTIVATE POPUP popRelatNo
SCROLL
Places a scroll bar to the right of the menu you create. The scroll bar is displayed only when there are more items than can fit on the menu, or if the menu is too long to fit in the main Visual FoxPro window or the user-defined window in which it is placed.
SHORTCUT
Creates a shortcut menu. A shortcut menu typically appears when a selection, toolbar, or taskbar button is clicked with the right mouse button. The shortcut menu lists commands that pertain to the screen region on which the mouse was right-clicked.

You can include MROW( ) and MCOL( ) in the FROM clause to activate the popup at the location where the mouse is clicked.

TITLE cMenuTitleText
Displays a title in the center of the top border of the menu. cTitleText specifies the menu title.
COLOR SCHEME nSchemeNumber
Specifies the colors for all elements of a menu. By default, the colors of menus created with DEFINE POPUP are controlled by color scheme 2.
COLOR ColorPairList
Specifies the colors for all elements of a menu.

Remarks

To place a set of menu items that you define on a menu, use a series of DEFINE BAR commands. To place records, files, or fields in a menu, use the PROMPT FIELD, PROMPT FILES, or PROMPT STRUCTURE options of DEFINE POPUP.

When the menu is displayed and activated with ACTIVATE POPUP, you can choose one of the items on the menu. Depending on the item chosen, a routine can be executed or another menu can be displayed and activated. A menu that displays another menu when an item is chosen is called a cascading submenu. For more information on creating submenus, see ON BAR.

If you use the Menu Designer to create your menu, you may not have to use these commands at all. The Menu Designer automatically creates the commands for your menu. The Menu Designer uses the Visual FoxPro system menu, which you can then modify by adding your own menu items.

For more information on creating menus, see Menu System Creation.

Example

The following example uses DEFINE POPUP to create menus that are activated when a menu title in the menu bar is chosen. The current system menu bar is first saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Two new system menu titles are created with DEFINE PAD, and DEFINE POPUP creates a drop-down menu for each menu title. DEFINE BAR creates items on each of the menus. When a menu title is chosen, ON PAD uses ACTIVATE POPUP to activate the corresponding menu.

When an item is chosen from a menu, ON SELECTION POPUP uses PROMPT( ) and POPUP( ) to pass the item number and menu name to the CHOICE procedure. CHOICE displays the text of the chosen item and the name of the menu containing the item. If the Exit item is chosen from the Card Info menu, the original Visual FoxPro system menu is restored.

*** Name this program DEFINPOP.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD convpad OF _MSYSMENU PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD cardpad OF _MSYSMENU PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD convpad OF _MSYSMENU ACTIVATE POPUP conversion
ON PAD cardpad OF _MSYSMENU ACTIVATE POPUP cardinfo
DEFINE POPUP conversion MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF conversion PROMPT 'Ar\<ea' KEY CTRL+E, '^E'
DEFINE BAR 2 OF conversion PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF conversion PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF conversion PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF conversion PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF conversion PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF conversion PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
ON SELECTION POPUP conversion;
   DO choice IN definpop WITH PROMPT( ), POPUP( )
DEFINE POPUP cardinfo MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF cardinfo PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF cardinfo PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF cardinfo PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF cardinfo PROMPT '\-'
DEFINE BAR 5 OF cardinfo PROMPT '\<Charges '
DEFINE BAR 6 OF cardinfo PROMPT '\-'
DEFINE BAR 7 OF cardinfo PROMPT 'E\<xit '
ON SELECTION POPUP cardinfo;
   DO choice IN definpop WITH PROMPT( ), POPUP( )
PROCEDURE choice
PARAMETERS mprompt, mpopup
WAIT WINDOW 'You chose ' + mprompt + ;
   ' from popup ' + mpopup NOWAIT
IF mprompt = 'Exit'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

ACTIVATE POPUP | CNTBAR( ) | CREATE MENU | DEFINE BAR | GETBAR( ) | HIDE POPUP | MOVE POPUP | MRKBAR( ) | ON BAR | ON SELECTION BAR | POPUP( ) | PRMBAR( ) | PROMPT( ) | RELEASE POPUPS | SET MARK OF | SET MESSAGE | SIZE POPUP | SHOW POPUP


DEFINE WINDOW Command

Creates a window and specifies its attributes.

DEFINE WINDOW WindowName1 FROM nRow1, nColumn1 TO nRow2, nColumn2
   | AT nRow3, nColumn3 SIZE nRow4, nColumn4
   [IN [WINDOW] WindowName2 | IN SCREEN | IN DESKTOP [NAME ObjectName]
      [FONT cFontName [, nFontSize]] [STYLE cFontStyle]
      [FOOTER cFooterText] [TITLE cTitleText] [HALFHEIGHT]
      [DOUBLE | PANEL | NONE | SYSTEM | cBorderString]
      [CLOSE | NOCLOSE] [FLOAT | NOFLOAT] [GROW | NOGROW] [MDI | NOMDI]
      [MINIMIZE | NOMINIMIZE] [ZOOM | NOZOOM] [ICON FILE FileName1]
      [FILL cFillCharacter | FILL FILE FileName2]
      [COLOR SCHEME nSchemeNumber   | COLOR ColorPairList]]

Parameters

WindowName1
Specifies the name of the window to create. Window names can be up to 254 characters long in Visual FoxPro. They must begin with a letter or underscore, and cannot begin with a number. They can contain any combination of letters, numbers and underscores.
FROM nRow1, nColumn1 TO nRow2, nColumn2
Specifies the position and size of the user-defined window on the main Visual FoxPro window. FROM nRow1, nColumn1 specifies the position of the upper-left corner of the user-defined window on the main Visual FoxPro window. TO nRow2, nColumn2 specifies the position of the lower-right corner of the user-defined window on the main Visual FoxPro window.

A window can be defined with coordinates that lie outside the Visual FoxPro window border and can be larger than the main Visual FoxPro window.

The window's location and size are determined by the font of the window's parent. The window's parent can be another user-defined window or the main Visual FoxPro window.

AT nRow3, nColumn3 SIZE nRow4, nColumn4
Specifies the position and size of a user-defined window.

AT nRow3, nColumn3 specifies the position of the upper-left corner of the user defined window on the main Visual FoxPro window. This position is determined by the current font of the window's parent. Because the AT clause is identical to the FROM clause in all respects, the two clauses can be used interchangeably.

SIZE nRow4, nColumn4 specifies in rows and columns the size of the user-defined window and ensures that text displayed in a specific font will fit in the window you create.

You can specify a font and font style for a user-defined window by including the FONT and STYLE clauses. If you specify a font for the window and include the SIZE clause, its size is determined by the window's font height and width. If you don't specify a font for a window, the window's font is the default system font, 10-point FoxFont.

IN [WINDOW] WindowName2
Places a user-defined window in a parent window. The user-defined window becomes a child window and cannot be moved outside the parent window. If the parent window is moved, the child window moves with it.

When a child window is placed in a parent window, the child window coordinates specified with the FROM and TO clauses or the AT and SIZE clauses are relative to the parent window, not the main Visual FoxPro window.

In the following example, a parent window, wParent, is created. A child window, wChild, is placed in the parent window.

CLEAR
DEFINE WINDOW wParent ;
   FROM 1, 1 TO 20, 30 ;
   TITLE "Parent"         && Parent window.
ACTIVATE WINDOW wParent
DEFINE WINDOW wChild ;
   FROM 1, 1 TO 20, 20 ;
   TITLE "Child" ;
   IN WINDOW wParent       && Child window.
ACTIVATE WINDOW wChild
ACTIVATE SCREEN
WAIT WINDOW 'Press a key to clear the windows'
RELEASE WINDOW wParent, wChild
CLEAR
IN SCREEN
Explicitly places a user-defined window on the main Visual FoxPro window. If you omit IN SCREEN, the user-defined window is placed on the main Visual FoxPro window by default.

You can include the IN WINDOW clause in ACTIVATE WINDOW to place the window in another user-defined window and override this IN SCREEN clause.

IN DESKTOP
Places a user-defined window on the Microsoft Windows desktop, outside the main Visual FoxPro window. The position of the window is relative to the Windows desktop, and the current font of the main Visual FoxPro window.
NAME ObjectName
Creates an object reference for the window, allowing you to manipulate the window with object-oriented properties available for the form object.

For additional information about object-oriented programming in Visual FoxPro, see Object-Oriented Programming. For additional information about the form object properties you can specify for a window created with the NAME clause, see the Form Object topic.

FONT cFontName [, nFontSize]
Specifies a font for text placed in the window. cFontName specifies the name of the font and nFontSize specifies the point size. If you omit nFontSize, a 9-point font is used.

For example, this command creates a window that displays output directed to the window in a 16-point Courier font:

DEFINE WINDOW wDisplayFont FROM 2,2 TO 12,22 FONT 'Courier', 16

If you omit the FONT clause, a 10-point FoxFont is used. If the font you specify is not available, a font with similar font characteristics is substituted.

STYLE cFontStyle
Specifies a font style for text placed in the window. cFontStyle specifies the font. If you omit the STYLE clause, or if the font style you specify is not available, the Normal font style is used.

The following table lists font styles and their corresponding characters.

Character | Font style
B | Bold
I | Italic
N | Normal
Q | Opaque
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. In Visual FoxPro, the following commands specify the style Bold Italic:

DEFINE WINDOW wDisplayStyle FROM 2, 2 TO 12, 22 STYLE 'BI'
TITLE cTitleText
Assigns a title with the TITLE clause. cTitleText specifies the title's text and is centered in the top border of the window. If the title is wider than the window, the title is truncated.
HALFHEIGHT
Creates a window with a half-height title bar. This provides compatibility for windows created in previous versions of FoxPro that are imported into Visual FoxPro.

When you use DEFINE WINDOW to create a window, a half-height title bar is used, unless you include the SYSTEM keyword or you include a FONT clause.

If you include the HALFHEIGHT keyword, a half-height title bar is used regardless of whether the SYSTEM or FONT clause is included.

DOUBLE | PANEL | NONE | SYSTEM | cBorderString
Specifies a border style for a user-defined window. The default border is a single line.
Argument | Description
DOUBLE | Specifies a double-line border around the window.
PANEL | Specifies a wide border around the window.
NONE | Suppresses the border entirely.
SYSTEM | Specifies the user-defined window to look like a system window. When you include certain other clauses (GROW, ZOOM, and so on), the appropriate window controls are placed in the window's border.
cBorderString | Specifies a custom border. For more information on defining a custom border, see SET BORDER.

Including DOUBLE or a custom border string creates a window with the PANEL border. Including the CLOSE, FLOAT, GROW, ZOOM, or MINIMIZE clauses places the appropriate controls on the window even if the SYSTEM window definition clause is not included.

CLOSE
Allows the user to close a user-defined window using the keyboard or mouse. Closing a window removes it from the main Visual FoxPro window or a parent user-defined window and removes its definition from memory. If you omit CLOSE, you cannot close the window using the interface; the window must be closed using a command in a program or in the Command window.
NOCLOSE
Prevents the window from being closed except by a command in a program or in the Command window.
FLOAT
Allows the window to be moved using the keyboard or mouse. If you omit FLOAT, you cannot move the window except using the MOVE WINDOW command in a program or in the Command window.
NOFLOAT
Prevents the window from being moved except by using the MOVE WINDOW command in a program or in the Command window.
GROW
Allows you to resize a user-defined window using the keyboard or mouse. If you omit GROW, you cannot size the window except using the SIZE WINDOW command in a program or in the Command window.
NOGROW
Prevents the window from being resized except by the SIZE WINDOW command in a program or in the Command window.
MDI
Creates a user-defined window that is MDI-compliant. MDI (multiple document interface) is a specification that allows multiple document windows and determines their structure and behavior. If you omit MDI, the window you create isn't MDI-compliant.

When an MDI-compliant window is maximized:

  • The window assumes the size of the main Visual FoxPro window. The window's controls disappear and its pop-up menu icon appears in the Visual FoxPro system menu bar. The window's Restore button is also placed in the Visual FoxPro system menu bar.
  • The window title is placed in the Visual FoxPro title bar and is separated from the Visual FoxPro title by a hyphen.
  • If you activate another MDI-compliant window, it is automatically maximized.
NOMDI
Creates a window that isn't MDI-compliant.
MINIMIZE
Allows you to minimize a user-defined window using the keyboard or mouse.
NOMINIMIZE
Prevents the window from being minimized.
ZOOM
Allows the window to be maximized using the keyboard or mouse. You can also restore the window to its original size.
NOZOOM
Prevents the window from being maximized.
ICON FILE FileName
Specifies the icon that displays when the window is minimized. You must include the MINIMIZE keyword in DEFINE WINDOW. You can specify only an icon (.ico) file; you cannot specify a bitmap (.bmp) file.
FILL FILE FileName2
Specifies a wallpaper (the background) for the window. The window is tiled with the specified FileName2. You specify a .bmp bitmap file.
COLOR SCHEME nSchemeNumber
Specifies the colors for the user-defined window. By default, the colors of windows created with DEFINE WINDOW are controlled by color scheme 1.
COLOR ColorPairList
Specifies the colors for the user-defined window.

Remarks

After user-defined windows are created with DEFINE WINDOW, they can be displayed in the main Visual FoxPro window with ACTIVATE WINDOW or SHOW WINDOW. The number of user-defined windows you can create is limited only by the amount of available memory and system resources.

Activated windows remain in the main Visual FoxPro window until DEACTIVATE WINDOW or HIDE WINDOW is issued. DEACTIVATE WINDOW and HIDE WINDOW remove windows from the main Visual FoxPro window but don't remove the window definitions from memory. Windows can be placed back in the main Visual FoxPro window with ACTIVATE WINDOW or SHOW WINDOW.

Use CLEAR WINDOWS or RELEASE WINDOWS to remove windows from the main Visual FoxPro window and window definitions from memory. Windows whose definitions have been removed from memory must be recreated with DEFINE WINDOW in order to be redisplayed.

Example

In the following example, a window named output is created and activated. The program waits for you to press a key and then hides the window. The program waits for you to press a key again and then redisplays the window.

CLEAR
DEFINE WINDOW output FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
ACTIVATE WINDOW output
WAIT WINDOW 'press any key to hide window output'
HIDE WINDOW output
WAIT WINDOW 'press any key to show window output'
SHOW WINDOW output
WAIT WINDOW 'press any key to release window output'
RELEASE WINDOW  output

See Also

ACTIVATE WINDOW | DEACTIVATE WINDOW | Fonts Overview | Form Object | HIDE WINDOW | MODIFY WINDOW | MOVE WINDOW | RELEASE WINDOWS | SET BORDER | SHOW WINDOW


DELETE - SQL Command

Marks records for deletion.

DELETE FROM [DatabaseName!]TableName
   [WHERE FilterCondition1 [AND | OR FilterCondition2 ...]]

Parameters

FROM [DatabaseName!]TableName
Specifies the table in which records are marked for deletion.

DatabaseName! specifies the name of a non-current database containing the table. You must include the name of a database containing the table if the database is not the current database. Include the exclamation point (!) delimiter after the database name and before the table name.

WHERE FilterCondition1 [AND | OR FilterCondition2 ...]
Specifies that Visual FoxPro marks only certain records for deletion.

FilterCondition specifies the criteria that records must meet to be marked for deletion. You can include as many filter conditions as you like, connecting them with the AND or OR operator. You can also use the NOT operator to reverse the value of a logical expression, or use EMPTY( ) to check for an empty field.

Remarks

Records marked for deletion aren't physically removed from the table until PACK is issued. Records marked for deletion can be recalled (unmarked) with RECALL.

If SET DELETED is set to ON, records marked for deletion are ignored by all commands that include a scope.

You can determine the number of records marked for deletion by checking the value of the _TALLY system variable immediately after the DELETE - SQL command.

Unlike DELETE, DELETE - SQL uses record locking when marking multiple records for deletion in tables opened for shared access. This reduces record contention in multiuser situations, but may reduce performance. For maximum performance, open the table for exclusive use or use FLOCK( ) to lock the table.

Example

The following example opens the customer table in the testdata database. DELETE - SQL is used to mark all records for deletion where the country field contains USA. All the records marked for deletion are displayed. RECALL ALL is used to unmark all the records marked for deletion.

CLOSE DATABASES
CLEAR

OPEN DATABASE HOME(2)+"Data\testdata"
USE customer  && Open Customer table

DELETE FROM customer WHERE country = "USA"   && Mark for deletion

CLEAR
LIST FIELDS company, country FOR DELETED( )  && List marked records
* If the file were packed at this point the records would be deleted
WAIT WINDOW "Records currently marked for deletion"+CHR(13) + ;
   "Press any key to revert..."

* Unmark all records marked for deletion
RECALL ALL
CLEAR
* Verify reverted records
COUNT FOR DELETED( )=.T. TO nDeleted

* Convert nDeleted to a character string and display information
WAIT WINDOW ALLTRIM(STR(nDeleted)) + " records marked for deletion."

See Also

DELETE | DELETED( ) | PACK | RECALL | SET DELETED | _TALLY


DELETE Command

Marks records for deletion.

DELETE [Scope] [FOR lExpression1] [WHILE lExpression2]
   [IN nWorkArea | cTableAlias] [NOOPTIMIZE]

Parameters

Scope
Specifies a range of records to mark for deletion. The default scope for DELETE is the current record (NEXT 1). The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies a condition whereby only the records that satisfy the logical condition lExpression1 are marked for deletion.

Rushmore Query Optimization optimizes a query created with DELETE ... FOR if lExpression1 is an optimizable expression and the table is indexed on DELETED( ). For best performance, use an optimizable expression in the FOR clause.

For information on Rushmore optimizable expressions, see SET OPTIMIZE, and Using Rushmore Query Optimization to Speed Data Access in Optimizing Applications, .

WHILE lExpression2
Specifies a condition whereby records are marked for deletion for as long as lExpression2 evaluates to true (.T.).
IN nWorkArea
Specifies the work area of the table in which records are marked for deletion.
IN cTableAlias
Specifies the alias of the table in which records are marked for deletion.

If you omit nWorkArea and cTableAlias, records are marked for deletion in the table in the currently selected work area.

NOOPTIMIZE
Disables Rushmore optimization of DELETE.

Remarks

Records marked for deletion aren't physically removed from the table until PACK is issued. Records marked for deletion can be recalled (unmarked) with RECALL.

Example

The following example opens the customer table in the testdata database. DELETE is used to mark all records for deletion where the country field contains USA. All the records marked for deletion are displayed. RECALL ALL is used to unmark all the records marked for deletion.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

DELETE FOR country = 'USA'  && Mark for deletion
CLEAR
LIST FIELDS company, country FOR DELETED( ) && List marked records
RECALL ALL  && Unmark all records marked for deletion

See Also

DELETE - SQL | DELETED( ) | PACK | RECALL | SET DELETED


DELETE CONNECTION Command

Deletes a named connection from the current database.

DELETE CONNECTION ConnectionName

Parameters

ConnectionName
Specifies the name of the named connection to delete from the current database.

Remarks

Deleting a named connection definition does not close any active connections.

DELETE CONNECTION requires exclusive use of the database. To open a database for exclusive use, include EXCLUSIVE in OPEN DATABASE.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn is created. DISPLAY CONNECTIONS is used to display the named connections in the database. The connection is then removed from the database with DELETE CONNECTION.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CREATE CONNECTION Myconn DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"
DISPLAY CONNECTIONS    && Displays named connections in the database
DELETE CONNECTION Myconn  && Removes the connection just created

See Also

CREATE CONNECTION | MODIFY CONNECTION | RENAME CONNECTION


DELETE DATABASE Command

Deletes a database from disk.

DELETE DATABASE DatabaseName | ? [DELETETABLES] [RECYCLE]

Parameters

DatabaseName
Specifies the name of the database to delete from disk. The database you specify cannot be open. DatabaseName can include the path to the database with the database name.
?
Displays the Delete dialog box from which you can specify the name of the database to delete from disk.
DELETETABLES
Deletes the tables contained in the database from disk and the database containing the tables.
RECYCLE
Specifies that the database isn't immediately deleted from disk and is placed in the Windows Recycle Bin.

Remarks

Always use DELETE DATABASE to delete a database from disk. Unlike the file manipulation utility of the operating system, DELETE DATABASE removes references to the database from the tables in the database.

If SET SAFETY is ON, Visual FoxPro asks if you'd like to delete the database you specify. If SET SAFETY is OFF, the database is automatically deleted from disk.

Example

This example creates a database named people. A table named friends is created and is automatically added to the database. DISPLAY TABLES is used to display the tables in the database, and DISPLAY DATABASES is used to display information about the tables in the database.

DELETE DATABASE is used with the DELETETABLES option to remove the database and its friends table from disk.

CLOSE ALL
CREATE DATABASE people
CREATE TABLE friends (FirstName C(20), LastName C(20))
CLEAR
DISPLAY TABLES  && Displays tables in the database
DISPLAY DATABASES  && Displays table information
CLOSE ALL
DELETE DATABASE people DELETETABLES

See Also

ADD TABLE | CLOSE DATABASES | DBC( ) | DBGETPROP( ) | DBSETPROP( ) | DISPLAY TABLES | OPEN DATABASE | REMOVE TABLE


DELETE FILE Command

Deletes a file from a disk.

DELETE FILE [FileName | ?] [RECYCLE]

Parameters

FileName
Specifies the file to delete. FileName can contain wildcard characters such as * and ?. For example, to delete backup files with the extension .bak in the current directory, issue DELETE FILE *.BAK. If FileName contains spaces, enclose the entire file name in quotes.
?
Displays the Delete dialog from which you can choose a file to delete.
RECYCLE
Specifies that the file isn't immediately deleted from disk and is placed in the Windows Recycle Bin.
Caution Any file deleted with this command cannot be retrieved. Even if SET SAFETY is ON, you are not warned before the file is deleted.

Remarks

The file you want to delete cannot be open when DELETE FILE is issued. The file name must include a path if it is on a different drive or volume, or in a different directory from the default, and the file name extension must be included. The file name cannot contain wildcards.

Before you delete a table in a database, issue REMOVE TABLE with the table name to remove references to the table from the database. If you delete a table that has an associated .FPT memo file, be sure to delete the memo file.

This command does not generate an error if the specified file does not exist.

Example

In the following example, the structure of Customer.dbf and all records in which the country is USA are copied to a table named backup. The data in backup is then copied to a text file, temp, which is opened and then deleted when it is closed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

COPY STRUCTURE TO backup
USE backup
APPEND FROM customer FOR country = 'USA'
COPY TO temp TYPE DELIMITED

WAIT WINDOW 'Press Esc to close and erase temp.txt' NOWAIT
MODIFY FILE temp.txt NOEDIT
DELETE FILE temp.txt
? IIF(FILE('temp.txt'),'File not deleted','File deleted')
USE
DELETE FILE backup.dbf

See Also

ERASE | REMOVE TABLE | SET SAFETY


DELETE TAG Command

Removes a tag or tags from a compound index (.cdx) file.

DELETE TAG TagName1 [OF CDXFileName1] [, TagName2 [OF CDXFileName2]]...

-or-

DELETE TAG ALL [OF CDXFileName]

Parameters

TagName1 [OF CDXFileName1] [, TagName2 [OF CDXFileName2]] ...
Specifies a tag to remove from a compound index file. You can delete multiple tags with one DELETE TAG by including a list of tag names separated by commas. If two or more tags with the same name exist in the open index files, you can remove a tag from a specific index file by including OF CDXFileName.
ALL [OF CDXFileName]
Removes every tag from a compound index file. If the current table has a structural compound index file, all tags are removed from the index file, the index file is deleted from the disk, and the flag in the table's header indicating the presence of an associated structural compound index file is removed. Use ALL with OF CDXFileName to remove all tags from an open compound index file other than the structural compound index file.

Remarks

Compound index files, created with INDEX, contain tags corresponding to index entries. DELETE TAG is used to remove a tag or tags from open compound index files. You can delete only tags from compound index files open in the current work area. If you remove all the tags from a compound index file, the file is deleted from the disk.

Visual FoxPro looks first for a tag in the structural compound index file (if one is open). If the tag isn't in the structural compound index file, Visual FoxPro then looks for the tag in the other open compound index files.

Visual FoxPro issues a warning if you attempt to delete a primary or candidate index tag and SET SAFETY is ON.

See Also

COPY INDEXES | COPY TAG | INDEX | TAG( )


DELETE TRIGGER Command

Removes a Delete, Insert, or Update trigger for a table from the current database.

DELETE TRIGGER ON TableName FOR DELETE | INSERT | UPDATE

Parameters

TableName
Specifies the name of table for which the trigger is deleted.
FOR DELETE | INSERT | UPDATE
Specifies the trigger to delete. Include FOR DELETE to remove the Delete trigger, FOR INSERT to remove the Insert trigger, and FOR UPDATE to remove the Update trigger.

Remarks

Use CREATE TRIGGER to create a Delete, Insert, or Update trigger for a table.

Example

The following example creates an Update trigger, which prevents values greater than 50 from being entered in the maxordamt field in the customer table. DISPLAY DATABASE is used to display the Update trigger. DELETE TRIGGER is then used to remove the Update trigger, and DISPLAY DATABASE is issued again to verify the removal of the Update trigger.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')  && Open testdata database
USE CUSTOMER  && Open customer table

CREATE TRIGGER ON customer FOR UPDATE AS maxordamt <= 50
CLEAR
DISPLAY DATABASE
DELETE TRIGGER ON customer FOR UPDATE
DISPLAY DATABASE

See Also

ADD TABLE | AERROR( ) | CREATE DATABASE | CREATE TRIGGER | DISPLAY DATABASE | LIST DATABASE | OPEN DATABASE


DELETE VIEW Command

Deletes a SQL view from the current database.

DELETE VIEW ViewName

Parameters

ViewName
Specifies the name of the view deleted from the current database.

Remarks

Use CREATE SQL VIEW to create a SQL view and add the view to the current database. If a SQL view is opened and then deleted, the cursors containing the SQL view results are not closed.

DELETE VIEW requires exclusive use of the database. To open a database for exclusive use, include EXCLUSIVE in OPEN DATABASE.

Example

The following example opens the testdata database. CREATE SQL VIEW is used to create a local SQL view named myview. The View Designer is displayed, making it possible for you to specify tables and conditions for the SQL view. After you save the SQL view, DISPLAY DATABASE is used to display information about the SQL view. DELETE VIEW is then used to delete the local SQL view named myview.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CREATE SQL VIEW myview
CLEAR
DISPLAY DATABASE
DELETE VIEW myview

See Also

CREATE SQL VIEW | OPEN DATABASE


DIMENSION Command

Creates a one- or two-dimensional array of variables.

DIMENSION ArrayName1(nRows1 [, nColumns1]) [AS cType]
   [, ArrayName2(nRows2 [, nColumns2])] ...

Parameters

ArrayName1
Specifies the name of the array. Multiple arrays can be created with a single DIMENSION command by including additional array names (ArrayName2, ArrayName3, and so on).
nRows1 [, nColumns1]
Specifies the size of the array to create. If you include just nRows1, a one-dimensional array is created. One-dimensional arrays have one row and nColumn1 columns. For example, the following command creates a one-dimensional array named gaArrayOne that contains one row and ten columns.
DIMENSION gaArrayOne(10)

To create a two-dimensional array, include both nRows1 and nColumns1. nRows1 specifies the number of rows in the array, and nColumns1 specifies the number of columns. The following example creates a two-dimensional array named gaArrayTwo containing two rows and four columns:

DIMENSION gaArrayTwo(2,4)

You must specify a size for each array you create with DIMENSION. In the following example, three arrays are created: gaArrayOne and gaArrayTwo from the previous examples and a third array called gaArrayThree:

DIMENSION gaArrayOne(10), gaArrayTwo(2,4), gaArrayThree(3,3)

You can use either brackets or parentheses to enclose the expressions in DIMENSION or DECLARE. For example, the following two commands create identical arrays:

DIMENSION gaArrayOne(10), gaArrayTwo[2,4], gaArrayThree(3,3)
DIMENSION gaArrayOne[10], gaArrayTwo(2,4), gaArrayThree[3,3]
AS cType
Specifies a data type for the array. Using the AS cType clause, you can define and specify a data type other than Variant for arrays. The AS cType syntax does not appear in IntelliSense during design time; it is meant for use only at run time. For an example, see Example 4 in the Example section.

The AS cType clause applies only when passing an array to a COM component. Otherwise, Visual FoxPro disregards the AS cType clause. If you specify a data type that is not a valid COM data type, Visual FoxPro automatically defaults to VARIANT type. Data specified as VARIANT can only be passed by reference and not by strongly typed values.

The following table lists valid COM type mappings.

VFP defined type | IntelliSense Quick Info | COM friendly name | COM Typelib | .NET system type | XSD (SOAP) type
Boolean | Logical | Boolean | VARIANT_BOOL (VT_BOOL) | System.Boolean | boolean
Byte | Number | Byte | unsigned char (VT_UI1) | System.Byte
Character * | String | String | BSTR (VT_BSTR) | System.String | string
Currency * | Currency | Currency | CURRENCY (VT_CY)
Date | Date | Date | DATE (VT_DATE) | System.DateTime | dateTime
DateTime | Date | Date | DATE (VT_DATE) | System.DateTime | dateTime
Decimal * | Number | wchar_t (VT_DECIMAL) | System.UInt16
Double | Number | Double | double (VT_R8) | System.Double | double
Float | Variant | VARIANT (VT_VARIANT) | System.Object | anyType
Integer | Number | Long | long (VT_I4) | System.Int32 | int
Logical | Logical | Boolean | VARIANT_BOOL (VT_BOOL) | System.Boolean | boolean
Long | Number | Long | long (VT_I4) | System.Int32 | int
Memo | Variant | VARIANT (VT_VARIANT) | System.Object | anyType
Number | Number | Double | double (VT_R8) | System.Double | double
Object | Object | Object | IDispatch* (VT_DISPATCH) | System.Object
Short | Number | Long | long (VT_I4) | System.Int32 | int
Single * | Number | Single | single (VT_R4) | System.Single
String | String | String | BSTR (VT_BSTR) | System.String | string
Variant | Variant | VARIANT (VT_VARIANT) | System.Object | anyType
Void | VOID | Void | void (VT_VOID) | System.IntPtr
Array | Array | SAFEARRAY(type) | Type[] | Base64Binary

Remarks

DIMENSION is identical in operation and syntax to DECLARE.

Array Elements The size of an array determines how many elements it can contain. Each element in an array can store a single piece of information. To determine how many elements an array contains and how much information it can store, multiply the number of rows (nRows1) in the array by the number of columns (nColumns1) in the array.

Array elements can contain any type of data and are initialized to false (.F.) when the array is first created. You can initialize all the elements in an array to the same value with STORE if SET COMPATIBLE is FOXPLUS or OFF (the default setting). For example:

DIMENSION gaArray(10,3)
STORE 'initial' TO gaArray

Array Subscripts Elements in an array are referenced by their subscripts. Each array element has a unique numeric subscript that identifies it. If the array is one-dimensional, an element's subscript is the same as its row number. For example, the subscript for the element in the third row of a one-dimensional array is 3.

Elements in two-dimensional arrays are referenced by two subscripts. The first subscript indicates the row location of the element, and the second subscript indicates the column location. For example, the subscripts for the element in the third row and fourth column of a two-dimensional array are 3,4. For a further discussion of array element subscripts, see ASUBSCRIPT( ).

The subscript or subscripts for the first element in an array always start with 1. If an array is two-dimensional, it can also be referenced by a single subscript. Use AELEMENT( ) to return the single subscript from a pair of array row and column subscripts. Use ASUBSCRIPT( ) to return the row and column subscripts from a single subscript.

Redimensioning Arrays You can change the size and dimensions of an array by issuing DIMENSION again. The size of an array can be increased or decreased; one-dimensional arrays can be converted to two dimensions, and two-dimensional arrays can be reduced to one dimension.

Note If a two-dimensional array is redimensioned with fewer rows or columns, the number of elements is decreased by element number, not by row or column number. For example, a 10 by 10 array redimensioned to 10 by 7 will lose all element data for elements 71 and higher. For more information, see AELEMENT( ) Function.

If the number of elements in an array is increased, the contents of all the elements in the original array are copied to the newly redimensioned array. The additional array elements are initialized to false (.F.).

When the size of an array is increased or decreased when SET COMPATIBLE is set to ON or DB4, the value of each element in the array is reinitialized to .F.

Typed Arrays You can pass a typed array by reference or by value. You should not explicitly specify Visual FoxPro objects, such as CommandButton. Instead, use Object:

DIMENSION aObjects[] AS CommandButton   && Not supported
DIMENSION aObjects[] AS Object   && Recommended
Note If the COM server is a Visual FoxPro server, you can specify a valid Visual FoxPro object. However, non Visual FoxPro servers will not recognize this type.

You should use COMARRAY( ) to control other settings for how arrays are passed to COM servers, for example, zero-based, byref, and so on.

Note When passing arrays to servers running the Microsoft .NET Framework, you must explicitly call COMARRAY(<object>, 10) to pass a zero-based array by reference. The interop marshaling code provided by the .NET Framework expects a byref array but receives a byval array instead and fails.

Typed arrays of Single (scaler) are not supported for COM servers other than Visual FoxPro COM servers. You cannot pass Currency types to servers running the Microsoft .NET Framework.

When servers running the Microsoft .NET Framework return System.Decimal and System.UInt16 types, they are converted to wchart_t, which maps to the Visual FoxPro Decimal data type.

Example

Example 1

The following example demonstrates the result of increasing the size of a one-dimensional array.

Note If you type these commands in the Command window, the array will be PUBLIC. However, the array will be PRIVATE if you copy them into a program and run it.

If the number of elements in an array is decreased, the elements and any data they contain are deleted. When a one-dimensional array is redimensioned to two dimensions, the contents of the original one-dimensional array are copied to the new array in an element-to-row order.

DIMENSION marray(2)
STORE 'A' TO marray(1)
STORE 'B' TO marray(2)
CLEAR
DISPLAY MEMORY LIKE marray
DIMENSION marray(4)
DISPLAY MEMORY LIKE marray
WAIT WINDOW

Example 2

In the following example, a one-dimensional array is converted to a two-dimensional array. The contents of the elements of the one-dimensional array are copied to the first row of the new array, followed by the second row and so on. The additional elements are initialized to False (.F.).

When a two-dimensional array is converted to one dimension, the contents of the original two-dimensional array are copied to the new array in a row-to-element order. The first element in the first row becomes the first element in the one-dimensional array, the second element in the first row becomes the second element, and so on.

Use ADEL( ) or AINS( ) to delete or insert array elements, rows and columns. Use APPEND FROM ARRAY, COPY TO ARRAY, SCATTER, and GATHER to transfer data between table records and arrays.

DIMENSION marrayone(4)
STORE 'E' TO marrayone(1)
STORE 'F' TO marrayone(2)
STORE 'G' TO marrayone(3)
STORE 'H' TO marrayone(4)
CLEAR
DISPLAY MEMORY LIKE marrayone
DIMENSION marrayone(2,3)
DISPLAY MEMORY LIKE marrayone
WAIT WINDOW

Example 3

In the following example, a two-dimensional array is created and loaded with data. The array elements and the data they contain are displayed.

DIMENSION sample(2,3)
STORE 'Goodbye' TO sample(1,2)
STORE 'Hello' TO sample(2,2)
STORE 99 TO sample(6)
STORE .T. TO sample(1)
CLEAR
DISPLAY MEMORY LIKE sample

Example 4

In the following example, an array is created in Visual FoxPro and is then passed by reference to a Visual Basic COM server, which expects a strong type of Long. Previously, calling FillIntArray would fail because aMyArray has Variant type. However, after including a definition in the Visual Basic class that defines the array as type Variant, calling FillIntArray works as shown:

* Visual FoxPro code
DIMENSION aMyArray [10] AS Long
lo.FillIntArray(@aMyArray, 100)   && Passing to Visual Basic COM Server

' Add following Visual Basic code to .CLS file and compile
' to COM component
Public Sub FillIntArray(ByRef aInts() As Long, iCount As Long)
   ReDim aInts(1 to 100)
   Dim ii As Interger
   For ii = 1 to 100
      AInts(ii) = ii
   Next
End Sub

See Also

ACOPY( ) | ADEL( ) | ADIR( ) | AELEMENT( ) | AFIELDS( ) | AFONT( ) | AINS( ) | ALEN( ) | APPEND FROM ARRAY | ASCAN( ) | ASORT( ) | ASUBSCRIPT( ) | COPY TO ARRAY | DECLARE | EXTERNAL | GATHER | PRIVATE | PUBLIC | SCATTER | SET COMPATIBLE | STORE


DIR or DIRECTORY Command

Displays information about the files in a directory.

DIR | DIRECTORY [ON Drive] [[LIKE] [Path] [FileSkeleton]]
   [TO PRINTER [PROMPT] | TO FILE FileName]

Parameters

ON Drive
Specifies the name of the drive on which the directory is located.
[LIKE] [Path] [FileSkeleton]
Specifies the path to the directory containing the files. The path can include the drive name if you omit ON Drive.

Include FileSkeleton to display information about file types other than tables. FileSkeleton is a file specification skeleton that supports wildcards. For example, to list all program files in the current directory, issue the following command:

DIR *.PRG

In Visual FoxPro, you can issue the following command to list all files without extensions:

DIR *.
TO PRINTER [PROMPT]
Directs output from DIRECTORY to a printer.

In Microsoft Visual FoxPro, you can include the optional PROMPT clause to display a print dialog box before printing starts. In this dialog box you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DIRECTORY to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.

Remarks

Use DIR to display information about files.

DIR without the LIKE clause or a skeleton displays the following:

  • Names of all tables in the directory.
  • Number of records in each table.
  • Date each table was last updated.
  • Size of each table in bytes (tables in the original Microsoft FoxBASE format are noted as such).
  • If each table is part of a database.
  • The total size in bytes the tables occupy on disk (not including associated .fpt memo files).
  • Number of tables displayed.
  • Total number of bytes remaining on the disk.

The table information for the default drive and directory is displayed unless otherwise specified with Drive or Path or both.

Example

CLEAR
DIR  && Display tables in the current directory
DIR *.CDX && Display index files in the current directory
DIR A*.DBF  && Display tables that begin with A
DIR *.*  && Display all files, including those without extensions

See Also

DISPLAY FILES | DIRECTORY( ) Function


DISPLAY Command

Displays information about the current table in the main Visual FoxPro window or in the user-defined window.

DISPLAY [[FIELDS] FieldList] [Scope] [FOR lExpression1]
   [WHILE lExpression2] [OFF] [NOCONSOLE] [NOOPTIMIZE]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]

Parameters

FIELDS FieldList
Specifies the fields to display. If you omit FIELDS FieldList, all fields from the table are displayed by default.

Memo field contents aren't displayed unless the memo field name is explicitly included in the field list. The displayed width of memo fields is determined by SET MEMOWIDTH.

Scope
Specifies the range of records to display. Only the records that fall within the range are displayed. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. Commands that include Scope operate only on the table in the active work area.

For more information on scope clauses, see the Scope Clauses online topic.

The default scope for DISPLAY is the current record (NEXT 1).

FOR lExpression1
Specifies that only the records that satisfy the logical condition lExpression1 are displayed. This makes it possible for you to filter out undesired records.

Rushmore Query Optimization optimizes a query created with DISPLAY ... FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are displayed for as long as the logical expression lExpression2 evaluates to true (.T.).
OFF
Suppresses the display of record numbers. If you omit OFF, the record number is displayed before each record.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.
NOOPTIMIZE
Disables Rushmore optimization of DISPLAY.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

TO PRINTER [PROMPT]
Directs output from DISPLAY to a printer.

In Visual FoxPro you can include the optional PROMPT clause to display a dialog box before printing starts. In this dialog box, you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.

Remarks

DISPLAY displays the contents of records and the results of expressions for the current table. If there is more information than can be displayed in the window, the first screen of information is displayed and Visual FoxPro pauses. Press any key or click anywhere to see the next screen of information. DISPLAY is similar to LIST, except that LIST displays the same information in a continuous stream without pausing.

DISPLAY can also be used to display the results of expressions, which can consist of combinations of literals, memory variables, array elements, fields, and memo fields. Field names and expressions are displayed if SET HEADINGS is ON.

Example

The following example opens the customer table in the testdata database. The contents of the first record are displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

CLEAR
DISPLAY FIELD cust_id, company, contact OFF NEXT 10

See Also

LIST | SET HEADINGS | SET MEMOWIDTH


DISPLAY CONNECTIONS Command

Displays information about the named connections in the current database.

DISPLAY CONNECTIONS [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY CONNECTIONS to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY CONNECTIONS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

DISPLAY CONNECTIONS displays the connection names, datasource, and connection string in the current database. Use DBGETPROP( ) to return additional information about connections in the current database.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn is created. DISPLAY CONNECTIONS is used to display the named connections in the database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')

CREATE CONNECTION Myconn DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"
CLEAR
DISPLAY CONNECTIONS     && Displays named connections in the database

See Also

CREATE CONNECTION | DELETE CONNECTION | DBGETPROP( ) | LIST CONNECTIONS | RENAME CONNECTION


DISPLAY DATABASE Command

Displays information about the current database or fields, named connections, tables, or views in the current database.

DISPLAY DATABASE [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY DATABASE to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY DATABASE to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Use DBGETPROP( ) to return additional information about the current database.

Example

The following example creates a database named people. A table named friends is created and is automatically added to the database. DISPLAY TABLES is used to display the tables in the database, and DISPLAY DATABASES is used to display information about the tables in the database.

CREATE DATABASE people
CREATE TABLE friends (FirstName C(20), LastName C(20))
CLEAR
DISPLAY TABLES  && Displays tables in the database
DISPLAY DATABASES  && Displays table information

See Also

LIST DATABASE | DELETE DATABASE Command | DISPLAY FILES Command


DISPLAY DLLS Command

Displays information about shared library functions registered in Visual FoxPro with DECLARE – DLL.

DISPLAY DLLS [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY DLLS to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY DLLS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

See Also

DECLARE – DLL | LIST DLLS | DISPLAY FILES Command


DISPLAY FILES Command

Displays information about files.

DISPLAY FILES [ON Drive] [LIKE FileSkeleton]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]

Parameters

ON Drive
Specifies the drive or volume on which the files reside.
LIKE FileSkeleton
Specifies a condition whereby Visual FoxPro displays information only about files that match the skeleton pattern FileSkeleton. The skeleton pattern can contain wildcards such as ? and *.
TO PRINTER [PROMPT]
Directs output from DISPLAY FILES to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a dialog box before printing starts. In this dialog box, you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY FILES to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.

Remarks

Use DISPLAY FILES to display information about files residing on a disk. You can display information about all files on a specified drive, volume, directory, or folder, or only files that match a skeleton pattern containing wildcards such as ? and *.

Issuing DISPLAY FILES without any arguments displays information about tables in the current directory. The information displayed includes the following:

  • Table name.
  • Number of records in the table.
  • Date and time of the last update to the table.
  • The size of each table in bytes.
  • If each table is part of a database.

Example

The following example displays the names of the databases in the ...\Samples\Data directory.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CLEAR
DISPLAY FILES LIKE *.DBC

See Also

DIR or DIRECTORY | LIST | DISPLAY DATABASE Command


DISPLAY MEMORY Command

Displays the current contents of variables and arrays.

DISPLAY MEMORY [LIKE FileSkeleton]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

LIKE FileSkeleton
Displays information about variables and arrays that match the skeleton pattern FileSkeleton. If you include LIKE FileSkeleton, Microsoft Visual FoxPro displays only the contents of variables and arrays that match FileSkeleton. FileSkeleton supports wildcards such as ? and *. For example, to display all variables that begin with the letter A, issue:
DISPLAY MEMORY LIKE A*
TO PRINTER [PROMPT]
Directs output from DISPLAY MEMORY to a printer.

You can include the optional PROMPT clause to display a dialog box before printing starts. In this dialog box, you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY MEMORY to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

DISPLAY MEMORY shows the name, type, contents, and status of all currently defined variables and variable arrays. It also displays the number of variables defined, the number of bytes used, and the number of additional variables available. Note that the number of bytes used represents memory used by character type variables. Character type variables are the only type of variables that require additional memory beyond that allocated by the variable count specified with the MVCOUNT configuration item.

Information about system variables, menus, menu bars, menu titles, and windows is also displayed.

Example

In the following example, several variables are created and assigned values. DISPLAY MEMORY first displays all variables that begin with "sam" and then displays all variables that contain five letters and end with "exit."

STORE 'Goodbye' TO sample1
STORE 'Hello' TO sample2
STORE .T. TO texit
STORE .F. TO mexit

CLEAR
DISPLAY MEMORY LIKE sam*
DISPLAY MEMORY LIKE ?exit

See Also

DECLARE | DIMENSION | LIST | STORE


DISPLAY OBJECTS Command

Displays information about an object or a group of objects.

DISPLAY OBJECTS [LIKE cObjectSkeleton]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

LIKE cObjectSkeleton
Displays information about a subset of objects. cObjectSkeleton is an object specification skeleton that supports wildcards (* and ?). For example, to display all objects that begin with A, use the following command:
DISPLAY OBJECTS LIKE A*
TO PRINTER [PROMPT]
Directs output from DISPLAY OBJECTS to a printer.

You can include the optional PROMPT clause to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY OBJECTS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

DISPLAY OBJECTS displays the following information about all existing objects:

  • Properties and their values.
  • Methods.
  • Member objects and the class or subclass on which they are based.
  • Class or subclass on which objects are based.
  • Class hierarchy for the objects.

DISPLAY OBJECTS fills the entire main Visual FoxPro window or user-defined window with information and then pauses. Press any key or click anywhere to see the next set of information. DISPLAY is similar to LIST, except that LIST displays the same information in a continuous stream without pausing.

Example

The following example uses DEFINE CLASS and CREATEOBJECT( ) to create two custom classes named FormChild and FormGrandChild from the Visual FoxPro Form base class. DISPLAY OBJECTS displays information about the objects and their properties.

CLEAR
frmMyForm = CREATEOBJECT("FormGrandChild")
DISPLAY OBJECTS LIKE frm*
RELEASE frmMyForm

DEFINE CLASS FormChild AS FORM
ENDDEFINE

DEFINE CLASS FormGrandChild AS FormChild
ENDDEFINE

See Also

LIST OBJECTS | @ ... SAY - Pictures & OLE Objects Command | DISPLAY MEMORY Command


DISPLAY PROCEDURES Command

Displays the names of procedures stored in the current database.

DISPLAY PROCEDURES [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs information returned from DISPLAY PROCEDURES to a printer.

You can include PROMPT to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY PROCEDURES to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Stored procedures are created with APPEND PROCEDURES, COPY PROCEDURES, or MODIFY PROCEDURE.

Example

The following example opens the testdata database, and uses DISPLAY PROCEDURES to display the stored procedures (if any) in the database. If there are no stored procedures in the database, you can run the example for APPEND PROCEDURES to add a procedure to the database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CLEAR
DISPLAY PROCEDURES  && Displays stored procedures in the database

See Also

APPEND PROCEDURES | COPY PROCEDURES | CREATE DATABASE | DISPLAY DATABASE | LIST PROCEDURES | MODIFY PROCEDURE


DISPLAY STATUS Command

Displays the status of the Visual FoxPro environment.

DISPLAY STATUS [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY STATUS to a printer.

You can include the optional PROMPT clause to display a print dialog box before printing starts. In this dialog box, you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY STATUS to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

This form of DISPLAY lists information about the current Visual FoxPro environment. The categories of information and the information in each category are as follows.

Table and index file information:

  • Open tables
  • Open memo files
  • Table aliases
  • Table code pages
  • Table relations
  • Active indexes
  • Index file keys
  • The controlling index file or tag
  • Open structural compound files
  • Open compound index tags
  • The shared attribute status of each open table
  • The currently locked records in each table
  • The EXCLUSIVE use setting
  • The LOCK setting
  • The MULTILOCKS setting
  • The SET REFRESH value
  • The SET REPROCESS value

Open low-level file information:

  • Open low-level files
  • The file handle number for each low-level file
  • The file pointer position for each low-level file
  • Read/write attributes for each low-level file

Additional Visual FoxPro environment information:

  • The procedure file in use
  • The processor type
  • The Visual FoxPro path
  • The Visual FoxPro default directory
  • The print destination
  • The margin setting
  • The current work area
  • SET command settings
  • Binary modules currently loaded
  • DDE information in Visual FoxPro
  • Current code page
  • Current collating sequence
  • Compiler code page
  • Current date format
  • Keyboard macro key combination
  • How UDF parameters are passed
  • Textmerge options
  • External registered shared library functions (DLLs)

See Also

LIST | DISPLAY STRUCTURE Command | DISPLAY PROCEDURES Command


DISPLAY STRUCTURE Command

Displays the structure of a table file.

DISPLAY STRUCTURE [IN nWorkArea | cTableAlias]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

IN nWorkArea | cTableAlias
Displays the structure of the table in a work area other than the current work areas. nWorkArea specifies the work area number and cTableAlias specifies the table alias.
TO PRINTER [PROMPT]
Directs output from DISPLAY STRUCTURE to a printer.

You can include the optional PROMPT clause to display a dialog box before printing starts. In this dialog box, you can adjust printer settings, including the number of copies and page numbers to print. The printer settings that you can adjust depend on the currently installed printer driver. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY STRUCTURE to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Use DISPLAY STRUCTURE to display the field structure of a table. The name of each field in the table is displayed with its type and width. If a field is a Numeric, Double, or Float type field, the number of decimal places in the field is displayed. Null value support for each field is also displayed. The last two columns display the Next and Step values for fields that use autoincrementing.

DISPLAY STRUCTURE also displays the current number of records in the table and the date it was last updated. If the table has an associated memo field, the memo field block size is shown. The total width of all fields is also displayed, as is the table's code page.

The table can have a structural compound index that is opened with the table. If a tag in the structural compound index has the same name as a field in the table, the order of the tag (ascending or descending) and the tag's collation sequence is displayed next to the field name.

If SET FIELDS is used to limit access to fields in the table, an angle bracket (>) appears beside the names of fields that can be accessed.

Example

In the following example, the customer table in the testdata database is opened. DISPLAY STRUCTURE is used to display the table structure.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

CLEAR
DISPLAY STRUCTURE

See Also

LIST | DISPLAY TABLES Command | DISPLAY STATUS Command


DISPLAY TABLES Command

Displays names and information about all the tables contained in the current database.

DISPLAY TABLES [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY TABLES to a printer.

You can include PROMPT to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY TABLES to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

The information returned is a subset of the information shown using DISPLAY STATUS. However, the information displayed using DISPLAY TABLES contains only table-related information and displays the information regardless of whether the tables are open or not.

The following information is displayed:

  • Table name
  • Table path

Example

The following example opens the customer table in the testdata database. DISPLAY TABLES is used to display information about the tables in the database.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'Data\')   && Sets path to database
OPEN DATABASE testdata  && Open testdata database

CLEAR
DISPLAY TABLES  && Displays information about tables in the database

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | LIST TABLES | OPEN DATABASE | REMOVE TABLE


DISPLAY VIEWS Command

Displays information about SQL views in the current database and indicates whether the SQL views are based on local or remote tables.

DISPLAY VIEWS [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]] [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from DISPLAY VIEWS to a printer.

You can include PROMPT to display the Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from DISPLAY VIEWS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Use DBGETPROP( ) to return additional information about SQL views in the current database.

SQL views are created with CREATE SQL VIEW.

Example

The following example opens the testdata database. CREATE SQL VIEW is used to create a local SQL view named myview. The View Designer is displayed, making it possible for you to specify tables and conditions for the SQL view. After you save the SQL view you create, information about the SQL views in the database is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
CREATE SQL VIEW myview

CLEAR
DISPLAY VIEWS

See Also

CREATE DATABASE | CREATE SQL VIEW | DBGETPROP( ) | DISPLAY DATABASE | LIST VIEWS


DO CASE ... ENDCASE Command

Executes the first set of commands whose conditional expression evaluates to true (.T.).

DO CASE
   CASE lExpression1
   [Commands]
   [CASE lExpression2
   [Commands]]
   ...
   [CASE lExpressionN
   [Commands]]
   [OTHERWISE
   [Commands]]
ENDCASE

Parameters

CASE lExpression1 Commands ...
When the first true (.T.) CASE expression is encountered, the set of commands following it is executed. Execution of the set of commands continues until the next CASE or ENDCASE is reached. Execution then resumes with the first command following ENDCASE.

If a CASE expression is false (.F.), the set of commands following it up to the next CASE clause is ignored.

Only one set of commands is executed. These are the first commands whose CASE expression evaluates to true (.T.). Any succeeding true (.T.) CASE expressions are ignored.

OTHERWISE Commands
If all of the CASE expressions evaluate to false (.F.), OTHERWISE determines if an additional set of commands is executed.
  • If you include OTHERWISE, the commands following OTHERWISE are executed and execution skips to the first command following ENDCASE.
  • If you omit OTHERWISE, execution skips to the first command following ENDCASE.

Remarks

DO CASE is used to execute a set of Visual FoxPro commands based on the value of a logical expression. When DO CASE is executed, successive logical expressions are evaluated; the values of the expressions determine which set of commands is executed.

Comments can be placed after DO CASE and ENDCASE on the same line. The comments are ignored during program compilation and execution.

Example

In this example, Visual FoxPro evaluates each CASE clause until the MONTH variable is found in one of the lists. The appropriate string is stored to the variable rpt_title and the DO CASE structure is exited.

STORE CMONTH(DATE( )) TO month  && The month today

DO CASE  && Begins loop

   CASE INLIST(month,'January','February','March')
      STORE 'First Quarter Earnings' TO rpt_title

   CASE INLIST(month,'April','May','June')
      STORE 'Second Quarter Earnings' TO rpt_title

   CASE INLIST(month,'July','August','September')
      STORE 'Third Quarter Earnings' TO rpt_title

   OTHERWISE
      STORE 'Fourth Quarter Earnings' TO rpt_title
ENDCASE  && Ends loop
WAIT WINDOW rpt_title NOWAIT

See Also

DO WHILE ... ENDDO | EXIT | FOR EACH ... ENDFOR | FOR ... ENDFOR | IF ... ENDIF | IIF( ) | SCAN ... ENDSCAN


DO Command

Executes a Visual FoxPro program or procedure. A program file can also contain additional DO commands, making it possible for you to nest DO commands up to 128 levels.

DO ProgramName1 | ProcedureName [IN ProgramName2] [WITH ParameterList]

Parameters

ProgramName1
Specifies the name of the program to execute.

If you do not include an extension with the program you execute, Visual FoxPro looks for and executes these versions of the program in the following order:

  • .exe (executable version)
  • .app (an application)
  • .fxp (compiled version)
  • .prg (program)

To execute a specific menu program, form program, or query using DO, you must include the file extension (.mpr, .spr, or .qpr).

ProcedureName
Specifies the name of the procedure to execute. Visual FoxPro first looks for the procedure in the currently executing program. If the procedure is not located there, Visual FoxPro then looks for the procedure in the procedure files opened with SET PROCEDURE.

You can include the IN ProgramName2 clause to tell Visual FoxPro to look for the procedure in a file you specify.

Multiple procedures within an executable (.exe) version or an application (.app) can have the same name. When you use DO to start a procedure in an executable version or in an application, Visual FoxPro searches only the main program of the executable version or application for the specified procedure.

IN ProgramName2
Executes a procedure in the program file specified with ProgramName2.

When the file is located, the procedure is executed. If the program file cannot be located, the message "File does not exist" appears. If the program file is located but the specified procedure isn't in the program file, the message "Procedure is not found" appears.

WITH ParameterList
Specifies parameters to pass to the program or procedure. The parameters listed in ParameterList can be expressions, memory variables, literals, fields, or user-defined functions. By default, parameters are passed to programs and procedures by reference. You can pass a parameter by value by placing it in parentheses.

See SET UDFPARMS for a discussion of passing parameters by value or reference. The maximum number of parameters you can pass to a program or procedure is 26. For more information on parameter passing, see LPARAMETERS and PARAMETERS.

Remarks

When you use DO to run a program, the commands contained in the program file are executed until one of the following occurs:

  • RETURN is encountered.
  • CANCEL is executed.
  • Another DO is issued.
  • The end of the file is reached.
  • QUIT is executed.

When program execution is complete, control is returned to one of the following:

  • Program that called DO
  • Command window
  • Operating system

If you choose Do from the Program menu and execute a program in a directory on a drive other than the current directory or drive, Visual FoxPro automatically changes the default directory and drive to the directory and drive containing the program.

You can also modify how an application searches for data and resources such as functions, procedures, executable files, and so on using SYS(2450) - Application Search Path Order.

See Also

CLEAR | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PRIVATE | PROCEDURE | PUBLIC | SET DEFAULT | SET DEVELOPMENT | SET PATH | SET PROCEDURE


DO FORM Command

Runs a compiled form or form set created with the Form designer.

DO FORM FormName | ? [NAME VarName [LINKED]] [WITH cParameterList]
   [TO VarName] [NOREAD] [NOSHOW]

Parameters

FormName
Specifies the name of the form or form set to run.
?
Displays the Do dialog box from which you can choose a form or form set to run.
NAME VarName [LINKED]
Specifies a variable or array element with which you can reference the form or form set. If you specify a variable that doesn't exist, Microsoft Visual FoxPro automatically creates it. If you specify an array element, the array must exist before you issue DO FORM. If the variable or array element you specify already exists, its contents are overwritten.

If you omit the NAME clause, Visual FoxPro creates an object type variable with the same name as the form or form set file.

Include LINKED to link the form to the variable associated with it so that the form is released when the variable goes out of scope. If you don't include LINKED, a form can still be active, even though there is no object variable associated with the form.

WITH cParameterList
Specifies the parameters passed to the form or form set.

If a form set is run, the parameters are passed to the form set's Init method if the form set's WindowType property is set to ModeLess (0) or Modal (1). The parameters are passed to the Load method if the form set's WindowType property is set to Read (2) or ReadModal (3).

TO VarName
Specifies a variable to hold a value returned from the form. If the variable doesn't exist, Visual FoxPro automatically creates it. Use the RETURN command in the Unload event procedure of the form to specify the return value. If you do not include a return value, the default value of true (.T.) is returned. If you use TO, the WindowType property of the form must be set to 1 (Modal). If the form Init event procedure returns .F., preventing the form from being instantiated, the Unload event procedure will not return a value to VarName.
NOREAD
Specifies that the form set is created and displayed, even though controls are not activated until READ is issued. NOREAD is ignored if the form set object's WindowType property is not set to 2 (Read).
NOSHOW
Specifies that the form's Show method isn't called when the form is run. When you include NOSHOW and run the form, the form is not visible until the form's Visible property is set to true (.T.) or the form's Show method is called.

Remarks

DO FORM executes the Show method for the form or form set.

The WindowType property settings of Read (2) or ReadModal (3) are included for backward compatibility, and are available only for forms converted from previous versions of FoxPro.

Example

The following example runs the stop watch (Swatch.scx) control sample.

DO FORM (HOME(2) + 'Solution\Controls\Timer\Swatch.scx')

See Also

COMPILE FORM | CREATE FORM | MODIFY FORM


DO WHILE ... ENDDO Command

Executes a set of commands within a conditional loop.

DO WHILE lExpression
   Commands
   [LOOP]
   [EXIT]
ENDDO

Parameters

lExpression
Specifies a logical expression whose value determines whether the commands between DO WHILE and ENDDO are executed. As long as lExpression evaluates to true (.T.), the set of commands are executed.
Commands
Specifies the set of Visual FoxPro commands to be executed as long as lExpression evaluates to true (.T.).
LOOP
Returns program control directly back to DO WHILE. LOOP can be placed anywhere between DO WHILE and ENDDO.
EXIT
Transfers program control from within the DO WHILE loop to the first command following ENDDO. EXIT can be placed anywhere between DO WHILE and ENDDO.

Remarks

Commands between DO WHILE and ENDDO are executed for as long as the logical expression lExpression remains true (.T.). Each DO WHILE statement must have a corresponding ENDDO statement.

Comments can be placed after DO WHILE and ENDDO on the same line. The comments are ignored during program compilation and execution.

Example

In the following example, the number of products in stock priced over $20 is totaled in the DO WHILE loop until the end of the file (EOF) is encountered. The DO WHILE loop is exited and the total is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE products  && Opens Products table
SET TALK OFF
gnStockTot = 0

DO WHILE .T.  && Begins loop
   IF EOF( )
      EXIT
   ENDIF
   IF unit_price < 20
      SKIP
      LOOP
   ENDIF
   gnStockTot = gnStockTot + in_stock
   SKIP
ENDDO     && Ends loop

CLEAR
? 'Total items in stock valued over 20 dollars:'
?? gnStockTot

See Also

DO CASE ... ENDCASE | FOR EACH ... ENDFOR | FOR ... ENDFOR | IF ... ENDIF | IIF( ) | SCAN ... ENDSCAN


DOCK WINDOW Command

Docks an Integrated Development Environment (IDE) tool window or toolbar to the Visual FoxPro desktop window or another IDE window.

Deleting or editing the FoxUser.dbf resource file, which contains your user settings, restores your default window settings.

DOCK WINDOW WindowName POSITION nPosition [ WINDOW WindowName ]

-or-

DOCK WINDOW WindowName WINDOW WindowName

Parameters

WindowName
Specifies the name of the window to dock.
POSITION nPosition
Specifies the docking position of the window. The following table lists the possible values for nPosition. If nPosition is set to 4, the window is tab-docked, for example, it appears as a tabbed window. If nPosition is set between 0 and 3, the window is link-docked, for example, it appears attached to the side of another window.
nPosition | Docking position
-3 | Undock inner container
-2 | Undock outer container
-1 | Undock window
0 | Top
1 | Left
2 | Right
3 | Bottom
4 | Tabbed
WINDOW WindowName
Specifies the name of the target window or toolbar to dock with. If you omit this parameter, the window is docked to the Microsoft Visual FoxPro desktop window.

Remarks

In prior versions of Visual FoxPro, the Data Session window is always referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the DOCK WINDOW command.

The following IDE windows and toolbars are supported by DOCK WINDOW:

  • All system toolbars
  • Call Stack
  • Command
  • Data Session (View)
  • Document View
  • Locals
  • Output
  • Properties
  • Trace
  • Watch

The specified window must first exist on the Visual FoxPro desktop. Otherwise, an error occurs.

If you use DOCK WINDOW...WINDOW without including a POSITION clause, DOCK WINDOW uses a tab-docking position as the default.

DOCK WINDOW always forces the window, if it exists, to become dockable and changes the setting for the Visible property of the window to True (.T.).

Tab and link docking is not supported for debugger windows inside the Debug Frame. You can control the Frame setting in the Options dialog box.

Toolbars do not support linked or tabbed docking. You can dock toolbars only to the desktop. No other window can be docked to a toolbar. Visual FoxPro disregards the WINDOW keyword for toolbars. For more information about linked and tabbed docking, see Docking Windows.

Both system and user-defined toolbars are supported by DOCK WINDOW. You can use the Caption property of the user-defined toolbar as its name.

You can use the WINDOW clause for linked and tabbed docking. You can dock the entire tabbed or linked container to the Visual FoxPro desktop window by calling DOCK WINDOW with any of the windows in the container and omit the WINDOW clause. If you want to dock a single window that is currently bound inside a tabbed or linked container to the main Visual FoxPro window, you must first undock it from the container, for example, by using POSITION -1 or WDOCKABLE(, .F. ).

When you specify a value of -1 for POSITION, you cannot include the WINDOW clause. Otherwise, a syntax error occurs. For example, the following is not permitted:

DOCK WINDOW Command POSITION -1 WINDOW Properties

If you specify a value of 4 for POSITION, you must specify a WINDOW clause. Otherwise, an error occurs.

If you specify an undockable window as the docking target, Visual FoxPro generates "Function argument value, type, or count is invalid (Error 11)". For example:

DOCK WINDOW Command WINDOW Standard   && Generates an error.

If you specify an undockable window as the window to be docked, it becomes dockable internally. For example:

WDOCKABLE("Command", .F.)
DOCK WINDOW Command
? WDOCKABLE("Command")  && Returns .T.

You can dock multiple windows that are docked as a group to another window by specifying one of the docked windows. However, if the docking target exists in the same container as the specified window, only that window is docked. This prevents cyclical relations. For example, the following code redocks the Command window to the right side of the Properties window:

DOCK WINDOW Command POSITION 4 WINDOW Properties
DOCK WINDOW Command POSITION 2 WINDOW Properties

Compare this example to the following code, which docks the Command and View windows to the Properties window as tabbed windows:

DOCK WINDOW Command POSITION 4 WINDOW View
DOCK WINDOW Command POSITION 4 WINDOW Properties

If a container (tab or link set of windows) is docked, you can undock that container if you specify a value of -2 or -3 for any of the windows in the container, according to the following details:

  • If you pass a value of -2, the entire container is undocked if the container is docked to the Visual FoxPro desktop.
  • If you pass a value of -3, only the inner container that is part of an larger outer container is undocked. This applies only to tab-docked containers bound inside link-docked containers. If the window specified is not part of an inner tab-docked container, Visual FoxPro treats the value of -3 as a value of -2 and undocks entire outer container.
  • If the window specified is not part of a container, Visual FoxPro undocks it as if you passed a value of -1.
  • If the window or container is already undocked, Visual FoxPro does nothing.

Example

The following example shows how to use the DOCK WINDOW command to dock the Command window to the Visual FoxPro desktop window and use ADOCKSTATE( ) to obtain the dock state of the Command window. First, make sure the Command window is open. After docking the Command window, you can see that the Standard toolbar and Command windows are docked to the Microsoft Visual FoxPro desktop window. The position of the toolbars or windows in the array returned by ADOCKSTATE( ) can vary depending on the order in which the toolbars or windows are docked.

CLEAR
DOCK WINDOW Command POSITION 0
dockNum = ADOCKSTATE(dockState)
? dockNum   && Returns 2 only if Command window and
            && Standard toolbar exist.
? dockState(1)  && Outputs "Standard".
? dockState(4)  && Outputs "Microsoft Visual FoxPro".
? dockState(5)  && Outputs "COMMAND".
? dockState(8)  && Outputs "Microsoft Visual FoxPro".

See Also

Commands | ADOCKSTATE( ) Function | WDOCKABLE( ) Function | Dock Method | DockPosition Property


DOEVENTS Command

Executes all pending Windows events.

Note You can no longer call DOEVENTS using parentheses (()), for example, DOEVENTS( ).

You can use DOEVENTS for simple tasks such as making it possible for the user to cancel a process after it starts, for example, searching for a file. Long-running processes that yield control of the processor are better performed using a Timer control or delegating the task to an ActiveX executable (.exe) component. In this situation, the task can continue independently of your application, and the operating system takes care of multitasking and time allocation.

Caution Any time you temporarily yield control of the processor in an event procedure, make sure the procedure is not run again from a different part of code before the first call ends. Doing so might cause unpredictable results. In addition, do not use DOEVENTS if other applications might interact with your procedure in unforeseen ways during the time you have yielded control of the processor.
DOEVENTS [FORCE]

Parameters

FORCE
Pauses Visual FoxPro code execution until a Windows event occurs, such as moving the mouse.
Note Using the FORCE keyword can impact performance. Therefore, use caution when calling DOEVENTS FORCE in a tight code loop, such as a DO WHILE loop.

Remarks

When the AutoYield property is set to False (.F.), and program code is executing, Window events are placed in a queue. DOEVENTS executes all pending Windows events and processes any user code associated with the Windows events. If no events are in the queue, Visual FoxPro disregards DOEVENTS and continues program execution.

See Also

AutoYield Property | Events


DROP TABLE Command

Removes a table from the current database and deletes it from disk.

DROP TABLE TableName | FileName | ? [RECYCLE]

Property Values

TableName
Specifies the table to remove from the current database and delete from disk.
FileName
Specifies a free table to delete from disk.
?
Displays the Remove dialog from which you can choose a table to remove from the current database and delete from disk.
RECYCLE
Specifies that the table isn't immediately deleted from disk and is placed in the Microsoft Windows Recycle Bin.

Remarks

When DROP TABLE is issued, all primary indexes, default values, and validation rules associated with the table are also removed. DROP TABLE also affects other tables in the current database if those tables have rules or relations associated with the table being removed. The rules and relations are no longer valid when the table is removed from the database.

Any table deleted with this command cannot be retrieved. Even if SET SAFETY is set to ON, you are not warned before the table is deleted.

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | FREE TABLE | OPEN DATABASE | OPEN DATABASE


DROP VIEW Command

Deletes a SQL view from the current database.

DROP VIEW ViewName

Property Values

ViewName
Specifies the name of the view deleted from the current database.

Remarks

DROP VIEW is identical to DELETE VIEW; DROP VIEW is the ANSI SQL standard syntax for deleting a SQL view.

Use CREATE SQL VIEW to create a SQL view and add the view to the current database. If a SQL view is opened and then deleted, the cursors containing the SQL view results are not closed.

See Also

CREATE SQL VIEW | DELETE VIEW | OPEN DATABASE


EDIT Command

Displays fields for editing.

EDIT [FIELDS FieldList] [Scope] [FOR lExpression1] [WHILE lExpression2]
[FONT cFontName[, nFontSize]] [STYLE cFontStyle] [FREEZE FieldName]
[KEY eExpression1[, eExpression2]] [LAST | NOINIT] [LPARTITION]
[NAME ObjectName] [NOAPPEND] [NOCAPTION] [NODELETE] [NOEDIT | NOMODIFY]
[NOLINK] [NOMENU] [NOOPTIMIZE] [NORMAL] [NOWAIT]
[PARTITION nColumnNumber [LEDIT] [REDIT]]
[PREFERENCE PreferenceName] [REST] [SAVE] [TIMEOUT nSeconds]
[TITLE cTitleText] [VALID [:F] lExpression3 [ERROR cMessageText]]
[WHEN lExpression4] [WIDTH nFieldWidth] [WINDOW WindowName1]
[IN [WINDOW] WindowName2 | IN SCREEN [COLOR SCHEME nSchemeNumber]

Parameters

FIELDS FieldList
Specifies the fields that appear in the Edit window. The fields are displayed in the order specified in FieldList. You can include fields from other related tables in the field list. When you include a field from a related table, preface the field name with its table alias and a period.

If you omit FIELDS, all fields in the table are displayed in the order they appear in the table structure.

The field list can specify any combination of fields or calculated fields, including fields from tables open in other work areas. The syntax of the field list is:

FieldName1
   [:R]
   [:nColumnWidth]
   [:V = lExpression1 [:F] [:E = cMessageText]]
   [:P = cFormatCodes]
   [:B = eLowerBound, eUpperBound [:F]]
   [:H = cHeadingText]
   [:W = lExpression2]
   [, FieldName2 [:R]...]

Calculated Fields

The field list can contain statements for creating calculated fields. A calculated field contains read-only data created with an expression. This expression may take any form but it must be a valid Visual FoxPro expression.

The syntax of the statement you use to create a calculated field is:

CalculatedFieldName = eExpression

This example creates a calculated field called location:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
EDIT FIELDS location = ALLTRIM(city) + ', ' + country

The FIELDS clause field list includes eight options, which enable special handling of fields displayed in the Edit window.

:nColumnWidth
Specifies the display size for a field in columns. The value of :nColumnWidth doesn't affect the size of the field in the table; it alters only the way the field appears in the Edit window.
:R
In the following example, an Edit window is opened with the cust_id and company fields. The cust_id field is read-only and cannot be changed.
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
EDIT FIELDS cust_id:R, company
:V = lExpression1
Specifies a verify option that performs field-level data validation within the Edit window. If lExpression1 evaluates to true (.T.) when you move the cursor from the field, the data input into the field is considered correct and the cursor moves to the next field.

If lExpression1 evaluates to false (.F.), the data input is considered incorrect, the cursor remains in the field and an error or exception is raised. If lExpression1 evaluates to 0, the data input is considered incorrect and the cursor remains in the field, but no error message is displayed.

By default, lExpression1 is evaluated only when the field is modified. To force verification, include the :F option.

You can display your own error message by including the :E option.

The verify option isn't executed for memo fields.

:F
Specifies a forced validation option that determines if the expression in the verify option (lExpression1) is evaluated when you move the cursor from a field or another window is activated. If :F is not included, lExpression1 is evaluated only if changes are made to the field. If :F is included, lExpression1 is evaluated, even if the field isn't modified.
:E = cMessageText
Displays an error message specified with cMessageText instead of the default system message.

If the validation expression :V = lExpression1 evaluates to true (.T.), the cursor leaves the field normally. If the expression evaluates to false (.F.), the cursor remains in the field and the error message appears.

If the validation expression :V = lExpression1 evaluates to 0, no message is displayed and the cursor remains in the field being validated. This lets you display your own error messages in validation routines.

The error message is displayed only if SET NOTIFY is ON. The bell is sounded if SET BELL is ON.

The following example opens the products table and displays the product_id and prod_name fields. Enter a value greater than 100 in the product_id field to perform the field validation.

:V specifies the validation criteria. :F forces the validation check to be performed whether the data is changed or not. :E replaces the Visual FoxPro system error message with a user-defined error message.

In Visual FoxPro, the error message is displayed in the status bar at the bottom of the main Visual FoxPro window.

Press ESC to close the Edit window.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
IF _WINDOWS OR _MAC
   SET STATUS BAR ON
ENDIF
USE products
EDIT FIELDS in_stock :V = in_stock < 100 ;
   :F ;
   :E = 'The stock amount must be less than 100'
:P = cFormatCodes
Specifies a picture option that lets you create an editing template specified with cFormatCodes that controls the display and input of data for each field in an Edit window.

For more information on using picture editing codes, see the Format and InputMask properties.

The following example uses the picture option to allow only numeric data in a specific format to be entered in the unit_price field:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
EDIT FIELDS unit_price :P = '99,999.99'
:B = eLowerBound, eUpperBound [:F]
Specifies a set of boundaries between which data must fall. The boundary expressions eLowerBound and eUpperBound must match the data type of the field and cannot be the names of user-defined functions. If the data entered doesn't fall between eLowerBound and eUpperBound, a system message is displayed indicating the range between which the data must fall.

By default, the data you enter is checked against the boundary values only if you make a change to the contents of the field. To force checking against the boundary values, include the forced validation option (:F).

The following example ensures that the value in the in_stock field is between 1 and 100. Press ESC to close the Edit window.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
EDIT FIELDS in_stock :B = 1, 100 :F
:H = cHeadingText
Specifies a heading option (:H) that allows you to replace the default field names with your own headings, which you specify with cHeadingText. By default, field names are placed to the left side of the fields in the Edit window.

The following example provides user-defined headings for the displayed fields.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Open products table
EDIT FIELDS prod_name :H = 'Product Name:', ;
   unit_price :H = 'Price per Unit:'
:W = lExpression2
Specifies a WHEN option that allows you to conditionally prohibit the cursor from being moved to a field based on the value of the logical expression lExpression. (:W) evaluates lExpression. If lExpression2 evaluates to false (.F.), you can't move the cursor to the field. If lExpression2 evaluates to true (.T.), you can move the cursor to the field. User-defined functions are supported in lExpression2.

Moving the cursor to all fields is prohibited if the current field is marked read-only. This occurs only when every field contains a WHEN clause that evaluates to false.

Scope
Specifies a range of records that are displayed in the Edit window. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. Commands that include Scope operate only on the table in the active work area. The default scope for EDIT is ALL records.

For more information, see the Scope Clauses online topic.

FOR lExpression1
Specifies that only the records that satisfy the logical condition lExpression1 are displayed in the Edit window. Using this argument allows you to filter out undesired records.

Rushmore Query Optimization optimizes an EDIT FOR query if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are displayed in the Edit window for as long as the logical expression lExpression2 evaluates to true (.T.).
FONT cFontName [, nFontSize]
Specifies the Edit window's font and font size. The character expression cFontName specifies the name of the font, and the numeric expression nFontSize specifies the font size. For example, the following clause specifies 16-point Courier font for the fields displayed in an Edit window:
FONT 'Courier',16

If you include the FONT clause but omit the font size nFontSize, a 10-point font is used in the Edit window.

If you omit the FONT clause, 8-point MS Sans Serif is used. If the font you specify is not available, a font with similar font characteristics is substituted.

STYLE cFontStyle
Specifies the Edit window's font style in Visual FoxPro. If you omit the STYLE clause, the Normal font style is used.

If the font style you specify is not available, a font style with similar characteristics is substituted.

Character | Font style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. The following example opens an Edit window and uses an underlined font:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens customer table
IF _WINDOWS
   EDIT FIELDS contact FONT 'System', 15  STYLE 'NU'
ENDIF
IF _MAC
   EDIT FIELDS contact FONT 'Geneva', 14  STYLE 'NU'
ENDIF
FREEZE FieldName
Allows changes to be made to only one field specified with FieldName in the Edit window. The remaining fields are displayed and cannot be edited.
KEY eExpression1 [, eExpression2]
Limits the scope of records that are displayed in the Edit window. With KEY, you can specify an index key value (eExpression1) or a range of key values (eExpression1 , eExpression2) for the records displayed in the Edit window. The table must be indexed, and the index key value or values included in the KEY clause must be the same data type as the index expression of the master index file or master tag.

In the following example, only records with postal codes falling within the range of 10,000 to 30,000 are displayed in the Edit window:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
SET ORDER TO postalcode
EDIT KEY '10000', '30000'
LAST | NOINIT
Saves any configuration changes made to the appearance of an Edit window. The changes are saved in the FoxUser.dbf file and can include changes to the field list, the size of each field, and the location and size of the Edit window. For more information on this file, see SET RESOURCE.

If you issue EDIT with the LAST clause, the Edit window opens in the same configuration that was last saved in the FoxUser.dbf file. This restores the previous Edit window configuration created with the last EDIT. If the last EDIT command issued in the Command window included a long list of clauses, issue EDIT LAST to avoid having to retype the command.

Any Edit window configuration changes you make in the current session aren't saved if you exit EDIT by pressing CTRL+Q.

LPARTITION
Places the cursor in the first field in the left partition of the Edit window. An Edit window can be split into left and right partitions by including the PARTITION clause. By default, the cursor is placed in the first field in the right partition when the Edit window is opened.

The cursor is placed in the right partition of the Edit window if you include LPARTITION without the PARTITION clause.

NAME ObjectName
Creates an object reference for the Edit window, allowing you to manipulate the Edit window with object-oriented properties available for the Grid control.

For additional information about object-oriented programming in Visual FoxPro, see Object-Oriented Programming. For additional information about the Grid control properties that you can specify for an Edit window created with the NAME clause, see the Grid Control topic.

NOAPPEND
Prevents the user from adding records to the table by pressing CTRL+Y or choosing Append Mode from the View menu.
Note Including NOAPPEND doesn't prevent you from appending a record from within a routine (created with VALID, WHEN, or ON KEY LABEL) while in the Edit window.
NOCAPTION
Specifies to always use the field name of a table or view for the column headers, even when the database contains a friendly caption for the table. This clause applies only to tables or views in a database.
NODELETE
Prevents records from being marked for deletion from within an Edit window. By default, a record can be marked for deletion by pressing CTRL+T, choosing Toggle Deletion Mark from the Table menu or clicking in the leftmost column of the record to be deleted.
Note Including NODELETE doesn't prevent you from marking a record for deletion from within a routine (created with VALID, WHEN or ON KEY LABEL) while in the Edit window.
NOEDIT | NOMODIFY
Prevents a user from modifying the table. NOEDIT and NOMODIFY are identical. If you include either clause, you can browse or search the table, but you cannot edit it. However, you can append and delete records.
NOLINK
Unlinks partitions in the Edit window. By default, the left and right partitions of the Edit window are linked; when you scroll through one partition, the other partition scrolls.
NOMENU
Removes the Table menu title in Visual FoxPro from the system menu bar, preventing access to the Edit menu.
NOOPTIMIZE
Disables Rushmore Query Optimization of EDIT.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access .

NORMAL
Opens the Edit window with its normal default settings, such as its colors, size, position, title, and control options (GROW, FLOAT, ZOOM, and so on). If you omit NORMAL and the current output window is a user-defined window with its own settings, the Edit window assumes those user-defined settings as well.
NOWAIT
Continues program execution immediately after the Edit window is opened. The program doesn't wait for the Edit window to be closed but continues executing on the program line immediately following the program line containing EDIT NOWAIT. If you omit NOWAIT, when EDIT is issued from within a program, an Edit window is opened and program execution pauses until the Edit window is closed.

NOWAIT is available only from within a program. Including NOWAIT when issuing EDIT from the Command window has no effect.

PARTITION nColumnNumber
Splits an Edit window into left and right partitions with nColumnNumber specifying the column number of the split bar. For example, if nColumnNumber is 20, the split bar is placed in column 20 of the Edit window.
LEDIT
Specifies that the left partition of the Edit window appears in Browse mode.
REDIT
Specifies that the right partition of the Edit window appears in Browse mode. The following examples opens an Edit window with the split bar placed in column 20 and the right partition open in Browse mode.

Include both keywords to open both partitions in Browse mode.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens customer table

EDIT PARTITION 30 REDIT
PREFERENCE PreferenceName
Saves an Edit window's attributes and options for later use. Unlike LAST, which restores the Edit window as it appeared in the previous session, PREFERENCE saves an Edit window's attributes indefinitely in the FoxUser.dbf resource file. Preferences can be retrieved at any time. For more information about the FoxUser.dbf resource file, see SET RESOURCE.

Issuing EDIT with the specified preference name PreferenceName for the first time creates an entry in the FoxUser.dbf file that saves the Edit window configuration. Issuing EDIT later with the same preference name restores the Edit window to that preference state. When the Edit window is closed, the preference state is updated.

Preference names can be up to 10 characters long, must begin with a letter or an underscore, and can contain any combination of letters, numbers, and underscores.

Once you have a preference the way you like it, you can prevent it from being changed. Close the Edit window, issue SET RESOURCE OFF, open the FoxUser.dbf file as a table, and change the field containing the preference to read-only by changing the value of the logical field READONLY to true (.T.).

For more information about the FoxUser.dbf resource file, see SET RESOURCE.

REST
Prevents the record pointer from being moved from its current position to the top of the table. By default, EDIT positions the record pointer at the top of the table.
SAVE
Keeps the Edit window and any of its memo field text-editing windows active and visible (open). You can then return to the Edit window after cycling through other open windows with the keyboard or the mouse.

SAVE is available only from within a program. SAVE has no effect when included with EDIT in the Command window because EDIT SAVE is always the default in the interactive mode.

TIMEOUT nSeconds
Specifies how long an Edit window waits for input. The numeric expression nSeconds specifies how many seconds can elapse without any input before the Edit window automatically closes.

TIMEOUT is available only from within a program; it has no effect when you issue EDIT from the Command window. In the following example, the Edit window is closed if no input occurs in 10 seconds.

DEFINE WINDOW wEdit FROM 1,1 TO 24,40 ;
   CLOSE ;
   GROW ;
   COLOR SCHEME 10
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
EDIT WINDOW wEdit ;
   FIELDS phone :H = 'Phone Number:' , ;
   company :H = 'Company:' ;
   TIMEOUT 10
RELEASE WINDOW wEdit
TITLE cTitleText
Overrides the default table name or alias that appears in the Edit window title bar with the title you specify with cTitleText. Otherwise, the name or alias of the table being browsed appears in the title bar.

If you issue EDIT WINDOW to place the Edit window in a user-defined window, the Edit window's title replaces the user-defined window's title.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open customer table
EDIT;
   TITLE 'My Edit Window' ;
   FIELDS phone :H = 'Phone Number' , ;
   company :H = 'Company:'
VALID lExpression3
Performs record-level validation in an Edit window. The VALID clause is executed only if a change is made to the record and you move the cursor to another record. The VALID clause is not executed if the only change is to a memo field.

If VALID returns true (.T.), you can move the cursor to another record. If VALID returns false (.F.), the cursor remains in the current field and Visual FoxPro displays an error message. You can display your own error message when VALID returns false by including the ERROR clause. The character expression cMessageText is displayed as the error message. If VALID returns 0, the cursor remains in the current field, and an error message isn't displayed.

The VALID clause shouldn't be confused with the verify option (:V), which enables field-level validation.

:F
Forces the VALID clause to execute before the user moves the cursor to the next record. In this case, VALID is executed even if the record isn't changed.
ERROR cMessageText
Specifies an error message that overrides the system default and whose contents you define with cMessageText. Visual FoxPro displays your error message when VALID returns false (.F.).
WHEN lExpression4
Evaluates a condition when the user moves the cursor to another record. If lExpression4 evaluates to true (.T.), the user can modify the record moved to. If lExpression4 evaluates to false (.F.) or 0, the record the user moves to becomes read-only and cannot be modified.

The WHEN clause isn't executed when another window is activated.

WIDTH nFieldWidth
Limits the number of characters displayed for all fields in a partition of the Edit window to nFieldWidth. Including the WIDTH clause doesn't change the size of fields in the table itself; it alters only the way the fields are displayed in the Edit window. If a width has been specified for an individual field with the FIELDS clause, it overrides the width specified with the WIDTH clause for that field.
WINDOW WindowName1
Specifies a user-defined window whose characteristics the Edit window assumes. For example, if the user-defined window is created with the FLOAT clause, the Edit window can be moved. The specified window doesn't have to be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies the parent window within which the Edit window is opened. The Edit window doesn't assume the characteristics of the parent window. An Edit window activated inside a parent window cannot be moved outside the parent window. If the parent window is moved, the Edit window moves with it.

To access the Edit window, the parent window must first be defined with DEFINE WINDOW and must be active and visible.

IN SCREEN
Explicitly places an Edit window in the main Visual FoxPro window when a user-defined window is active.
COLOR SCHEME nSchemeNumber
Specifies the number of a color scheme used for the Edit window's colors. In Visual FoxPro, the Edit window assumes the color scheme established using the Color Control Panel.

Remarks

EDIT allows you to edit the selected table within a window. EDIT behaves identically to CHANGE.

If you press ESC to exit the Edit window, changes made to the last field you modified are discarded. However, if you move to another record after modifying a field, your changes to the field are saved.

In a program, use DEACTIVATE WINDOW to save your changes and close an Edit window. Include the name of the Edit window in DEACTIVATE WINDOW. For more information on Edit window names, see WTITLE( ).

SET SKIP Support

SET SKIP lets you establish a one-to-many relationship between two tables (see the example). For each record in the parent table, there can be multiple related records in the child table. If you create a one-to-many relationship, you can use EDIT to view records from both the parent and child tables.

The parent record appears once, along with the first matching record from the child table. Any subsequent matching records are displayed in the rows following the parent record and first matching child record. In FoxPro for MS-DOS, shaded blocks are displayed in any column containing information from the parent table beyond the first matching record. In Visual FoxPro, the fill character for repeated parent information depends on the current Edit window font.

For more information, see SET SKIP.

COL( ) and ROW( ) Support

Use COL( ) and ROW( ) to return the current screen row and column position of the cursor in an Edit window. If an Edit window is opened in the main Visual FoxPro window, the returned cursor position is relative to the main Visual FoxPro window, not to the Edit window itself. If an Edit window is opened in a user-defined window, COL( ) and ROW( ) return the cursor position relative to the user-defined window.

Example

The following example uses SET SKIP to create a one-to-many relationship between two tables. There is a single record in the parent table (customer) for each invoice created. The child table (orders) contains multiple records for each record in the parent table.

After the relationship is created, an Edit window displaying records from both the parent and child tables is opened.

CLEAR
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer ORDER cust_id IN 0   && Parent table
USE orders ORDER cust_id IN 0  && Child table
SELECT customer     && Back to parent work area
SET RELATION TO cust_id INTO orders     && Establish relationship
SET SKIP TO orders  && One-to-many relationship
WAIT WINDOW 'Scroll to see shipping dates for each customer' NOWAIT
EDIT FIELDS customer.cust_id :H='Customer Number', ;
   customer.city :H='Customer City', orders.shipped_on

See Also

BROWSE | Grid Control | SET SKIP | WTITLE( ) | COL( ) Function | ROW( ) Function


EJECT Command

Sends a formfeed to the printer.

EJECT

Remarks

EJECT advances the printer to the top of the next page. EJECT sends a formfeed to the printer if the _PADVANCE system memory variable is set to FORMFEED. If _PADVANCE is set to LINEFEEDS, EJECT issues linefeeds to advance to the top of the next page.

EJECT resets PCOL( ) and PROW( ) values to the current column and row position of the printer's print head, but doesn't affect the value of the _PAGENO or _PLINENO system variables.

Example

In the following example, the company and phone fields in the customer table are printed. (Make sure a printer is attached and turned on for this example.) When the number of rows printed is greater than 62, the page is ejected.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens customer table

SET DEVICE TO PRINTER
SET PRINT ON
DO WHILE NOT EOF( )
   @ PROW( )+1,10 SAY 'Company: ' + company
   @ PROW( )+1,10 SAY 'Phone: ' + phone
   @ PROW( )+1,1  SAY ''
   IF PROW( ) > 62
      EJECT
   ENDIF
   SKIP
ENDDO
SET PRINT OFF
SET DEVICE TO SCREEN

See Also

EJECT PAGE | ON PAGE | SET DEVICE | SET PRINTER | PCOL( ) | PROW( ) | System Variables Overview


EJECT PAGE Command

Sends a conditional page advance to the printer.

EJECT PAGE

Remarks

Use EJECT PAGE to advance streaming output. The advance depends on the value of _PADVANCE and if an ON PAGE routine is in effect.

If _PADVANCE is set to FORMFEED and an ON PAGE routine isn't in effect, EJECT PAGE performs the following:

  • Sends a formfeed to the printer if the printer is online.
  • Sends linefeeds, as determined by the system memory variables _PLENGTH and _PLINENO, to the screen or to an alternate file or to both.
  • Increments _PAGENO by 1.
  • Sets _PLINENO to 0.
  • If the system memory variable _PADVANCE is set to LINEFEEDS, and if an ON PAGE routine is in effect and _PLINENO is less than the page line number specified in the ON PAGE routine, EJECT PAGE sends to the printer, to the main Visual FoxPro window, or to an alternate file or to both, as many linefeeds as needed to advance to the top of the next page.

If an ON PAGE routine is not in effect, or if _PADVANCE is set to LINEFEEDS and _PLINENO is greater than the page line number specified with ON PAGE, EJECT PAGE does the following:

  • Sends linefeeds, as determined by the system memory variables _PLENGTH and _PLINENO, to the printer, the main Visual FoxPro window, or to the alternate file or to both.
  • Increments _PAGENO by 1.
  • Sets _PLINENO to 0.

See Also

EJECT | ON PAGE | SET ALTERNATE | SET DEVICE | SET PRINTER | PCOL( ) | PROW( ) | System Variables Overview


END TRANSACTION Command

Ends the current transaction and saves any changes made to tables, table memo files, or index files included in a transaction.

END TRANSACTION

Remarks

Any updates to the database that were made between the previous BEGIN TRANSACTION and the END TRANSACTION are committed. If the transaction is the first or only transaction (that is, the transaction isn't nested), the changes are written to disk.

If a transaction is nested, END TRANSACTION causes all cached updates to be folded into the next higher transaction level. Nesting transactions has the potential to overwrite changes made to data at a higher transaction level.

If END TRANSACTION generates an error (for example, there is insufficient disk space to write changes to disk), changes made during the transaction are cancelled and the transaction ends.

See Also

BEGIN TRANSACTION | ROLLBACK | TXNLEVEL( )


ERASE Command

Erases a file from disk.

ERASE FileName | ? [RECYCLE]

Parameters

FileName
Specifies the file to be erased. Include the path with the file name if the file is on a different drive or directory from the current drive or directory.

FileName can contain wildcard characters such as * and ?. For example, to erase backup files with ERASE *.BAK. If FileName contains spaces, enclose the entire file name in quotes.

?
Displays the Delete dialog box, from which you can choose a file to erase.
RECYCLE
Specifies that the file isn't immediately deleted from disk and is placed in the Windows Recycle Bin.
Caution Exercise caution when using ERASE. Any file erased with this command cannot be retrieved. You aren't warned before the file is erased, even if SET SAFETY is ON.

This command does not generate an error if the specified file does not exist.

Example

In the following example, the structure of CUSTOMER.DBF and all records in which the country is USA are copied to a table named backup. The data in backup is then copied to a text file, temp, which is opened and then deleted when it is closed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens customer table

COPY STRUCTURE TO backup
USE backup
APPEND FROM customer FOR country = 'USA'
COPY TO temp TYPE DELIMITED

WAIT WINDOW 'Press Esc to close and erase temp.txt' NOWAIT
MODIFY FILE temp.txt NOEDIT
ERASE temp.txt
? IIF(FILE('temp.txt'),'File not deleted','File deleted')
USE
ERASE backup.dbf

See Also

DELETE FILE | SET SAFETY Command | APPEND FROM Command


ERROR Command

Generates a Visual FoxPro error.

ERROR nErrorNumber | nErrorNumber, cMessageText1 | [cMessageText2]

Parameters

nErrorNumber
Specifies the number of the error to generate. The standard Visual FoxPro error message is used when an error number is specified.

For a list of Visual FoxPro error messages and their error numbers, see Error Messages A-Z.

cMessageText1
Specifies the text displayed in an error message that supplies additional information about the error. For example, if you reference a memory variable that doesn't exist, Visual FoxPro supplies the name of the memory variable in the error message.
cMessageText2
Specifies the text displayed in the error message. When cMessageText2 is specified instead of nErrorNumber, Visual FoxPro error number 1098 (user-defined error) is generated. Use a carriage return (CHR(13)) in cMessageText2 to move a portion of the error message to the next line.

Remarks

ERROR can be used to test error handling routines or to display custom error messages.

If an ON ERROR error handling routine is in effect when ERROR is issued, Visual FoxPro executes the ON ERROR routine. If an error occurs for an object, the object's Error event is executed.

If you issue ERROR from the Command window and an ON ERROR error handling routine is not in effect, Visual FoxPro displays the error message. If ERROR is issued in a program and an ON ERROR error handling routine is not in effect, Visual FoxPro displays the error message and allows you to cancel or suspend the program or ignore the error.

Note The Error event does not occur if an ON ERROR routine is on the call stack.

Example

The following example generates three error messages. The first error message is the Visual FoxPro error message "Variable not found" (error number 12). The second error message again generates error 12, and includes a variable name of Myvariable. The last error message is a user-defined error message (error number 1089) "My error message."

ERROR 12  && Generates the Visual FoxPro error "Variable not found"
ERROR 12, 'Myvariable'  && Variable 'Myvariable' not found error
ERROR 'My error message'  && Generates 'My error message' error

See Also

ON ERROR | AERROR( ) Function | Debugging and Error Handling | Error Messages A-Z | Error Messages by Number


EXIT Command

Exits a DO WHILE, FOR, or SCAN loop.

EXIT

Remarks

EXIT transfers control from within a DO WHILE ... ENDDO, FOR ... ENDFOR, or SCAN ... ENDSCAN loop to the command immediately following ENDDO, ENDFOR, or ENDSCAN.

Example

In the following example, the number of products in stock priced over 20 dollars is totaled in the DO WHILE loop until the end of the file (EOF) is encountered. The DO WHILE loop is exited and the total is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE products  && Opens Products table
SET TALK OFF
gnStockTot = 0

DO WHILE .T.     && Beginning of loop
   IF EOF( )
      EXIT
   ENDIF
   IF unit_price < 20
      SKIP
      LOOP
   ENDIF
   gnStockTot = gnStockTot + in_stock
   SKIP
ENDDO  && End of loop

CLEAR
? 'Total items in stock valued over 20 dollars:'
?? gnStockTot

See Also

DO WHILE ... ENDDO | FOR EACH ... ENDFOR | FOR ... ENDFOR | SCAN ... ENDSCAN


EXPORT Command

Copies data from a Visual FoxPro table to a file in a different format.

EXPORT TO FileName [TYPE]
   DIF | MOD | SYLK | WK1 | WKS | WR1 | WRK | XLS | XL5
   [FIELDS FieldList] [Scope] [FOR lExpression1] [WHILE lExpression2]
   [NOOPTIMIZE] [AS nCodePage]

Parameters

FileName
Specifies the name of the file to which Visual FoxPro exports data. If you do not include an extension with the file name, the default extension for the specified file type is assigned.
TYPE
Specifies the type of file to be created. The TYPE keyword is optional, but you must specify one of the following file types.
File type | Description
DIF | Each field from a Visual FoxPro table becomes a vector (column) and each record becomes a tuple (row) in a DIF (Data Interchange Format) file, used by VisiCalc. The new file name is assigned a .DIF extension if an extension isn't included in FileName.
MOD | Use the MOD clause to export to a file in Microsoft Multiplan version 4.01 MOD format. The new file name is assigned a .MOD extension if you don't include an extension in FileName.
SYLK | A Symbolic Link interchange format (used by Microsoft Multiplan) in which each field from a Visual FoxPro table becomes a column in the spreadsheet and each record becomes a row. By default, SYLK file names have no extension.
WK1 | Include this option to create a Lotus 1-2-3 spreadsheet from a Visual FoxPro table. A .WK1 extension is assigned to the spreadsheet file name for use with Lotus 1-2-3 revision 2.x. Each field from the table becomes a column in the new spreadsheet, and each record in the table becomes a spreadsheet row.
WKS | Include this option to create a Lotus 1-2-3 spreadsheet from a Visual FoxPro table. A .WKS extension is assigned to the spreadsheet file name for use with Lotus 1-2-3 revision 1-A. Each field from the table becomes a column in the new spreadsheet, and each record becomes a row in the spreadsheet.
WR1 | Include this option to create a Lotus Symphony spreadsheet from a Visual FoxPro table. A .WR1 extension is assigned to the spreadsheet for use with Symphony version 1.01. Each field from the table becomes a column in the new spreadsheet, and each record in the table becomes a row in the spreadsheet.
WRK | Include this option to create a Lotus Symphony spreadsheet from a Visual FoxPro table. A .WRK extension is assigned to the spreadsheet file name for use with Symphony version 1.10. Each field from the table becomes a column in the new spreadsheet, and each record in the table becomes a row in the spreadsheet.
XLS | Include this option to create a Microsoft Excel worksheet from a Visual FoxPro table. Each field in the selected table becomes a column in the worksheet, and each table record becomes a row. An .xls file name extension is assigned to the newly created worksheet file unless you specify a different extension. You can export a maximum of 65,535 rows, which includes one row reserved for the field header.
XL5 | Include this option to create a Microsoft Excel version 5.0 worksheet file from a Visual FoxPro table. Each field from the currently selected table becomes a column in the spreadsheet and each record becomes a row. An .xls extension is assigned to the new worksheet if you do not include a file extension. You can export a maximum of 65,535 rows, which includes one row reserved for the field header.
FIELDS FieldList
Specifies which fields are copied to the new file. If you omit the FIELDS clause, all fields are copied to the new file. Memo and general fields are not copied to the new file even if their names are included in the field list.
Scope
Specifies a range of records to copy to the new file. Scope Specifies a range of records to copy to the new file. Only the records that fall within the range are copied to the new file. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

For more information on scope clauses, see the Scope Clauses online topic. Commands that include Scope operate only on the table in the active work area.

The default scope for EXPORT is all records.

FOR lExpression1
Specifies that only records that satisfy the logical condition lExpression1 are copied to the new file. Using this argument makes it possible for you to filter out undesired records.

Rushmore Query Optimization optimizes an EXPORT ... FOR lExpression1 command if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are copied to the new file for as long as the logical expression lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Disables Rushmore Query Optimization of EXPORT.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

AS nCodePage
Specifies the code page for the file EXPORT creates. Visual FoxPro copies the contents of the currently selected table, and, as it copies the data, automatically converts the data to the code page you specify for the new file. If possible, Visual FoxPro marks the newly created file with the code page you specify.

If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, making it possible for you to specify a code page for the file Visual FoxPro creates.

If you omit AS nCodePage, no code page conversion occurs. If possible, Visual FoxPro marks the newly created file with the code page of the table from which the data is copied.

If nCodePage is 0, no code page conversion occurs and the newly created file is not marked with a code page.

Remarks

Use EXPORT to use Visual FoxPro data in other software packages.

If the table you are exporting from is indexed, the new file is created in the indexed order.

See Also

APPEND FROM | COPY TO | GETCP( ) | IMPORT | SET OPTIMIZE | Using Rushmore Query Optimization to Speed Data Access


EXTERNAL Command

Alerts the Project Manager to an undefined reference.

EXTERNAL FILE FileList | ARRAY ArrayList
   | CLASS | FORM | LABEL | LIBRARY | MENU
   | PROCEDURE | QUERY | REPORT | SCREEN | TABLE

Parameters

FILE FileList
Specifies that the file you include in an indirect file reference or macro substitution is a stand-alone file, such as a text file, .BMP bitmap file, and so on. FileList may contain a list of file names separated by commas.
ARRAY ArrayList
When an array is created in a program and then used in a lower-level program, include ARRAY with the array name in the lower-level program. ArrayList may contain a list of array names separated by commas.

In the following example, the first program creates an array named gaInvoice. The array is initialized and a lower-level program named dispinvo is called. dispinvo displays the contents of the array created in the higher-level program. The command EXTERNAL ARRAY GAINVOICE is included to alert the Project Manager.

DIMENSION gaInvoice(4)
STORE 'Paid' TO gaInvoice
DO dispinvo
*** Program dispinvo ***
PROCEDURE dispinvo
EXTERNAL ARRAY gaInvoice
? gaInvoice(1)
? gaInvoice(2)
? gaInvoice(3)
? gaInvoice(4)
RETURN
*** End of dispinvo program ***

When an array is passed to a user-defined function or procedure, the corresponding array in the user-defined function or procedure must be identified to the Project Manager. Include the ARRAY option with the name of the array included in the PARAMETER statement.

DIMENSION gaArrayOne(2)      && Create an array
EXTERNAL ARRAY gaArrayTwo   && Name of the array used in the UDF
SET TALK OFF
STORE 10 TO gaArrayOne(1)
STORE  2 TO gaArrayOne(2)
= ADDTWO(@gaArrayOne)      && Pass the array by reference to a UDF
FUNCTION ADDTWO
PARAMETER gaArrayTwo
CLEAR
gaArrayTwo(1) = gaArrayTwo(1) + 2
gaArrayTwo(2) = gaArrayTwo(2) + 2
? gaArrayTwo(1)
? gaArrayTwo(2)
CLASS
Specifies that the file you include in an indirect file reference or macro substitution is a visual class library.
EXTERNAL CLASS myvclass  && CLASS myvclass must exist
STORE 'myvclass' TO gcClassFile
MODIFY CLASS (gcClassFile)
FORM
If a Form definition file is included in an indirect file reference or macro substitution, include FORM and the Form file name. FORM is identical to SCREEN.
EXTERNAL FORM dataentr  && FORM dataentr must exist
STORE 'dataentr' TO gcFormFile
DO FORM (gcFormFile)
LABEL
Specifies that the file you include in an indirect file reference or macro substitution is a label definition file.
EXTERNAL LABEL Maillabl     && LABEL FORM Maillabl must exist
STORE 'Maillabl' TO gcLabelFile
LABEL FORM (gcLabelFile) PREVIEW
LIBRARY
Include LIBRARY when a library file is referenced by indirect file referencing or macro substitution in SET LIBRARY.
EXTERNAL LIBRARY regress  && LIBRARY regress must exist
STORE 'regress' TO gcStatFunc
SET LIBRARY TO (gcStatFunc)
MENU
If a menu definition file is included in an indirect file reference or macro substitution, include MENU and the menu file name.
EXTERNAL MENU pickfile  && MENU pickfile must exist
STORE 'pickfile' TO gcSysMenPad
MODIFY MENU (gcSysMenPad)
PROCEDURE
Identifies an external procedure or user-defined function.
EXTERNAL PROCEDURE delblank     && PROCEDURE delblank must exist
STORE 'delblank' TO gcTrimBlanks
DO (gcTrimBlanks) WITH 'A B C D E'
QUERY
Specifies that the file you include in an indirect file reference or macro substitution is a query file.
EXTERNAL QUERY sales  && QUERY sales must exist
STORE 'sales.qpr' TO gcSalesFile
DO (gcSalesFile)
REPORT
Specifies that the file you include in an indirect file reference or macro substitution is a report definition file.
EXTERNAL REPORT overdue     && REPORT overdue must exist
STORE 'overdue' TO gcReportFile
REPORT FORM (gcReportFile) PREVIEW
SCREEN
If a form definition file is included in an indirect file reference or macro substitution, include SCREEN and the screen file name. SCREEN is identical to FORM.
EXTERNAL SCREEN dataentr  && SCREEN dataentr must exist
STORE 'dataentr' TO gcScreenFile
MODIFY SCREEN (gcScreenFile)
TABLE
Specifies that the file you include in an indirect file reference or macro substitution is a Visual FoxPro table.
EXTERNAL TABLE customer && Table customer must exist
STORE 'customer' TO gcMyTable
USE (gcMyTable)

Remarks

Use EXTERNAL to include files and to resolve undefined references in a project created by the Project Manager. EXTERNAL is used only by the Project Manager and is ignored during program execution.

For more information on creating projects with the Project Manager, see Compiling an Application.

Files whose names you specify with EXTERNAL are included in a project by the Project Manager. You must include CLASS, FILE, FORM, LABEL, LIBRARY, MENU, PROCEDURE, QUERY, REPORT, SCREEN, or TABLE before the file name or a set of file names separated with commas to tell the Project Manager the type of files to include in the project.

The Project Manager must also be alerted to file names contained in a name expression or macro substitution. This ensures that all necessary files are included in a project when the project is built. It must also be alerted to arrays that are created in another procedure or user-defined function.

For more information on name expressions and macro substitution, see the & command. Whenever possible, use a name expression instead of macro substitution to improve performance.

See Also

BUILD APP | BUILD PROJECT | Compiling an Application | & | Project Manager


FLUSH Command

Saves table and index modifications to disk.

FLUSH

Remarks

FLUSH ensures that modifications you make to all open tables and indexes are saved to disk.

Visual FoxPro automatically saves changes to disk when:

  • You close a table with USE, CLOSE ALL, or CLOSE DATABASES. Only information for the file or files you close is flushed to disk.
  • You unlock a record or file. Only information for the record or file unlocked is flushed to disk.

See Also

CLOSE DATABASES | FFLUSH( ) | SET AUTOSAVE


FOR EACH … ENDFOR Command

Visual FoxPro Language Reference

FOR EACH ... ENDFOR Command

Executes a set of commands for each element in a Visual FoxPro array or collection.

FOR EACH Var IN Group
   Commands
   [EXIT]
   [LOOP]
ENDFOR | NEXT [Var]

Property Values

Var
A variable or array element used to iterate through the elements of Group.
Group
A Visual FoxPro array, an OLE array, a Visual FoxPro collection, or an OLE collection.
Commands
Specifies the Visual FoxPro commands to be executed for each element in Group. Commands can include any number of commands.
EXIT
Transfers control from within the FOR EACH ... ENDFOR loop to the command immediately following ENDFOR. You can place EXIT anywhere between FOR EACH and ENDFOR.
LOOP
Returns control directly back to the FOR EACH clause without executing the statements between LOOP and ENDFOR. LOOP can be placed anywhere between FOR EACH and ENDFOR.

Examples

The following examples demonstrate how FOR EACH is used to enumerate elements in a Visual FoxPro array, an OLE array, and a set command buttons assigned to an object array.

In the following example, a Visual FoxPro variable array is created and FOR EACH is used to display the contents of each element in the array.

DIMENSION cMyArray(3)
cMyArray[1] = 'A'
cMyArray[2] = 'B'
cMyArray[3] = 'C'

FOR EACH cMyVar IN cMyArray
   ? cMyVar
ENDFOR

In the following example, an instance of Microsoft Excel is created, and a new workbook is added. FOR EACH is used to display the name of each worksheet in the workbook. This example requires that Microsoft Excel be properly installed on the machine on which the example is run.

oExcel = CREATE("Excel.Application")
oExcel.Workbooks.ADD

FOR EACH oMyVar IN oExcel.sheets
   ? oMyVar.name
NEXT oMyVar

In the following example, five command buttons are placed on a form. FOR EACH is used to display the buttons on the form and specify the captions, font styles and positions of each button.

PUBLIC oMyObject
oMyObject = CREATEOBJECT("frmTest")
oMyObject.SHOW

DEFINE CLASS frmTest AS FORM
Height = 200
DIMENSION MyArray[5]
   PROCEDURE Init

      FOR i = 1 to 5
         THIS.AddObject('THIS.MyArray[i]',;
            'COMMANDBUTTON')
      ENDFOR

      ****** FOR EACH - NEXT ******
      FOR EACH oButton IN THIS.MyArray
         oButton.Visible = .T.
      NEXT

      ****** FOR EACH - NEXT element  ******
      FOR EACH oButton IN THIS.MyArray
         oButton.FontBold = .T.
      NEXT obutton

      j = 1
      ****** FOR EACH - ENDFOR ******
      FOR EACH oButton IN THIS.MyArray
         oButton.top = j * 30
         j = j + 1
      ENDFOR

      ****** FOR EACH - ENDFOR element ******
      FOR EACH oButton IN THIS.MyArray
         oButton.FontItalic = .T.
      ENDFOR obutton

      j = 1
      ****** EXIT  ******
      FOR EACH oButton IN THIS.MyArray
         oButton.Caption = "test" + str(j)
         j = j+1
         IF j > 3
            EXIT
         ENDIF
      NEXT

      j = 1
      ****** LOOP  ******
      FOR EACH oButton IN THIS.MyArray
         IF j > 3
            LOOP
         ENDIF
         j = j + 1
         oButton.Left = 25
      NEXT
   ENDPROC
ENDDEFINE

See Also

FOR ... ENDFOR | DO CASE ... ENDCASE | DO WHILE ... ENDDO | IF ... ENDIF | SCAN ... ENDSCAN EXIT | LOOP


FOR ... ENDFOR Command

Executes a set of commands a specified number of times.

FOR Var = nInitialValue TO nFinalValue [STEP nIncrement]
   Commands
   [EXIT]
   [LOOP]
ENDFOR | NEXT

Parameters

Var
Specifies a variable or an array element that acts as the counter. The variable or array element doesn't have to exist before FOR ... ENDFOR is executed.
nInitialValue TO nFinalValue
nInitialValue is the initial value of the counter; nFinalValue is the final value of the counter.
STEP nIncrement
nIncrement is the amount the counter is incremented or decremented. If nIncrement is negative, the counter is decremented. If you omit STEP, the counter is incremented by 1.
Commands
Specifies the Visual FoxPro commands to be executed. Commands can include any number of commands.
EXIT
Transfers control from within the FOR ... ENDFOR loop to the command immediately following ENDFOR. You can place EXIT anywhere between FOR and ENDFOR.
LOOP
Returns control directly back to the FOR clause without executing the statements between LOOP and ENDFOR. The counter is incremented or decremented as if ENDFOR were reached. LOOP can be placed anywhere between FOR and ENDFOR.

Remarks

A variable or an array element is used as a counter to specify how many times the Visual FoxPro commands inside the FOR ... ENDFOR loop are executed.

The Visual FoxPro commands after FOR are executed until ENDFOR or NEXT is reached. The counter MemVarName is then incremented by the value of nIncrement. If you omit the STEP clause, the counter is incremented by 1. The counter is then compared with nFinalValue. If the counter is less than or equal to nFinalValue, the commands following the FOR clause are executed again. If the counter is greater than nFinalValue, the FOR ... ENDFOR loop is exited and program execution continues with the first command following ENDFOR or NEXT.

Note The values of nInitialValue, nFinalValue, and nIncrement are only read initially. However, changing the value of the counter MemVarName inside the loop affects the number of times the loop is executed.

If the value of nIncrement is negative and the initial value nInitialValue is greater than the final value nFinalValue, the counter is decremented each time through the loop.

Example

In Example 1, the numbers 1 through 10 are displayed.

Example 2 uses memory variables for the initial, final, and STEP values to display all even-numbered records from 2 through 10 in customer.

* Example 1
CLEAR
FOR gnCount = 1 TO 10
   ? gnCount
ENDFOR

* Example 2
SET TALK OFF
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
STORE 2 TO gnI  && Initial value
STORE 10 TO gnJ  && Final value
STORE 2 TO K  && Step value
FOR gnCount = gnI TO gnJ STEP K
   GOTO gnCount  && Move record pointer
   DISPLAY company && Display company name
ENDFOR

See Also

DO CASE ... ENDCASE | DO WHILE ... ENDDO | FOR EACH ... ENDFOR | IF ... ENDIF | SCAN ... ENDSCAN | EXIT | LOOP


FREE TABLE Command

Removes a database reference from a table.

FREE TABLE TableName

Parameters

TableName
Specifies the name of the table from which the database reference is removed.

Remarks

If a database is accidentally deleted from disk, references to the database remain in the tables formerly contained in the database. FREE TABLE removes the database references from a table, making it possible for you to open the table or add the table to a different database.

Caution FREE TABLE should never be issued to remove a table from a database if the database exists on disk. If the database exists on disk, FREE TABLE may render the database unusable. Use REMOVE TABLE instead. Unlike FREE TABLE, REMOVE TABLE removes all references from the database to primary indexes, default values, and validation rules associated with the table.

See Also

ADD TABLE | CREATE DATABASE | OPEN DATABASE | REMOVE TABLE


FUNCTION Command

Identifies the start of a definition for a user-defined function.

FUNCTION FunctionName
   [ LPARAMETERS parameter1 [ ,parameter2 },... ]
   Commands
   [ RETURN [ eExpression ] ]
ENDFUNC

Or

FUNCTION FunctionName( [ parameter1 [ AS para1type ][ ,parameter2 [ AS para2type ] ],...] ) [ AS returntype ]
   Commands
   [ RETURN [ eExpression ] ]
ENDFUNC

Parameters

FUNCTION
Indicates the beginning of the FUNCTION structure.
FunctionName
Specifies the name of the user defined function. In Visual FoxPro, function names can be up to 254 characters long.
LPARAMETERS parameter1 [ ,parameter2 },...]
Assigns data passed from the calling program to local variables or arrays.
( [ parameter1 [ AS para1type ][ ,parameter2 [ AS para2type ] ],...] )
Assigns data passed from the calling program to local variables or arrays. The optional clause AS para1type specifies the data type of the variable.
AS returntype
Specifies the data type that the returned value is based on.
Commands
Specifies the Visual FoxPro commands that are executed when the function is executed.
RETURN [ eExpression ]
Returns control to the calling program or to another program. The optional parameter eExpression can be used to specify a value to return.
ENDFUNC
Indicates the end of the FUNCTION structure.

Remarks

In many programs, certain routines are frequently repeated. Defining commonly used routines as separate functions reduces program size and complexity and facilitates program maintenance.

FUNCTION FunctionName is a statement within a program. It designates the beginning of a function in a program and identifies the function by name.

FUNCTION FunctionName is followed by a series of Visual FoxPro commands that make up the function. You can include RETURN anywhere in the function to return control to the calling program or to another program, and to define a value returned by the user-defined function. If you do not include a RETURN command, an implicit RETURN is automatically executed when the function quits. If the RETURN command does not include a return value (or if an implicit RETURN is executed), Visual FoxPro assigns .T. (True) as the return value.

The function ends with the ENDFUNC command. This command is optional; the function quits when it encounters another FUNCTION command, a PROCEDURE command, or the end of the program file.

Comments can be placed on the same line after FUNCTION and ENDFUNC. These comments are ignored during compilation and program execution.

You cannot have normal executable program code included in a program file after user-defined functions; only user-defined functions, procedures, and class definitions can follow the first FUNCTION or PROCEDURE command in the file.

When you issue DO with a function name, Visual FoxPro searches for the function in a specific order as follows:

  1. Visual FoxPro searches the file containing the DO command.
  2. If the function isn't found there, Visual FoxPro searches the open procedure files. Procedure files are opened with SET PROCEDURE.
  3. If the function isn't found in an open procedure file, Visual FoxPro searches the programs in the execution chain. Program files are searched from the most recently executed program through the first program executed.
  4. If the function is still not found, Visual FoxPro searches for a stand-alone program. If a matching program file is found, the program is executed. Otherwise, Visual FoxPro generates an error message.

Include the IN clause in DO to execute a function in a specific file.

By default, parameters are passed to functions by value. For information on passing parameters to functions by reference, see SET UDFPARMS. A maximum of 26 parameters can be passed to a function. Parameters can be passed to a function by including a PARAMETERS or LPARAMETERS statement in the function, or by placing a list of parameters immediately after FUNCTION FunctionName. Enclose the list of parameters in a set of parentheses, and separate the parameters with commas.

For information about use of the FUNCTION command in creating classes, See DEFINE CLASS and Strong Typing in Class, Objects, and Variable code in Help.

Example

This example creates a custom object class called Hello and adds a function method called SayHello. The SayHello method returns the character string "Hello World", which is displayed by the MESSAGEBOX function. Note: The class definition code is placed after the program code that instantiates the object.

Local oHello
oHello=CREATEOBJECT("Hello")
=MESSAGEBOX(oHello.SayHello(),48)
RELEASE oHello

* Class definition code
DEFINE CLASS Hello AS CUSTOM
 FUNCTION SayHello
  RETURN "Hello World"
 ENDFUNC
ENDDEFINE

See Also

LPARAMETERS | PARAMETERS | PARAMETERS( ) | PRIVATE | PROCEDURE | PUBLIC | RETURN | SET PROCEDURE | SET UDFPARMS


GATHER Command

Replaces the data in the current record of the currently selected table with data from an array, a set of variables, or an object.

GATHER FROM ArrayName | MEMVAR | NAME ObjectName
   [FIELDS FieldList | FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton]
   [MEMO]

Parameters

FROM ArrayName
Specifies the array whose data replaces the data in the current record. The contents of the elements of the array, starting with the first element, replace the contents of the corresponding fields of the record. The contents of the first array element replace the first field of the record; the contents of the second array element replace the second field, and so on.

If the array has fewer elements than the table has fields, the additional fields are ignored. If the array has more elements than the table has fields, the additional array elements are ignored.

MEMVAR
Specifies the variables or array from which data is copied to the current record. Data is transferred from the variable to the field that has the same name as the variable. The contents of a field are not replaced if a variable doesn't exist with the same name as the field.
Tip You can create variables with the same names as fields by including MEMVAR or BLANK in SCATTER.
NAME ObjectName
Specifies an object whose properties have the same names as fields in the table. The contents of each field are replaced by the value of the property with the same names as the fields. The contents of a field are not replaced if a property doesn't exist with the same name as the field.
FIELDS FieldList
Specifies the fields whose contents are replaced by the contents of the array elements or variables. Only the field specified with FieldList has its contents replaced.
FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton
You can selectively replace fields with the contents of array elements or variables by including the LIKE or EXCEPT clause or both. If you include LIKE Skeleton, Visual FoxPro replaces the fields that match Skeleton. If you include EXCEPT Skeleton, Visual FoxPro replaces all fields except those that match Skeleton.

Skeleton supports wildcards (* and ?). For example, to replace all fields that begin with the letters A and P, use:

GATHER FROM gamyarray FIELDS LIKE A*,P*
MEMO
Specifies that the contents of memo fields are replaced with the contents or array elements or variables. If you omit MEMO, memo fields are skipped when GATHER replaces the contents of fields with the contents of an array or variable. General and picture fields are always ignored in GATHER, even if you include the MEMO keyword.

Example

This example uses GATHER to copy data to a new record in a table. After the table Test is created, SCATTER is used to create a set of variables based on the fields in the table. Each field is then assigned a value and a new blank record is added to the table.

CREATE TABLE Test FREE ;
   (Object C(10), Color C(16), SqFt n(6,2))
SCATTER MEMVAR BLANK
m.Object="Box"
m.Color="Red"
m.SqFt=12.5
APPEND BLANK
GATHER MEMVAR
BROWSE

The following example uses GATHER along with the NAME clause to copy data to a new record in a table. After the table Test is created, SCATTER is used to create an object with properties based on the fields in the table. The object's properties are then assigned values and a new blank record is added to the table.

CREATE TABLE Test FREE ;
   (Object C(10), Color C(16), SqFt n(6,2))

SCATTER NAME oTest BLANK
oTest.Object="Box"
oTest.Color="Red"
oTest.SqFt=12.5
APPEND BLANK
GATHER NAME oTest
RELEASE oTest
BROWSE

See Also

APPEND FROM ARRAY | COPY TO ARRAY | DIMENSION | SCATTER


GETEXPR Command

Displays the Expression Builder dialog box so you can create an expression and store the expression to a variable or array element.

GETEXPR [cCaptionText] TO MemVarName
   [TYPE cExpressionType [; cErrorMessageText]]
   [DEFAULT cDefaultExpression]

Parameters

cCaptionText
Specifies the caption that appears in the Expression Builder. The caption can be used to remind the user of what kind of expression to build.
TO MemVarName
Specifies the variable or array element in which the expression is stored. If the variable doesn't already exist, Visual FoxPro creates it. GETEXPR won't create an array element.

If you exit the Expression Builder by pressing ESC or by choosing Cancel, the empty string is stored to the variable or array element. If a default expression is created with the DEFAULT clause, the default expression is stored to the variable if you exit the Expression Builder by pressing ESC or choosing Cancel.

TYPE cExpressionType [; cErrorMessageText]
Specifies the expression type. The following table lists the character to specify in cExpressionType for each expression type:
cExpressionType | Expression type
C | Character
D | Date
T | DateTime
N | Numeric
F | Float
I | Integer
B | Double
Y | Currency
L | Logical

You can specify the error message cErrorMessageText to be displayed if the expression isn't valid. If cErrorMessageText is included with cExpressionType, cExpressionType and cErrorMessageText must be separated by a semicolon (;). The combination of cExpressionType, the semicolon, and cErrorMessageText must be enclosed in single or double quotes in matching pairs.

DEFAULT cDefaultExpression
Makes it possible for you to display the initial default expression in the Expression Builder. You can accept the default expression or overwrite it with your own expression specified with cDefaultExpression. cDefaultExpression is stored to the variable or array element if you exit the Expression Builder by pressing ESC or choosing Cancel.

Example

In the following example, GETEXPR is used to get a LOCATE expression of the proper type. If LOCATE is successful, the company name is displayed; otherwise, a message is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

GETEXPR 'Enter condition to locate ' TO gcTemp;
   TYPE 'L' DEFAULT 'COMPANY = ""'
LOCATE FOR &gcTemp
IF FOUND( )
   DISPLAY
ELSE
   ? 'Condition ' + gcTemp + ' was not found '
ENDIF

See Also

_GETEXPR | GETFILE( ) | GETPICT( ) | LOCFILE( ) | PUTFILE( )


GO | GOTO Command

Moves the record pointer to the specified record number.

GO [RECORD] nRecordNumber [IN nWorkArea | IN cTableAlias]

-or-

GO TOP | BOTTOM [IN nWorkArea | IN cTableAlias]

-or-

GOTO [RECORD] nRecordNumber [IN nWorkArea | IN cTableAlias]

-or-

GOTO TOP | BOTTOM [IN nWorkArea | IN cTableAlias]

Parameters

RECORD nRecordNumber
Specifies the physical record number to move the record pointer to. You can omit GO or GOTO entirely and specify just the record number. If you specify just the record number, you can move the record pointer only within the current work area.
IN nWorkArea
Specifies the work area of the table in which the record pointer is moved.
IN cTableAlias
Specifies the alias of the table in which the record pointer is moved.
TOP
Positions the record pointer on the first record in the table. If the table has an ascending index in use, the first record is the record with the lowest key value. If the index is in descending order, the first record is the record with the highest key value.
BOTTOM
Positions the record pointer on the last record in the table. If the table has an ascending index in use, the last record is the record with the highest key value. If the index is in descending order, the last record is the record with the lowest key value.

Remarks

GO and GOTO can be used interchangeably. These commands operate on the table in the current work area unless you specify another work area with the IN clause.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Opens Products table
USE customer IN 0  && Opens Customer table
GO BOTTOM IN products
CLEAR
? RECNO('products')
GO TOP
? RECNO( )     && Displays 1
GO 5
? RECNO( )     && Displays 5

See Also

RECNO( ) | SELECT | SKIP


HELP Command

Opens the Help window.

HELP   [Topic | ID nContextID] [IN [WINDOW] WindowName | IN [WINDOW]
   SCREEN | IN [WINDOW] [NOWAIT]

Parameters

Topic
Specifies the Help topic to display. If you include just a partial spelling of a topic title, Visual FoxPro opens the Help window and displays the topic with the closest matching title.
ID nContextID
Specifies the Help topic to display, based on the topic's context ID.

When you are using graphical style Help, nContextID is a context number in the MAP section of the help project file.

IN [WINDOW] WindowName
Opens the Help window within a parent window. The Help window doesn't assume the characteristics of the parent window it is placed in. If the Help window is activated inside a parent window, it cannot be moved outside the parent window. If the parent window is moved, the Help window moves with it. Before you can open the Help window from within a parent window, the parent window must first be defined with DEFINE WINDOW.
IN [WINDOW] SCREEN
Explicitly places the Help window on the main Visual FoxPro window.
NOWAIT
In graphical style Help, the NOWAIT argument has no effect, and program execution always continues after the HELP command has been issued.

Remarks

For more information on creating your own Help system, see Creating Help.

See Also

SET HELP | SET TOPIC


HIDE MENU Command

Hides one or more active user-defined menu bars.

HIDE MENU MenuBarName1 [, MenuBarName2 ...] | ALL [SAVE]

Parameters

MenuBarName1 [, MenuBarName2 ...]
Specifies the name of the menu bar or a list of menu bars (separated by commas) to hide.
ALL
Hides all defined menu bars.
SAVE
Places an image of a menu bar on the screen or in a window. Placing an image of a menu bar on the screen is useful during program development and testing. Menu bar images can be cleared from the main Visual FoxPro window or a user-defined window with CLEAR.

Remarks

HIDE MENU removes the specified menu bar, a set of menu bars, or all menu bars from the main Visual FoxPro window or from a user-defined window without removing the menu definition from memory. Before a menu bar can be hidden, it must first be created with DEFINE MENU. Hiding a menu bar isn't the same as deactivating it. When a menu bar is hidden, it stays resident in memory and can be displayed in the main Visual FoxPro window or in a user-defined window with ACTIVATE MENU or SHOW MENU.

See Also

ACTIVATE MENU | DEFINE MENU | DEFINE PAD | SHOW MENU


HIDE POPUP Command

Hides one or more active menus created with DEFINE POPUP.

HIDE POPUP MenuName1 [, MenuName2 ...] | ALL [SAVE]

Parameters

MenuName1 [, MenuName2 ...]
Specifies the name of the menu or a list of menus (separated by commas) to hide.
ALL
Hides all defined menus.
SAVE
Places an image of a menu in the main Visual FoxPro window or in a user-defined window. Placing an image of a menu on the screen is useful during program development and testing. Menu images can be cleared from the main Visual FoxPro window or from a user-defined window with CLEAR.

Remarks

HIDE POPUP removes the specified menu, a set of menus, or all menus from the main Visual FoxPro window or from a user-defined window without removing the menu definitions from memory. Before a menu can be hidden, it must first be created with DEFINE POPUP. Hiding a menu isn't the same as deactivating it. When a menu is hidden, it stays resident in memory and can be displayed in the main Visual FoxPro window or in a user-defined window with ACTIVATE POPUP or SHOW POPUP.

See Also

ACTIVATE POPUP | DEFINE BAR | DEFINE POPUP | SHOW POPUP


HIDE WINDOW Command

Hides an active user-defined window or Microsoft Visual FoxPro system window.

HIDE WINDOW WindowName1 [, WindowName2 ... ] | ALL | SCREEN
   [ IN [WINDOW] WindowNameN | IN [WINDOW] SCREEN | IN [WINDOW]
   [BOTTOM | TOP | SAME]

Parameters

WindowName1 [, WindowName2 ...]
Specifies the name of the window or a list of windows (separated by commas) to hide. If you issue HIDE WINDOW without any arguments, the active window is hidden. In Visual FoxPro, you can specify the name of a toolbar to hide. See SHOW WINDOW for a list of Visual FoxPro toolbar names.
ALL
Hides all windows.
SCREEN
Hides the main Visual FoxPro window. To display the main Visual FoxPro window again, issue ACTIVATE WINDOW SCREEN or SHOW WINDOW SCREEN.
IN [WINDOW] WindowNameN
Hides the window within a parent window.
IN [WINDOW] SCREEN
Explicitly hides a window in the main Visual FoxPro window.
BOTTOM | TOP | SAME
Specifies where windows are hidden with respect to other windows. BOTTOM places a window behind all other windows. TOP (the default) places a window in front of all other windows. SAME hides a window without affecting its front-to-back placement. To preserve the relative positions of multiple hidden windows when they are redisplayed with SHOW WINDOW ALL, include the SAME keyword when you hide the windows.

Remarks

HIDE WINDOW removes a window or a set of windows from the main Visual FoxPro window or from a user-defined window. You can use HIDE WINDOW to hide system windows, such as the Command window, the Data Session window, and so on.

Hiding a window isn't the same as closing it. When a window is hidden, it stays resident in memory and remains active. Output can be sent to a hidden window, but you cannot see it.

Releasing a window removes it from memory. Windows removed from memory must be defined again to be redisplayed. A window can be displayed with ACTIVATE WINDOW or SHOW WINDOW.

To hide a system window and or a toolbar (in Visual FoxPro), enclose the entire system window or toolbar name in quotation marks. For example, to hide the Report Controls toolbar in Visual FoxPro, issue the following command:

HIDE WINDOW "Report Controls"

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the HIDE WINDOW command.

Example

In the following example, a window named wOutput1 is defined and activated. The program waits for you to press a key and then hides the window. The program waits for you to press a key again and then displays the window. Pressing a key a third time removes the window from the screen and from memory.

DEFINE WINDOW wOutput1 FROM 6,1 TO 19,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
ACTIVATE WINDOW wOutput1

WAIT WINDOW 'Press a key to hide this window'
HIDE WINDOW wOutput1

WAIT WINDOW 'Press a key to see the window again'
SHOW WINDOW wOutput1

WAIT WINDOW 'Press a key to remove the window from memory'
DEACTIVATE WINDOW wOutput1
RELEASE WINDOW wOutput1

See Also

ACTIVATE WINDOW | DEACTIVATE WINDOW | DEFINE WINDOW | RELEASE WINDOW | SHOW WINDOW


IF ... ENDIF Command

Conditionally executes a set of commands based on the value of a logical expression.

IF lExpression [THEN]
   Commands
[ELSE
   Commands]
ENDIF

Parameters

lExpression
Specifies the logical expression that is evaluated. If lExpression evaluates to true (.T.), any commands following IF or THEN and preceding ELSE or ENDIF (whichever occurs first) are executed.
  • If lExpression is false (.F.) and ELSE is included, any commands after ELSE and before ENDIF are executed.
  • If lExpression is false (.F.) and ELSE isn't included, all commands between IF and ENDIF are ignored. In this case, program execution continues with the first command following ENDIF.

Remarks

You can nest an IF ... ENDIF block within another IF ... ENDIF block.

Comments preceded by && can be placed on the same line after IF, THEN, ELSE, and ENDIF. These comments are ignored during compilation and program execution.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table

GETEXPR 'Enter condition to locate ' TO gcTemp;
   TYPE 'L' DEFAULT 'COMPANY = ""'
LOCATE FOR &gcTemp  && Enter LOCATE expression
IF FOUND( )  && Was it found?
   DISPLAY  && If so, display the record
ELSE  && If not found
   ? 'Condition ' + gcTemp + ' was not found '   && Display a message
ENDIF
USE

See Also

DO CASE ... ENDCASE | DO WHILE ... ENDDO | FOR EACH ... ENDFOR | FOR ... ENDFOR | IIF( ) | SCAN ... ENDSCAN


INSERT - SQL Command

Appends a new record to the end of a table that contains the specified field values. The INSERT SQL command has three syntaxes:

  • Use the first syntax to insert specified values into the specified fields in the table.
  • Use the second syntax to insert the contents of elements from an array, memory variables, or properties of an object that match the field names in the table.
  • Use the third syntax to insert rows from an SQL SELECT command into the specified fields in the table.
INSERT INTO dbf_name [(fname1 [, fname2, ...])]
   VALUES (eExpression1 [, eExpression2, ...])

-or-

INSERT INTO dbf_name FROM ARRAY ArrayName | FROM MEMVAR | FROM NAME ObjectName

-or-

INSERT INTO dbf_name [(fname1 [, fname2, ...])]
   SELECT [(fname1 [, fname2, ...])] FROM tablename WHERE condition

Parameters

INSERT INTO dbf_name
Specifies the name of the table to which the new record is appended. dbf_name can include a path and can be a name expression.

If the table you specify is not open, Visual FoxPro opens it in a new work area, and the new record is appended to the table. The new work area is not selected; the current work area remains selected.

If the table you specify is open, INSERT appends the new record to the table. If the table is open in a work area other than the current work area, it is not selected after the record is appended; the current work area remains selected.

While the command is executing, the current work area becomes the area into which the new record is being inserted. In other words, when the INSERT command is executed, it is in the context of the table being inserted into, regardless of what the current work area was before the command was issued.

[(fname1 [, fname2 [, ...]])]
Specifies the names of the fields in the new record into which the values are inserted.
VALUES (eExpression1 [, eExpression2 [, ...]])
Specifies the field values inserted into the new record. If you omit the field names, you must specify the field values in the order defined by the table structure. If SET NULL is ON, INSERT attempts to insert null values into any fields not specified in the VALUES clause.

If eExpression is a field name, it must include the table alias.

FROM ARRAY ArrayName
Specifies the array whose data is inserted into the new record.

The contents of the elements of the array, starting with the first element, are inserted into the corresponding fields of the record. The contents of the first array element are inserted into the first field of the new record; the contents of the second array element are inserted into the second field, and so on.

When you include the FROM ARRAY clause, Visual FoxPro disregards any default values for fields.

FROM MEMVAR
Specifies that the contents of memory variables are inserted into fields with the same names as the variables. If a variable does not exist with the same name as the field, the field is left empty.
FROM NAME ObjectName
Specifies a valid Visual FoxPro object, whose property names match the field names in the table for which you want to insert a new record containing the object's property values. You can specify any valid Visual FoxPro object, which you would typically create using the SCATTER...NAME command.

When specifying an object, if the table has a field that does match an object property, Visual FoxPro disregards the field and leaves it blank as an APPEND BLANK command was called.

Note If the type of an object's property does not match the field type in the table, Visual FoxPro generates a data type mismatch error. Use caution when specifying objects derived from Visual FoxPro classes because many native properties have types that might differ from the fields you are working with and cannot be changed.

When specifying an object, if an autoincrementing field exists in the table, you cannot have an object property that matches the autoincrementing field unless you use SET AUTOINCERROR OFF for the data session. Otherwise, Visual FoxPro generates an error. If you use SCATTER...NAME to create the object while SET AUTOINCERROR is set to ON, you can use the REMOVEPROPERTY( ) function to remove any autoincrementing properties to avoid generating an error. For more information, see REMOVEPROPERTY( ) Function.

SELECT [(fname1 [, fname2, ...])] FROM tablename WHERE condition
Specifies the fields to select from a table or cursor to be inserted into another table or cursor. The SELECT statement cannot contain any nonSQL clauses, for example, INTO or TO clauses such as the following:

INTO Destination, TO FILE FileName [ADDITIVE], TO PRINTER [PROMPT], TO SCREEN, PREFERENCE PreferenceName [NOCONSOLE] [PLAIN] [NOWAIT]

Visual FoxPro updates the _TALLY system variable with the number or rows inserted.

Remarks

After executing the INSERT command, Visual FoxPro positions the record pointer on the new record.

When you use INSERT with a SELECT statement, you must make sure that the data you insert is compatible with the data types in the table into which you are inserting. Visual FoxPro attempts to convert the data types in the SELECT cursor into the data types in the corresponding table or cursor column into which it is being inserted. If the inserted data is not compatible, precision might be lost, date data types converted to character data types, and so on.

Examples

Example 1

The following example opens the employee table and adds one record.

USE employee
INSERT INTO employee (emp_no, fname, lname, officeno) ;
   VALUES (3022, "John", "Smith", 2101)

Example 2

The following example uses USE to open the Customer table in the testdata database and SCATTER to copy the contents of the current record to variables. COPY STRUCTURE copies the table structure to a new table named cust2. INSERT inserts a new record into the cust2 table from memory variables. SELECT retrieves the data from cust2, and BROWSE displays the new record. To clean up, USE with no table specified closes the table in the current work area, and DELETE removes cust2.dbf.

CLOSE DATABASES
CLEAR
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer
SCATTER MEMVAR
COPY STRUCTURE TO cust2
INSERT INTO cust2 FROM MEMVAR
SELECT CUST2
BROWSE
USE
DELETE FILE cust2.dbf

Example 3

The following example inserts data from the OrdersArchive table from a SELECT statement performed on the Orders table.

INSERT INTO OrdersArchive (order_id, order_date, ship_name) ;
   SELECT order_id, order_date, ship_date FROM Orders ;
   WHERE order_date >= (DATE()-30)

See Also

CREATE QUERY | CREATE TABLE – SQL | MODIFY QUERY | SELECT – SQL | _TALLY System Variable


IMPORT Command

Imports data from an external file format to create a new Visual FoxPro table.

IMPORT FROM FileName   [DATABASE DatabaseName [NAME LongTableName]]
   [TYPE] FW2 | MOD | PDOX | RPD | WK1    | WK3 | WKS | WR1 | WRK | XLS
    | XL5 [SHEET cSheetName]   | XL8 [SHEET cSheetName]   [AS nCodePage]

Parameters

FileName
Specifies the name of the file from which to import data. If you don't include an extension with the file name, the default extension for the specified file type is assumed.
DATABASE DatabaseName
Specifies a database to which the new table is added.
NAME LongTableName
Specifies a long name for the new table. Long names can contain up to 128 characters and can be used in place of short file names in the database.
TYPE
The keyword TYPE is optional, but you must include one of the following file types:
File type | Description
FW2 | Include FW2 to import FW2 files, created by Framework II.
MOD | Include MOD to import MOD files, created by Microsoft Multiplan version 4.1.
PDOX | Include PDOX to import Paradox files. Database files in Paradox versions 3.5 and 4.0 by Borland can be imported by including the PDOX option.
RPD | Include RPD to import RPD files, created by RapidFile.
WK1 | WK3 | WKS | Include WK1 to import data from a Lotus 1-2-3 spreadsheet. Columns from the spreadsheet become fields in the table and the spreadsheet rows become records in the table. A WK1 extension is assigned to spreadsheets created in Lotus 1-2-3 revision 2.x; a WK3 extension is assigned to spreadsheets created in Lotus 1-2-3 revision 3.x; and a .wks extension is assigned to spreadsheets created in Lotus 1-2-3 revision 1-A.
WR1 | WRK | Include WR1 to import data from a Lotus Symphony spreadsheet. Columns from the spreadsheet become fields in the table and the spreadsheet rows become records in the table. A WR1 extension is assigned to spreadsheets created in Symphony version 1.10, and a .wrk extension is assigned to spreadsheets created in Symphony version 1.1.
XLS | Include XLS to import data from Microsoft Excel worksheets versions 2.0, 3.0, and 4.0. Columns from the worksheet become fields in the table and the worksheet rows become records in the table. Worksheet files created in Microsoft Excel have an .xls extension.
XL5 [SHEET cSheetName] Include XL5 to import data from Microsoft Excel version 5.0. Columns from the worksheet become fields in the table and the worksheet rows become records in the table. Worksheet files created in Microsoft Excel have an .xls extension.

If you omit the SHEET clause, the data in Sheet1 is imported. To import data from a specific sheet, include the SHEET keyword and specify the sheet name with cSheetName.
XL8 [SHEET cSheetName] Include XL8 to import data from Microsoft Excel 97. Columns from the worksheet become fields in the table and the worksheet rows become records in the table. Worksheet files created in Microsoft Excel have an .xls extension.

If you omit the SHEET clause, the data in Sheet1 is imported. To import data from a specific sheet, include the SHEET keyword and specify the sheet name with cSheetName.
AS nCodePage
Specifies the code page of the imported file. Visual FoxPro copies the contents of the imported file and, as it copies the data, automatically converts the data to the current Visual FoxPro code page.

If you specify a value for nCodePage that is not supported, Visual FoxPro displays an error message. You can use GETCP( ) for nCodePage to display the Code Page dialog box, allowing you to specify a code page for the imported file.

If you omit AS nCodePage and Visual FoxPro cannot determine the code page of the imported file, Visual FoxPro copies the contents of the imported file and, as it copies the data, automatically converts the data to the current Visual FoxPro code page. If you omit AS nCodePage and Visual FoxPro can determine the code page of the imported file, Visual FoxPro automatically converts the data in the imported file from the data's code page to the current Visual FoxPro code page. Use CPCURRENT( ) to determine the current Visual FoxPro code page.

If nCodePage is 0, Visual FoxPro assumes the code page of the imported file is the same as the current Visual FoxPro code page and no code page conversion occurs.

Remarks

Most software packages store their data in file formats that cannot be opened directly in Visual FoxPro. IMPORT creates a new Visual FoxPro table from data stored in file formats that Visual FoxPro cannot directly read.

A new table is created with the same name as the file from which the data is imported. A .dbf extension is assigned to the newly created table.

See Also

APPEND FROM | COPY TO | EXPORT | GETCP( )


INDEX Command

Creates an index file to display and access table records in a logical order.

INDEX ON eExpression TO IDXFileName | TAG TagName
   [ COLLATE cCollateSequence ] [OF CDXFileName] [FOR lExpression]
   [COMPACT] [ASCENDING | DESCENDING] [UNIQUE | CANDIDATE] [ADDITIVE]

Parameters

eExpression
Specifies an index expression that can include the name of a field or fields from the current table. An index key based on the index expression is created in the index file for each record in the table. Visual FoxPro uses these keys to display and access records in the table.
Note Do not use a variable, an array element, or a field or field expression from a table in another work area for eExpression. If you access an index that contains a variable or field that no longer exists or cannot be located, Visual FoxPro generates an error message.
Memo fields cannot be used alone in index file expressions; they must be combined with other character expressions. If you include a field prefaced by a table alias or work area letter in the index expression, Visual FoxPro generates an error message.
Even though you can optimize FOR clauses with Rushmore Query Optimization technology if aliased fields are included, it is still highly recommended that you avoid using aliased fields when creating indexes. In several cases (USE ... AGAIN, SQL queries, and so on), a different alias is automatically assigned to a table and the index might not be properly updated or used. For more information on Rushmore technology, see Using Rushmore Query Optimization to Speed Data Access.

If you attempt to build an index with a key that varies in length, the key will be padded with spaces. Variable-length index keys are not supported in Visual FoxPro.

It is possible to create an index key with 0 length. For example, a 0-length index key is created when the index expression is a substring of an empty memo field. A 0-length index key generates an error message. When Visual FoxPro creates an index, it evaluates fields in the first record in the table. If a field is empty, it may be necessary to enter some temporary data in the field in the first record to prevent a 0-length index key.

The length of an index key for an .idx index must be between 1 and 100 characters. The length of an index key for a .cdx index must be between 1 and 240 characters. Under some collating sequences, or when using Double-Byte Character Set characters, each character in eExpression uses two characters in the index key. In these cases, the length of eExpression is limited to 120 characters.

Attempting to create an index with a key that exceeds the limit results in an "Invalid key length" error.

TO IDXFileName
Creates an .idx index file. The index file is given the default extension .idx, which you can override by including a different extension or by changing the default index extension in the Visual FoxPro configuration file. Standard Windows rules for naming files, which include long file names, must be observed when creating index files.
TAG TagName [COLLATE cCollateSequence] [OF CDXFileName]
Creates a compound index file. A compound index file is a single index file that consists of any number of separate tags (index entries). Each tag is identified by its unique tag name. Tag names must begin with a letter or an underscore and can consist of any combination of up to 10 letters, digits, or underscores. The number of tags in a compound index file is limited only by available memory and disk space.

Multiple-entry compound index files are always compact. It is not necessary to include COMPACT when creating a compound index file. Names of compound index files are given a .cdx extension.

The COLLATE cCollateSequence clause specifies a collation sequence other than the default setting, MACHINE. The cCollateSequence parameter must be a valid Visual FoxPro collation sequence. For more information about setting collation sequences, see Optimization of International Applications and SET COLLATE Command.

Two types of compound index files can be created: structural and non-structural.

If you exclude the optional OF CDXFileName clause from TAG TagName, you create a structural compound index file. A structural compound index file always has the same base name as the table and is automatically opened when the table is opened.

If a table's structural compound index file cannot be located or is deleted or renamed, a dialog box appears when you try to open the table. If you choose the default Cancel push button, the table isn't opened. Choosing Ignore opens the table and removes the flag in the table's header that indicates an associated structural compound index file is present.

Tip To reassociate a structural compound index that has become dissociated from its table, issue the following command:
USE TableName INDEX CDXFileName

If you include the optional OF CDXFileName clause after TAG TagName, you create a non-structural compound index file. Unlike a structural compound index file, a non-structural compound index file must be explicitly opened with SET INDEX or the INDEX clause in USE.

If a compound index file has already been created and opened, issuing INDEX with TAG TagName adds a tag to the compound index file.

CDXFileName is the name of the dissociated structural compound index. Be sure to reindex the table if it has been modified since the structural compound index was dissociated.

FOR lExpression
Specifies a condition whereby only records that satisfy the filter expression lExpression are available for display and access; index keys are created in the index file for just those records matching the filter expression.

Rushmore optimizes an INDEX ... FOR lExpression command if lExpression is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

COMPACT
Creates a compact .idx file.
ASCENDING
Specifies an ascending order for the .cdx file. By default, .cdx tags are created in ascending order (you can include ASCENDING as a reminder of the index file's order). A table can be indexed in reverse order by including DESCENDING.
DESCENDING
Specifies a descending order for the .cdx file. You can't include DESCENDING when creating .idx index files. You can, however, specify a descending order for an .idx index file with SET INDEX and SET ORDER.
UNIQUE
Specifies that only the first record encountered with a particular index key value is included in an .idx file or a .cdx tag. UNIQUE can be used to prevent the display of or access to duplicate records. All records added with duplicate index keys are excluded from the index file. Using the UNIQUE option of INDEX is identical to executing SET UNIQUE ON before issuing INDEX or REINDEX.

When a UNIQUE index or index tag is active and a duplicate record is changed in a manner that changes its index key, the index or index tag is updated. However, the next duplicate record with the original index key cannot be accessed or displayed until you reindex the file using REINDEX.

CANDIDATE
Creates a candidate structural index tag. The CANDIDATE keyword can be included only when creating a structural index tag; otherwise Visual FoxPro generates an error message.

A candidate index tag prevents duplicate values in the field or combination of fields specified in the index expression eExpression. The term "candidate" refers to the type of index; because candidate indexes prevent duplicate values, they qualify as a "candidate" to be a primary index.

Visual FoxPro generates an error if you create a candidate index tag for a field or combination of fields that already contain duplicate values.

For additional information about candidate and primary index tags, see Setting a Primary or Candidate Index.

ADDITIVE
Keeps open any previously opened index files. If you omit the ADDITIVE clause when you create an index file or files for a table with INDEX, any previously opened index files (except the structural compound index) are closed.

Remarks

Records in a table that has an index file are displayed and accessed in the order specified by the index expression. The physical order of the records in the table isn't changed by an index file.

If SET TALK is ON, Visual FoxPro reports how many records are indexed during the indexing process. The record interval displayed during indexing can be specified with SET ODOMETER.

Use DISPLAY STATUS to display more information about open index files. This information includes the names of all open index files, their types (structural, .cdx, .idx), their index expressions, their collation sequences, and the name of the master index file or master tag.

The number of index files (.idx or .cdx) you can open is limited only by memory and system resources. In Visual FoxPro, FoxPro for Windows, and FoxPro for MS-DOS, the total number of files you can open is determined by the FILES setting in the MS-DOS Config.sys configuration file. For more information on the FILES setting, see your MS-DOS manual.

Index Types Visual FoxPro makes it possible for you to create two types of index files:

  • Compound .cdx index files containing multiple index entries called tags.
  • .idx index files containing one index entry.

You can also create a structural compound index file, which is automatically opened with the table.

Tip Because structural compound index files are automatically opened when the table is opened, they are the preferred index type.

Include COMPACT to create compact .idx index files. Compound index files are always compact.

Index Order and Updating Only one index file (the master index file) or tag (the master tag) controls the order in which the table is displayed or accessed. Certain commands (SEEK, for example) use the master index file or tag to search for records. However, all open .idx and .cdx index files are updated as changes are made to the table. You can designate the master index file or tag with the INDEX clause of USE or with SET INDEX and SET ORDER.

Note Replacing a key field changes the relative position in the index for the current record. Therefore you should be careful when performing an operation such as REPLACE ALL or SCAN ... ENDSCAN while changing the index for the scope. This also applies to REPLACE operations on indexes built with a FOR clause.

User-Defined Functions Although an index expression can contain a user-defined function, you should not use user-defined functions in an index expression. User-defined functions in an index expression increase the time it takes to create or update the index. Also, index updates may not occur when a user-defined function is used for an index expression.

If you use a user-defined function in an index expression, Visual FoxPro must be able to locate the user-defined function. When Visual FoxPro creates an index, the index expression is saved in the index file, but only a reference to the user-defined function is included in the index expression.

Example

Example 1 opens the customer table and creates an index file named complist, which displays and processes records in the alphabetic order of the company field.

In Example 2, the customer table is again opened and an index file named citycomp is created from a substring of the first five characters of the city field and the first six characters of the company field. When this index file is used, records in the table are ordered primarily according to the city field and secondarily according to the company field.

In Example 3, index tags are created. The first tag is a structural compound index tag for address. The second tag is created in a non-structural index file named custcdx.

* Example 1
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
INDEX ON company TO complist
CLEAR
DISPLAY STATUS

* Example 2
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
INDEX ON SUBSTR(city,1,5) + SUBSTR(company,1,6) TO citycomp
CLEAR
DISPLAY STATUS

* Example 3
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
INDEX ON address TAG address
INDEX ON company TAG company OF custcdx
CLEAR
DISPLAY STATUS

See Also

ALTER TABLE | CDX( ) | COPY INDEXES | COPY TAG | DELETE TAG | DESCENDING( ) | FOR( ) | INDEXSEEK( ) | KEY( ) | MDX( ) | NDX( ) | ORDER( ) | REINDEX | SET COLLATE | SET INDEX | SET ODOMETER | SET ORDER | SET TALK | SET UNIQUE | SORT | SYS(14) | SYS(21) | SYS(22) | SYS(2021) | TAG( ) | TAGCOUNT( ) | USE


KEYBOARD Command

Places the specified character expression in the keyboard buffer.

KEYBOARD cKeyboardValue   [PLAIN] [CLEAR]

Parameters

cKeyboardValue
Specifies the character expression that is placed in the keyboard buffer. The character expression can be a character string, a key label, a set of key labels, or a user-defined function that returns a character expression.

If cKeyboardValue is a key label, it must be enclosed in braces and quotes. For example:

KEYBOARD '{CTRL+LEFTARROW}'

For a listing of key labels, see ON KEY LABEL.

The keyboard buffer can be filled with up to 128 characters. Once the keyboard buffer is full, additional characters are ignored.

PLAIN
If you have keyboard macros defined or active ON KEY LABEL commands, you can include PLAIN to bypass these key assignments. PLAIN fills the keyboard with the literal key character, not the key assignment.

For example, if you have assigned a command to the A key with ON KEY LABEL and A is included in cKeyboardValue, use PLAIN to place the letter A in the keyboard buffer. The ON KEY LABEL command assigned to A isn't executed.

CLEAR
Empties the keyboard buffer before the keyboard buffer is filled with cKeyboardValue.

Remarks

Use KEYBOARD to place characters in the keyboard buffer. The characters remain in the buffer until Visual FoxPro looks for keyboard input. At that point, the characters are read and acted upon as if they were entered directly from the keyboard.

You can use KEYBOARD to create self-running demonstration systems that showcase your applications.

See Also

CHRSAW( ) | ON KEY LABEL | PLAY MACRO | SET FUNCTION


LABEL Command

Prints labels from a table file and a label definition file.

LABEL [FORM FileName1 | FORM ?] [ENVIRONMENT] [Scope]
   [FOR lExpression1] [WHILE lExpression2] [NOCONSOLE]
   [NOOPTIMIZE] [PDSETUP] [PREVIEW [NOWAIT]] [NAME ObjectName]
   [TO PRINTER [PROMPT] | TO FILE FileName2]

Parameters

FORM FileName1
Specifies the name of a label definition file whose labels you want to print. The default extension for a label definition file is .lbx. If the label definition file is on a drive or volume other than the default or in a directory other than the current directory, you must also specify the drive designator and directory.
FORM ?
Displays the Open dialog box from which you can choose an existing label file.
ENVIRONMENT
Included for backward compatibility with 2.x labels. To restore the data environment associated with a Visual FoxPro label, set the data environment AutoOpenTables property to true (.T.), which is the default. To make sure that the label environment is closed when the label is finished printing, set the data environment AutoCloseTables property to true (.T.), which is also the default.

When you create or modify labels, you can save the current Visual FoxPro data environment with the label definition file. Saving the Visual FoxPro data environment places additional records in the label definition table for all open tables and index files, the index order, and any relationships between the tables.

Scope
Specifies a range of records. Only the records that fall within the range are printed. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see Scope Clauses. Commands that include Scope operate only on the table in the active work area.

The default scope for LABEL is ALL records.

FOR lExpression1
Specifies a condition whereby only the records that satisfy the logical condition lExpression1 are printed. This argument allows you to filter out records you don't want to print.

Rushmore Query Optimization optimizes a query created with LABEL ... FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are printed for as long as the logical expression lExpression2 evaluates to true (.T.).
NOCONSOLE
Suppresses the display of label output to the main Visual FoxPro window or to a user-defined window when labels are being printed or sent to a file.
NOOPTIMIZE
Disables Rushmore query optimization of LABEL.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

PDSETUP
Loads a printer driver setup.

In Visual FoxPro, you can include PDSETUP to use a printer driver setup for printing character-based labels created in FoxPro for MS-DOS. PDSETUP is ignored when you print graphics-based labels created in Visual FoxPro.

PREVIEW [NOWAIT]
Displays the labels in a preview window before printing, but doesn't print the labels. To print the labels, you must issue LABEL again without the PREVIEW clause.

In Visual FoxPro, you can include the optional NOWAIT clause so that at run time Visual FoxPro does not wait for the page preview window to be closed before continuing program execution. Instead, Visual FoxPro continues program execution while the page preview window is open.

NAME ObjectName
Specifies an object variable name for the data environment of a label. The data environment and the objects in the data environment have properties and methods, for example AddObject, that need to be set or called at run time. The object variable provides access to these properties and methods. If you don't specify a NAME, Visual FoxPro uses as a default the name of the label file that can be referenced in the code associated with the events.
TO PRINTER [PROMPT]
Sends a label to the printer. You can include the optional PROMPT clause to display the Print dialog box before printing starts.
TO FILE FileName2
Sends character-based labels created in FoxPro for MS-DOS to the text file specified with FileName2. The file that is created when you include TO FILE has the default extension .txt.

Remarks

Label definition files are created with MODIFY LABEL or CREATE LABEL.

If LABEL is issued without any additional arguments, the Open dialog box appears, displaying a list of existing label files to choose from.

See Also

Commands | CREATE LABEL | MODIFY LABEL


LIST Commands

Continuously displays table or environment information.

LIST   [FIELDS FieldList]    [Scope] [FOR lExpression1]
 [WHILE lExpression2]   [OFF]   [NOCONSOLE]   [NOOPTIMIZE]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
-or-
LIST FILES   [ON Drive]    [LIKE FileSkeleton]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
-or-
LIST MEMORY   [LIKE FileSkeleton]   [NOCONSOLE]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
-or-
LIST STATUS   [NOCONSOLE]
[TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
-or-
LIST STRUCTURE   [IN nWorkArea | cTableAlias]   [NOCONSOLE]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]

Remarks

These LIST commands are identical to the DISPLAY commands except for the following differences:

ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, the file is overwritten with the value of the expression.
  • The scope for LIST defaults to ALL records.
  • LIST doesn't prompt you after filling the main Microsoft Visual FoxPro window or a user-defined window with information.
  • LIST doesn't display records flagged for deletion when SET DELETED is ON.

For more information about the LIST commands, see the corresponding commands in DISPLAY.

See Also

DISPLAY | DISPLAY FILES | DISPLAY MEMORY | DISPLAY STATUS | DISPLAY STRUCTURE | SET DELETED


LIST CONNECTIONS Command

Continuously displays information about the named connections in the current database.

LIST CONNECTIONS   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from LIST CONNECTIONS to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST CONNECTIONS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

The information displayed includes the names of named connections, datasources, and connection strings in the current database. Use DBGETPROP( ) to return additional information about connections in the current database.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn is created. LIST CONNECTIONS is used to list the named connections in the database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')

CREATE CONNECTION Myconn DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"
CLEAR
LIST CONNECTIONS     && Lists named connections in the database

See Also

CREATE CONNECTION | DELETE CONNECTION | DBGETPROP( ) | DISPLAY CONNECTIONS | RENAME CONNECTION


LIST DATABASE Command

Continuously displays information about the current database.

LIST DATABASE   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from LIST DATABASE to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST DATABASE to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Use DBGETPROP( ) to return additional information about the current database.

Example

This example creates a database named people. A table named friends is created and is automatically added to the database. DISPLAY TABLES is used to display the tables in the database, and LIST DATABASES is used to list information about the tables in the database.

CREATE DATABASE people
CREATE TABLE friends (FirstName C(20), LastName C(20))
CLEAR
DISPLAY TABLES  && Displays tables in the database
LIST DATABASE  && Lists table information

See Also

DISPLAY DATABASE | CREATE DATABASE Command | DBGETPROP( ) Function


LIST DLLS Command

Continuously displays information about shared library functions registered in Visual FoxPro with DECLARE - DLL.

LIST DLLS   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs output from LIST DLLS to a printer.

In Visual FoxPro, you can include the optional PROMPT clause to display a Print dialog box before printing starts. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST DLLS to the file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or the active user-defined window.

See Also

DECLARE - DLL | DISPLAY DLLS | SET SAFETY Command


LIST OBJECTS Command

Continuously displays information about an object or a group of objects.

LIST OBJECTS   [LIKE cObjectSkeleton]
   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

LIKE cObjectSkeleton
Displays information about a subset of objects. cObjectSkeleton is an object specification skeleton that supports wildcards (* and ?). For example, to continuously display all objects that begin with A, use the following command:
LIST OBJECTS LIKE A*
TO PRINTER [PROMPT]
Directs output from LIST OBJECTS to a printer.

You can include the optional PROMPT clause to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST OBJECTS to the disk file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

LIST OBJECTS displays the following information about all existing objects:

  • Properties and their values.
  • Methods.
  • Member objects and the class or subclass on which they are based.
  • Class or subclass on which objects are based.
  • Class hierarchy for the objects.

LIST OBJECTS fills the entire main Visual FoxPro window without pausing.

Example

The following example uses DEFINE CLASS and CREATEOBJECT( ) to create two custom classes named FormChild and FormGrandChild from the Visual FoxPro Form base class. LIST OBJECTS lists information about the objects and their properties.

CLEAR
frmMyForm = CREATEOBJECT("FormGrandChild")
LIST OBJECTS LIKE frm*
RELEASE frmMyForm

DEFINE CLASS FormChild AS FORM
ENDDEFINE

DEFINE CLASS FormGrandChild AS FormChild
ENDDEFINE

See Also

DISPLAY OBJECTS | DEFINE CLASS Command | CREATEOBJECT( ) Function


LIST PROCEDURES Command

Continuously displays the names of stored procedures in the current database.

LIST PROCEDURES   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs the information returned from LIST PROCEDURES to a printer.

You can include PROMPT to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST PROCEDURES to the disk file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

Stored procedures are created with MODIFY PROCEDURES.

Example

The following example opens the testdata database and uses LIST PROCEDURES to list the stored procedures (if any) in the database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')

CLEAR
LIST PROCEDURES  && Lists stored procedures in the database

See Also

APPEND PROCEDURES | COPY PROCEDURES | CREATE DATABASE | DISPLAY DATABASE | DISPLAY PROCEDURES | MODIFY PROCEDURE


LIST TABLES Command

Displays without pausing all tables and information about the tables contained in the current database.

LIST TABLES   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]
   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs the information returned from LIST TABLES to a printer.

You can include PROMPT to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST TABLES to the disk file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

The information returned includes the table names and paths and is a subset of the information shown using LIST STATUS. However, the information displayed using LIST TABLES contains only table-related information and displays the information regardless of whether the tables are open.

Example

The following example opens the customer table in the testdata database. LIST TABLES is used to list information about the tables in the database.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'data\')   && Sets path to database
OPEN DATABASE testdata  && Open testdata database
CLEAR
LIST TABLES  && Lists information about tables in the database

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | DISPLAY TABLES | OPEN DATABASE | REMOVE TABLE


LIST VIEWS Command

Displays without pausing information about SQL views in the current database.

LIST VIEWS   [TO PRINTER [PROMPT] | TO FILE FileName [ADDITIVE]]   [NOCONSOLE]

Parameters

TO PRINTER [PROMPT]
Directs the information returned from LIST VIEWS to a printer.

You can include PROMPT to display a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs output from LIST VIEWS to the disk file specified with FileName. If the file already exists and SET SAFETY is ON, Visual FoxPro displays a prompt asking if you want to overwrite the file.
ADDITIVE
Appends to the end of the named file. If you omit ADDITIVE, then the file is overwritten with the value of the expression.
NOCONSOLE
Suppresses output to the main Microsoft Visual FoxPro window or to the active user-defined window.

Remarks

LIST VIEWS displays the names of SQL views in the current database, and indicates if the SQL views are based on local or remote tables. Use DBGETPROP( ) to return additional information about SQL views in the current database.

SQL views are created with CREATE SQL VIEW.

Example

The following example opens the testdata database. CREATE SQL VIEW is used to create a local SQL view named myview. The View Designer is displayed, allowing you to specify tables and conditions for the SQL view. After you save the SQL view you create, information about the SQL views in the database is listed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
CREATE SQL VIEW myview

CLEAR
LIST VIEWS

See Also

CREATE DATABASE | CREATE SQL VIEW | DBGETPROP( ) | DISPLAY DATABASE | DISPLAY VIEWS


LOCAL Command

Creates local variables and variable arrays.

LOCAL Var1 [AS type [OF ClassLib]] | [ArrayName1(nRows1, [, nColumns1]) [AS type [OF ClassLib]] ]
    [, Var2 [AS type [OF ClassLib]]] [, ArrayName2(nRows2, [, nColumns2]) [AS type [OF ClassLib]] ]
-or-
LOCAL [ARRAY] ArrayName1(nRows1 [, nColumns1]) [AS type [OF ClassLib]]
    [, ArrayName2(nRows2 [, nColumns2]) [AS type [OF ClassLib]] ]

Parameters

VarList
Specifies one or more local variables to create.
[ARRAY] ArrayName1 (nRows1 [, nColumns1]) [, ArrayName2 (nRows2 [, nColumns2])] ...
Specifies one or more local arrays to create. See DIMENSION for a description of each argument.
AS type
Specifies the data type on which this variable or array is based.
OF ClassLib
Specifies the class library containing the type description on which the type element of this variable or array is based.

Remarks

Items within VarList are separated by commas. Local variables and variable arrays can be used and modified only within the procedure or function in which they are created, and cannot be accessed by higher- or lower-level programs. Local variables and arrays are released once the procedure or function containing the local variables and arrays completes execution.

Variables and arrays created with LOCAL are initialized to false (.F.). Any variable or array you wish to declare as local must be declared local prior to assigning it a value. Visual FoxPro generates an error message if you assign a value to a variable or array and later declare it local with LOCAL.

Local variables can be passed by reference.

You cannot abbreviate LOCAL because LOCAL and LOCATE have the same first four letters.

The strong typing required by the CodeSense parser in IntelliSense is available only when you create strongly typed object and variable references by using the optional AS clause.

When you specify a valid classname, Visual FoxPro uses the typelib (if you specify a ProgID) or instantiates the object to get the list of Properties, methods, and events. If the specified classname is not found, Visual FoxPro displays a dropdown list of available classes.

See Also

DIMENSION | FUNCTION | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PRIVATE | PUBLIC | RELEASE


LOCATE Command

Sequentially searches the table for the first record that matches the specified logical expression.

LOCATE [FOR lExpression1]   [Scope]   [WHILE lExpression2]   [NOOPTIMIZE]

Parameters

FOR lExpression1
Sequentially searches the current table for the first record that matches the logical expression lExpression1.

Rushmore Query Optimization optimizes a query created with LOCATE FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Scope
Specifies a range of records to locate. Only the records that fall within the range are located. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. Commands that include Scope operate only on the table in the active work area.

The default scope for LOCATE is ALL records.

WHILE lExpression2
Specifies a condition whereby records are searched for as long as the logical expression lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Disables Rushmore Query Optimization of LOCATE.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

The table doesn't have to be indexed.

If you use the LOCATE command without the FOR expression, Visual FoxPro positions the record pointer at the first logical record. This is faster than using GO TOP when a filter is in use or when DELETED is ON.

If LOCATE finds a matching record, you can use RECNO( ) to return the number of the matching record. If a matching record is found, FOUND( ) returns true (.T.), and EOF( ) returns false (.F.). If SET TALK is ON, the record number of the matching record is displayed.

After LOCATE finds a matching record, you can issue CONTINUE to search the remainder of the table for additional matching records. When CONTINUE is executed, the search process resumes, starting with the record immediately following the matching record. You can issue CONTINUE repeatedly until the end of the scope or the end of the table is reached.

If a match isn't found, RECNO( ) returns the number of records in the table plus 1, FOUND( ) returns false (.F.), and EOF( ) returns true (.T.).

LOCATE and CONTINUE are specific to the current work area. If another work area is selected, the original search process can be continued when the original work area is reselected.

Example

In the following example, records for customers from Germany are located. The total count is then displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Open Customer table
SET TALK OFF

STORE 0 TO gnCount
LOCATE FOR ALLTRIM(UPPER(customer.country)) = 'GERMANY'
DO WHILE FOUND( )
   gnCount = gnCount + 1
   ? company
   CONTINUE
ENDDO

? 'Total companies Germany: '+ LTRIM(STR(gnCount))

See Also

CONTINUE | EOF( ) | FIND | FOUND( ) | INDEXSEEK( ) | RECNO( ) | SEEK | SEEK( ) | SET OPTIMIZE


LOOP Command

Returns program control directly to the beginning of a looping structure.

LOOP

Remarks

You can place LOOP anywhere between DO WHILE and ENDDO, anywhere between FOR and ENDFOR or FOR EACH and ENDFOR, or anywhere between SCAN and ENDSCAN.

The LOOP command returns control directly to the DO WHILE, FOR, or FOR EACH clause without executing the statements between LOOP and ENDDO or ENDFOR. The counter is incremented or decremented as if the END... statement were reached.

See Also

DO WHILE ... ENDDO | FOR ... ENDFOR | FOR EACH ... ENDFOR | SCAN ... ENDSCAN | EXIT


LPARAMETERS Command

Assigns data passed from a calling program to local variables or arrays.

LPARAMETERS Parameter1 [AS type [OF ClassLib]] [, Parameter2 [AS type [OF ClassLib]]]

Parameters

ParameterList
Specifies the local variable or array names to which the data is assigned.

Parameters within ParameterList are separated by commas. There must be at least as many parameters in the LPARAMETERS statement as in the DO ... WITH statement. If more variables or arrays are listed in the LPARAMETERS statement than are passed by DO ... WITH, the remaining variables or arrays are initialized to false (.F.). A maximum of 26 parameters can be passed.

You can use PARAMETERS( ) to determine the number of parameters passed to the most recently executed program, procedure, or user-defined function.

AS type
Specifies the data type on which this variable is based.
OF ClassLib
Specifies the class library containing the type description on which the type element of this variable is based.

Remarks

Multiple items in ParameterList are separated by commas. LPARAMETERS creates local variables or arrays within a called program, procedure, or user-defined function. Use PARAMETERS to create private variables or arrays.

LPARAMETERS must be the first executable statement in the called program, procedure, or user-defined function if you pass values, variables, or arrays to the program, procedure, or user-defined function.

By default, DO ... WITH passes variables and arrays to procedures by reference. When a value is changed in the called procedure, the new value is passed back to the associated variable or array in the calling program. If you want to pass a variable or array to a procedure by value, enclose the variable or array in parentheses in the DO ... WITH parameter list. Any changes made to the parameter in the called procedure are not passed back to the calling program.

Variables are by default passed by reference to a procedure and by value to a user-defined function. Use SET UDFPARMS TO REFERENCE to pass variables to a user-defined function by reference.

The strong typing required by the CodeSense parser in IntelliSense is available only when you create strongly typed object and variable references by using the optional AS clause.

See Also

DO | FUNCTION | LOCAL | PARAMETERS | PARAMETERS( ) Function | PRIVATE | PROCEDURE | PUBLIC | SET UDFPARMS | PCOUNT( ) Function


MD | MKDIR Command

Creates a new directory or subdirectory on disk.

MD cPath | MKDIR cPath

Parameters

cPath
Specifies a directory or a path (with a drive designator and directories).

If cPath is a directory without a drive designator, the directory is created as a subdirectory of the current Microsoft Visual FoxPro default directory.

Remarks

Visual FoxPro generates an error message if you attempt to create a directory that already exists.

Example

The following example uses MKDIR to create a new directory named mytstdir, then CHDIR is used to change to the new directory. GETDIR( ) is used to display the directory structure, and then RMDIR is used to remove the newly created directory. GETDIR( ) is used to display the directory structure again.

SET DEFAULT TO HOME( )  && Restore Visual FoxPro directory
MKDIR mytstdir  && Create a new directory
CHDIR mytstdir  && Change to the new directory
= GETDIR( )  && Display the Select Directory dialog box
SET DEFAULT TO HOME( )  && Restore Visual FoxPro directory
RMDIR mytstdir  && Remove the new directory
= GETDIR( )  && Display the Select Directory dialog box

See Also

CD | CHDIR | DIRECTORY | DIRECTORY( ) | GETDIR( ) | HOME( ) | RD | RMDIR | SET DEFAULT | SET PATH | SYS(5) - Default Drive | SYS(2003) - Current Directory | SYS(2004) - Visual FoxPro Start Directory


MENU Command

Included for backward compatibility. Use the Menu Designer instead.


MODIFY CLASS Command

Opens the Class Designer, making it possible for you to modify an existing class definition or create a new class definition.

MODIFY CLASS ClassName [OF ClassLibraryName1]
   [AS cBaseClassName [FROM ClassLibraryName2]]
   [NOWAIT] [METHOD MethodName] [SAVE]

Parameters

ClassName
Specifies the name of the class definition to modify or create.
OF ClassLibraryName1
Specifies the name of the .vcx visual class library containing the class definition. If you are creating a new class definition and the .vcx visual class library already exists, the class definition is added to it.

A .vcx file extension is assumed for the visual class library. Be sure to include the file extension if the visual class library you specify has a file extension other than .vcx.

If the .vcx visual class library you specify is currently in the SET CLASSLIB search list, the visual class library is removed from the search list.

AS cBaseClassName
Specifies the class on which the class definition is based. You can specify any Visual FoxPro base class except Column and Header. You can also specify a user-defined class if you include the FROM ClassLibraryName2 clause that specifies the name of the visual class library (.vcx) file containing the user-defined class.

If you omit AS cBaseClassName, the class definition is based on the Visual FoxPro FormSet base class.

FROM ClassLibraryName2
Specifies the name of the .vcx visual class library containing the user-defined class specified with cBaseClassName.
METHOD MethodName
Specifies an event or method for which the Code window is opened in the Class Designer. The METHOD clause makes it possible for you to immediately begin editing event or method code in the Class Designer.

MethodName supports the Visual FoxPro object syntax. For example, to immediately edit the Click event code for a text box named txtFirstName in the class named MyClass in a visual class library named MyClassLibrary, use the following command:

MODIFY CLASS MyClass OF MyClassLibrary METHOD txtFirstName.Click

If you only include an event or method name in the METHOD clause, the Code window is opened for the class's event or method. For example, to immediately edit the Click event code for a class named MyClass in a visual class library named MyClassLibrary, use the following command:

MODIFY CLASS MyClass OF MyClassLibrary METHOD Click
NOWAIT
Continues program execution after the Class Designer is opened. The program doesn't wait for the Class Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY CLASS NOWAIT. If you omit NOWAIT when MODIFY CLASS is issued in a program, the Class Designer is opened and program execution pauses until the Class Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY CLASS when issued from the Command window. If NOWAIT is included with the METHOD clause, be sure to place NOWAIT before the METHOD clause or NOWAIT will be ignored.

SAVE
Leaves the Class Designer open after another window is activated. If you omit SAVE, the Class Designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

Use MODIFY CLASS to modify an existing class definition or to create a new class definition and save it in a .vcx visual class library. You can open the .vcx visual class library with SET CLASSLIB, making it possible for you to access the class definitions within the .vcx visual class library.

See Also

ADD CLASS | CREATE CLASS | CREATE CLASSLIB | RELEASE CLASSLIB | SET CLASSLIB


MODIFY COMMAND Command

Opens an editing window so you can modify or create a program file.

MODIFY COMMAND [FileName | ?] [NOEDIT] [NOMENU] [NOWAIT]
   [RANGE nStartCharacter, nEndCharacter] [[WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN]] [AS nCodePage] [SAME]
   [SAVE]

Parameters

FileName
Specifies the file name for the program to open or create. If you don't specify an extension for a new program file, Visual FoxPro automatically assigns a .prg extension. MODIFY COMMAND supports a file skeleton that contains the asterisk (*) and question mark (?) wildcards. An editing window is opened for each program whose file name matches the file skeleton.

If you omit the file name, an editing window opens for a file initially named Prog1.prg. When you close the editing window, you can save the file with a different name.

?
Displays the Open dialog box. Choose one of the existing programs or enter the name of a new program to create.
NOEDIT
Specifies that the program file can't be changed, but can be viewed and copied to the Clipboard.
NOMENU
Removes the Format menu title from the Visual FoxPro system menu bar, preventing changes to font, font size, line spacing, and indentation.
NOWAIT
Continues program execution after the editing window is opened. The program doesn't wait for the editing window to be closed, but continues execution on the program line immediately following the line that contains MODIFY COMMAND NOWAIT. If you omit NOWAIT when MODIFY COMMAND is used in a program, an editing window is opened and program execution pauses until the editing window is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY COMMAND when issued from the Command window.

An implicit NOWAIT occurs if you open more than one editing window with a single MODIFY COMMAND command. For example:

MODIFY COMMAND *.PRG.
RANGE nStartCharacter, nEndCharacter
Specifies a range of characters selected when the editing window is opened. Characters are selected starting at the position specified with nStartCharacter up to (but not including) the character position of nEndCharacter. If nStartCharacter is equal to nEndCharacter, no characters are selected, and the cursor is placed at the position specified with nStartCharacter.
WINDOW WindowName1
Specifies a window whose characteristics the editing window takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the editing window can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the editing window is opened. The editing window doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the editing window moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the editing window.

IN SCREEN
Explicitly opens the editing window in the main Visual FoxPro window, after it has been placed in a parent window. An editing window is placed in a parent window by including the IN WINDOW clause.
AS nCodePage
Automatically converts accented characters in a program file created on another Visual FoxPro platform. The numeric expression nCodePage specifies the code page of the Visual FoxPro platform on which the program file was created. The file is saved in this code page unless you choose Save As from the File menu to save the file in a different code page.
SAME
Prevents the editing window from coming forward as the active window. If the editing window is hidden, it is displayed but doesn't become the active window.
SAVE
Leaves the editing window open after another window is activated. If you omit SAVE, the editing window is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

When modifications are made to a program file, the updated file is written to disk. In Visual FoxPro, a backup file with a .BAK extension is created if you select the Make Backup Copy check box on the Edit Properties dialog box, which appears when you choose Properties from the Edit menu.

The built-in Visual FoxPro editor is used unless you specify an external editor with TEDIT in your configuration file.

See Also

* | && | DO | MODIFY FILE | NOTE | EDITSOURCE( )


MODIFY CONNECTION Command

Displays the Connection Designer, making it possible for you to interactively modify an existing named connection stored in the current database.

MODIFY CONNECTION [ConnectionName | ?]

Parameters

ConnectionName
Specifies the name of the connection to modify.
?
Displays the Open dialog box from which you can choose an existing named connection to modify.

Remarks

If you omit the optional arguments, the Open dialog box is displayed, making it possible for you to specify an existing named connection to modify. The Connection Designer is displayed after you choose a named connection to modify.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn is created. MODIFY CONNECTION is used to displays the Connection Designer so you can modify the connection.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')

CREATE CONNECTION Myconn DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"
MODIFY CONNECTION Myconn && Displays named connections in the database

See Also

CREATE CONNECTION | DELETE CONNECTION | OPEN DATABASE | RENAME CONNECTION


MODIFY DATABASE Command

Opens the Database Designer, making it possible for you to interactively modify the current database.

MODIFY DATABASE [DatabaseName | ?] [NOWAIT] [NOEDIT]

Parameters

DatabaseName
Specifies the name of the database to modify.
?
Displays the Open dialog box from which you can specify the name of the database to modify.
NOWAIT
Continues program execution after the Database Designer is opened. The program doesn't wait for the Database Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY DATABASE NOWAIT. If you omit NOWAIT when MODIFY DATABASE is issued in a program, the Database Designer is opened and program execution pauses until the Database Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY DATABASE when issued from the Command window.

NOEDIT
Prevents changes to the database.

Remarks

MODIFY DATABASE fires the dbc_Activate Event. For more information about interactively modifying a database with the Database Designer, see the Database Designer and Adding Tables to a Database.

Example

The following example displays the Database Designer with the tables in the testdata database.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'data\')     && Sets path to database
MODIFY DATABASE testdata  && Open testdata database

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | DBC( ) | DBGETPROP( ) | DBSETPROP( ) | DELETE DATABASE | DISPLAY TABLES | OPEN DATABASE | REMOVE TABLE | Database Designer | Adding Tables to a Database


MODIFY FILE Command

Opens an editing window so you can modify or create a text file.

MODIFY FILE [FileName | ?] [NOEDIT] [NOMENU] [NOWAIT]
   [RANGE nStartCharacter, nEndCharacter] [[WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN]] [AS nCodePage] [SAME] [SAVE]

Parameters

FileName
Specifies the file name for the text file. If you don't specify an extension for a new text file, Visual FoxPro automatically assigns a .txt extension. MODIFY FILE supports a file skeleton that can contain the asterisk (*) and question mark (?) wildcards. An editing window is opened for each text file whose name matches the file skeleton.

If you omit the file name, an editing window opens for a file initially named FILE1. When you close the editing window, you can save the file with a different name.

?
Displays the Open dialog box, from which you can choose a text file.
NOEDIT
Specifies that the text file can't be changed, but can be viewed and copied to the Clipboard.
NOMENU
Removes the Format menu title from the Visual FoxPro system menu bar, preventing changes to font, font size, line spacing, and indentation.
NOWAIT
Continues program execution after the editing window is opened. The program doesn't wait for the editing window to be closed, but continues execution on the program line immediately following the line that contains MODIFY FILE NOWAIT. If you omit NOWAIT when MODIFY FILE is issued in a program, the editing window is opened and program execution pauses until the editing window is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY FILE when issued from the Command window.

An implicit NOWAIT occurs if you open more than one editing window with a single MODIFY FILE command. For example:

MODIFY FILE *.TXT
RANGE nStartCharacter, nEndCharacter
Specifies a range of characters selected when you open an editing window. Characters are selected starting at the position specified with nStartCharacter up to (but not including) the character position of nEndCharacter. If nStartCharacter is equal to nEndCharacter, no characters are selected, and the cursor is placed at the position specified with nStartCharacter.
WINDOW WindowName1
Specifies a window whose characteristics the editing window takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the editing window can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the editing window is opened. The editing window doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the editing window moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible in order to access the editing window.

IN SCREEN
Explicitly opens the editing window in the main Visual FoxPro window, after it has been placed in a parent window. An editing window is placed in a parent window by including the IN WINDOW clause.
AS nCodePage
Automatically converts accented characters in a text file created on another Visual FoxPro platform. The numeric expression nCodePage specifies the code page of the Visual FoxPro platform on which the text file was created. The file is saved in this code page unless you choose Save As from the File menu to save the file in a different code page.
SAME
Prevents the editing window from coming forward as the active window. If the editing window is hidden, it is displayed but doesn't become the active window.
SAVE
Leaves the editing window open after another window is activated. If you omit SAVE, the editing window is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

When modifications are made to a text file, the updated file is written to disk. In Visual FoxPro, a backup file with a .bak extension is created if you select the Make Backup Copy check box on the Edit Properties dialog box, which appears when you choose Properties from the Edit menu. In previous versions of FoxPro, a backup file with a .bak extension is created if you select the Backup check box in the Preferences dialog box, which appears when you choose Preferences from the Edit menu.

The Visual FoxPro editor is used unless you specify an external editor with TEDIT in your configuration file.

See Also

* | && | DO | MODIFY COMMAND | NOTE


MODIFY FORM Command

Opens the Form Designer so you can modify or create a Form.

MODIFY FORM [FormName | ?][NOWAIT][METHOD MethodName]
   [NOENVIRONMENT][SAVE]
   [[WINDOW WindowName1] [IN [WINDOW] WindowName2 | IN SCREEN]]

Parameters

FormName
Specifies the file name for the Form. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .scx extension.
?
Displays the Open dialog box from which you can choose an existing Form or enter the name of a new Form to create.
NOWAIT
Continues program execution after the Form Designer has been opened. The program doesn't wait for the Form Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY FORM NOWAIT. If you omit NOWAIT, when MODIFY FORM is issued in a program the Form Designer is opened and program execution pauses until the Form Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY FORM when issued from the Command window. If NOWAIT is included with the METHOD clause, be sure to place NOWAIT before the METHOD clause or NOWAIT will be ignored.

METHOD MethodName
Specifies an event or method for which the Code window is opened in the Form Designer. The METHOD clause makes it possible for you to immediately begin editing event or method code in the Form Designer.

MethodName supports the Visual FoxPro object syntax. For example, to immediately edit the Click event code for a text box named txtFirstName in a form named frmAddress, use the following command:

MODIFY FORM frmAddress METHOD txtFirstName.Click

If you only include an event or method name in the METHOD clause, the Code window is opened for the form's event or method. For example, to immediately edit the Click event code for a form named frmAddress, use the following command:

MODIFY FORM frmAddress METHOD Click
NOENVIRONMENT
Included for backward compatibility with 2.x screens, preventing the environment saved with the screen from being restored.

In Visual FoxPro, the data environment associated with a Visual FoxPro form is restored by setting the data environment AutoOpenTables property to true (.T.), which is the default. To make sure that the form environment is closed when the form is releases, set the data environment AutoCloseTables property to true (.T.), which is also the default.

When you create or modify forms, you can save the current Visual FoxPro data environment with the form definition file. Saving the Visual FoxPro data environment places additional records in the form definition table for all open tables and index files, the index order, and any relationships between the tables.

SAVE
When issued in a program, leaves the Form Designer open after another window is brought forward. Including the SAVE option has no effect when issued from the Command window.
WINDOW WindowName1
Specifies a window whose characteristics the Form Designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Form Designer can be moved. The window need not be active or visible, but it must be defined.

The Form Designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Form Designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Form Designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Form Designer is opened. The Form Designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Form Designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Form Designer.

IN SCREEN
Specifies that the Form Designer is explicitly opened in the main Visual FoxPro window, after the Form Designer has been placed in a parent window. The Form Designer is placed in a parent window by including the IN WINDOW clause.

Remarks

Issuing MODIFY FORM without any arguments displays the Open dialog box. You can save the form with a different name when you close the Form Designer.

Example

The following example open the stop watch (SWATCH.SCX) control sample in the Form Designer.

MODIFY FORM (HOME(2) + 'solution\controls\timer\swatch.scx')

See Also

COMPILE FORM | CREATE FORM | DO FORM


MODIFY GENERAL Command

Opens editing windows for general fields in the current record.

MODIFY GENERAL GeneralField1 [, GeneralField2 ...] [NOMODIFY]
   [NOWAIT] [[WINDOW WindowName1] [IN [WINDOW] WindowName2 | IN SCREEN]]

Parameters

GeneralField1 [, GeneralField2 ...]
Specify the names of the general fields to open. To open an editing window for a general field in a table open in a noncurrent work area, include the table alias with the field name. You can open multiple general fields in the current record by including a list of general fields separated by commas.
NOMODIFY
Specifies that the OLE object contained in the general field can't be changed, but can be viewed and copied to the Clipboard.
NOWAIT
Continues program execution after the general field editing window is opened. The program doesn't wait for the editing window to be closed, but continues execution on the program line immediately following the line that contains MODIFY GENERAL NOWAIT. If you omit NOWAIT when MODIFY GENERAL is issued in a program, an editing window is opened and program execution pauses until the editing window is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY GENERAL when issued from the Command window.

WINDOW WindowName1
Specifies a window whose characteristics the general field editing window takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the general field editing window can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the general field editing window is opened. The general field window doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the general field window moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the general field window.

IN SCREEN
Explicitly opens the general field window in the main Visual FoxPro window, after it has been placed in a parent window. A general field editing window is placed in a parent window by including the IN WINDOW clause.

Remarks

When an editing window is open, you can insert, modify, or delete an OLE object.

For more information, see Adding OLE Objects to Your Applications.

See Also

@ ... SAY - Pictures & OLE Objects | APPEND GENERAL


MODIFY LABEL Command

Opens the Label designer so you can create or modify a label.

MODIFY LABEL [FileName | ?] [[WINDOW WindowName1] [IN [WINDOW]
   WindowName2 | IN SCREEN]] [NOENVIRONMENT] [NOWAIT] [SAVE]

Parameters

FileName
Specifies the file name for the label. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .lbx extension. If the file you specify doesn't exist or can't be found, a new label file is created.
?
Displays the Open dialog box, from which you can choose an existing label or enter the name of a new label to create.
WINDOW WindowName1
Specifies a window whose characteristics the Label Designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Label Designer can be moved. The window doesn't have to be active or visible, but it must be defined.

The Label Designer has a default size that can be larger than the window from which it takes its characteristics. In this case, the Label Designer still assumes the characteristics of the window in which it is placed. The upper-left corner of the Label Designer is placed at the same coordinates as the upper-left corner of the window, and extends beyond the window's borders.

IN [WINDOW] WindowName2
Specifies a parent window in which the Label Designer is opened. The Label Designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Label Designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible to access the Label Designer.

IN SCREEN
Explicitly opens the Label Designer in the main Visual FoxPro window, after it has been placed in a parent window. A Label Designer is placed in a parent window by including the IN WINDOW clause.
NOENVIRONMENT
Included for backward compatibility with 2.x labels, preventing the environment saved with the label.

In Visual FoxPro, the data environment associated with a Visual FoxPro label is restored by setting the data environment AutoOpenTables property to true (.T.), which is the default. To make sure that the label environment is closed when the label is finished printing, set the data environment AutoCloseTables property to true (.T.), which is also the default.

When you create or modify labels, you can save the current Visual FoxPro data environment with the label definition file. Saving the Visual FoxPro data environment places additional records in the label definition table for all open tables and index files, the index order, and any relationships between the tables.

NOWAIT
Continues program execution after the Label Designer is opened. The program doesn't wait for the Label Designer to be closed, but continues execution on the program line immediately following the line that contains CREATE LABEL NOWAIT. If you omit NOWAIT when CREATE LABEL is issued in a program, a Label Designer is opened and program execution pauses until the Label Designer is closed.

Including the NOWAIT option has no effect on the CREATE LABEL command when issued from the Command window.

SAVE
Leaves the Label Designer open after another window is activated. If you omit SAVE, the Label Designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

See Also

CREATE LABEL | LABEL


MODIFY MEMO Command

Opens an editing window for a memo field in the current record.

MODIFY MEMO MemoField1 [, MemoField2 ...] [NOEDIT] [NOMENU]
   [NOWAIT] [RANGE nStartCharacter, nEndCharacter]
   [[WINDOW WindowName1] [IN [WINDOW] WindowName2 | IN SCREEN]]
   [SAME] [SAVE]

Parameters

MemoField1 [, MemoField2 ...]
Specifies the names of the memo fields to edit. To open an editing window for a memo field in a table open in another work area, include the table alias with the field name.
NOEDIT
Specifies that the memo field opened can't be changed, but can be viewed and copied to the Clipboard.
NOMENU
Removes the Format menu title from the Visual FoxPro system menu bar, preventing changes to font, font size, line spacing, and indentation.
NOWAIT
Continues program execution after the editing window is opened. The program doesn't wait for the editing window to be closed, but continues execution on the program line immediately following the line that contains MODIFY MEMO NOWAIT. If you omit NOWAIT when MODIFY MEMO is issued in a program, an editing window is opened and program execution pauses until the editing window is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY MEMO when issued from the Command window.

RANGE nStartCharacter, nEndCharacter
Specifies a range of characters selected when the editing window is opened. Characters are selected starting at the position specified with nStartCharacter up to (but not including) the character position of nEndCharacter. If nStartCharacter is equal to nEndCharacter, no characters are selected, and the cursor is placed at the position specified with nStartCharacter.
WINDOW WindowName1
Specifies a window whose characteristics the editing window takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the editing window can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the editing window is opened. The editing window doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the editing window moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the editing window.

IN SCREEN
Explicitly opens the editing window in the main Visual FoxPro window, after it has been placed in a parent window. An editing window is placed in a parent window by including the IN WINDOW clause.
SAME
Prevents the editing window from coming forward as the active window. If the editing window is hidden, it is displayed but doesn't become the active window.
SAVE
Leaves the editing window open after another window is activated. If you omit SAVE, the editing window is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

In the editing window, you can view or change the contents of the memo field.

In a table opened for shared access on a network, the current record is automatically locked when editing begins on one of its memo fields.

Note Syntax coloring in memo field editing windows is disabled in distributed run-time applications.

To enable syntax coloring in an editing window during development

  1. Right-click the editing window and choose Properties from the shortcut menu.
  2. Select the Syntax coloring check box.

Example

The following example opens the notes memo field for the first record in employee in an editing window with a highlighted range.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE employee  && Opens Employee table
MODIFY MEMO notes NOEDIT RANGE 1,10  && First 10 characters selected
USE

See Also

CLOSE MEMO | APPEND MEMO Command | COPY MEMO Command


MODIFY MENU Command

Opens the Menu designer so you can modify or create a menu system.

MODIFY MENU [FileName | ?] [[WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN]] [NOWAIT] [SAVE]

Parameters

FileName
Specifies the file name for the menu. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .mnx extension.
?
Displays the Open dialog box, from which you can choose an existing menu file or enter the name of a new menu to create.
WINDOW WindowName1
Specifies a window whose characteristics the Menu Designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Menu Designer can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the Menu Designer is opened. The Menu Designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Menu Designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Menu Designer.

IN SCREEN
Explicitly opens the Menu Designer in the main Microsoft Visual FoxPro window, after it has been placed in a parent window. The Menu Designer is placed in a parent window by including the IN WINDOW clause.
NOWAIT
Continues program execution after the Menu Designer is opened. The program doesn't wait for the Menu Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY MENU NOWAIT. If you omit NOWAIT when MODIFY MENU is issued in a program, the Menu Designer is opened and program execution pauses until the Menu Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY MENU when issued from the Command window.

If you issue MODIFY MENU from the Command window without a menu name and include NOWAIT, the Open dialog is not displayed. The New Menu dialog makes it possible for you to specify the type of menu (standard or shortcut) created.

SAVE
Leaves the Menu Designer open after another window is activated. If you omit SAVE, the Menu Designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

For more information on creating menus, see Menu System Creation.

See Also

DEFINE BAR | DEFINE MENU | DEFINE PAD | DEFINE POPUP | SET SYSMENU


MODIFY PROCEDURE Command

Opens the Visual FoxPro text editor, making it possible for you to create new stored procedures for the current database, or modify existing stored procedures in the current database.

MODIFY PROCEDURE [NOWAIT]

Parameters

NOWAIT
Continues program execution after the procedure editor for the current database opens. The program doesn't wait for the editor to close, but continues execution on the program line immediately following the line that contains MODIFY PROCEDURE NOWAIT. Without the NOWAIT clause, MODIFY PROCEDURE opens a procedure editor and program execution pauses until you close the editor.

Remarks

A database must be open before you can create or modify stored procedures. Stored procedures are typically specified in Delete, Insert, or Update triggers created for a database with CREATE TRIGGER.

Stored procedures in the current database can be executed like other Visual FoxPro procedures in an open procedure file or program. See PROCEDURE for a description of the order and location in which Visual FoxPro searches for procedures.

Example

The following example opens the testdata database and uses MODIFY PROCEDURE to open the Visual FoxPro text editor, making it possible for you to create new stored procedures or modify existing stored procedures.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

MODIFY PROCEDURE  && Opens the Visual FoxPro text editor

See Also

CREATE TRIGGER | DISPLAY PROCEDURES | OPEN DATABASE | PROCEDURE


MODIFY PROJECT Command

Opens the Project Manager so you can modify or create a project file.

MODIFY PROJECT [FileName | ?] [IN SCREEN] [NOWAIT] [SAVE]
   [NOSHOW] [NOPROJECTHOOK]

Parameters

FileName
Specifies the file name for the project. If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .pjx extension.
?
Displays the Open dialog box, from which you can open an existing project file or enter the name of a new project to create.
IN SCREEN
Explicitly opens the Project Manager in the main Visual FoxPro window, after it has been placed in a parent window. The Project Manager is placed in a parent window by including the IN WINDOW clause.
NOWAIT
Continues program execution after the Project Manager is opened. The program doesn't wait for the Project Manager to be closed, but continues execution on the program line immediately following the line that contains MODIFY PROJECT NOWAIT. If you omit NOWAIT when MODIFY PROJECT is issued in a program, the Project Manager is opened and program execution pauses until the Project Manager is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY PROJECT when issued from the Command window.

SAVE
Leaves the Project Manager open after another window is activated. If you omit SAVE, the Project Manager is closed when another window is activated. Including SAVE has no effect when issued from the Command window.
NOSHOW
Specifies that the Project Manager is hidden (its Visible property is set to false (.F.)) when it is opened. To display the Project Manager, set the Project Manager's Visible property to true (.T.). NOSHOW makes it possible for you to manipulate a project before displaying it in the Project Manager. Note that to avoid confusion with the NOSHADOW keyword, you cannot abbreviate NOSHOW to less than five characters.
NOPROJECTHOOK
Specifies that a ProjectHook object isn't created when the Project Manager is opened. Include NOPROJECTHOOK for projects that will not be manipulated programmatically through the Project Manager hooks. Note that a Project object is still created whenever a project file (.pjx) is opened.

Remarks

In a project, you specify all the source files that are required for a final application, and then Visual FoxPro makes sure the generated application is based on the latest source files.

A project file is a table that keeps track of all the source files such as programs, forms, menus, libraries, reports, labels, tables, indexes, and format files. A project also keeps track of all the dependencies, references, and connections among the files.

Note Shared libraries (.fll, .mlb, .dll, and CFM files) cannot be included in projects.

A project file has a .pjx file name extension and an associated memo file with a .pjt extension.

Issuing MODIFY PROJECT without any arguments displays the Open dialog box.

For information on the Project Manager, see Compiling an Application .

See Also

BUILD APP | BUILD EXE | BUILD PROJECT | COMPILE | CREATE PROJECT


MODIFY QUERY Command

Opens the Query designer so you can modify or create a query.

MODIFY QUERY [FileName | ?] [[WINDOW WindowName1] [IN SCREEN]
   [NOWAIT] [SAVE] [AS nCodePage]

Parameters

FileName
Specifies the file name for the query. If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .qpr extension.
?
Displays the Open dialog box from which you can choose an existing query or enter the name of a new query to create.
WINDOW WindowName1
Specifies a window whose characteristics the Query Designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Query Designer can be moved. The window need not be active or visible, but it must be defined.
IN SCREEN
Explicitly opens the Query Designer in the main Visual FoxPro window, after it has been placed in a parent window. The Query Designer is placed in a parent window by including the IN WINDOW clause.
NOWAIT
Continues program execution after the Query Designer is opened. The program doesn't wait for the Query Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY QUERY NOWAIT. If you omit NOWAIT when MODIFY QUERY is issued in a program, the Query Designer is opened and program execution pauses until the Query Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY QUERY when issued from the Command window.

SAVE
Leaves the Query Designer open after another window is activated. If you omit SAVE, the Query Designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.
AS nCodePage
Specifies the code page of the query. Include AS nCodePage if the query was created with a code page other than the current Visual FoxPro code page. When the query is opened, Visual FoxPro automatically converts the query to the current Visual FoxPro code page. You can use GETCP( ) for nCodePage to display the Code Page dialog box, making it possible for you to specify a code page for the query.

The query is saved in its original code page when it is closed.

If you omit the AS nCodePage clause or nCodePage is 0, the query is not converted to the current Visual FoxPro code page. If you specify a value for nCodePage that is not supported, Visual FoxPro generates an error message.

In Visual FoxPro, queries can be added to a project, and you can specify the query's code page from within the Project Container. The Project Container keeps track of the query's code page. However, if you use MODIFY QUERY to open a query outside of the Project Container, you should include AS nCodePage to specify the query's code page.

Remarks

For more information about creating queries, see Creating a Query.

Issuing MODIFY QUERY without any arguments displays the Open dialog box. If you choose New from this dialog box, the name QUERY1 is assigned to the query. You can save the query with a different name when you exit the Query Designer.

After you have created a query, the query is stored as a Visual FoxPro program file with a .qpr extension. You can execute a query program with DO, but you must include the .qpr extension with the query file name.

See Also

CREATE QUERY | DO | GETCP( )


MODIFY REPORT Command

Opens the Report designer so you can modify or create a report.

MODIFY REPORT [FileName | ?] [[WINDOW WindowName1]
   [IN [WINDOW] WindowName2 | IN SCREEN]] [NOENVIRONMENT] [NOWAIT] [SAVE]

Parameters

FileName
Specifies the file name for the report. If you don't specify an extension for the file name, Visual FoxPro automatically assigns an .frx extension.
?
Displays the Open dialog box from which you can choose an existing report file or enter the name of a new report to create.
WINDOW WindowName1
Specifies a window whose characteristics the Report Designer takes on. For example, if the window is created with the FLOAT option of DEFINE WINDOW, the Report Designer can be moved. The window need not be active or visible, but it must be defined.
IN [WINDOW] WindowName2
Specifies a parent window in which the Report Designer is opened. The Report Designer doesn't assume the characteristics of the parent window and cannot be moved outside the parent window. If the parent window is moved, the Report Designer moves with it.

The parent window must first be defined with DEFINE WINDOW, and must be visible, to access the Report Designer.

IN SCREEN
Explicitly opens the Report Designer in the main Visual FoxPro window, after it has been placed in a parent window. The Report Designer is placed in a parent window by including the IN WINDOW clause.
NOENVIRONMENT
Included for backward compatibility with 2.x reports; prevents the environment from being saved with the report.

In Visual FoxPro, the data environment associated with a Visual FoxPro report is restored by setting the data environment AutoOpenTables property to true (.T.), which is the default. To make sure that the report environment is closed when the report is finished printing, set the data environment AutoCloseTables property to true (.T.), which is also the default.

When you create or modify reports, you can save the current Visual FoxPro data environment with the report definition file. Saving the Visual FoxPro data environment places additional records in the report definition table for all open tables and index files, the index order, and any relationships between the tables.

NOWAIT
Continues program execution after the Report Designer is opened. The program doesn't wait for the Report Designer to be closed, but continues execution on the program line immediately following the line that contains MODIFY REPORT NOWAIT. If you omit NOWAIT when MODIFY REPORT is issued in a program, the Report Designer is opened and program execution pauses until the Report Designer is closed.

NOWAIT is effective only from within a program. It has no effect on MODIFY REPORT when issued from the Command window.

SAVE
Leaves the Report Designer open after another window is activated. If you omit SAVE, the Report Designer is closed when another window is activated. Including SAVE has no effect when issued from the Command window.

Remarks

Issuing MODIFY REPORT without any arguments displays the Open dialog box. If you choose New from this dialog box, the name REPORT1 is assigned to the report file. You can save the report file with a different name when you close the Report Designer.

See Also

_ASCIICOLS | _ASCIIROWS | CREATE REPORT | REPORT


MODIFY STRUCTURE Command

Displays the Table designer, making it possible for you to modify the structure of a table.

MODIFY STRUCTURE

Remarks

In previous versions of FoxPro, MODIFY STRUCTURE opens the Table Structure dialog box.

If a table isn't open in the currently selected work area, the Open dialog box is displayed, making it possible for you to choose a table to modify.

Changes you can make to a table's structure include adding and deleting fields; modifying field names, sizes, and data types; adding, deleting, or modifying index tags; and specifying null value support for fields.

You can also modify the structure of a table using the interface. For more information, see Modifying the Table Structure.

Caution Changing a field from one data type to another may not transfer the contents of the field correctly, or at all. For example, if you convert a field of date type to a numeric type, the field contents do not transfer.

Visual FoxPro automatically makes a backup copy of the current table before you change the table's structure. When the modifications are complete, the data contained in the backup copy of the table is appended to the newly modified table structure. If the table has a memo field, a memo backup file is also created. The table backup file has a .bak extension, and the memo backup file has a .tbk extension.

If you accept the structure changes and then interrupt the data-copying process, the new file will not contain all the records in the original table.

Remember that Visual FoxPro creates a .bak file for the original table file and, if the table has a memo field, a .tbk copy of the original memo file. If you have any problems with MODIFY STRUCTURE, you can delete the new file or files and rename the .bak file and .tbk file, if any, to the original file extensions (.dbf and .fpt).

When you modify the structure of a table that has a memo field, the blocksize of the memo file is set to the current blocksize setting. You can specify the memo file blocksize with SET BLOCKSIZE.

See Also

ALTER TABLE - SQL | CREATE | CREATE TABLE - SQL | SET BLOCKSIZE | Modifying the Table Structure


MODIFY VIEW Command

Displays the View Designer, making it possible for you to modify an existing SQL view.

MODIFY VIEW ViewName [REMOTE][NOWAIT]

Parameters

ViewName
Specifies the name of the view to modify.
REMOTE
Specifies that the view is a remote view that uses remote tables. If you omit REMOTE, you can modify a view using local tables.
NOWAIT
Continues program execution after the VIEW Designer opens. The program doesn't wait for the VIEW Designer to close, but continues execution on the program line immediately following the line that contains MODIFY VIEW … NOWAIT. Without the NOWAIT clause, MODIFY VIEW opens the VIEW Designer and program execution pauses until you close the Designer.

Remarks

SQL views are created with CREATE SQL VIEW.

See Also

CREATE SQL VIEW | OPEN DATABASE


MODIFY WINDOW Command

Modifies a user-defined window or the main Visual FoxPro window.

MODIFY WINDOW WindowName | SCREEN
[FROM nRow1, nColumn1 TO nRow2, nColumn2
   | AT nRow3, nColumn3 SIZE nRow4, nColumn4]
   [FONT cFontName [, nFontSize]] [STYLE cFontStyle]
   [TITLE cTitleText] [HALFHEIGHT] [DOUBLE | PANEL | NONE | SYSTEM]
   [CLOSE | NOCLOSE] [FLOAT | NOFLOAT] [GROW | NOGROW]
   [MINIMIZE | NOMINIMIZE] [ZOOM | NOZOOM] [ICON FILE FileName1]
   [FILL FILE FileName2]
   [COLOR SCHEME nSchemeNumber | COLOR ColorPairList]

Parameters

WindowName
Specifies which user-defined window to modify. The window you specify must first be created with DEFINE WINDOW.
SCREEN
Specifies the main Visual FoxPro window as the window to modify. Do not abbreviate SCREEN or Visual FoxPro generates an error message. To return the main Visual FoxPro window to its startup configuration, issue the following command without any additional clauses:
MODIFY WINDOW SCREEN
Tip Use MODIFY WINDOW SCREEN NOCLOSE to prevent accidentally terminating Visual FoxPro prematurely.

For more information about the MODIFY WINDOW clauses, see DEFINE WINDOW.

Remarks

MODIFY WINDOW changes the attributes of an existing user-defined window (a window created with DEFINE WINDOW) or the main Visual FoxPro window. MODIFY WINDOW can't be used to change the attributes of Visual FoxPro system windows (such as the Command window and Browse window).

Use MODIFY WINDOW to change the location, default font, title, border, controls, icon, wallpaper, and color of a user-defined window or the main Visual FoxPro window. You can change any of these attributes by including the optional clauses for the MODIFY WINDOW command. (Note that if you change colors, you must use CLEAR to apply the color changes.)

For example, include the FROM and TO or AT and SIZE clauses to specify a new location or size for a user-defined window or the main Visual FoxPro window. To prevent a user-defined window or the main Visual FoxPro window from being moved, include the NOFLOAT keyword.

Example

The following example changes the contents of the title bar of the main Visual FoxPro window.

MODIFY WINDOW SCREEN TITLE 'My Application'

See Also

DEFINE WINDOW | _SCREEN


MOUSE Command

Performs the equivalent of clicking, double-clicking, or moving the mouse, or performs a drag operation.

MOUSE [CLICK | DBLCLICK] [AT nRow1, nColumn1]
| DRAG TO nRow2, nColumn2, nRow3, nColumn3 ...][PIXELS]
[WINDOW cWindowName][LEFT | MIDDLE | RIGHT][SHIFT] [CONTROL] [ALT]

Parameters

CLICK | DBLCLICK
Specifies that the mouse is clicked or double-clicked. If you omit the AT clause, the mouse is clicked or double-clicked at the current mouse pointer position.
AT nRow1, nColumn1
Specifies where the mouse is clicked, double-clicked, or the position to which the mouse pointer is moved. If you omit CLICK or DBLCLICK, the mouse pointer is moved to the position specified with nRow1, nColumn1.

Unless you specify a WINDOW, the position specified by nRow1, nColumn1 is relative to the main Microsoft Visual FoxPro window, and the position is determined by the font of the main Visual FoxPro window. Most fonts can be displayed in a wide variety of sizes, and some are proportionally spaced. A row corresponds to the height of the current font; a column corresponds to the average width of a letter in the current font.

You cannot use the AT clause to choose a Visual FoxPro menu title. Use SYS(1500) – Activate a System Menu Item instead to choose a menu title.

DRAG TO nRow2, nColumn2, nRow3, nColumn3 ...]
Specifies that the mouse pointer is dragged to a position or a set of positions.

When the mouse pointer is dragged, a mouse button is pressed and held down until the mouse pointer reaches the destination position; then the mouse button is released. If you omit the LEFT, MIDDLE, and RIGHT clauses, the left (primary) mouse button is pressed and held down by default.

The DRAG clause accepts multiple sets of nRow, nColumn coordinates, allowing the mouse pointer to be dragged to several positions.

If CLICK or DBLCLICK is included, the mouse is clicked or double-clicked at its current position; then the mouse pointer is dragged to the specified position.

PIXELS
Specifies that the position you include in the AT and DRAG TO clause is in pixels.

If PIXELS is omitted, the position is determined by the font of the main Visual FoxPro window or the window specified with cWindowName. Most fonts can be displayed in a wide variety of sizes, and some are proportionally spaced. A row corresponds to the height of the current font; a column corresponds to the average width of a letter in the current font.

WINDOW cWindowName
Specifies the window to which the coordinates in the AT and DRAG TO clauses are relative. If you don't include WINDOW and the name of an active window, the coordinates in the AT and DRAG TO clauses are relative to the main Visual FoxPro window.

To specify a system window or a toolbar, enclose the entire system window or toolbar name in quotation marks.

LEFT | MIDDLE | RIGHT
Specifies which mouse button is pressed when the mouse is clicked, double-clicked, or dragged. If you omit the LEFT, MIDDLE, and RIGHT clauses, the MOUSE commands acts as if you had clicked the left (primary) mouse button.
[SHIFT] [CONTROL] [ALT]
Specifies a key that is pressed when the mouse is clicked, double-clicked, or dragged. In Visual FoxPro for Windows, SHIFT specifies the SHIFT key, CONTROL specifies the CTRL key, and ALT specifies the ALT key.

You can specify any combination of SHIFT, CONTROL, and ALT.

Remarks

MOUSE is typically used to automate interactive application testing or to create demonstration programs.

Example

In the following example, the first command clicks the mouse at row and column 3 of the main Visual FoxPro window. The second command clicks the mouse at row and column 3 of the main Visual FoxPro window, and then drags the mouse pointer to the tenth row and column of the main Visual FoxPro window. The third command drags the mouse pointer from its current position to row and column 20. The fourth command double-clicks the mouse at its current position, and then drags the mouse pointer to row and column 30. The last command drags the mouse pointer from its current position to row and column 10, then to row and column 20, and then to row and column 30.

MOUSE CLICK AT 3,3
MOUSE CLICK AT 3,3 DRAG TO 10,10
MOUSE DRAG TO 20,20
MOUSE DBLCLICK DRAG TO 30,30
MOUSE DRAG TO 10,10,20,20,30,30

See Also

MCOL( ) | MDOWN( ) | MROW( ) | SYS(1500) - Activate a System Menu Item


MOVE POPUP Command

Moves a user-defined menu created with DEFINE POPUP to a new location.

MOVE POPUP MenuName TO nRow1, nColumn1 | BY nRow2, nColumn2

Parameters

MenuName
Specifies the menu to move.

In Visual FoxPro, you cannot move the system menu.

TO nRow1, nColumn1
Moves the menu to a location, specified by nRow1, nColumn1, in a user-defined window or in the main Visual FoxPro window.
BY nRow2, nColumn2
Moves the menu to a location relative to its current position. nRow2 specifies the number of rows to move the menu (down if nRow2 is positive, up if negative). The numeric expression nColumn2 specifies the number of columns to move the menu (to the right if nColumn2 is positive, to the left if negative).

Remarks

A menu can be moved to a specific position or relative to its current position. If a menu has been defined, it can be moved; it doesn't have to be active or visible.

Example

The following example defines and activates a menu, then moves and changes its size.

CLOSE DATABASE
CLEAR
DEFINE POPUP popMovIn FROM 2,2 TO 7, 14 PROMPT FILES LIKE *.PRG ;
   TITLE 'Programs'
ACTIVATE POPUP popMovIn NOWAIT
=CHRSAW(2)
MOVE POPUP popMovIn BY 5,5     && Move menu down
=CHRSAW(2)
SIZE POPUP popMovIn BY 5,5     && Enlarge the menu
=CHRSAW(2)
SIZE POPUP popMovIn BY -5,-5     && Shrink the menu
=CHRSAW(2)
MOVE POPUP popMovIn BY -5,-5     && Move menu up
=CHRSAW(2)
DEACTIVATE POPUP popMovIn
RELEASE POPUP popMovIn

See Also

ACTIVATE POPUP | DEFINE POPUP | SIZE POPUP


MOVE WINDOW Command

Moves a user-defined window created with DEFINE WINDOW, or a Visual FoxPro system window (such as the Command window or Browse window) to a new location.

MOVE WINDOW WindowName TO nRow1, nColumn1   | BY nRow2, nColumn2 | CENTER

Parameters

WindowName
Specifies the name of the window to move.
TO nRow1, nColumn1
Moves the window to a location, specified by nRow1, nColumn1, in the main Visual FoxPro window or in a user-defined window.
BY nRow2, nColumn2
Moves a window to a location relative to its current position. The numeric expression nRow2 specifies the number of rows to move the window (down if nRow2 is positive, up if negative). The numeric expression nColumn2 specifies the number of columns to move the window (to the right if nColumn2 is positive, to the left if negative).
CENTER
Centers a window in the main Visual FoxPro window or in its parent window.

Remarks

A window can be moved to a specific position or relative to its current position. If a window is defined, it can be moved; it doesn't have to be active or visible.

To move a system window and or a toolbar (in Visual FoxPro), enclose the entire system window or toolbar name in quotation marks. For example, to move the Report Controls toolbar (when it isn't docked) in Visual FoxPro, issue the following command:

MOVE WINDOW "Report Controls" BY 1,1

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the MOVE WINDOW command.

Example

In the following example, after the window named wEnter is defined and activated, the window is moved.

DEFINE WINDOW wEnter FROM 10,4 TO 15,54 SYSTEM ;
   TITLE "Nomadic Window"
ACTIVATE WINDOW wEnter
WAIT WINDOW 'Press any key to move the window'
MOVE WINDOW wEnter TO 20,15
WAIT WINDOW 'Press any key to center the window'
MOVE WINDOW wEnter CENTER
WAIT WINDOW 'Press any key to release the window'
RELEASE WINDOW wEnter

See Also

ACTIVATE WINDOW | WAIT Command | DEFINE WINDOW Command | DOCK WINDOW Command | WDOCKABLE( ) Function


NODEFAULT Command

Prevents Visual FoxPro from performing its default event or method processing for Visual FoxPro events and methods. For example, if the KeyPress event occurs, including NODEFAULT in the KeyPress procedure or function prevents Visual FoxPro from placing the key press into the Visual FoxPro keyboard buffer. This makes it possible for you to create a KeyPress procedure that enables you to test which key is pressed before the key is sent to the keyboard buffer.

You can place NODEFAULT anywhere within the event or method procedure. Note that NODEFAULT may also be placed within an event or method procedure in the Form Designer.

See Also

DEFINE CLASS Command | Method and Event Code Guidelines | Run Method | BeforeRowColChange Event | Add Method | OLEDragDrop Event | OLESetData Event | OLEGiveFeedback Event | OLECompleteDrag Event | QueryRunFile Event | BeforeBuild Event | QueryAddFile Event | QueryRemoveFile Event | QueryUnload Event | OLEStartDrag Event | QueryModifyFile Event


NOTE Command

Indicates the beginning of a nonexecuting comment line in a program file.

NOTE [Comments]

Parameters

Comments
Specifies the comment.

Remarks

Place a semicolon (;) at the end of each comment line that continues on a following line.

Example

NOTE  Initialize the page number;
   variable.
STORE 1 to gnPageNum
* Set up the loop
DO WHILE gnPageNum <= 25  && loop 25 times
   gnPageNum = gnPageNum + 1
ENDDO  && DO WHILE gnPageNum <= 25

See Also

&& | * | MODIFY COMMAND | MODIFY FILE


ON BAR Command

Specifies a menu or menu bar that is activated when you choose a specific menu item from a menu.

ON BAR nMenuItemNumber OF MenuName1   [ACTIVATE POPUP MenuName2
   | ACTIVATE MENU MenuBarName]

Parameters

nMenuItemNumber OF MenuName1
Specifies the menu item number and menu of the menu item that activates another menu or menu bar. Each item in a menu can have another menu or menu bar assigned to it.

A menu item with a menu or menu bar assigned to it has an arrow placed to the right of the menu item. The arrow indicates that choosing that menu item activates an additional menu or menu bar. An additional space for the cascading submenu arrow is placed to the right of each item if you define the menu with DEFINE POPUP ... MARGIN. If you create the menu without the MARGIN clause, the cascading submenu arrow might overwrite the last character of the menu item.

ACTIVATE POPUP MenuName2
Specifies the name of the menu to activate when the menu item is chosen. Use ON BAR without ACTIVATE POPUP to release a menu from a menu item.
ACTIVATE MENU MenuBarName
Specifies the name of the menu bar to activate when the menu item is chosen. Use ON BAR without ACTIVATE MENU to release a menu bar from a menu item.

Remarks

A menu that displays and activates another menu is called a cascading submenu. Use ON SELECTION BAR or ON SELECTION POPUP to execute a command when an item is chosen from a menu.

The menus and menu bar can be user-defined (created with DEFINE POPUP and DEFINE MENU) or part of the Visual FoxPro menu system.

Example

The following example demonstrates a system of cascading submenus. A menu bar named mnuDinner is created with two menu bar titles. Each title uses ON PAD to activate the menu named popMainCourse or popDessert. The menus named popMainCourse and popDessert each have additional menus named popBurger, popPizza and popPie assigned to their item lists with three ON BAR commands. The popOlives and popPie items have additional menus assigned with two ON BAR commands.

When you make a selection, ON SELECTION POPUP ALL executes a procedure named yourchoice that activates a window and displays your choice. The choice is determined with POPUP( ) and PROMPT( ), which return the name of the menu and the contents (text) of the menu item.

DEFINE WINDOW wOrder FROM 10,0 TO 13,39
DEFINE MENU mnuDinner
DEFINE PAD padOne OF mnuDinner PROMPT '\<Main Course' KEY ALT+M, ''
DEFINE PAD padTwo OF mnuDinner PROMPT '\<Dessert'   KEY ALT+D, ''
ON PAD padOne OF mnuDinner ACTIVATE POPUP popMainCourse
ON PAD padTwo OF mnuDinner ACTIVATE POPUP dessert
DEFINE POPUP popMainCourse MARGIN MESSAGE ;
   'We have burgers and pizza today'
DEFINE BAR 1 OF popMainCourse PROMPT '\<Hamburgers'
DEFINE BAR 2 OF popMainCourse PROMPT '\<Pizza'
ON BAR 1 OF popMainCourse ACTIVATE POPUP burger
ON BAR 2 OF popMainCourse ACTIVATE POPUP pizza
DEFINE POPUP burger MARGIN MESSAGE ;
   'What would you like on your burger?'
DEFINE BAR 1 OF burger PROMPT '\<Ketchup'
DEFINE BAR 2 OF burger PROMPT '\<Mustard'
DEFINE BAR 3 OF burger PROMPT '\<Onions'
DEFINE BAR 4 OF burger PROMPT '\<Pickles'
DEFINE POPUP pizza MARGIN MESSAGE ;
   'Here are the available toppings'
DEFINE BAR 1 OF pizza PROMPT '\<Anchovies'
DEFINE BAR 2 OF pizza PROMPT '\<Green Peppers'
DEFINE BAR 3 OF pizza PROMPT '\<Olives'
DEFINE BAR 4 OF pizza PROMPT '\<Pepperoni'
ON BAR 3 OF pizza ACTIVATE POPUP olives
DEFINE POPUP olives MARGIN
DEFINE BAR 1 OF olives PROMPT '\<Black' MESSAGE 'Black olives?'
DEFINE BAR 2 OF olives PROMPT '\<Green' MESSAGE 'Green olives?'
DEFINE POPUP dessert MARGIN MESSAGE 'Our dessert offerings'
DEFINE BAR 1 OF dessert PROMPT '\<Brownies'
DEFINE BAR 2 OF dessert PROMPT '\<Cookies'
DEFINE BAR 3 OF dessert PROMPT '\<Ice Cream'
DEFINE BAR 4 OF dessert PROMPT '\<Pie'
ON BAR 4 OF dessert ACTIVATE POPUP pie
DEFINE POPUP pie MARGIN MESSAGE 'What kind of pie?'
DEFINE BAR 1 OF pie PROMPT '\<Blueberry'
DEFINE BAR 2 OF pie PROMPT '\<Cherry'
DEFINE BAR 3 OF pie PROMPT '\<Peach'
DEFINE BAR 4 OF pie PROMPT '\<Rhubarb'
ON SELECTION POPUP ALL DO yourchoice
ACTIVATE MENU mnuDinner
PROCEDURE yourchoice
ACTIVATE WINDOW wOrder
CLEAR
DO CASE
   CASE POPUP( ) = 'BURGER'
      @ 0,0 SAY 'A ' + POPUP( ) + ' order:'
      @ 1,0 SAY 'You ordered a burger with ' + LOWER(PROMPT( ))
   CASE POPUP( ) = 'PIZZA'
      @ 0,0 SAY 'A ' + POPUP( ) + ' order:'
      @ 1,0 SAY 'You ordered a pizza with ' + LOWER(PROMPT( ))
   CASE POPUP( ) = 'OLIVES'
      @ 0,0 SAY 'A ' + POPUP( ) + ' order:'
      @ 1,0 SAY 'You ordered a pizza with ' ;
         + LOWER(PROMPT( )) + ' olives'
   CASE POPUP( ) = 'DESSERT'
      @ 0,0 SAY 'A ' + POPUP( ) + ' order:'
      @ 1,0 SAY 'You ordered ' + LOWER(PROMPT( )) + ' for dessert'
   CASE POPUP( ) = 'PIE'
      @ 0,0 SAY 'A ' + POPUP( ) + ' order:'
      @ 1,0 SAY 'You ordered ' + LOWER(PROMPT( )) + ' pie'
ENDCASE
WAIT WINDOW
DEACTIVATE WINDOW wOrder
RETURN

See Also

ACTIVATE MENU | DEFINE BAR | DEFINE MENU | DEFINE POPUP | ON SELECTION BAR | ON SELECTION POPUP


ON ERROR Command

Specifies a command that executes when an error occurs.

ON ERROR   [Command]

Parameters

Command
Specifies the Microsoft Visual FoxPro command to execute. After the command executes, program execution resumes on the line immediately following the line that caused the error. However, if the error-handling procedure includes RETRY, the program line that caused the error is executed again.

If the command specifies a procedure to execute when an error occurs, you can use ERROR( ), MESSAGE( ), LINENO( ), and PROGRAM( ) to pass the error number, the error message, the program line number, and the program name to the procedure. This information can be used to correct the cause of the error.

Remarks

When an error occurs during program execution, Visual FoxPro executes the command you specify with ON ERROR. Typically, ON ERROR uses DO to execute an error-handling procedure.

Use ON ERROR without a command to restore the default Visual FoxPro error handler.

ON ERROR procedures cannot be nested. If ON ERROR is issued within an ON ERROR procedure, the default Visual FoxPro error handler is restored.

Example

ON ERROR DO errhand WITH ;
   ERROR( ), MESSAGE( ), MESSAGE(1), PROGRAM( ), LINENO( )
*** The next line should cause an error ***
USE nodatabase
ON ERROR  && restore system error handler
PROCEDURE errhand
PARAMETER merror, mess, mess1, mprog, mlineno
CLEAR
? 'Error number: ' + LTRIM(STR(merror))
? 'Error message: ' + mess
? 'Line of code with error: ' + mess1
? 'Line number of error: ' + LTRIM(STR(mlineno))
? 'Program with error: ' + mprog

See Also

AERROR( ) | COMRETURNERROR( ) | DO | ERROR | ERROR( ) | FUNCTION | LINENO( ) | MESSAGE( ) | PROGRAM( ) | PROCEDURE | RETRY | Error Messages A-Z | Error Messages by Number


ON ESCAPE Command

Specifies a command that executes when you press the ESC key during program or command execution.

ON ESCAPE   [Command]

Parameters

Command
Specifies the Visual FoxPro command to execute. After the command executes, program execution resumes on the line immediately following the program line that was executing when you pressed ESC. However, if a procedure specified with ON ESCAPE includes RETRY, the program line that was executing when you pressed ESC executes again.

Remarks

Typically, ON ESCAPE uses DO to execute a procedure.

If both ON ESCAPE and ON KEY are in effect and you press ESC, Visual FoxPro executes the command specified with ON ESCAPE.

Use ON ESCAPE without a command to cause no command to execute when ESC is pressed (the default).

Note Visual FoxPro doesn't execute an ON ESCAPE routine if SET ESCAPE is OFF.

Example

The following example sets up an infinite loop but defines an ON ESCAPE routine to exit it.

SET ESCAPE ON
ON ESCAPE DO stopit
WAIT WINDOW 'Press ESC to stop loop' NOWAIT
glMoreLoop = .T.

DO WHILE glMoreLoop
ENDDO
RETURN

PROCEDURE stopit
glMoreLoop = .F.
RETURN

See Also

INKEY( ) | ON ESCAPE Command | DO Command


ON EXIT BAR Command

Included for compatibility with dBASE.


ON EXIT MENU Command

Included for compatibility with dBASE.


ON EXIT PAD Command

Included for compatibility with dBASE.


ON EXIT POPUP Command

Included for compatibility with dBASE.


ON KEY LABEL Command

Specifies a command that executes when you press a specific key or key combination or click the mouse button.

ON KEY [LABEL KeyLabelName] [Command]

Parameters

LABEL KeyLabelName
Specifies the key label name assigned to the key. The KeyLabelName is the letter or digit on the key or a special name assigned to the key. The following table lists the special key label names.

Visual FoxPro key label assignments

For this key | Specify this KeyLabelName value
LEFTARROW
RIGHTARROW
UPARROW
DNARROW
HOME | HOME
END | END
PAGE UP | PGUP
PAGE DOWN | PGDN
DEL | DEL
BACKSPACE | BACKSPACE
SPACEBAR | SPACEBAR
INS | INS
TAB | TAB
SHIFT+TAB | BACKTAB
Left Brace | LBRACE
Right Brace | RBRACE
ENTER | ENTER
F1 to F12 | F1, F2, F3 ...
CTRL+F1 to CTRL+F12 | CTRL+F1, CTRL+F2 ...
SHIFT+F1 to SHIFT+F12 | SHIFT+F1, SHIFT+F2 ...
ALT+F1 to ALT+F12 | ALT+F1, ALT+F2, ALT+F3 ...
ALT+0 to ALT+9 | ALT+0, ALT+1, ALT+2 ...
ALT+A to ALT+Z | ALT+A, ALT+B, ALT+C ...
CTRL+LEFT ARROW | CTRL+LEFTARROW
CTRL+RIGHT ARROW | CTRL+RIGHTARROW
CTRL+HOME | CTRL+HOME
CTRL+END | CTRL+END
CTRL+PAGE UP | CTRL+PGUP
CTRL+PAGE DOWN | CTRL+PGDN
CTRL+A TO CTRL+Z | CTRL+A, CTRL+B, CTRL+C ...
CTRL+0 | CTRL+0
RIGHT MOUSE BUTTON | RIGHTMOUSE
LEFT MOUSE BUTTON | LEFTMOUSE
MOUSE BUTTON | MOUSE
ESC | ESC
Command
Specifies the command that executes when you press the specified key or key combination or click the mouse button.

You can include parameter or parameter expressions with the command that you assign to the key, as in the following example:

ON KEY LABEL ALT+V WAIT WINDOW "Version: " + VERSION()

You can include variables in the assignment, but they must be public. For example:

PUBLIC message
message = "Default drive: " + SYS(5)
ON KEY LABEL ALT+D WAIT WINDOW message

Remarks

ON KEY LABEL typically uses DO to execute a procedure.

ON KEY LABEL executes the command immediately during the execution of READ, BROWSE, EDIT, CHANGE, and user-defined menus. If a program is executing when you press the key or click the mouse button, Visual FoxPro executes the current program line and then executes the ON KEY LABEL command. Any ON KEY LABEL key assignments created in a program remain in effect after the program is run. You can also create key assignments in the Command window.

To restore the behavior of a specific key to normal, issue ON KEY LABEL KeyLabelName. To restore all keys to their default behavior, issue ON KEY.

Tip To prevent recursive calls during the execution of an ON KEY LABEL procedure, include PUSH KEY CLEAR early in the procedure to disable all active ON KEY LABEL commands. Issue POP KEY at the end of the procedure to enable the ON KEY LABEL commands.

The ON KEY LABEL key assignments aren't in effect in the Visual FoxPro system menu bar, system menus, dialog boxes, alerts, and so on. The key assignments are effective in the Visual FoxPro system windows — the Visual FoxPro text editor, the Command window, the Trace window, and so on.

Unlike ON KEY, there can be multiple active ON KEY LABEL commands. For example, you can assign a command to each of the arrow keys and a mouse button.

Executing an ON KEY LABEL resets PARAMETERS( ) to 0. For more information, see PARAMETERS( ).

In Visual FoxPro, certain events cannot be trapped because they are under the control of Windows. In particular, ON KEY LABEL MOUSE, ON KEY LABEL LEFTMOUSE, and ON KEY LABEL RIGHTMOUSE are not executed when you click a Windows control such as a Control menu, scroll bar, or the like. Also, CTRL+0 is supported in ON KEY LABEL in Visual FoxPro, allowing you to redefine the key combination used to enter a null value into a field.

Note that ON KEY LABEL operates outside of the scope of a form; the KeyPress event can be used within forms to execute code when a key is pressed.

Example

The following example displays a message when an arrow key is pressed.

CLEAR
PUBLIC msg
msg = CHR(13) + CHR(13) + "Press F9 to " + ;
   "restore default key definition."
ON KEY LABEL RIGHTARROW Wait Window "Right Arrow " + msg NOWAIT
ON KEY LABEL LEFTARROW Wait Window "Left Arrow " + msg NOWAIT
ON KEY LABEL UPARROW Wait Window "Up Arrow " + msg NOWAIT
ON KEY LABEL DNARROW Wait Window "Down Arrow " + msg NOWAIT

* Press F9 to clear the ON KEY LABEL assignments
ON KEY LABEL F9 ON KEY

See Also

INKEY( ) | KeyPress Event | ON( ) | POP KEY | PUSH KEY


ON PAD Command

Specifies the menu or menu bar that is activated when you choose a specific menu title.

ON PAD MenuTitleName OF MenuBarName1   [ACTIVATE POPUP MenuName
   | ACTIVATE MENU MenuBarName2

Parameters

MenuTitleName OF MenuBarName1
Specifies the menu title to which a menu or menu bar is assigned.
ACTIVATE POPUP MenuName
Specifies the menu to activate when the menu title is chosen. Use ON PAD MenuTitleName OF MenuBarName1 without ACTIVATE POPUP to release a menu from a menu title.

If you specify the system menu bar _MSYSMENU for MenuBarName1, MenuName cannot specify a menu that is created with the DEFINE POPUP PROMPT clause.

ACTIVATE MENU MenuBarName2
Specifies the name of the menu bar to activate when the menu title is chosen. Use ON PAD MenuTitleName OF MenuBarName1 without ACTIVATE MENU to release a menu bar from a menu name.

Remarks

Use ON SELECTION PAD to execute a command when a menu title is chosen.

See Also

ACTIVATE MENU | DEFINE MENU | ON SELECTION MENU | ON SELECTION PAD


ON PAGE Command

Specifies a command that executes when printed output reaches a specified line number in a report or when you issue EJECT PAGE.

ON PAGE   [AT LINE nLineNumber [Command]]

Parameters

AT LINE nLineNumber [Command]
Specifies the command to execute at the designated line number. The specified command executes when _PLINENO, the system variable that keeps track of the current line number in a report, becomes greater than the line number specified with nLineNumber. The command specified with ON PAGE also executes when you issue EJECT PAGE. For more information, see EJECT PAGE.

Remarks

ON PAGE typically uses DO to execute a procedure for handling page breaks, headers, and footers.

Executing ON PAGE without the AT LINE clause clears the ON PAGE command.

See Also

EJECT PAGE | DO Command | _PLINENO System Variable


ON SELECTION BAR Command

Specifies a command that executes when you choose a specific menu item.

ON SELECTION BAR nMenuItemNumber OF MenuName   [Command]

Parameters

nMenuItemNumber OF MenuName [Command]
Specifies the menu item's bar number, the menu name, and the command to execute for the specified menu item.

Remarks

Typically, ON SELECTION BAR uses DO to execute a procedure or program. When you create and activate a menu, place ON SELECTION BAR between DEFINE POPUP and ACTIVATE POPUP.

You can also use ON SELECTION BAR with a Visual FoxPro system menu.

Use ON SELECTION POPUP to execute a command when you choose any menu item on a menu. Use ON BAR to activate a menu or menu bar when you choose a specific menu item.

Use ON SELECTION BAR nMenuItemNumber OF MenuName without a command to release a command assigned to a menu item.

See Also

DEFINE BAR | DEFINE POPUP | ON BAR | ON SELECTION POPUP


ON SELECTION MENU Command

Specifies a command that executes when you choose any menu title on a menu bar.

ON SELECTION MENU MenuBarName | ALL [Command]

Parameters

MenuBarName
Specifies the name of the menu bar to which you assign a command. The command executes when you choose any menu title from the menu bar. You can specify the name of a user-defined menu bar created with DEFINE MENU or the Microsoft Visual FoxPro system menu bar _MSYSMENU.
ALL
Executes a command when you choose any menu title from any menu bar.
Command
Specifies the command to execute when you choose a menu title. Use ON SELECTION MENU without a command to release a command assigned to a menu bar.

Remarks

When you create and activate a menu bar, place ON SELECTION MENU between DEFINE MENU and ACTIVATE MENU.

Use ON SELECTION PAD to execute a command when you choose a specific menu item. ON SELECTION PAD takes precedence over ON SELECTION MENU. Use ON PAD to activate a menu or menu bar when you choose a specific menu title.

Use ON SELECTION MENU without a command to release a command assigned to a menu bar.

Example

In the following example, ON SELECTION MENU is used to execute a procedure when a menu title is chosen from the Visual FoxPro system menu bar.

The current system menu bar is saved to memory with SET SYSMENU SAVE and all system menu titles are removed with SET SYSMENU TO.

DEFINE PAD creates several system menu titles. When you choose a menu title, the choice procedure assigned to the menu bar with ON SELECTION MENU executes. The choice procedure displays the name of the menu title you choose and the name of the menu bar. If you choose the Exit menu title, the original Visual FoxPro system menu is restored.

*** Name this program ONMENU.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD padSys OF _MSYSMENU PROMPT '\<System' COLOR SCHEME 3 ;
   KEY ALT+S, ''
DEFINE PAD padEdit OF _MSYSMENU PROMPT '\<Edit' COLOR SCHEME 3 ;
   KEY ALT+E, ''
DEFINE PAD padRecord OF _MSYSMENU PROMPT '\<Record' COLOR SCHEME 3 ;
   KEY ALT+R, ''
DEFINE PAD padWindow OF _MSYSMENU PROMPT '\<Window' COLOR SCHEME 3 ;
   KEY ALT+W, ''
DEFINE PAD padReport OF _MSYSMENU PROMPT 'Re\<ports' COLOR SCHEME 3 KEY ALT+P, ''
DEFINE PAD padExit OF _MSYSMENU PROMPT 'E\<xit' COLOR SCHEME 3 ;
   KEY ALT+X, ''
ON SELECTION MENU _MSYSMENU ;
   DO choice IN onmenu WITH PAD( ), MENU( )
PROCEDURE choice
PARAMETER gcPad, gcMenu
WAIT WINDOW 'You chose ' + gcPad + ;
   ' from menu ' + gcMenu NOWAIT
IF gcPad = 'PADEXIT'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

ACTIVATE MENU | DEFINE MENU | ON PAD | ON SELECTION PAD


ON SELECTION PAD Command

Specifies a command that executes when you choose a specific menu title on a menu bar.

ON SELECTION PAD MenuTitleName OF MenuBarName [Command]

Parameters

MenuTitleName OF MenuBarName
Specifies the menu title name to which the command is assigned.
Command
Specifies the Visual FoxPro command to execute when you choose the specified menu title.

Remarks

When you choose the specified menu title, Visual FoxPro executes the command you specify with ON SELECTION PAD. Typically, ON SELECTION PAD uses DO to execute a procedure or program when you choose a specific menu title from the menu bar. When you create and activate the menu bar, place ON SELECTION PAD between DEFINE MENU and ACTIVATE MENU.

Use ON SELECTION MENU to execute a command when you choose any menu title on a menu bar. Use ON PAD to activate a menu or menu bar when you choose a specific menu title on a menu bar.

Use ON SELECTION PAD without a command to release a command assigned to the menu title.

See Also

ACTIVATE MENU | DEFINE MENU | DEFINE PAD | ON PAD | ON SELECTION MENU


ON SELECTION POPUP Command

Specifies a command that executes when you choose any menu item from a specified menu or from all menus.

ON SELECTION POPUP MenuName | ALL [Command]

Parameters

MenuName
Specifies the menu to which the command is assigned.
ALL
If you include ALL instead of a menu name, Visual FoxPro executes the command when you choose a menu item from any menu.
Command
Specifies the command to execute when you choose a menu item.

Remarks

When you choose any menu item from a menu, Visual FoxPro executes the command you specify with ON SELECTION POPUP. When you create and activate the menu, place ON SELECTION POPUP between DEFINE POPUP and ACTIVATE POPUP.

Use ON SELECTION BAR to execute a command when you choose a specific menu item. ON SELECTION BAR takes precedence over ON SELECTION POPUP. Use ON BAR to activate a menu or menu bar when you choose a specific menu item.

Use ON SELECTION POPUP without a command to release a command assigned to a menu item with a previous ON SELECTION POPUP.

See Also

ACTIVATE POPUP | DEFINE BAR | DEFINE POPUP | ON BAR


ON SHUTDOWN Command

Specifies a command that executes when you try to exit Visual FoxPro, or Microsoft Windows.

ON SHUTDOWN [Command]

Parameters

Issue ON SHUTDOWN without Command to release the current ON SHUTDOWN command.

Remarks

The command you specify in ON SHUTDOWN is executed if you try to exit Visual FoxPro. If you try to exit Microsoft Windows while Visual FoxPro is open, control is returned to Visual FoxPro and the command you specify in ON SHUTDOWN is executed.

The ON SHUTDOWN command is typically a DO command that executes a routine to display a dialog box. The dialog box asks if you are sure you want to exit the current application and Visual FoxPro. If you want to exit the application, the routine can close open files, clean up the Visual FoxPro environment and then execute QUIT. If you don't want to exit the current application, the routine can return control back to the application.

See Also

QUIT | EXIT Command | ON EXIT MENU Command


OPEN DATABASE Command

Opens a database.

OPEN DATABASE [FileName | ?] [EXCLUSIVE | SHARED] [NOUPDATE] [VALIDATE]

Parameters

FileName
Specifies the name of the database to open. If you don't specify an extension for the file name, Visual FoxPro automatically assigns a .dbc extension. If you omit FileName, the Open dialog box is displayed. You can specify a path name as part of the database name.
Note Visual FoxPro will not recognize a path name properly if a disk or directory name contains an exclamation point (!).
?
Displays the Open dialog box from which you can choose an existing database or enter the name of a new form to create.
EXCLUSIVE
Opens the database in exclusive mode. If you open the database exclusively, other users cannot access it and will receive an error if they try to gain access. If you do not include EXCLUSIVE or SHARED, the current SET EXCLUSIVE setting determines how the database is opened.
SHARED
Opens the database in shared mode. If you open the database for shared use, other users have access to it. If you do not include EXCLUSIVE or SHARED, the current SET EXCLUSIVE setting determines how the database is opened.
NOUPDATE
Specifies that no changes can be made to the database. In other words, the database is read-only. If you omit NOUPDATE, the database is opened with read/write access.

Tables contained in the database are not affected by NOUPDATE. To prevent changes to a table in the database, include NOUPDATE in USE when you open the table.

VALIDATE
Specifies that Visual FoxPro ensures that references in the database are valid. Visual FoxPro checks to see that tables and indexes referenced in the database are available on disk. Visual FoxPro also checks to see that referenced fields and index tags exist in the tables and indexes.

Remarks

While the database is open, all tables contained in it are available. However, the tables are not implicitly opened. You must open them with USE.

When USE executes, Visual FoxPro looks for the table within the current database. If the table isn't found, Visual FoxPro then looks for a table outside the database. This means that if a table in a database has the same name as a table outside the database, the table in the database is found first.

You cannot open a database that has been opened exclusively by another user.

Example

In the following example, OPEN DATABASE is used to open the testdata database. DISPLAY DATABASE is used to display information about the tables in the database.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'Data\')     && Sets path to database
OPEN DATABASE testdata  && Open testdata database
DISPLAY DATABASE  && Displays table information

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | DBUSED( ) | DISPLAY DATABASE | FREE TABLE | LIST DATABASE | REMOVE TABLE


PACK Command

Permanently removes all records marked for deletion in the current table and reduces the size of a memo file associated with the table.

PACK [MEMO] [DBF] [Tablename ] [IN nWorkarea | cTableAlias]

Parameters

MEMO
Removes unused space from the memo file but doesn't remove records marked for deletion from the table. Information in memo fields is stored in an associated memo file. A memo file has the same name as the table and an .fpt extension.
DBF
Removes records marked for deletion from the table but doesn't affect the memo file.
Tablename
Specifies the table to pack. Visual FoxPro opens the specified table, then packs, and closes it.
IN nWorkArea | cTableAlias
Specifies the workarea or table alias affected by the PACK command. Use this clause to specify a workarea or a table outside the current work area.

Remarks

When you use PACK, Microsoft Visual FoxPro copies all records not marked for deletion to a temporary table. After PACK is finished executing, Visual FoxPro deletes the original table from disk and renames the temporary table with the original table name. If you press ESC to interrupt PACK, the temporary table is deleted, and the original table remains unchanged. The original table is also recovered if you run out of disk space while PACK is executing.

When you issue PACK without the MEMO and DBF clauses, PACK affects both the table and the memo file.

PACK requires exclusive use of the table. For more information about opening a table exclusively on a network, see SET EXCLUSIVE.

If the current table has one or more indexes open, PACK rebuilds the index files.

Caution Be careful to mark only records that you no longer need. There is no way to retrieve deleted records after using PACK.

If you omit the IN clause, PACK works in the current work area.

When you use PACK with a table containing autoincrementing fields, the resulting table is not reincremented, that is, existing values are preserved, and gaps exist where deleted records were removed. For more information, see Autoincrementing Field Values in Tables.

See Also

DELETE – SQL | DELETE | DELETED( ) | RECALL | SET EXCLUSIVE


PACK DATABASE Command

Removes records marked for deletion from the current database.

PACK DATABASE

Remarks

A database contains records marked for deletion after a table or view is removed from the database, or if the structure of a table in the database is modified.

The database must be opened exclusively, and no table or view in the database can be open.

Example

In the following example, PACK DATABASE is used to pack the testdata database, removing records marked for deletion.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'data\')     && Sets path to database
OPEN DATABASE testdata  && Open the database
PACK DATABASE && Pack the current database

See Also

CLOSE DATABASES | DELETE DATABASE | MODIFY DATABASE | OPEN DATABASE | SET DATABASE | VALIDATE DATABASE


PARAMETERS Command

Assigns data passed from a calling program to private variables or arrays.

PARAMETERS Parameter1 [AS type [OF ClassLib]] [, Parameter2 [AS type [OF ClassLib]]]

Parameters

ParameterList
Specifies the variable or array names to which the data is assigned.

Parameters within ParameterList are separated by commas. There must be at least as many parameters in the PARAMETERS statement as in the DO ... WITH statement. If more variables or arrays are listed in the PARAMETERS statement than are passed by DO ... WITH, the remaining variables or arrays are initialized to false (.F.). You can pass a maximum of 26 parameters.

PARAMETERS( ) returns the number of parameters that were passed to the most recently executed routine.

AS type
Specifies the data type on which this variable is based.
OF ClassLib
Specifies the class library containing the type description on which the type element of this variable is based.

Remarks

Multiple items in ParameterList are separated by commas. When PARAMETERS is used with DO ... WITH, it must be the first executable statement in the called program, procedure, or user-defined function.

By default, DO ... WITH passes variables and arrays to procedures by reference. When a value is changed in the called procedure, the new value is passed back to the associated variable or array in the calling program. If you want to pass a variable or array to a procedure by value, enclose the variable or array in parentheses in the DO ... WITH parameter list. Any changes made to the parameter in the called procedure are not passed back to the calling program.

Variables are by default passed by reference to a procedure and by value to a user-defined function. Use SET UDFPARMS TO REFERENCE to pass variables to a user-defined function by reference.

The strong typing required by the CodeSense parser in IntelliSense is available only when you create strongly typed object and variable references by using the optional AS clause.

Example

The following example passes parameters to an error-handling routine.

ON ERROR DO errhand WITH ERROR( ), MESSAGE( ), ;
   MESSAGE(1),PROGRAM( ),LINENO( )
USE nodatabase
ON ERROR         && restores system error-handling routine

PROCEDURE errhand
PARAMETERS gnError, gcMess, gnMess1, gcProg, gnLineNo
? 'Error number: ' + LTRIM(STR(gnError))
? 'Error message: ' + gcMess
? 'Line of code with error: ' + gnMess1
? 'Line number of error: '+ LTRIM(STR(gnLineNo))
? 'Program with error: ' + gcProg

See Also

PCOUNT( ) Function | DO | LOCAL | LPARAMETERS | PARAMETERS( ) Function | PRIVATE | PUBLIC | SET UDFPARMS


PLAY MACRO Command

Executes a keyboard macro.

PLAY MACRO MacroName [TIME nDelay]

Parameters

MacroName
Specifies the name of the keyboard macro to play.
TIME nDelay
Specifies the time interval between the delivery of each keystroke in a keyboard macro. The delay time must be between 0 and 10 seconds. nDelay can evaluate to a number with a decimal fraction. For example, if you specify nDelay equal to 1.5, keystrokes from the macro will be played with a one-and-a-half-second delay between each keystroke.

Remarks

You can save a series of keystrokes as a keyboard macro by choosing Macros from the Tools menu. PLAY MACRO plays this series of keystrokes. Playing keyboard macros within programs lets you create self-running demo programs.

If you issue PLAY MACRO from the Command window, it executes immediately. If PLAY MACRO is issued in a program, execution is delayed until the program executes a command that allows keyboard input. Examples of commands that wait for input are @ ... GET, BROWSE, CHANGE, and EDIT.

If a series of PLAY MACRO commands is pending in a program, Visual FoxPro doesn't execute the commands in the order in which they are issued. Macros are played in reverse order — the first PLAY MACRO executes last, the last PLAY MACRO executes first — in their bottom-to-top order within the program.

See Also

CLEAR Commands | ON KEY LABEL Command | RESTORE MACROS Command | SAVE MACROS Command


POP KEY Command

Restores ON KEY LABEL assignments that were placed on the stack with PUSH KEY.

POP KEY [ALL]

Parameters

ALL
Clears all current key assignments defined with ON KEY LABEL and clears all key assignments defined with ON KEY LABEL from the stack.

Remarks

POP KEY, when used with PUSH KEY, lets you save a set of key assignments created with ON KEY LABEL commands, make changes to the key assignments with more ON KEY LABEL commands, and then restore the original key assignments.

Key assignments take up memory, so every POP KEY should have a corresponding PUSH KEY to make sure your application's memory usage does not grow unnecessarily.

For more information on placing ON KEY LABEL commands on the stack, see PUSH KEY Command.

See Also

ON KEY LABEL Command | ON( ) Function | PUSH KEY Command


POP MENU Command

Restores the specified menu bar definition that was placed on the stack with PUSH MENU.

POP MENU MenuBarName [TO MASTER]

Parameters

MenuBarName
Specifies the name of the menu bar whose definition is pulled off the stack. The specified menu bar can be user-defined or the Visual FoxPro system menu bar.
TO MASTER
Restores the first menu bar definition pushed onto the stack, and then clears the stack.

Remarks

When used with PUSH MENU, POP MENU lets you save a menu bar definition, make changes to the menu bar definition, and then restore the menu bar definition to its original state.

Menu bars are placed on and removed from the stack in last-in, first-out order.

Menu definitions take up memory, so every POP MENU should have a corresponding PUSH MENU to make sure your application's memory usage does not grow unnecessarily.

Example

In the following example, the system menu bar definition is pushed to the stack and then modified. The original system menu definition is then restored by popping it off the stack.

PUSH MENU _MSYSMENU
SET SYSMENU TO _MFILE, _MEDIT
POP MENU _MSYSMENU

See Also

ACTIVATE MENU Command | DEFINE MENU Command | POP POPUP Command | PUSH MENU Command | PUSH POPUP Command


POP POPUP Command

Restores the specified menu definition that was placed on the stack with PUSH POPUP.

POP POPUP MenuName

Parameters

MenuName
Specifies the name of the menu whose definition is pulled off the stack. The menu can be a user-defined menu created with DEFINE MENU or a Visual FoxPro system menu.

Remarks

When used with PUSH POPUP, POP POPUP makes it possible for you to save a menu definition, make changes to the menu definition, and then restore the menu definition to its original state.

Menu definitions are placed on and removed from the stack in a last-in, first-out order.

Menu definitions take up memory, so every POP POPUP should have a corresponding PUSH POPUP to make sure your application's memory usage does not grow unnecessarily.

Example

In the following example, a menu named popExam is created. Menu definition is pushed to the stack and then one of the menu items is modified. The original menu definition is then restored by popping it off the stack.

DEFINE POPUP popExam FROM 5,5
DEFINE BAR 1 OF popExam PROMPT 'One'
DEFINE BAR 2 OF popExam PROMPT 'Two'
DEFINE BAR 3 OF popExam PROMPT 'Three'
DEFINE BAR 4 OF popExam PROMPT 'Four'
ACTIVATE POPUP popExam NOWAIT

PUSH POPUP popExam
WAIT 'Popup pushed' WINDOW
RELEASE BAR 2 OF popExam
WAIT 'This is the modified popup' WINDOW

POP POPUP popExam
WAIT 'Popup popped, original popup restored' WINDOW
DEACTIVATE POPUP popExam
RELEASE POPUP popExam

See Also

ACTIVATE POPUP | DEFINE POPUP | POP MENU | PUSH MENU | PUSH POPUP


PRINTJOB ... ENDPRINTJOB Command

Activates the settings for print job system variables.

PRINTJOB
   Commands
ENDPRINTJOB

Parameters

Commands
Specifies the Visual FoxPro commands that are executed until the print job is completed.

Remarks

PRINTJOB ... ENDPRINTJOB initializes the printer and certain system variables that affect printed output. It can send control codes to the printer, eject a page from the printer before and/or after a print job, initialize the printer column number, and control the number of copies printed.

PRINTJOB performs these tasks:

  • Sends starting printer control codes, stored in the system variable _PSCODE, to the printer. For more information on printer control codes, see the System Variables Overview topic and your printer manual.
  • Ejects a page if the system variable _PEJECT is set to BEFORE or to BOTH.
  • Sets the system variable _PCOLNO to 0. _PCOLNO stores the printer column number.

ENDPRINTJOB performs these tasks:

  • Sends ending printer control codes, stored in the system variable _PECODE, to the printer. You can reset the printer to the configuration it had before PRINTJOB was issued.
  • Ejects a page if the system variable _PEJECT is set to AFTER or to BOTH.
  • Loops back to PRINTJOB to print another copy of the report if the _PCOPIES system variable is set to a value higher than 1 (the default). The value of the system variable _PCOPIES determines the number of copies. When the number of copies printed equals the value of _PCOPIES, Visual FoxPro exits the loop. Program control then begins with the command immediately following ENDPRINTJOB.

PRINTJOB and ENDPRINTJOB may be executed only from within a program. You may not nest PRINTJOB ... ENDPRINTJOB commands.

See Also

ON PAGE | System Variables Overview | Printing | PRINTSTATUS( ) Function


PRIVATE Command

Hides specified variables or arrays that were defined in a calling program from the current program.

PRIVATE VarList

-or-

PRIVATE ALL[LIKE Skeleton | EXCEPT Skeleton]

Parameters

VarList
Specifies the variables or arrays to be declared private.
ALL LIKE Skeleton
Causes PRIVATE to hide all variables and arrays whose names match Skeleton, which can contain the question mark (?) and asterisk (*) wildcards.
ALL EXCEPT Skeleton
Causes PRIVATE to hide all variables or arrays unless their names match Skeleton, which can contain the question mark (?) and asterisk (*) wildcards.

Remarks

Items within VarList are separated by commas. The hiding of variables created in higher-level programs enables variables of the same name as the private variables to be manipulated in the current program without affecting the values of the hidden variables. Once the program containing PRIVATE has completed execution, all variables and arrays that were declared private are again available.

PRIVATE doesn't create variables; it simply hides variables declared in higher-level programs from the current program.

Example

*** Program example demonstrating PRIVATE ***
SET TALK OFF
val1 = 10
val2 = 15

DO down
? val1, val2  && Displays 10, 100

PROCEDURE down
PRIVATE val1
val1 = 50
val2 = 100
? '   Val1   Val2'
? val1, val2  && Displays 50, 100
RETURN

See Also

DIMENSION | FUNCTION | LOCAL | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PROCEDURE | PUBLIC


PROCEDURE Command

Identifies the beginning of a procedure in a program file.

PROCEDURE ProcedureName
   [LPARAMETERS parameter1[,parameter2},...]
   Commands
   [RETURN [eExpression]]
ENDPROC

or

PROCEDURE ProcedureName([parameter1[AS para1type][,parameter2
[AS para2type]],...]) [AS returntype]
   Commands
   [RETURN [eExpression]]
ENDPROC

Parameters

ProcedureName
Specifies the name of the procedure to create.

Remarks

PROCEDURE is a statement within a program file that specifies the beginning of each procedure in the program file and defines the procedure name. Procedure names must begin with a letter or underscore and may contain any combination of letters, numbers, and underscores.

In Visual FoxPro for Windows, procedure names can be up to 254 characters long.

Comments can be placed on the same line after PROCEDURE and ENDPROC. These comments are ignored during compilation and program execution.

The PROCEDURE statement is followed by a series of commands that make up the procedure. You can include RETURN anywhere in the procedure to return control to the calling program or to another program, and to define a value returned by the procedure. If you do not include a RETURN command, an implicit RETURN is automatically executed when the function quits. If the RETURN command does not include a return value (or if an implicit RETURN is executed), Visual FoxPro assigns .T. (True) as the return value.

The procedure ends with the ENDPROC command. This command is optional; the procedure quits when it encounters another PROCEDURE command, a FUNCTION command, or the end of the program file.

Note You cannot have normal executable program code included in a program file after procedures; only procedures, user-defined functions, and class definition can follow the first PROCEDURE or FUNCTION command in the file.

When you execute a procedure with DO ProcedureName, Visual FoxPro searches for the procedure in a specific order. Visual FoxPro searches:

  1. The program containing DO ProcedureName.
  2. The current database.
  3. The procedure files opened with SET PROCEDURE.
  4. Programs in the execution chain. It searches program files beginning with the most recently executed program and continuing back to the first executed program.
  5. A stand-alone program file. If a program file with the same name as the file name specified with DO is found, Visual FoxPro executes the program. If a matching program file name isn't found, Visual FoxPro generates an error message.

Include the IN clause in DO to execute a procedure in a specific file.

By default, parameters are passed to procedures by value. For information on passing parameters to procedures by reference, see SET UDFPARMS. A maximum of 26 parameters can be passed to a procedure. Parameters can be passed to a procedure by including a PARAMETERS or LPARAMETERS statement in the procedure, or by placing a list of parameters immediately after PROCEDURE ProcedureName. Enclose the list of parameters in a set of parentheses, and separate the parameters with commas.

For information about use of the PROCEDURE command in creating classes, see DEFINE CLASS and Strong Typing in Class, Objects, and Variable code in Help.

Example

The following example illustrates how a procedure can be called to accomplish a discrete task such as making an entry in a log file. The procedure opens the log file (which is assumed to exist in the example), constructs an entry based in information passed in parameters, writes the entry out, and closes the file. The procedure is called with a DO command similar to the one at the top of the program.

DO MakeLogEntry WITH "Logged in", "jsmith"

PROCEDURE MakeLogEntry
 PARAMETERS message, username
 pnHandle = FOPEN("LOG2.TXT",2)     && Assume the file exists
 pnSize = FSEEK(pnHandle,0,2)           && Move to end of file
 logEntry = dtoc(date())+","+time()+","+username+","+message
 =FPUTS(pnHandle, logEntry)
 =FCLOSE(pnHandle)  && Close file
ENDPROC

The following example shows how a procedure can be called to return a value.

SET CENTURY ON
? longdate(({^1998-02-16}))  && Displays Monday, February 16, 1998

PROCEDURE longdate
 PARAMETER mdate
 RETURN CDOW(mdate) + ", " + MDY(mdate)
ENDPROC

See Also

FUNCTION | LPARAMETERS | LOCAL | PARAMETERS | PARAMETERS( ) | PRIVATE | PUBLIC | RETURN | SET PROCEDURE | SET UDFPARMS


PUBLIC Command

Defines global variables or arrays.

PUBLIC MemVarList

-Or-

PUBLIC [ARRAY] ArrayName1(nRows1 [, nColumns1])
   [, ArrayName2(nRows2 [, nColumns2])] ...
   [AS type [OF ClassLib]]

Parameters

MemVarList
Specifies one or more memory variables to be initialized and designated as global.
[ARRAY] ArrayName1 (nRows1 [, nColumns1]) [, ArrayName2 (nRows2 [, nColumns2])] ...
Specifies one or more arrays to be initialized and designated as global. See DIMENSION for a description of each argument.
AS type
Specifies the data type on which this variable or array is based.
OF ClassLib
Specifies the class library containing the type description on which the type element of this variable or array is based.

Remarks

Multiple items within MemVarList are separated by commas. Global variables and arrays can be used and modified from any program you execute during the current Visual FoxPro session.

Variables and arrays created with PUBLIC are initialized false (.F.) except for the public variables FOX and FOXPRO, which are initialized true (.T.). The public variables FOX and FOXPRO can be used to conditionally execute code based on the product you are running.

Any Variable or array you create in the Command window is automatically public.

Any Variable or array you wish to declare as public must be declared public prior to assigning it a value.

Visual FoxPro generates a syntax error if, within a program, you assign a value to a variable or array and later declare it public with PUBLIC.

The strong typing required by the CodeSense parser in IntelliSense is available only when you create strongly typed object and variable references by using the optional AS clause.

Example

SET TALK OFF
PUBLIC val1,val2
val1 = 10
val2 = 15

DO down
? val1
? val2

RELEASE ALL     && Releases private variables only
DISPLAY MEMORY LIKE val?
RELEASE val1,val2  && Public variables must be released explicitly
DISPLAY MEMORY LIKE val?

PROCEDURE down
PRIVATE val1
val1 = 50
val2 = 100
? val1
? val2
RETURN

See Also

DIMENSION | FUNCTION | LOCAL | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PRIVATE | PROCEDURE | RELEASE


PUSH KEY Command

Places all current ON KEY LABEL command settings on a stack in memory.

PUSH KEY [CLEAR]

Parameters

CLEAR
Clears all current key assignments from memory.

Remarks

PUSH KEY, when used with POP KEY, makes it possible for you to save key assignments defined with ON KEY LABEL commands, change these assignments, and then restore the previous assignments.

For example, you may want to use a new set of ON KEY LABEL commands when you open a Browse window. Before you open the Browse window, use PUSH KEY to save the current ON KEY LABEL key assignments in memory. You can then add or change ON KEY LABEL assignments specifically for the Browse window. After you close the Browse window, your previous ON KEY LABEL key assignments can be restored from memory with POP KEY.

ON KEY LABEL settings are placed on and removed from the stack in a last-in, first-out order.

DISPLAY STATUS and LIST STATUS show the current key assignments defined with ON KEY LABEL commands. Key assignments take up memory, so every PUSH KEY should have a corresponding POP KEY to make sure your application's memory usage does not grow unnecessarily.

See Also

ON KEY LABEL | ON( ) | POP KEY


PUSH MENU Command

Places a menu bar definition in a stack of menu bar definitions in memory.

PUSH MENU MenuBarName

Parameters

MenuBarName
Specifies the name of the menu bar whose definition is placed on the stack. The menu bar can be user-defined or the Visual FoxPro system menu bar.

Remarks

When used with POP MENU, PUSH MENU makes it possible for you to save a menu bar definition, make changes to the menu bar definition, and then restore the menu bar definition to its original state.

Menu bar definitions are placed on and removed from the stack in last-in, first-out order. Menu definitions take up memory, so every PUSH MENU should have a corresponding POP MENU to make sure your application's memory usage does not grow unnecessarily.

Example

In the following example, the Visual FoxPro system menu bar is pushed to the stack and then modified. The original system menu bar is then restored by popping it off the stack.

WAIT WINDOW 'Press a key to push the system menu bar'
PUSH MENU _MSYSMENU
WAIT WINDOW 'Press a key to change the system menu bar'
SET SYSMENU TO _MFILE, _MEDIT
WAIT WINDOW 'Press a key to restore the system menu bar'
POP MENU _MSYSMENU

See Also

ACTIVATE MENU | DEFINE MENU | SET SYSMENU


PUSH POPUP Command

Places a menu definition on a stack of menu definitions in memory.

PUSH POPUP MenuName

Parameters

MenuName
Specifies the name of the menu whose definition is placed on the stack. The menu can also be a Visual FoxPro system menu.

Remarks

When used with POP POPUP, PUSH POPUP makes it possible for you to save a menu definition, make changes to the menu definition, and then restore the menu definition to its original state.

Menu definitions are placed on and removed from the stack in last-in, first-out order. Menu definitions take up memory, so every PUSH POPUP should have a corresponding POP POPUP to make sure your application's memory usage does not grow unnecessarily.

Example

In the following example, a menu named popExam is created. The menu definition is pushed to the stack and then modified. The original menu is then restored by popping it off the stack.

DEFINE POPUP popExam FROM 5,5
DEFINE BAR 1 OF popExam PROMPT 'One'
DEFINE BAR 2 OF popExam PROMPT 'Two'
DEFINE BAR 3 OF popExam PROMPT 'Three'
DEFINE BAR 4 OF popExam PROMPT 'Four'
ACTIVATE POPUP popExam NOWAIT
PUSH POPUP popExam
WAIT 'Original Popup' WINDOW
RELEASE BAR 2 OF popExam
WAIT 'Modified Popup. Original Popup is pushed to a stack.' WINDOW
POP POPUP popExam
WAIT 'Original Popup restored' WINDOW
DEACTIVATE POPUP popExam
RELEASE POPUP popExam

See Also

ACTIVATE POPUP | DEFINE POPUP | POP POPUP Command


QUIT Command

Ends the current Visual FoxPro session and returns control to the operating system.

QUIT

Remarks

Always use QUIT to terminate a Visual FoxPro session. If you turn the computer off without issuing QUIT, open files may be damaged and data lost, and temporary work files that would normally be deleted may be left on disk.

See Also

CANCEL | RESUME | RUN | SUSPEND


RD | RMDIR Command

Removes a directory or folder from disk.

RD cPath | RMDIR cPath

Parameters

cPath
Specifies the name and location of the directory or folder to remove from disk.

Remarks

Visual FoxPro generates an error message if you attempt to remove a directory or folder that is not empty.

Example

The following example uses MKDIR to create a new directory named mytstdir, then CHDIR is used to change to the new directory. GETDIR( ) is used to display the directory structure, and then RMDIR is used to remove the newly created directory. GETDIR( ) is used to display the directory structure again.

SET DEFAULT TO HOME( )  && Restore Visual FoxPro directory
MKDIR mytstdir  && Create a new directory
CHDIR mytstdir  && Change to the new directory
= GETDIR( )  && Display the Select Directory dialog box
SET DEFAULT TO HOME( )  && Restore Visual FoxPro directory
RMDIR mytstdir  && Remove the new directory
= GETDIR( )  && Display the Select Directory dialog box

See Also

CD | CHDIR | GETDIR( ) | HOME( ) | MD | MKDIR | SET DEFAULT | SET PATH | SYS(5) – Default Drive | SYS(2003) – Current directory | SYS(2004) – Visual FoxPro Start Directory


READ Command

Included for backward compatibility. Use the Form Designer instead.


READ EVENTS Command

Starts event processing.

READ EVENTS

Remarks

When READ EVENTS is issued, Visual FoxPro starts event processing.

Issue CLEAR EVENTS to stop event processing. When CLEAR EVENTS is issued, program execution continues with the line immediately following READ EVENTS.

Note that only one READ EVENTS can be active at a time. If a READ EVENTS is in effect, any subsequent READ EVENTS commands have no effect.

See Also

CLEAR Command | Form Designer | DOEVENTS Command


RECALL Command

Unmarks records marked for deletion in the selected table.

RECALL [Scope] [FOR lExpression1] [WHILE lExpression2] [NOOPTIMIZE]
   [IN nWorkArea | cTableAlias]

Parameters

Scope
Specifies a range of records to recall. The default scope for RECALL is the current record (NEXT 1).

Only the records that fall within the range specified are recalled. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies that only the records for which lExpression1 evaluates to true (.T.) are recalled. This option allows you to filter out undesired records.

Rushmore Query Optimization optimizes a RECALL FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records are recalled for as long as lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Prevents Rushmore optimization of RECALL

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

IN nWorkArea | cTableAlias
Specifies the workarea or table alias affected by the RECALL command. Use this clause to specify a workarea or a table outside the current work area.

Remarks

You can use RECALL to recover records, provided you have not issued PACK or ZAP.

Caution Once a file has been packed, all records marked for deletion are gone forever.

You can mark records for deletion by issuing DELETE or DELETE – SQL, or by choosing Delete Records from the Table menu when a Browse or Edit window is active. You can recall records by issuing RECALL, or by choosing Recall Records from the Record menu when a Browse or Edit window is active.

If you omit the IN clause, the RECALL command operates in the current work area.

Example

The following example opens the customer table in the testdata database. DELETE – SQL is used to mark all records for deletion where the country field contains USA. All the records marked for deletion are displayed. RECALL ALL is used to unmark all the records marked for deletion.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens Customer table

DELETE FROM customer WHERE country = 'USA'  && Mark for deletion
CLEAR
LIST FIELDS company, country FOR DELETED( ) && List marked records
RECALL ALL  && Unmark all records marked for deletion

See Also

DELETE | DELETE – SQL | PACK | SET DELETED | ZAP


REINDEX Command

Rebuilds open index files.

REINDEX updates all index files open in the selected work area.

REINDEX [COMPACT]

Parameters

COMPACT
Converts regular single index (.idx) files to compact .idx files.

Remarks

Index files become outdated when you open a table without opening its corresponding index files and make changes to the index files' key fields. When index files become outdated, you can update them by reindexing.

Visual FoxPro recognizes each index file type: compound index (.cdx) files, structural .cdx files, and single index (.idx) files), and reindexes them accordingly. It updates all tags in .cdx files and updates structural .cdx files, which automatically open with the table.

Tip To speed network traffic during a REINDEX operation, you can use SYS(3050) - Set Buffer Memory Size to set buffer memory to a size large enough to store the entire table. During the first pass, the table is paged locally, and later passes will not attempt to read paged data from the remote computer.

Any index files created with the UNIQUE keyword of the INDEX command or with SET UNIQUE ON retain their UNIQUE status when reindexed.

To REINDEX outdated index files, issue these commands:

USE TableName INDEX OutdatedIndexNames
REINDEX

Example

In the following example, ISEXCLUSIVE( ) verifies that the customer table was opened for exclusive use. The table is not reindexed since the one in the current work area was not opened for exclusive use.

cExclusive = SET('EXCLUSIVE')
SET EXCLUSIVE OFF
SET PATH TO (HOME(2) + 'Data\')
OPEN DATA testdata  && Opens the test databsase
USE Customer     && Not opened exclusively
USE Employee IN 0 EXCLUSIVE    && Opened exclusively in another work area

IF ISEXCLUSIVE( )
 REINDEX  && Can only be done if table opened exclusively
ELSE
  WAIT WINDOW 'The table has to be exclusively opened'
ENDIF

SET EXCLUSIVE &cExclusive

See Also

INDEX | SET INDEX | SET EXCLUSIVE | SET UNIQUE | SYS( ) Functions Overview | USE


RELEASE BAR Command

Removes a specified menu item or all menu items on a menu from memory.

RELEASE BAR nMenuItemNumber OF MenuName | ALL OF MenuName

Parameters

nMenuItemNumber OF MenuName
Specifies a menu item in a user-defined menu to remove from memory. To remove a menu item from a Microsoft Visual FoxPro system menu, include the internal Visual FoxPro system menu item name in nMenuItemNumber. For more information, see the System Menu Names online topic.
ALL OF MenuName
Specifies that every menu item on a user-defined menu is removed from memory. ALL cannot be used to remove menu items from a Visual FoxPro system menu.

See Also

DEFINE BAR | RELEASE PAD | System Menu Names


RELEASE CLASSLIB Command

Closes .vcx visual class libraries containing class definitions.

RELEASE CLASSLIB ClassLibraryName1 | ALIAS AliasName1
   [, ClassLibraryName2 | ALIAS AliasName2 …]
   [IN APPFileName | EXEFileName]

Parameters

ClassLibraryName1 | ALIAS AliasName1
Specifies the name or alias of a visual class library file to close.
ClassLibraryName2 | ALIAS AliasName2 …
Specifies the names or aliases of additional visual class library files to close.
IN APPFileName | EXEFileName
Specifies a Visual FoxPro application file (.app) or executable file (.exe) containing the visual class library.

Remarks

.Vcx visual class libraries are opened with SET CLASSLIB. Once the library is open, the class definitions within the visual class library are available to programs and from the Command window.

To close all open visual class libraries, issue SET CLASSLIB TO without any additional arguments.

Example

The following example uses CREATE CLASSLIB to create a visual class library named myclslib. A class named myform based on the Visual FoxPro Form base class is created and is stored in the myclslib visual class library. SET CLASSLIB is used to open the myclslib visual class library so that classes within it can be used. RELEASE CLASSLIB is then used to close the myclslib visual class library.

CREATE CLASSLIB myclslib     && Creates a new .VCX visual class library
CREATE CLASS myform OF myclslib AS "Form"  && Creates new class
SET CLASSLIB TO myclslib ADDITIVE     && Opens MyClsLib.VCX
RELEASE CLASSLIB myclslib

See Also

ADD CLASS | CREATE CLASS | CREATE CLASSLIB | MODIFY CLASS | REMOVE CLASS | RENAME CLASS | SET CLASSLIB


RELEASE Command

Removes variables and arrays from memory.

RELEASE MemVarList

-Or-

RELEASE ALL [EXTENDED]

-Or-

RELEASE ALL [LIKE Skeleton | EXCEPT Skeleton]

Parameters

RELEASE MemVarList
Specifies the variables and arrays released from memory. Separate the variables and array names with commas.
RELEASE ALL
Releases from memory all variables and arrays.
EXTENDED
When issued in a program, specifies that all public variables are released. RELEASE ALL does not release public variables when issued in a program.
LIKE Skeleton | EXCEPT Skeleton
Releases from memory all variables and arrays that match the specified skeleton, or all variables and arrays except those that match the specified skeleton. Skeleton can include the wildcards ? and *. RELEASE ALL LIKE and RELEASE ALL EXCEPT do not release public variables when issued in a program.

See Also

CLEAR MEMORY | DIMENSION | PRIVATE | PUBLIC | STORE


RELEASE LIBRARY Command

Removes a single external API library from memory.

RELEASE LIBRARY LibraryName

Parameters

LibraryName
Specifies the name of the API library to remove from memory.

Remarks

Issue SET LIBRARY TO to remove all API libraries from memory. An external API routine library is loaded into memory with SET LIBRARY. For more information on API routine libraries, see SET LIBRARY.

See Also

SET LIBRARY | API Library Routines A-Z | API Library Routines by Category


RELEASE MENUS Command

Removes user-defined menu bars from memory.

RELEASE MENUS [MenuBarNameList [EXTENDED]]

Parameters

MenuBarNameList
Specifies the menu bars to be released from memory. Separate the menu bar names with commas.
EXTENDED
Releases a menu bar and all its subordinate menus, menu titles, menu items, and all associated ON SELECTION BAR, ON SELECTION MENU, ON SELECTION PAD, and ON SELECTION POPUP commands.

Remarks

An active menu bar must first be deactivated with DEACTIVATE MENU before it can be released from memory.

If RELEASE MENUS is issued without any additional arguments, all user-defined menu bars are removed from memory.

See Also

DEFINE MENU | ON SELECTION BAR | DEACTIVATE MENU | ON SELECTION MENU | ON SELECTION PAD | ON SELECTION POPUP


RELEASE PAD Command

Removes a specific menu title or all menu titles from memory.

RELEASE PAD MenuTitleName OF MenuBarName | ALL OF MenuBarName

Parameters

MenuTitleName OF MenuBarName
Specifies the menu title to remove from memory.

You can remove a menu title from the Visual FoxPro system menu bar by specifying its name in MenuTitleName. For example, the command RELEASE PAD _MEDIT OF _MSYSMENU removes the Edit menu title from the Visual FoxPro system menu bar.

ALL OF MenuBarName
Specifies that every menu title in a user-defined menu bar is removed from memory. The ALL clause cannot be used to remove menu titles from the Visual FoxPro system menu bar.

Example

The following example removes the Window menu title from the system menu bar.

PUSH MENU _MSYSMENU
RELEASE PAD _MSM_WINDO OF _MSYSMENU  && Removes Window menu title

WAIT WINDOW 'Press a key to restore the default menu'
POP MENU _MSYSMENU  && Restore default Visual FoxPro menu system

See Also

DEFINE PAD | RELEASE BAR | System Menu Names


RELEASE POPUPS Command

Removes a specific menu or all menus from memory.

RELEASE POPUPS [MenuNameList [EXTENDED]]

Parameters

MenuNameList
Specifies the menus to release from memory. Separate the menu names with commas.

Visual FoxPro system menus that appear under the Visual FoxPro system menu bar can also be released. To release a Visual FoxPro system menu, include the internal name of the system menu (_MFILE, _MEDIT, _MDATA, and so on). Use SET SYSMENU TO DEFAULT to restore the default system menu bar and system menus.

EXTENDED
Releases a menu, its items, and all commands associated with ON SELECTION POPUP and ON SELECTION BAR.

Remarks

An active menu must be deactivated with DEACTIVATE POPUP before it can be released from memory.

If RELEASE POPUPS is issued without any additional arguments, all user-defined menus are removed from memory.

See Also

DEFINE POPUP | System Menu Names | SET SYSMENU Command


RELEASE PROCEDURE Command

Closes procedure files opened with SET PROCEDURE.

RELEASE PROCEDURE FileName1 [, FileName2 …]

Parameters

FileName1 [, FileName2 …]
Specifies the name of the procedure file or a set of procedure files to close.

Remarks

Procedure files are opened with SET PROCEDURE. Once the file is open, the procedures within the file are available to programs and from the Command window.

To close all open procedure files, issue SET PROCEDURE TO without any additional arguments.

See Also

SET PROCEDURE | RELEASE BAR Command | RELEASE Command


RELEASE WINDOWS Command

Removes user-defined windows or Visual FoxPro system windows from memory.

RELEASE WINDOWS [WindowNameList]

Parameters

WindowNameList
Specifies the windows released from memory. WindowNameList can include both user-defined windows and Visual FoxPro system windows. Separate the window names with commas.

If WindowNameList isn't included, the active user-defined window is released.

Remarks

RELEASE WINDOWS can be used to remove Visual FoxPro system windows from the main Visual FoxPro window from or a parent, user-defined window.

The following list includes system windows that can be released from the main Visual FoxPro window or from a parent window.

  • Command
  • Data Session (use RELEASE WINDOW "View")
  • Debug
  • Debug Output
  • Document View
  • Locals
  • Trace
  • Watch
  • View

To release a system window and/or a toolbar (in Visual FoxPro), enclose the entire system window or toolbar name in quotation marks. For example, to release the Report Controls toolbar in Visual FoxPro, issue the following command:

RELEASE WINDOW "Report Controls"

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the RELEASE WINDOWS command.

Use ACTIVATE WINDOW to place a system window in the main Visual FoxPro window or in a user-defined window.

See Also

ACTIVATE WINDOW Command | DEFINE WINDOW Command


REMOVE CLASS Command

Removes a class definition from a .vcx visual class library.

REMOVE CLASS ClassName OF ClassLibraryName

Parameters

ClassName
Specifies the name of the class definition to remove from the visual class library.
OF ClassLibraryName
Specifies the name of the .vcx visual class library containing the class definition to remove. If no file extension is included in ClassLibraryName, a .vcx extension is assumed.

Remarks

Exercise care when removing class definitions — the class definition you remove may be a parent class on which other classes are based.

See Also

ADD CLASS Command | CREATE CLASS Command | CREATE CLASSLIB Command | MODIFY CLASS Command | RELEASE CLASSLIB Command | RENAME CLASS Command | SET CLASSLIB Command


REMOVE TABLE Command

Removes a table from the current database.

REMOVE TABLE TableName | ?   [DELETE] [RECYCLE]

Parameters

TableName
Specifies the table to remove from the current database.
?
Displays the Remove dialog box from which you can choose a table in the current database to remove.
DELETE
Specifies that the table is removed from the database and from disk.
Caution Any table deleted from disk with this clause cannot be retrieved. Even if SET SAFETY is ON, you are not warned before the table is deleted from disk.
RECYCLE
Specifies that the table isn't immediately deleted from disk and is placed in the Windows Recycle Bin.

Remarks

When a table is removed from the database, it becomes a free table and can be added to another database. Tables are added to a database with ADD TABLE.

When REMOVE TABLE is issued, all primary indexes, default values, and validation rules associated with the table are also removed. If SET SAFETY is ON, Visual FoxPro displays a prompt asking if you are sure you want to remove the table from the database.

Caution REMOVE TABLE affects other tables in the current database if those tables have rules or relations associated with the table being removed. The rules and relations are no longer valid when the table is removed from the database.

Example

The following example creates two databases named mydbc1 and mydbc2, and a table named table1. The table is added to mydbc1 when it is created. The table is then closed and removed from mydbc1. ADD TABLE is then used to add the table to mydbc2. RENAME TABLE is used to change the name of the table from table1 to table2.

CREATE DATABASE mydbc1
CREATE DATABASE mydbc2
SET DATABASE TO mydbc1
CREATE TABLE table1 (cField1 C(10), n N(10))  && Adds table to mydbc1
CLOSE TABLES     && A table must be closed to remove it from a database
REMOVE TABLE table1
SET DATABASE TO mydbc2
ADD TABLE table1
RENAME TABLE table1 TO table2

See Also

ADD TABLE Command | CLOSE Commands | CREATE DATABASE Command | DROP TABLE Command | FREE TABLE Command | OPEN DATABASE Command


RENAME CLASS Command

Renames a class definition contained in a .VCX visual class library.

RENAME CLASS ClassName1 OF ClassLibraryName TO ClassName2

Parameters

ClassName1
Specifies the name of the class definition that is renamed.
OF ClassLibraryName
Specifies the name of the .vcx visual class library containing the class definition to rename. If you don't specify a file extension in ClassLibraryName, Visual FoxPro automatically assigns a .vcx extension.
TO ClassName2
Specifies the new name of the class definition.

Remarks

Visual FoxPro does not update other class definitions within the visual class library that reference the renamed class definition — be careful when renaming class definitions.

Example

The following example uses CREATE CLASSLIB to create a visual class library named myclslib. A class named myform based on the Visual FoxPro Form base class is created with CREATE CLASS and is stored in the myclslib visual class library. RENAME CLASS is used to change the class name from myform to yourform.

CREATE CLASSLIB myclslib     && Creates a new .VCX visual class library
CREATE CLASS myform OF myclslib AS "Form"  && Creates new class
RENAME CLASS myform OF myclslib TO yourform  && Change class name

See Also

ADD CLASS Command | CREATE CLASS Command | MODIFY CLASS Command | RELEASE CLASSLIB Command | REMOVE CLASS Command | SET CLASSLIB Command


RENAME Command

Changes the name of a file to a new name.

RENAME FileName1 TO FileName2

Parameters

FileName1 TO FileName2
Specifies the file name to change and the new file name. Include a file extension for each file. If the file extensions are not included, the default extension .dbf is assumed. If you rename a free table that has an associated .fpt memo file, be sure to rename the memo file. Include a period (.) after the file name to rename a file that doesn't have an extension.

Do not use RENAME to change the name of a table in a database; RENAME does not change the name of the table in the database. Use RENAME TABLE to change the name of a table in a database.

Include paths with either or both file names if the files are not on the default path. If FileName1 and FileName2 are in different directories or folders, FileName1 is moved into the directory or folder of FileName2.

When you issue RENAME, FileName2 cannot already exist and FileName1 must exist and cannot be open.

FileName1 and FileName2 can contain wildcard characters such as * and ?. For example, to rename all program files with the extension .prg in the current directory or folder to backup files with extension .bak, issue RENAME *.prg TO *.bak.

See Also

COPY FILE Command | COPY TO Command | RENAME CLASS Command | RENAME TABLE Command


RENAME CONNECTION Command

Renames a named connection in the current database.

RENAME CONNECTION ConnectionName1 TO ConnectionName2

Parameters

ConnectionName1
Specifies the name of the connection to be renamed.
ConnectionName2
Specifies the new name of the connection.

Remarks

The database containing the named connection must be opened exclusively and must be current before the connection can be renamed. To open a database for exclusive use, include EXCLUSIVE in OPEN DATABASE.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. The testdata database is opened, and a connection named Myconn1 is created. DISPLAY CONNECTIONS is used to display the named connections in the database.

RENAME CONNECTION is then used to change the newly created connection name to Myconn2. DISPLAY CONNECTIONS is used again to display the connection with its new name. The newly renamed connection is then removed from the database with DELETE CONNECTION.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
CREATE CONNECTION Myconn1 DATASOURCE "MyFoxSQLNT" USERID "<userid>" PASSWORD "<password>"

CLEAR
DISPLAY CONNECTIONS  && Displays named connections in the database
RENAME CONNECTION Myconn1 TO Myconn2
DISPLAY CONNECTIONS  && Displays connection with new name

DELETE CONNECTION Myconn2  && Removes the connection just renamed

See Also

DELETE CONNECTION Command | DBGETPROP( ) Function | DISPLAY CONNECTIONS Command | LIST CONNECTIONS Command | MODIFY CONNECTION Command | OPEN DATABASE Command


RENAME TABLE Command

Renames a table in the current database.

RENAME TABLE TableName1 TO TableName2

Parameters

TableName1
Specifies the name of the table to be renamed.
TableName2
Specifies the new name of the table.

Remarks

You cannot use RENAME TABLE to change the name of a free table; use RENAME instead.

Example

The following example creates two databases named mydbc1 and mydbc2, and a table named table1. The table is added to mydbc1 when it is created. The table is then closed and removed from mydbc1. ADD TABLE is then used to add the table to mydbc2. RENAME TABLE is used to change the name of the table from table1 to table2.

CLOSE DATABASES
CREATE DATABASE mydbc1
CREATE DATABASE mydbc2
SET DATABASE TO mydbc1
CREATE TABLE table1 (cField1 C(10), n N(10))  && Adds table to mydbc1
CLOSE TABLES     && A table must be closed to remove it from a database
REMOVE TABLE table1
SET DATABASE TO mydbc2
ADD TABLE table1
RENAME TABLE table1 TO table2

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | COPY FILE | COPY TO | OPEN DATABASE | RENAME


RENAME VIEW Command

Renames a SQL view in the current database.

RENAME VIEW ViewName1 TO ViewName2

Parameters

ViewName1
Specifies the name of the SQL view to be renamed.
ViewName2
Specifies the new name of the SQL view.

Remarks

The database containing the SQL view must be opened exclusively and must be current before the SQL view can be renamed. To open a database for exclusive use, include EXCLUSIVE in OPEN DATABASE.

Example

The following example opens the testdata database. CREATE SQL VIEW is used to create a local SQL view named myview, which is created from a SELECT - SQL statement that selects all records from the customer table. RENAME VIEW is used to change the name of the view from myview to yourview.

The View Designer is displayed, allowing modify the newly renamed SQL view. After the View Designer is closed, the SQL view is erased.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CREATE SQL VIEW myview AS SELECT * FROM customer  && Create the view
RENAME VIEW myview TO yourview  && Change the view name
MODIFY VIEW yourview  && Open the View designer
DELETE VIEW yourview  && Delete the view

See Also

CREATE SQL VIEW | DELETE VIEW | DISPLAY VIEWS | LIST VIEWS | MODIFY VIEW | OPEN DATABASE | RENAME VIEW | SELECT - SQL | USE


REPLACE Command

Updates table records.

REPLACE FieldName1 WITH eExpression1 [ADDITIVE]
   [, FieldName2 WITH eExpression2 [ADDITIVE]] ... [Scope]
   [FOR lExpression1] [WHILE lExpression2] [IN nWorkArea | cTableAlias]
   [NOOPTIMIZE]

Parameters

FieldName1 WITH eExpression1 [, FieldName2 WITH eExpression2 ... ]
Specifies that the data in FieldName1 be replaced with the value of the expression eExpression1; that the data in FieldName2 be replaced with the value of the expression eExpression2; and so on.

When the expression value is longer than the width of a numeric field, REPLACE forces the value to fit by carrying out the following steps:

  • First, REPLACE truncates decimal places and rounds the remaining decimal portion of the field.
  • If the value still doesn't fit, REPLACE stores the field contents using scientific notation.
  • If the value still doesn't fit, REPLACE replaces the field contents with asterisks.
ADDITIVE
Appends to the end of the memo fields replacements to memo fields. ADDITIVE applies to replacements in memo fields only. If you omit ADDITIVE, the memo field is overwritten with the value of the expression.
Scope
Specifies a range of records to replace. The default scope for REPLACE is the current record (NEXT 1).

Only the records that fall within the range are replaced. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies that the designated fields be replaced only in records for which lExpression1 evaluates to true (.T.). Including FOR makes it possible for you to conditionally replace records, filtering out those you don't want replaced.

Rushmore Query Optimization optimizes REPLACE FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby fields are replaced for as long as the logical expression lExpression2 evaluates to true (.T.).
IN nWorkArea
Specifies the work area of the table in which records are updated.
IN cTableAlias
Specifies the alias of the table in which records are updated.

If you omit nWorkArea and cTableAlias, records are updated in the table in the currently selected work area.

NOOPTIMIZE
Prevents Rushmore optimization.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

REPLACE replaces data in a field with the value in an expression. Fields in unselected work areas must be prefaced with their alias.

Note If the IN clause is omitted, no replacement occurs if the record pointer is at the end of the file in the current work area and you specify a field in another work area.

Example

The following example creates a table with 10 records. REPLACE is used to place random values into a field. MIN( ) and MAX( ) displays the maximum and minimum values in the table.

CLOSE DATABASES
CREATE TABLE Random (cValue N(3))
FOR nItem = 1 TO 10  && Append 10 records,
   APPEND BLANK
   REPLACE cValue WITH 1 + 100 * RAND( )  && Insert random values
ENDFOR

CLEAR
LIST  && Display the values
gnMaximum = 1  && Initialize minimum value
gnMinimum = 100  && Initialize maximum value
SCAN
   gnMinimum = MIN(gnMinimum, cValue)
   gnMaximum = MAX(gnMaximum, cValue)
ENDSCAN
? 'The minimum value is: ', gnMinimum  && Display minimum value
? 'The maximum value is: ', gnMaximum  && Display maximum value

See Also

GATHER | INSERT - SQL | SCATTER


REPLACE FROM ARRAY Command

Updates data in fields with values from a variable array.

REPLACE FROM ARRAY ArrayName [FIELDS FieldList] [Scope]
   [FOR lExpression1] [WHILE lExpression2] [NOOPTIMIZE]

Parameters

ArrayName
Specifies the name of the array whose values replace the field data.
FIELDS FieldList
Specifies that only the fields in FieldList be replaced by the contents of the array. Fields in unselected work areas must be prefaced with their table alias.
Scope
Specifies a range of records to replace with the contents of the array. The default scope for REPLACE FROM ARRAY is the current record (NEXT 1).

Only the records that fall within the range are replaced. Replacement occurs until the end of the scope or the end of the array is reached.

The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies that fields be replaced only in records for which lExpression1 evaluates to true (.T.). Including FOR makes it possible for you to conditionally replace records, filtering out those you don't want. Replacement occurs in each record for which lExpression1 is true (.T.), or until the end of the array is reached.

Rushmore Query Optimization optimizes REPLACE FROM ARRAY FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access .

WHILE lExpression2
Specifies a condition whereby fields in records are replaced by the contents of the array for as long as the logical expression lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Prevents Rushmore optimization.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access .

Remarks

Memo and general fields are ignored in REPLACE FROM ARRAY. To import data into these fields, use GATHER and APPEND GENERAL.

Starting with the first element, the elements of the array replace the corresponding fields of the record. The first array element replaces the first field of the record, the second array element replaces the second field, and so on.

If the array has fewer elements than the table has fields, the additional fields are ignored. If the array has more elements than the table has fields, the additional array elements are ignored.

Note No replacement occurs if the record pointer is at the end of the file in the current work area and you specify a field in another work area.

See Also

APPEND FROM ARRAY | APPEND GENERAL | COPY TO ARRAY | GATHER | REPLACE | SCATTER | SET OPTIMIZE


REPORT Command

Displays or prints a report under the control of a report definition file created with MODIFY REPORT or CREATE REPORT.

REPORT FORM FileName1 | ? [ENVIRONMENT] [Scope] [FOR lExpression1]
   [WHILE lExpression2] [HEADING cHeadingText] [NOCONSOLE]
   [NOOPTIMIZE] [PLAIN] [RANGE nStartPage [, nEndPage]]
   [TO PRINTER [PROMPT] [NODIALOG] | TO FILE FileName2 [ASCII]] [NAME ObjectName]
   [SUMMARY] [NORESET] [NOPAGEEJECT]
   [PREVIEW [[IN] WINDOW WindowName | IN SCREEN] [NOWAIT]]

Parameters

FileName1
Specifies the name of the report definition file to print. Starting with version 7 of Visual FoxPro, this parameter is also reported to the Print Spooler dialog box.
?
Displays the Open dialog box, from which you can choose a report file.
ENVIRONMENT
Included for backward compatibility with 2.x reports. To restore the data environment associated with a Visual FoxPro report, set the data environment AutoOpenTables property to true (.T.), which is the default. To make sure that the report environment is closed when the report has finished printing, set the data environment AutoCloseTables property to true (.T.), which is also the default.

For reports converted from earlier versions of FoxPro, including ENVIRONMENT opens and restores all the tables and relations in the Data Environment even if AutoOpenTables is set to false (.F.).

When you create or modify reports, you can save the current Visual FoxPro data environment with the report definition file. Saving the Visual FoxPro data environment places additional records in the report definition table for all open tables and index files, the index order, and any relationships between the tables.

Scope
Specifies a range of records to include in the report. The default scope for REPORT is ALL records. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. Only the records that fall within the range are included in the report. For more information on scope clauses, see Scope Clauses.
FOR lExpression1
Prints data only in those records for which lExpression1 evaluates to true (.T.). Including FOR makes it possible for you to filter out the records you don't want to print.

Rushmore Query Optimization optimizes REPORT FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access .

WHILE lExpression2
Specifies a condition whereby data is printed for as long as the logical expression lExpression2 evaluates to true (.T.).
HEADING cHeadingText
Specifies text for an additional heading to be placed on each page of the report. The PLAIN clause takes precedence if you include both HEADING and PLAIN.
NOCONSOLE
Suppresses the echoing of a report to the main Visual FoxPro window or to a user-defined window when the report is being printed or sent to a file.
NOOPTIMIZE
To prevent Rushmore optimization of REPORT, include NOOPTIMIZE.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

PLAIN
Specifies that a page heading appears only at the beginning of the report.
RANGE nStartPage [, nEndPage]
Except in preview, specifies a range of pages to print. nStartPage specifies the first page printed; nEndPage specifies the last page printed. If nEndPage is omitted, the last page printed defaults to 32767.
TO PRINTER [PROMPT] [NODIALOG]
Sends a report to the printer.

The optional PROMPT clause displays a printer settings dialog box before printing starts. The printer settings that you can adjust depend on the currently installed printer driver.

The optional NODIALOG clause does not show the run-time print dialog box when a report is being sent to a printer.

TO FILE FileName2 [ASCII]
Specifies the text file to which you send a report. The current printer driver is used when the report is sent to the text file. The file created when you include TO FILE has the default extension .txt.

You can include the optional ASCII clause to create an ASCII text file from the report definition file. Without the ASCII clause, PostScript and other printer codes are written to the text file. Any graphics, lines, rectangles, or rounded rectangles in the report definition do not appear in the ASCII text file.

The number of columns and rows on each page in the ASCII text file is determined by the contents of the _ASCIICOLS and _ASCIIROWS system variables. The default values for _ASCIICOLS and _ASCIIROWS are 80 columns and 63 rows respectively. These values correspond to a standard portrait page.

NAME ObjectName
Specifies an object variable name for the data environment of a report. The data environment and the objects in the data environment have properties and methods, for example AddObject, that need to be set or called at run time. The object variable provides access to these properties and methods. If you don't specify a NAME, Visual FoxPro uses as a default the name of the report file that can be referenced in the code associated with the events.
SUMMARY
Suppresses detail line printing. Only totals and subtotals are printed.
NORESET
Specifies that the _PAGENO and _PAGETOTAL system variables are not reset. The page count for the current report begins at the current values of these two variables.

If you use the NORESET and RANGE keywords together, you must calculate beforehand which pages to print.

NOPAGEEJECT
Specifies that Visual FoxPro does not force a sheet eject at the end of a report and leaves the print job open. The next report printed is added to the open print job.

You can use NOPAGEEJECT to set up duplex printing, that is, printing on the reverse side of a previous report. You can also chain multiple reports and have page numbers continue from one report to the next, which is useful for tasks such as faxing reports.

Note You must make sure that the last report run does not have a NOPAGEEJECT clause so the print job can be closed. NOPAGEEJECT is valid only in a program (.prg) and is disregarded when issued in the Command window.

Changing between page orientations, such as landscape to portrait, between reports is not supported.

The REPORT command still allows a NOEJECT keyword, which Visual FoxPro no longer supports but was used in older DOS versions of FoxPro and FoxBASE+.

PREVIEW [[IN] WINDOW WindowName | IN SCREEN]
Displays the report in page preview mode instead of sending the report to the printer. To print a report, you must issue REPORT with TO PRINTER.

System variables are ignored when you include PREVIEW.

You can include the optional WINDOW or IN WINDOW clause to specify a window in which the report is previewed. WindowName can be the name of a window created with DEFINE WINDOW. If you include the WINDOW clause, the preview assumes the characteristics (title, size, and so on) of the window you specify with WindowName. If you include the IN WINDOW clause, the report is previewed in the window you specify with WindowName.

You can include the optional IN SCREEN clause to specify that the report preview window is contained in the main Visual FoxPro window and cannot be moved outside it.

You can include the optional NOWAIT clause so that at run time Visual FoxPro does not wait for the page preview window to be closed before continuing program execution. Instead, Visual FoxPro continues program execution while the page preview window is open.

In a distributed application, be sure that the View menu is available. If the Print Preview toolbar is closed, it cannot be restored unless the View menu is available.

Remarks

The .frx file extension is the default extension for a report definition file. If the report definition file is not in the default directory or folder, you must include file name with the path.

Examples

Example 1

The following example shows how you can direct a batch report print job to a file.

REPORT FORM customer.frx TO FILE custorder.txt ASCII
REPORT FORM orders.frx TO TO FILE temp1.txt ASCII NORESET
STRTOFILE(FILETOSTR("temp1.txt"),"custorder.txt",1)

Example 2

The following example shows how to run a batch report print job with two reports. Visual FoxPro runs through the set of reports twice to obtain a total page count, which is stored in the _PAGETOTAL system variable for enabling Page X of Y numbering. Both reports contain also have _PAGETOTAL system variables.

Using the NOCONSOLE keyword without the TO PRINT keyword enables a quick run through the report without producing output in order to obtain page counts. NORESET specifies that page numbers continue printing with the next report. NOPAGEEJECT specifies that the first page of the second report continue printing on the reverse side of the last page of the first report. The lnPageTotal variable is later used to display the page number.

REPORT FORM myReport1.frx NOCONSOLE NOPAGEEJECT
REPORT FORM myReport2.frx NOCONSOLE NORESET
lnPageTotal = _PAGETOTAL
REPORT FORM myReport1.frx TO PRINTER NOPAGEEJECT
REPORT FORM myReport2.frx TO PRINTER NORESET

Example 3

The following example shows how you can view a preview before sending the report to a printer.

REPORT FORM myReport1.frx TO PRINTER PROMPT NODIALOG PREVIEW

See Also

_ASCIICOLS | _ASCIIROWS | CREATE REPORT | DataEnvironment Object | MODIFY REPORT | _PAGENO System Variable | _PAGETOTAL System Variable


RESTORE FROM Command

Retrieves variables and variable arrays saved in a variable file or a memo field and places them into memory.

RESTORE FROM FileName | MEMO MemoFieldName   [ADDITIVE]

Parameters

FileName
Specifies the variable file from which the variables and arrays are restored. Variable files are assigned a .mem extension.
MEMO MemoFieldName
Specifies the memo field from which variables and arrays are restored.
ADDITIVE
Prevents any variables or arrays currently in memory from being erased. If the number of variables or arrays being added with ADDITIVE plus the number of existing variables exceeds the variable limit, Microsoft Visual FoxPro brings as many variables and arrays as possible into memory from the variable file or memo field.

If you restore a variable or array that has the same name as an existing variable or array, the value in the existing variable or array is overwritten with the value of the restored variable or array.

Remarks

When RESTORE FROM is issued in a program, all PUBLIC and PRIVATE variables and arrays are restored as PRIVATE; all LOCAL variables and arrays are restored as LOCAL. If RESTORE is issued in the Command window, PUBLIC and PRIVATE variables and arrays are restored as PUBLIC; LOCAL variables and arrays are restored as LOCAL.

RESTORE FROM clears any variables or arrays currently in memory unless you include the ADDITIVE keyword. RESTORE FROM does not affect system variables.

Note that object type variables cannot be restored from a variable file or memo field.

Example

In the following example, two variables are created. They are saved to a variable file and restored without clearing the existing variables.

gnVal1 = 50
gcVal2 = 'Hello'
SAVE TO temp
CLEAR MEMORY

gdVal3 = DATE( )
RESTORE FROM temp ADDITIVE
CLEAR
DISPLAY MEMORY LIKE g*

See Also

DIMENSION | PUBLIC | PRIVATE | RELEASE | SAVE TO | STORE


RESTORE MACROS Command

Restores to memory keyboard macros saved in a keyboard macro file or memo field.

RESTORE MACROS   [FROM FileName | FROM MEMO MemoFieldName]

Parameters

FROM FileName
Specifies the macro file from which macros are restored. Macro files have an .fky extension, and this extension is assumed if you don't specify one. If you have assigned a different extension to the file, you must include this extension in FileName.
FROM MEMO MemoFieldName
Specifies the memo field from which macros are restored.

Remarks

Use SAVE MACRO to store keyboard macros to a keyboard macro file or a memo field.

By default, restoring macros from a file or memo field is additive — the restored macros are appended to the existing set of macros in memory. If a macro name in the file or memo field is the same as an existing macro name, the macro in the file or memo field overwrites the existing macro.

If issued without a file name or memo field name, RESTORE MACROS clears all macros from memory and restores the default macros. The default macros are restored from the keyboard macro file named Default.fky. If Default.fky cannot be found, Visual FoxPro restores the F2 through F9 keys to the standard Visual FoxPro startup settings.

See Also

CLEAR | PLAY MACRO | SAVE MACROS


RESTORE SCREEN Command

Restores the main Visual FoxPro window or a user-defined window previously saved to the screen buffer, a variable, or an array element.

RESTORE SCREEN   [FROM VarName]

Parameters

FROM VarName
Specifies the name of a variable or array element from which you want to restore the screen or window image.

Remarks

Use SAVE SCREEN to place the current main Visual FoxPro window or active user-defined window in the screen buffer, a variable, or an array element.

Variables or array elements containing stored screen or window images have an S data type when you view the variables or array elements with DISPLAY or LIST MEMORY. The main Visual FoxPro window or user-defined windows saved to variables or array elements can also be saved to and restored from variable files with SAVE TO and RESTORE FROM.

If issued without the FROM clause, RESTORE SCREEN restores the main Visual FoxPro window or user-defined window from the screen buffer.

See Also

RESTORE FROM | SAVE SCREEN | SAVE TO


RESTORE WINDOW Command

Restores to memory window definitions and window statuses saved to a window file or memo field.

RESTORE WINDOW WindowNameList | ALL FROM FileName
 | FROM MEMO MemoFieldName

Parameters

WindowNameList
Specifies one or more windows to be restored. Separate the window names with commas.
ALL
Restores all window definitions in the window file or memo field.
FROM FileName
Specifies the window file from which windows are restored. A window file has a .win extension. If the file was given another extension when it was saved, you must include this extension in FileName.
FROM MEMO MemoFieldName
Specifies the memo field from which the windows are restored.

Remarks

Use SAVE WINDOW to store window definitions in a window file or in a memo field.

Any windows in memory with the same names as those restored are overwritten. A window's status (hidden, active, and so on) when it is saved is preserved when it is restored.

Example

In the following example, a window named wOutput1 is defined and saved to a variable. All windows are cleared and the window named wOutput1 is restored and activated.

CLEAR
DEFINE WINDOW wOutput1 FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
SAVE WINDOW wOutput1 TO temp
CLEAR WINDOWS
RESTORE WINDOW wOutput1 FROM temp
ACTIVATE WINDOW wOutput1
WAIT "The window wOutput1 has been restored" WINDOW
RELEASE WINDOW wOutput1

See Also

ACTIVATE WINDOW | DEFINE WINDOW | SAVE WINDOWS


RESUME Command

Continues execution of a suspended program.

RESUME

Remarks

Use SUSPEND to suspend program execution. The suspended program restarts at the line where execution was suspended.

SUSPEND and RESUME are valuable debugging tools. You can suspend a program to examine the current status of the Visual FoxPro environment, including memory variables, window, menu bar, or menu definitions.

Caution To prevent commands that are executed when a program is suspended from interfering with subsequent program output, issue CLEAR to clear the main Visual FoxPro window or the active user-defined window before you resume program execution.

See Also

CANCEL | CLEAR | RETURN | SUSPEND


RETRY Command

Executes the last command from the memory stack and then returns control to the calling program. RETRY is similar to RETURN, except RETURN executes the next line in the calling program.

RETRY

Remarks

RETRY is useful in error-handling routines. It is frequently used to execute a command until a record- or file-locking function succeeds in locking the record or file. You can use SET REPROCESS to control retries of a record- or file-locking function. SET REPROCESS is preferable in most network situations.

See Also

ON ERROR | RETURN | SET REPROCESS


RETURN Command

Returns program control to a calling program.

RETURN [eExpression | TO MASTER | TO ProcedureName]

Parameters

eExpression
Specifies an expression returned to the calling program. If you omit RETURN or the return expression, true (.T.) is automatically returned to the calling program.
TO MASTER
Returns control to the highest-level calling program.
TO ProcedureName
Specifies the procedure to which control is returned.

Remarks

RETURN terminates execution of a program, procedure, or function and returns control to the calling program, the highest-level calling program, another program, or the Command window.

Visual FoxPro releases PRIVATE variables when RETURN is executed.

RETURN is usually placed at the end of a program, procedure, or function to return control to a higher-level program. However, an implicit RETURN is executed if you omit RETURN.

Example

In the following example, the function longdate returns a character string that is suitable for printing from a date.

SET CENTURY ON
? longdate({^1998-02-16})  && Displays Monday, February 16, 1998

FUNCTION longdate
PARAMETER mdate
RETURN CDOW(mdate) + ', ' + MDY(mdate)

See Also

DO | FUNCTION | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PRIVATE | PROCEDURE | PUBLIC


ROLLBACK Command

Cancels any changes made during the current transaction.

ROLLBACK

Remarks

ROLLBACK restores the original tables, table memo files, and index files to the state they were in before the transaction began.

When you modify records in a database that is part of a transaction, other users on the network do not have access (read or write) to the records until you end the transaction.

When other users on the network try to access records you have modified, they must wait until you end your transaction. They receive the message "Record not available ... please wait" until the records become available. Because of this, it is important to keep the length of the transaction to a minimum or conduct the transaction during times when others do not need access.

ROLLBACK undoes any changes made during the current transaction. If the transaction is nested, only the modifications made since the previous BEGIN TRANSACTION are undone. Program execution continues with the next statement.

If any record or file locks were placed, they are released.

Example

In the following example, the customer table in the testdata database is opened. Optimistic table buffering is set for the customer table. The contents of the cust_id and company fields are displayed, and then the contents of the company field are replaced within the buffered data.

BEGIN TRANSACTION is issued to start a transaction. A TABLEUPDATE is used to write the changes to the table. The new contents are displayed, and ROLLBACK is issued to restore the original contents of the company field. The cust_id and company fields are displayed again with the company field containing its original values.

CLOSE DATABASES
CLEAR

* Transactions are only supported within a DBC
OPEN DATABASE (HOME(2) + 'Data\testdata')

SET MULTILOCKS ON      && Required for buffering

USE customer
=CURSORSETPROP("Buffering",5)
? 'The original company field'
LIST FIELDS cust_id, company NEXT 5
REPLACE ALL company WITH "***" && Change field contents

BEGIN TRANSACTION
   =TABLEUPDATE(.T.)
   GO TOP
   ? 'The modified company field'
   LIST FIELDS cust_id, company NEXT 5
ROLLBACK           && Restore original field contents

=TABLEREVERT(.T.)
GO TOP
? 'The restored company field'
LIST FIELDS cust_id, company NEXT 5

See Also

BEGIN TRANSACTION | END TRANSACTION | TXNLEVEL( )


RUN | ! Command

Executes external operating commands or programs.

RUN [/N] MS-DOSCommand | ProgramName

-or-

! [/N] MS-DOSCommand | ProgramName

Parameters

MS-DOSCommand
Specifies the MS-DOS command to execute. See your MS-DOS documentation for more information about available MS-DOS commands.
ProgramName
Specifies the program or application to run. You can specify a Windows-based or an MS-DOS-based program or application.
/N
Specifies NOWAIT. Include the letter N to execute another Windows-based application.

Remarks

You can issue RUN from within the Command window or from within a program.

Note To use RUN, you must have the operating system file Command.com in the current directory, or it must be located where the MS-DOS COMSPEC parameter can find it. For more information on COMSPEC, see your MS-DOS documentation.
Caution Do not use RUN to run disk reorganization programs such as CHKDSK from within Visual FoxPro. These programs modify the contents of your disk in a manner that may prevent Visual FoxPro from operating properly.

RUN and Visual FoxPro When RUN is used to run programs outside of Visual FoxPro, it searches for programs in a slightly different manner from FoxPro for MS-DOS.

If the program you specify in RUN doesn't have an extension, Visual FoxPro first look along the MS-DOS path for a Program Information File (PIF) with the name you specify. A PIF lets you run a non-Windows program under Windows. You can specify parameters for the program, whether the program is run in a window or on the full screen, the amount of memory allocated for the program, and so on.

If the PIF is found, the program specified in the PIF is executed with the PIF parameters. If a PIF isn't found, the MS-DOS path is then searched for an executable file with the name you specify.

When a PIF isn't found, Visual FoxPro uses FOXRUN.PIF, a PIF installed in the Visual FoxPro directory. FOXRUN.PIF is configured to run the program in a window. You can modify FOXRUN.PIF to run programs in another configuration.

Windows 2000 logo Certification If you plan to submit your application for certification, you should not use the RUN command, because it can potentially violate the following System Group Policy requirement.

"RUN only allowed Windows application - your application must not start any application that is not on this list. Note this does not apply when launching applications through COM. If you use ShellExecuteEx, Windows 2000 will perform this check automatically."

Instead, you should use DECLARE DLL with ShellExecuteEx.API.

FOXRUN.PIF Foxrun.pif allows you to execute MS-DOS® and Windows® programs and commands from within Visual FoxPro. Foxrun.pif must be in the same directory as Vfp8.exe in Visual FoxPro.

/N means NOWAIT. Include the letter N to execute another Windows-based application. For example, the following statement opens the Windows Character Map accessory:

! /N CHARMAP.EXE

The following example opens the Windows color picker from the Windows Control Panel:

! /N CONTROL COLOR

A Windows-based application executed with RUN /N or ! /N behaves the same way the application does when you open it through the Windows Explorer or by selecting Run from the Start menu. You can switch between the application and Visual FoxPro or FoxPro for Windows using the standard Windows operations.

You can include an optional numeric value immediately after /N to specify how the Windows-based application is opened. Do not include any spaces between /N and the numeric value. The following table lists the numeric value you can include and describes the state of the Windows-based application when opened.

Value | Application attributes
1 | Active and normal size
2 | Active and minimized
3 | Active and maximized
4 | Inactive and normal size
7 | Inactive and minimized

Running MS-DOS Programs in Visual FoxPro By default, Foxrun.pif runs the specified external MS-DOS program in a window. While the MS-DOS program or command is running, the title of the window is FoxPro Run Command. In Visual FoxPro, the FoxPro Run Command window is closed after the external program or command is finished executing.

You can use the Windows PIF editor to customize Foxrun.pif. You can edit the PIF to specify if the Inactive FoxPro Run Command window is left open or is closed (the default in Visual FoxPro) with the Close Window on Exit check box. You can also open external programs in a full screen by selecting Full Screen; allocate memory for the program; and so on.

Memory Considerations By default, Foxrun.pif allocates a minimum of 256K of memory for running an external command or program. If you do not have 256K of free conventional memory, Visual FoxPro displays an error message. To correct this, try one or both of the following:

  • Close applications and files to free up additional memory.
  • Edit Foxrun.pif to reduce the amount of memory required in the KB Required text box.

If the external command requires more than 256K, MS-DOS displays an error message in the FoxPro Run Command window. To correct this, edit your Foxrun.pif to increase the amount of memory required in the KB Required text box.

See Also

GETENV( ) | _SHELL System Variable


SAVE MACROS Command

Saves a set of keyboard macros to a keyboard macro file or to a memo field.

SAVE MACROS TO FileName | TO MEMO MemoFieldName

Parameters

TO FileName
Specifies the file to which the macros are saved. Keyboard macro file names can contain a maximum of eight characters and must begin with a letter or an underscore; they cannot begin with a number. The subsequent characters can be any combination of letters, numbers, and underscores. The file is assigned an .fky extension. If you assign an extension other than .fky, you must include that extension in RESTORE MACROS.
TO MEMO MemoFieldName
Specifies the memo field to which the macros are saved. The table containing the memo field must be open; however, it does not have to be in the selected work area. To save macros to a table in another work area, include the table's alias when specifying the memo field.

Remarks

When you quit Visual FoxPro, the macros you have created are lost unless you use SAVE MACROS to store them to a keyboard macro file or to a memo field.

Example

The following example saves the current set of macros to a file called Mymacros.fky.

SAVE MACROS TO mymacros

See Also

CLEAR | PLAY MACRO | RESTORE MACROS


SAVE SCREEN Command

Saves an image of the main Visual FoxPro window or an active user-defined window to the screen buffer, a variable, or an array element.

SAVE SCREEN [TO VarName]

Parameters

TO VarName
Specifies the variable or array element to which the screen or window image is saved.

Remarks

Use RESTORE SCREEN to redisplay images saved to the screen buffer, a variable, or an array element.

Variables or array elements containing an image of the main Visual FoxPro window or user-defined window have an S data type when you view the variables or array elements with DISPLAY or LIST MEMORY.

If issued without the TO VarName clause, SAVE SCREEN saves the main Visual FoxPro window or user-defined window to the screen buffer.

See Also

RESTORE FROM | RESTORE SCREEN | SAVE TO


SAVE TO Command

Stores current variables and arrays to a variable file or memo field.

SAVE TO FileName | MEMO MemoFieldName
   [ALL LIKE Skeleton | ALL EXCEPT Skeleton]

Parameters

FileName
Specifies the variable file in which the variables and arrays are saved. The default extension for a variable file is .mem.
MEMO MemoFieldName
Specifies the memo field in which the variables and arrays are saved.
ALL LIKE Skeleton
Specifies that all variables and arrays, which match the specified Skeleton, be saved. The skeleton can include the question mark (?) and asterisk (*) wildcards.
ALL EXCEPT Skeleton
Specifies that all variables and arrays except those that match the specified Skeleton be saved. The skeleton can include the question mark (?) and asterisk (*) wildcards.

Remarks

Use RESTORE FROM to place variables and arrays back into memory from a variable file or memo field. Note that object type variables cannot be saved to a variable file or memo field.

The variable file or memo field is marked with the current code page.

Example

In the following example, two variables are created. They are saved to a variable file and restored without clearing the existing variables.

gnVal1 = 50
gcVal2 = 'Hello'
SAVE TO temp
CLEAR MEMORY

gdVal3 = DATE( )
RESTORE FROM temp ADDITIVE
CLEAR
DISPLAY MEMORY LIKE g*

See Also

PRIVATE | PUBLIC | RELEASE | RESTORE FROM


SAVE WINDOWS Command

Saves all or specified window definitions to a window file or memo field.

SAVE WINDOWS WindowNameList | ALL TO FileName | TO MEMO MemoFieldName

Parameters

WindowNameList
Specifies one or more windows to be saved. Separate the window names with commas.
ALL
Saves all window definitions to the window file or memo field.
TO FileName
Specifies the window file to which the window definitions are saved.

If you don't specify an extension when naming the file, the default extension of .win is assigned. If you specify another extension when you save the window definitions to a file, you must include the extension when you restore the window definitions from the file.

TO MEMO MemoFieldName
Specifies the memo field to which the window definitions are saved. The table containing the memo field must be open; however, it does not have to be in the currently selected work area. To save window definitions to a table in another work area, include the table's alias when specifying the memo field.

Remarks

Use RESTORE WINDOW to restore window definitions from a window file or memo field. The status of each window is also saved. For example, if a window is hidden when it is saved to a file or memo field, it remains hidden when it is restored.

Example

In the following example, a window named wOutput1 is created, and the window definition is saved to the file Temp.win. All windows are cleared and wOutput1 is restored from the file and activated.

CLEAR
DEFINE WINDOW wOutput1 FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
ACTIVATE WINDOW wOutput1
@ 1,1 SAY 'This is the contents of the window'
SAVE WINDOWS wOutput1 TO temp
CLEAR WINDOWS
WAIT WINDOW 'The window has been saved - Press a key'

RESTORE WINDOW wOutput1 FROM temp
ACTIVATE WINDOW wOutput1
WAIT WINDOW 'The window has been restored - Press a key'

DEACTIVATE WINDOW wOutput1
RELEASE WINDOW wOutput1
DELETE FILE temp.win

See Also

DEFINE WINDOW | RESTORE SCREEN | RESTORE WINDOW | SAVE SCREEN


SCAN ... ENDSCAN Command

Moves the record pointer through the currently selected table and executes a block of commands for each record that meets the specified conditions.

SCAN [NOOPTIMIZE] [Scope] [FOR lExpression1] [WHILE lExpression2]
   [Commands]
   [LOOP]
   [EXIT]
ENDSCAN

Parameters

NOOPTIMIZE
Prevents Rushmore Query Optimization of SCAN.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Scope
Specifies a range of records to be scanned. Only the records within the range are scanned. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see the Scope Clauses online topic.

The default scope for SCAN is all records (ALL).

FOR lExpression1
Executes commands only for records for which lExpression1 evaluates to true (.T.). Including the FOR clause lets you filter out records you don't want scanned.

Rushmore optimizes a query created with SCAN ... FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby the commands are executed for as long as lExpression2 evaluates to true (.T.).
Commands
Specifies the Visual FoxPro commands to be executed.
LOOP
Returns control directly back to SCAN. LOOP can be placed anywhere between SCAN and ENDSCAN.
EXIT
Transfers program control from within the SCAN ... ENDSCAN loop to the first command following ENDSCAN. EXIT can be placed anywhere between SCAN and ENDSCAN.
ENDSCAN
Indicates the end of the SCAN procedure.

Remarks

SCAN automatically advances the record pointer to the next record that meets the specified conditions and executes the block of commands.

You can place comments after ENDSCAN on the same line. The comments are ignored during program compilation and execution.

SCAN ... ENDSCAN ensures that, upon reaching ENDSCAN, Visual FoxPro reselects the table that was current when the SCAN ... ENDSCAN loop began.

Example

The following example uses a SCAN ... ENDSCAN loop to display all the companies in Sweden.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
CLEAR

SCAN FOR UPPER(country) = 'SWEDEN'
   ? contact, company, city
ENDSCAN

See Also

DO CASE ... ENDCASE | DO WHILE ... ENDDO | FOR EACH ... ENDFOR | FOR ... ENDFOR


SCATTER Command

Copies data from the current record to a set of variables or to an array.

SCATTER and COPY TO ARRAY behave similarly. SCATTER copies only a single and current record into an array or a set of variables and automatically creates the array or variables if they do not already exist. COPY TO ARRAY copies multiple records into an array. For more information, see COPY TO ARRAY Command.

To copy variables or array elements to table records, use the GATHER Command.

SCATTER [FIELDS FieldNameList | FIELDS LIKE Skeleton
   | FIELDS EXCEPT Skeleton] [MEMO]
   TO ArrayName | TO ArrayName BLANK | MEMVAR | MEMVAR BLANK
   | NAME ObjectName [BLANK] [ADDITIVE]

Parameters

FIELDS FieldNameList
Specifies the fields whose values are to be copied to the variables or the array.

SCATTER disregards memo fields by default; however, you can include memo fields in the field list by following the field list with the MEMO keyword. However, SCATTER disregards general fields even when you include the MEMO keyword.

Omitting FIELDS FieldNameList copies values from all fields.

FIELDS LIKE Skeleton | FIELDS EXCEPT Skeleton
Copies fields matching or excluding Skeleton to variables or an array. You can include the LIKE or EXCEPT clause or both.

To copy values of fields matching Skeleton to variables or an array, use LIKE Skeleton. To copy values of all fields except those matching Skeleton to variables or an array, use EXCEPT Skeleton. Skeleton supports wildcard characters. For example, to copy the values from all fields that begin with the letters A and P to variables or an array, use the following lines of code:

SCATTER FIELDS LIKE A*,P* TO myArray

The LIKE clause can be combined with the EXCEPT clause:

SCATTER FIELDS LIKE A*,P* EXCEPT PARTNO* TO myArray
MEMO
Specifies that the field list include one or more memo fields.
Note Your computer must have sufficient memory to scatter large memo fields to variables or to an array. Visual FoxPro generates an error message if your computer lacks sufficient memory. SCATTER does not copy data from a memo field if it is too large to fit in memory nor does it copy from any additional memo fields in the field list. If SCATTER does not succeed for a memo field, the value of the variable or array element is set to False (.F.).
TO ArrayName
Specifies an array to which the record contents are copied. Starting with the first field, SCATTER copies the contents of each field into each element of the array in sequential order.

If the array you specify contains more elements than the number of fields, the extra array elements remain unchanged. SCATTER automatically creates a new array if the array does not already exist, or if it contains fewer elements than the number of fields. The array elements have the same size and data types as the corresponding fields.

TO ArrayName BLANK
Creates an array with empty elements, which are the same size and type as the fields in the table.
MEMVAR
Scatters the data to a set of variables instead of an array. SCATTER creates one variable for each field in the table and fills each variable with data from the corresponding field in the current record, assigning to the variable the same name, size, and type as its field.

SCATTER creates a variable for each field in the field list if a field list is included.

To reference a variable that has the same name as a field in the current table, preface the variable name with the m. qualifier.

Caution Do not include the word TO with MEMVAR. Visual FoxPro creates an array named MEMVAR if you include the word TO.
MEMVAR BLANK
Creates a set of empty variables. Each variable is assigned the same name, data type, and size as its field. If a field list is included, a variable is created for each field in the field list.
NAME ObjectName [BLANK] [ADDITIVE]
Creates an object whose properties have the same names as fields in the table.

To copy the value of each field in the table to each object property, do not include the BLANK keyword. To leave the properties empty, include the BLANK keyword. For a description of what the empty properties contain, based on the corresponding field type, see EMPTY( ) Function. Properties are not created for general fields that exist in the table.

To update the property values of an existing and valid Visual FoxPro object specified by ObjectName, but not COM objects, with values from the current record, include the ADDITIVE keyword. If the object does not exist, Visual FoxPro creates the object automatically. You cannot use the ADDITIVE keyword without the NAME clause. Doing so generates an error.

Using BLANK with ADDITIVE omits the values for existing properties that have matching field names.

Remarks

If properties corresponding to field names do not exist for the object, SCATTER...NAME ADDITIVE automatically creates them. However, SCATTER might not create all the necessary properties because some might be marked as Hidden or Protected. If Visual FoxPro cannot create or set a property, it generates an error. For example, you can have a field name that matches a native Visual FoxPro object property name as long as the field and property data types are the same. However, Visual FoxPro generates an error if the field name matches a method, event, or object name.

You can avoid problems by using an object created by SCATTER...NAME and not one derived from a Visual FoxPro class. Unlike when SCATTER is used with only NAME, Visual FoxPro does not overwrite the existing object to create a new object.

SCATTER...NAME ADDITIVE does not generate an error when a read-only property cannot be set for a field in the table. However, the value of the property remains unchanged.

To reference a property in an object that has the same name as an open table, preface the property name with the m. qualifier. The following example displays the value of the Company field in the Customer table followed by the value of the Company property for the Customer object:

USE Customer
SCATTER NAME Customer
? Customer.Company  && Returns the table value
? m.Customer.Company  && Returns the object property value

Examples

Example 1

This example uses SCATTER to create a set of variables based on the fields in the test table. Each field is then assigned a value and a new blank record is added to the table. The data is copied to the table using the GATHER command.

CREATE TABLE Test FREE ;
   (Object C(10), Color C(16), SqFt n(6,2))

SCATTER MEMVAR BLANK
m.Object="Box"
m.Color="Red"
m.SqFt=12.5
APPEND BLANK
GATHER MEMVAR
BROWSE

Example 2

This example uses SCATTER along with the NAME clause to create an object with properties based on the fields in the table. The object's properties are then assigned values and a new blank record is added to the table. The data is copied to the new record using GATHER with the NAME clause.

CREATE TABLE Test FREE ;
   (Object C(10), Color C(16), SqFt n(6,2))

SCATTER NAME oTest BLANK
oTest.Object="Box"
oTest.Color="Red"
oTest.SqFt=12.5
APPEND BLANK
GATHER NAME oTest
RELEASE oTest
BROWSE

Example 3

Suppose you have two or more tables or cursors and wish to create an object that combines the data from those cursors. The following example selects the Customer table and uses SCATTER...NAME to create the oCustomer object and its properties from fields in the Customer table. SCATTER...NAME...ADDITIVE then updates the values from the ReportDate and Rating fields in the CreditHistory table and the CookieText and SessionId fields in the MySessionTable table in the oCustomer object or creates those properties if they do not exist.

SELECT Customer
SCATTER NAME oCustomer
SELECT CreditHistory
SCATTER FIELDS ReportDate, Rating NAME oCustomer ADDITIVE
SELECT MySessionTable
SCATTER FIELDS CookieText, SessionId NAME oCustomer ADDITIVE

See Also

ALINES( ) | APPEND FROM ARRAY | DECLARE | DIMENSION


SCROLL Command

Scrolls an area of the main Visual FoxPro window or a user-defined window up, down, left, or right.

SCROLL nRow1, nColumn1, nRow2, nColumn2, nRowsScrolled
    [, nColumnsScrolled]

Parameters

nRow1, nColumn1, nRow2, nColumn2
Specifies the rectangular region where scrolling occurs in the main Visual FoxPro window or in the active user-defined window. nRow1, nColumn1 specifies the upper-left corner of the region, and nRow2, nColumn2 specifies the lower-right corner.
nRowsScrolled
Specifies the number of rows up or down to scroll inside the rectangular region. If the numeric expression nRowsScrolled is positive, Visual FoxPro scrolls up the number of rows. If nRowsScrolled is negative, Visual FoxPro scrolls down the number of rows. If nRowsScrolled is 0 and you omit nColumnsScrolled, Visual FoxPro clears the rectangular region.
nColumnsScrolled
Specifies the number of columns left or right to scroll inside the rectangular region. If the numeric expression nColumnsScrolled is positive, Visual FoxPro scrolls to the right the number of columns. If nColumnsScrolled is negative, Visual FoxPro scrolls to the left the number of columns. If you include both nRowsScrolled and nColumnsScrolled, Visual FoxPro scrolls the area diagonally.

Example

The following command scrolls a small rectangular region:

CLEAR
@ 4, 1 FILL TO 10, 8 COLOR GR+/B
WAIT WINDOW 'Press key to scroll left top corner'
SCROLL 0, 0, 5, 5, -2, 1

See Also

MOVE WINDOW | ScrollBars Property | @ ... SCROLL Command


SEEK Command

Searches a table for the first occurrence of a record whose index key matches a general expression, then moves the record pointer to the matching record.

SEEK eExpression   [ORDER nIndexNumber | IDXIndexFileName
    | [TAG] TagName [OF CDXFileName]    [ASCENDING | DESCENDING]]
   [IN nWorkArea | cTableAlias]

Parameters

eExpression
Specifies the index key for which SEEK searches. eExpression can be null.
ORDER nIndexNumber
Specifies the number of the index file or tag that is used to search for the index key. nIndexNumber refers to the index files as they are listed in USE or SET INDEX. Open .idx files are numbered first in the order in which they appear in USE or SET INDEX. Tags in the structural .cdx file (if one exists) are then numbered in the order in which they were created. Finally, tags in any open independent .cdx files are numbered in the order in which they were created. See SET ORDER for more information about index numbering.
ORDER IDXIndexFileName
Specifies an .idx file that is used to search for the index key.
ORDER [TAG] TagName [OF CDXFileName]
Specifies a tag of a .cdx file that is used to search for the index key. The tag name can be from a structural .cdx file or any open independent .cdx file.

If identical tag names exist in open independent .cdx files, use OF CDXFileName to specify the .cdx file containing the tag.

Note The .idx file takes precedence if duplicate .idx file and tag names exist.
ASCENDING
Specifies that the table is searched in ascending order.
DESCENDING
Specifies that the table is searched in descending order.
IN nWorkArea
Specifies the work area number of the table that is searched.
IN cTableAlias
Specifies the alias of the table that is searched.

If you omit IN nWorkArea and IN cTableAlias, the table in the currently selected work area is searched.

Remarks

You can use SEEK only with indexed tables, and you can search only on the index key. The match must be exact unless SET EXACT is set to OFF.

If SEEK finds a record with a matching index key, RECNO( ) returns the record number of the matching record, FOUND( ) returns true (.T.), and EOF( ) returns false (.F.).

If a matching key isn't found, RECNO( ) returns the number of records in the table plus 1, FOUND( ) returns false (.F.), and EOF( ) returns true (.T.).

If SET NEAR is on, the record pointer is positioned immediately after the record with the closest index key. If SET NEAR is off, the record pointer is positioned at the end of the file. In either case, RECNO() returns the record number of the closest record.

Example

In the following example, customer is opened and indexed on the company field. SEEK is used to find the index key expression that matches the value contained in the variable gcSeekVal.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer ORDER company  && Opens Customer table

SET EXACT OFF
STORE 'B' TO gcSeekVal
SEEK gcSeekVal

IF FOUND( )
   DISPLAY FIELDS company, contact
ENDIF

See Also

EOF( ) | FOUND( ) | INDEX | INDEXSEEK( ) | LOCATE | RECNO( ) | SEEK( ) | SET EXACT | SET NEAR


SELECT - SQL Command

Retrieves data from one or more tables. The SELECT SQL command is built into Visual FoxPro like any other Visual FoxPro command. When you use SELECT to pose a query, Visual FoxPro interprets the query and retrieves the specified data from the tables. You can create a SELECT query from within the following:

  • Command window
  • Visual FoxPro program as with any other Visual FoxPro command
  • Query Designer
SELECT [ALL | DISTINCT] [TOP nExpr [PERCENT]] [Alias.] Select_Item
   [[AS] Column_Name] [, [Alias.] Select_Item [[AS] Column_Name] ...]
   FROM [FORCE] [DatabaseName!] Table [[AS] Local_Alias]
   [ [INNER | LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER] JOIN DatabaseName!]
      Table [[AS] Local_Alias] [ON JoinCondition ...]
      [[INTO Destination] | [TO FILE FileName [ADDITIVE] | TO PRINTER [PROMPT] | TO SCREEN]]
      [PREFERENCE PreferenceName] [NOCONSOLE] [PLAIN] [NOWAIT]
      [WHERE JoinCondition [AND JoinCondition ...] [AND | OR FilterCondition [AND | OR FilterCondition ...]]]
   [GROUP BY GroupColumn [, GroupColumn ...]] [HAVING FilterCondition] [UNION [ALL] SELECTCommand]
   [ORDER BY Order_Item [ASC | DESC] [, Order_Item [ASC | DESC] ...]]

Parameters

SELECT
Specifies the fields, constants, and expressions displayed in the query results.
ALL
Displays all the rows in the query results by default.
DISTINCT
Excludes duplicates of any rows from the query results. You can use DISTINCT only once per SELECT clause.

Visual FoxPro does not support using the DISTINCT clause in a SQL SELECT statement that contains memo or general fields. Instead, you can wrap a Memo field expression inside a function such as PADR( ) or ALLTRIM( ). For more information, see PADL( ) | PADR( ) | PADC( ) Functions and ALLTRIM( ) Function.

TOP nExpr [PERCENT]
Specifies the query result contain a specific number of rows or a percentage of rows of the query result. You can specify from 1 to 32,767 rows. If you include the PERCENT option, permissible values for nExpr are 0.01 to 99.99. When you include the PERCENT option, the number of rows returned in the result is rounded up to the next highest integer.

Rows with identical values for the columns specified in the ORDER BY clause are included in the query result. Therefore, if you specify 10 for nExpr, the query result can contain more than 10 rows if there are more than 10 rows with identical values for the columns specified in the ORDER BY clause.

When you include the TOP clause, you must include an ORDER BY clause. The ORDER BY clause specifies the columns on which the TOP clause determines the number of rows to include in the query result.

[Alias.] Select_Item
Qualifies matching item names. Select_Item specifies an item to be included in the query results. An item can be one of the following:
  • The name of a field from a table in the FROM clause.
  • A constant specifying that the same constant value appears in every row of the query results.
  • An expression that can be the name of a user-defined function.

For more information about using user-defined functions, see User-Defined Functions with SELECT in the Remarks section.

Each item you specify with Select_Item generates one column of the query results.

If two or more items have the same name, include the table alias and a period before the item name to prevent columns from being duplicated.

[AS] Column_Name
Specifies the heading for a column in the query output. Column_Name can be an expression but cannot contain characters that are not permitted, for example, spaces, in table field names.

This option is useful when Select_Item is an expression or contains a field function and you want to give the column a meaningful name.

FROM [FORCE] DatabaseName!
Lists the tables containing the data that the query retrieves.

FORCE specifies that tables are joined in the order in which they appear in the FROM clause. If FORCE is omitted, Visual FoxPro attempts to optimize the query. However, the query might be executed faster by including the FORCE keyword to disable the Visual FoxPro query optimization.

DatabaseName! specifies the name of a non-current database containing the table. You must include the name of database containing the table if the database is not the current database. Include the exclamation point (!) delimiter after the database name and before the table name.

[[AS] Local_Alias]
Specifies a temporary name for the table named in Table. If you specify a local alias, you must use the local alias in place of the table name throughout the SELECT statement.

INNER JOIN specifies that the query result contain only rows from a table that match one or more rows in another table.

LEFT [OUTER] JOIN specifies that the query result contains all rows from the table to the left of the JOIN keyword and only matching rows from the table to the right of the JOIN keyword. The OUTER keyword is optional; you can include it to emphasize that an outer join is created.

RIGHT [OUTER] JOIN specifies that the query result contain all rows from the table to the right of the JOIN keyword and only matching rows from the table to the left of the JOIN keyword. The OUTER keyword is optional; it can be included to emphasize that an outer join is created.

FULL [OUTER] JOIN specifies that the query result contain all matching and nonmatching rows from both tables. The OUTER keyword is optional; you can include it to emphasize that an outer join is created.

For more information about joins, see Joins in the Remarks section.

ON JoinCondition specifies the conditions for which the tables are joined.

INTO Destination
Specifies where to store the query results. Destination can be one of the following clauses:
  • ARRAY ArrayName stores query results in a memory variable array.

    The array is not created if the query selects 0 records.

  • CURSOR CursorName [NOFILTER | READWRITE] stores query results in a cursor.

    To create a cursor that can be used in subsequent queries, use NOFILTER. For more information about NOFILTER, see the Remarks section.

    To specify that the cursor is temporary and modifiable, use READWRITE. If the source table or tables use autoincrementing, the settings are not inherited by the READWRITE cursor.

  • DBF | TABLE TableName [DATABASE DatabaseName [NAME LongTableName]] stores query results in a table.

    To specify a database to which the table is added, include DATABASE DatabaseName.

    To specify a long name for the table, include NAME LongTableName. Long names can contain up to 128 characters and can be used in place of short file names in the database.

If you do not include the INTO clause, query results are displayed in a Browse window. You can also use the TO FILE clause to direct the query results to the printer or a file.

TO FILE FileName [ADDITIVE] | TO PRINTER [PROMPT] | TO SCREEN
Directs the query results to the printer or a file.

ADDITIVE appends query output to the existing contents of the text file specified in TO FILE FileName.

TO PRINTER directs query output to a printer. To display a dialog box before printing starts, use the PROMPT clause immediately after TO PRINTER. You can adjust printer settings in the dialog box. The printer settings that you can adjust depend on the currently installed printer driver.

TO SCREEN directs query output to the main Visual FoxPro window or to an active user-defined window.

PREFERENCE PreferenceName
Saves the attributes and options of the Browse window for later use, if query results are sent to a Browse window. For more information about how PREFERENCE functions, see the Remarks section.
NOCONSOLE
Prevents display of query results sent to a file, the printer, or the main Visual FoxPro window.
PLAIN
Prevents column headings from appearing in the query output that is displayed. You can use PLAIN whether or not a TO clause is present. If an INTO clause is included, PLAIN is ignored.
NOWAIT
Continues program execution after the Browse window is opened and query results are directed to it. The program does not wait for the Browse window to close but continues execution on the program line immediately following the SELECT statement. For an explanation of how you can use NOWAIT, see the Remarks section.
WHERE JoinCondition
Specifies that Visual FoxPro include only records in the query results that meet specified criteria. JoinCondition specifies fields that link the tables in the FROM clause. For more information about specifying join conditions, see the Remarks section.

WHERE supports the ESCAPE operator for JoinCondition, making it possible for you to perform meaningful queries on data containing the SELECT SQL command percent (%) and underscore (_) wildcard characters. ESCAPE allows you to specify that a SELECT SQL command wildcard character be treated as a literal character. In the ESCAPE clause, you specify a character which, when placed immediately before the wildcard character, indicates that the wildcard character be treated as a literal character.

FilterCondition
Specifies the criteria that records must meet to be included in the query results. You can include as many filter conditions as you like in a query and connect them with the AND or OR operator. To reverse the value of a logical expression, use the NOT operator. To check for an empty field, use the EMPTY( ) function.

The SELECT SQL command supports "<field> IS / IS NOT NULL" in the filter condition. To learn how to use the FilterCondition, see the Examples section.

GROUP BY GroupColumn [, GroupColumn ...]
Groups rows in the query based on values in one or more columns. GroupColumn can be the name of a regular table field, a field that includes an SQL field function, or a numeric expression indicating the location of the column in the result table. The leftmost column number is 1.
HAVING FilterCondition
Specifies a filter condition that groups must meet to be included in the query results. The HAVING clause can include as many filter conditions as you like, connected with the AND or OR operators. To reverse the value of a logical expression, use NOT. You can use local aliases and field functions in the HAVING clause. For more information on the field functions you can use, see the Remarks section. FilterCondition cannot contain a subquery.

You can use a SELECT statement containing a HAVING clause without including a GROUP BY clause if SELECT does not contain aggregate functions. The HAVING clause without a GROUP BY clause acts like the WHERE clause. If the HAVING clause contains no field functions, use the WHERE clause for faster performance.

The HAVING clause should appear before an INTO clause or a syntax error occurs.

[UNION [ALL] SELECTCommand]
Combines the final result for one SELECT statement with the final result of another SELECT statement. UNION checks the combined results and eliminates duplicate rows by default. To combine multiple UNION clauses, use parentheses. You can use the UNION clause to simulate an outer join.

ALL prevents UNION from eliminating duplicate rows from the combined results.

When one of the columns has Memo or General type, unions of differing column types should not be allowed.

In versions earlier than Visual FoxPro 8.0, you needed to perform explicit conversion when performing UNION operations between two fields of different types. Visual FoxPro now supports implicit data type conversion for data types that support it. For more details about implicit data type conversion and data type precedence, rules that UNION clauses follow, and other information, see Data Type Conversion and Precedence in the Remarks section.

ORDER BY Order_Item [ASC | DESC]
Sorts the query results based on the data in one or more columns. Each Order_Item must correspond to a column in the query results and can be one of the following:
  • A field in a FROM table that is also a Select_Item in the main SELECT clause (not a subquery).
  • A numeric expression indicating the location of the column in the result table. The leftmost column is number 1.

ASC specifies an ascending order for query results according to the order item or items and acts as the default for ORDER BY.

DESC specifies a descending order for query results.

Remarks

If no table is open when using the FROM clause, Visual FoxPro displays the Open dialog box so you can specify the file location. Once open, the table remains open once the query is complete.

When using the CURSOR clause in the Destination parameter, if you specify the name of an open table, Visual FoxPro generates an error message. After SELECT is executed, the temporary cursor remains open and is active and read-only unless you specify the READWRITE option. When you close this temporary cursor, it is deleted. Cursors can exist as a temporary file on the drive or volume specified by SORTWORK.

When using the CURSOR clause in the Destination parameter, you can now use NOFILTER to create a cursor that can be used in subsequent queries. In previous versions of Visual FoxPro, you needed to include an extra constant or expression as a filter. For example, adding a logical true as a filter expression created a query that could be used in subsequent queries:

SELECT *, .T. FROM customers INTO CURSOR myquery

However, including NOFILTER can reduce query performance because a temporary table is created on disk. The temporary table is deleted from disk when the cursor is closed.

When using the DBF | TABLE clause in the Destination parameter, if you specify a table that is already open, and SET SAFETY is set to OFF, Visual FoxPro overwrites the table without warning. If you do not specify an extension, Visual FoxPro gives the table a .dbf extension. The table remains open and active after SELECT is executed.

If you include the INTO and TO clauses in the same query, Visual FoxPro disregards the TO clause. If you include a TO clause but not an INTO clause, you can direct query results to an ASCII text file named FileName, to the printer, or to the main Visual FoxPro window.

The PREFERENCE clause saves the attributes, or preferences, indefinitely in the FoxUser.dbf resource file. Preferences can be retrieved at any time. Issuing SELECT with PREFERENCE PreferenceName for the first time creates the preference. Issuing SELECT later with the same preference name restores the Browse window to that preference state. When the Browse window is closed, the preference is updated. If you exit a Browse window by pressing CTRL+Q+W, changes you made to the Browse window are not saved to the resource file.

As an example of how you can use the NOWAIT clause, when you include the TO SCREEN clause to direct output to the main Visual FoxPro window or to a user-defined window, output pauses when the main Visual FoxPro window or user-defined window is full of query results. To see the next set of query results, press a key. If you include NOWAIT, the query results scroll off the main Visual FoxPro window or the user-defined window without pausing for a key press. Visual FoxPro disregards NOWAIT if it is included with the INTO clause.

Including the EVALUATE( ) function in the WHERE clause of an SQL query can return incorrect data.

If you include more than one table in a query, you should specify a join condition for every table after the first. Join conditions can include filter conditions.

Note The maximum number of joins per SELECT statement is nine.

You must use the AND operator to connect multiple join conditions. Each join condition has the following form:

FieldName1 Comparison FieldName2

FieldName1 is the name of a field from one table, FieldName2 is the name of a field from another table, and Comparison is one of the following operators:

Operator | Comparison
= | Equal
== | Exactly equal
LIKE | SQL LIKE
<>, !=, # | Not equal
> | More than
>= | More than or equal to
< | Less than
<= | Less than or equal to

When you use the = operator with strings, it acts differently depending on the setting of SET ANSI. When SET ANSI is set to OFF, Visual FoxPro compares strings only to the end of the shorter string. When SET ANSI is set to ON, Visual FoxPro follows ANSI standards for string comparisons. For additional information about how Visual FoxPro performs string comparisons, see SET ANSI and SET EXACT.

The following field functions are available for use with a select item that is a field or an expression involving a field:

  • AVG(Select_Item), which averages a column of numeric data.
  • COUNT(Select_Item), which counts the number of select items in a column. COUNT(*) counts the number of rows in the query output.
  • MIN(Select_Item), which determines the smallest value of Select_Item in a column.
  • MAX(Select_Item), which determines the largest value of Select_Item in a column.
  • SUM(Select_Item), which totals a column of numeric data.

You cannot nest field functions.

UNION clauses follow these rules:

  • You cannot use UNION to combine subqueries.
  • Both SELECT commands must have the same number of columns in their query output.
  • When two columns of different data types are involved in a UNION operation, the data type with the lower precedence is converted to the data type with the higher precedence. For more information, see "Data Type Conversion and Precedence" section in the Remarks section.
  • Only the final SELECT statement can have an ORDER BY clause, which must refer to output columns by number. If an ORDER BY clause is included, it affects the entire result.

If you do not specify an order in the ORDER BY clause, query results appear in no order.

When you issue SET TALK ON and execute SELECT, Visual FoxPro displays the length of time the query took to execute and the number of records in the results. _TALLY contains the number of records in the query results.

SELECT does not respect the current filter condition specified with SET FILTER.

Note A subquery, referred to in the following arguments, is a SELECT within a SELECT and must be enclosed in parentheses. You can have one subquery in the WHERE clause (see that section of the arguments). Subqueries can contain multiple join conditions.

When you create query output, columns are named according to the following rules:

  • If Select_Item is a field with a unique name, the output column name is the field's name.
  • If more than one Select_Item has the same name, an underscore and a letter are appended to the column name. For example, if a table called CUSTOMER has a field called STREET, and a table called EMPLOYEES has a field called STREET also, output columns are named Extension_A and Extension_B (STREET_A and STREET_B). For a select item with a 10-character name, the name is truncated to add the underscore and letter. For example, DEPARTMENT would become DEPARTME_A.
  • If Select_Item is an expression, its output column is named EXP_A. Any other expressions are named EXP_B, EXP_C, and so on.
  • If Select_Item contains a field function such as COUNT( ), the output column is named CNT_A. If another select item contains SUM( ), its output column is named SUM_B.

User-Defined Functions with SELECT Although using user-defined functions in the SELECT clause has obvious benefits, you should also consider the following restrictions:

  • The speed of operations performed with SELECT might be limited by the speed at which such user-defined functions are executed. High-volume manipulations involving user-defined functions may be better accomplished by using API and user-defined functions written in C or assembly language.
  • You can assume nothing about the Visual FoxPro input/output (I/O) or table environment in user-defined functions invoked from SELECT. In general, you don't know which work area is selected, the name of the current table, or even the names of the fields being processed. The value of these variables depends on where precisely in the optimization process the user-defined function is invoked.
  • It isn't safe to change the Visual FoxPro I/O or table environment in user-defined functions invoked from SELECT. In general, the results are unpredictable.
  • The only reliable way to pass values to user-defined functions invoked from SELECT is by the argument list passed to the function when it is invoked.
  • If you experiment and discover a supposedly forbidden manipulation that works correctly in a certain version of FoxPro, there is no guarantee it will continue to work in later versions.

Apart from these restrictions, user-defined functions are acceptable in the SELECT clause. However, do not forget that using SELECT might slow performance. To learn how you can use SELECT with user-defined functions, see the Examples section.

Joins Visual FoxPro supports ANSI SQL '92 Join syntax, allowing you to create queries that link the rows in two or more tables by comparing the values in specified fields. For example, an inner join selects rows from two tables only when the values of the joined fields are equal. Visual FoxPro supports nested joins.

Because SQL is based on mathematical set theory, each table can be represented as a circle. The ON clause that specifies the join conditions determines the point of overlap, which represents the set of rows that match. For an inner join, the overlap occurs within the interior or "inner" portion of the two circles. An outer join includes not only those matched rows found in the inner cross section of the tables, but also the rows in the outer part of the circle to the left, or right, of the intersection.

Note Keep the following information in mind when creating join conditions:
  • If you include two tables in a query and do not specify a join condition, every record in the first table is joined with every record in the second table as long as the filter conditions are met. Such a query can produce lengthy results.
  • Be careful when using, in join conditions, functions such as DELETED( ), EOF( ), FOUND( ), RECCOUNT( ), and RECNO( ), which support an optional alias or work area. Including an alias or work area in these functions might yield unexpected results. SELECT doesn't use your work areas; it performs the equivalent of USE ... AGAIN. Single-table queries that use these functions without an optional alias or work area will return proper results. However, multiple-table queries that use these functions — even without an optional alias or work area — might return unexpected results.
  • Use caution when joining tables that contain empty fields because Visual FoxPro matches empty fields. For example, suppose you perform a join on CUSTOMER.ZIP and INVOICE.ZIP. If CUSTOMER contains 100 empty zip codes, and INVOICE contains 400 empty zip codes, the query output contains 40,000 extra records resulting from the empty fields. To eliminate empty records from the query output, use the EMPTY( ) function.
  • The limit to the number of joins that you can use per SELECT statement is nine.

For additional information about joins, see Join Conditions for Tables, Queries, and Views.

Data Type Conversion and Precedence Explicit data type conversions require you to use Visual FoxPro conversion functions, such as CTOD( ), while implicit conversions do not require you to use conversion functions. Visual FoxPro supports implicit data type conversion for data types that support it. When Visual FoxPro combines two columns of different data types in a SELECT...UNION operation, the data type with the lower precedence is converted to the data type with the higher precedence. For field properties, NULL takes higher precedence over NOT NULL.

The following table shows all the explicit and implicit data type conversions permitted for Visual FoxPro table data types.

Data type | Implicit conversion | Explicit conversion
Character | Character (Binary) | CTOD( ), CTOT( ), VAL( ), CTOBIN( )
Character (Binary) |  |
Currency |  | MTON( )
Date | DateTime | DTOC( ), DTOS( ), DTOT( )
DateTime |  | TTOC( ), TTOD( )
Double |  | STR( ), VAL( )
Float | Numeric | NTOM( ), STR( ), INT( )
Integer | Numeric, Float, Double, Currency | BINTOC( )
Logical |  |
Numeric | Float | NTOM( ), STR( ), INT( )

The following table illustrates implicit conversion results from a SELECT...UNION operation of two fields.

Data type 1 | Data type 2 | Data type expected
Character (N) | Character (X) | Character (MAX(N,X))
Character (N) | Character Binary (X) | Character Binary (MAX(N,X))
Character (N) | Memo | Memo
Character Binary (N) | Character Binary (X) | Character Binary (MAX(N,X))
Character Binary (N) | Memo | Memo
Currency | Currency | Currency
Date | Date | Date
Date | DateTime | DateTime
DateTime | DateTime | DateTime
Double (N) | Float (X,Y) | Float (MAX(MAX(8,Y),2))
Double (N) | Integer | Double (N)
Double (N) | Numeric (X,Y) | Double (MAX(MAX(8,Y),2))
Double (X) | Double (Y) | Double (MAX(X,Y))
Float (N,M) | Double (X) | Float (20, MAX(M,X))
Float (N,M) | Float (X,Y) | Float (MAX(N,M), MAX(X,Y))
Float (N,M) | Numeric (X,Y) | Float (MAX (N,X), MAX(M,Y))
Integer | Currency | Currency
Integer | Double (X) | Double (X)
Integer | Float (X,Y) | Float (MAX(11,X), Y)
Integer | Integer | Integer
Integer | Numeric (X,Y) | Numeric (MAX(11,X), Y)
Logical | Logical | Logical
Numeric (N,M) | Double (X) | Numeric (20, MAX(M,X))
Numeric (N,M) | Float (X,Y) | Float (MAX(N,X), MAX(M,Y))
Numeric (N,M) | Numeric (X,Y) | Numeric (MAX(N,X), MAX(M,Y))

Examples

The following examples illustrate how the FilterCondition parameter can take one of many forms:

Example 1

Example 1 displays FilterCondition in the form of FieldName1 Comparison FieldName2:

customer.cust_id = orders.cust_id

Example 2

Example 2 displays FilterCondition in the form of FieldName Comparison Expression:

payments.amount >= 1000

Example 3

Example 3 displays FilterCondition in the form of FieldName Comparison ALL (Subquery). When the filter condition includes ALL, the field must meet the comparison condition for all values generated by the subquery before its record is included in the query results.

company < ALL (SELECT company FROM customer WHERE country = "UK")

Example 4

Example 4 displays FilterCondition in the form of FieldName Comparison ANY | SOME (Subquery). When the filter condition includes ANY or SOME, the field must meet the comparison condition for at least one of the values generated by the subquery.

company < ANY (SELECT company FROM customer WHERE country = "UK")

Example 5

Example 5 displays FilterCondition in the form of FieldName [NOT] BETWEEN Start_Range AND End_Range. This example checks to see whether the values in the field are within a specified range of values.

customer.postalcode BETWEEN 90000 AND 99999

Example 6

Example 6 displays FilterCondition in the form of [NOT] EXISTS (Subquery). This example checks to see whether at least one row meets the criterion in the subquery. When the filter condition includes EXISTS, the filter condition evaluates to true (.T.) unless the subquery evaluates to the empty set.

EXISTS ;
(SELECT * FROM orders WHERE customer.postalcode =    orders.postalcode)

Example 7

Example 7 displays FilterCondition in the form of FieldName [NOT] IN Value_Set. When the filter condition includes IN, the field must contain one of the values before its record is included in the query results.

customer.postalcode NOT IN ("98052","98072","98034")
Note You can have a maximum of 24 items in the value set. If the set contains more values, the SELECT-SQL statement will fail as a result of being too complex.

Example 8

Example 8 displays FilterCondition in the form of FieldName [NOT] IN (Subquery). Here, the field must contain one of the values returned by the subquery before its record is included in the query results.

customer.cust_id IN ;
(SELECT orders.cust_id FROM orders WHERE orders.city="Seattle")

Example 9

Example 9 displays FilterCondition in the form of FieldName [NOT] LIKE cExpression.

customer.country NOT LIKE "UK"

This filter condition searches for each field that matches cExpression. You can use the percent sign (%) and underscore (_) wildcards as part of cExpression. The percent sign represents any sequence of unknown characters in the string. An underscore represents a single unknown character in the string.

The following examples illustrate the use of user-defined functions with the SELECT SQL command:

Example 1

Example 1 displays the names of all companies in customer (one field from one table).

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT customer.company ;
   FROM customer

Example 2

Example 2 displays the contents of three fields from two tables and joins the two tables based on the cust_id field. It uses local aliases for both tables.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT x.company, y.order_date, y.shipped_on ;
   FROM customer x
      INNER JOIN orders y ON x.cust_id = y.cust_id

Example 3

Example 3 displays only records with unique data in the specified fields.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT DISTINCT x.company, y.order_date, y.shipped_on ;
   FROM customer x, orders y ;
   WHERE  x.cust_id = y.cust_id

Example 4

Example 4 displays the country, postalcode, and company fields in ascending order.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT country, postalcode, company ;
   FROM customer ;
   ORDER BY country, postalcode, company

Example 5

Example 5 stores the contents of fields from two tables in a third table.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT x.company, y.order_date, y.shipped_on ;
   FROM customer x, orders y ;
   WHERE x.cust_id = y.cust_id ;
   INTO TABLE custship.dbf
BROWSE

Example 6

Example 6 displays only records with an order date earlier than 02/16/1994.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT x.company, y.order_date, y.shipped_on ;
   FROM customer x, orders y ;
   WHERE x.cust_id = y.cust_id ;
   AND y.order_date < {^1994-02-16}

Example 7

Example 7 displays all customers, but only orders with a date earlier than 02/16/1994.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT x.company, y.order_date, y.shipped_on ;
   FROM customer x ;
      LEFT JOIN orders y ;
   ON x.cust_id = y.cust_id ;
   AND y.order_date < {^1994-02-16}

Example 8

Example 8 displays the names of all companies from customer with a postal code that matches a postal code in the orders table.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT company FROM customer x WHERE ;
   EXISTS (SELECT * FROM orders y WHERE x.postalcode = y.postalcode)

Example 9

Example 9 displays all records from customer having a company name that begins with an uppercase C and is an unknown length.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT * FROM customer x WHERE x.company LIKE "C%"

Example 10

Example 10 displays all records from customer having a country name that begins with an uppercase U and is followed by one unknown character.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT * FROM customer x WHERE x.country LIKE "U_"

Example 11

Example 11 displays the names of all cities in customer in uppercase and names the output column CityList.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT UPPER(city) AS CityList FROM customer

Example 12

Example 12 demonstrates how you can perform a query on data that contains percentage signs (%). A backslash (\) is placed before the percentage sign to indicate that it should be treated as a literal, and the backslash is specified as the escape character in the ESCAPE clause.

Because the sample tables included with Visual FoxPro do not contain the percentage sign character, this query returns no results.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT * FROM customer;
WHERE company LIKE "%\%%" ESCAPE "\"

Example 13

Example 13 demonstrates how you can perform a query on data that contains underscores (_). A backslash (\) is placed before the underscore to indicate that it should be treated as a literal, and the backslash is specified as the escape character in the ESCAPE clause.

Because the sample tables included with Visual FoxPro do not contain the underscore character, this query returns no results.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT * FROM customer;
WHERE company LIKE "%\_%" ESCAPE "\"

Example 14

In Example 14, the Escape character uses itself as a literal. The dash is both the Escape character and a literal. The query returns all rows where the company name contains a percentage sign followed by a dash.

Because the sample tables included with Visual FoxPro do not contain the percentage sign character, this query returns no results.

CLOSE ALL
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SELECT * FROM customer;
WHERE company LIKE "%-%--%" Escape "-"

See Also

CREATE QUERY | CREATE TABLE - SQL | INSERT - SQL | MODIFY QUERY | SET ANSI | SET EXACT | SET PATH | _TALLY


SELECT Command

Activates the specified work area.

SELECT nWorkArea | cTableAlias

Parameters

nWorkArea
Specifies a work area to activate. If nWorkArea is 0, the lowest-numbered unused work area is activated.
cTableAlias
Specifies a work area containing an open table to activate. cTableAlias is the alias of the open table. You can also include a letter from A through J for cTableAlias to activate one of the first ten work areas.

Remarks

By default, work area number 1 is active when you start Visual FoxPro.

Note Fields in tables open in any work area can be included in Visual FoxPro commands and functions. Use the following formats to access fields in a table open in a work area other than the current one: alias.field or alias -> field.

Example

The following example demonstrates ways of selecting work areas.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
SELECT 1     && Work area 1
USE customer  && Opens Customer table

SELECT 2     && Work area 2
USE orders  && Opens Orders table

SELECT customer     && Work area 1
BROWSE

SELECT B     && Work area 2
BROWSE

See Also

ALIAS( ) | SELECT( ) | USE


SET Command Overview

Opens the Data Session window.

SET

Remarks

The Data Session window provides an easy way to open tables, establish relations, or set or change many Microsoft Visual FoxPro options.

The following table shows what each SET Command returns:

Function | Information returned
Set Alternate Command | Directs screen or printer output created with ?, ??, DISPLAY, or LIST to a text file.
SET ANSI Command | Determines how comparisons between strings of different lengths are made with the = operator in Visual FoxPro SQL commands.
SET ASSERTS Command | Specifies if ASSERT commands are evaluated or ignored.
SET AUTOINCERROR Command | Specifies whether attempts to update values in a field using autoincrementing generate an error or fail silently and proceed.
SET AUTOSAVE Command | Determines whether Visual FoxPro flushes data buffers to disk when you exit a READ or return to the Command window.
SET BELL Command | Turns the computer bell on or off and sets the bell attributes.
SET BLOCKSIZE Command | Specifies how Visual FoxPro allocates disk space for the storage of memo fields.
SET BROWSEIME Command | Specifies if the Input Method Editor is opened when you navigate to a text box in a Browse window.
SET CARRY Command | Determines whether Visual FoxPro carries data forward from the current record to a new record created with INSERT, APPEND, and BROWSE.
SET CENTURY Command | Determines whether Microsoft Visual FoxPro displays the century portion of date expressions and how Visual FoxPro interprets dates that specify only 2 digit years.
SET CLASSLIB Command | Opens a .vcx visual class library containing class definitions.
SET CLOCK Command | Determines whether Visual FoxPro displays the system clock and specifies the clock location on the main Visual FoxPro window.
SET COLLATE Command | Specifies a collation sequence for character fields in subsequent indexing and sorting operations.
SET COLOR OF SCHEME Command | Specifies the colors of a color scheme or copies one color scheme to another color scheme.
SET COLOR SET Command | Loads a previously defined color set.
SET COMPATIBLE Command | Controls compatibility with Microsoft FoxBASE+ and other FoxPro languages.
SET CONFIRM Command | Specifies whether the user can exit a text box by typing past the last character in the text box.
SET CONSOLE Command | Enables or disables output to the main Visual FoxPro window or to the active user-defined window from within programs.
SET COVERAGE Command | Turns code coverage on or off, or specifies a text file to which code coverage information is directed.
SET CPCOMPILE Command | Specifies the code page for compiled programs.
SET CPDIALOG Command | Specifies whether the Code Page dialog box is displayed when a table is opened.
SET CURRENCY Command | Defines the currency symbol and specifies its position in the display of numeric, currency, float, and double expressions.
SET CURSOR Command | Determines whether the insertion point is displayed when Visual FoxPro waits for input.
SET DATABASE Command | Specifies the current database.
SET DATASESSION Command | Activates the specified form's data session.
SET DATE Command | Specifies the format for the display of Date and DateTime expressions.
SET DEBUG Command | Included for backward compatibility. Makes the Debug and Trace windows either available or unavailable from the Visual FoxPro menu system in versions prior to 5.0.
SET DEBUGOUT Command | Directs debugging output to a file.
SET DECIMALS Command | Specifies the number of decimal places displayed in numeric expressions.
SET DEFAULT Command | Specifies the default drive and directory.
SET DELETED Command | Specifies whether Visual FoxPro processes records marked for deletion and whether they are available for use in other commands.
SET DEVELOPMENT Command | Causes Visual FoxPro to compare the creation date and time of a program with those of its compiled object file when the program is run.
SET DEVICE Command | Directs output from @ ... SAY to the screen, a printer, or a file.
SET Display Command | Included for backward compatibility.
SET DOHistory Command | Included for backward compatibility.
SET ECHO Command | Opens the Trace window for program debugging. Included for backward compatibility.
SET ENGINEBEHAVIOR Command | Enables SQL data engine compatibility with Visual FoxPro 7.0 or Visual FoxPro 8.0.
SET ESCAPE Command | Determines whether pressing the ESC key interrupts program and command execution.
SET EVENTLIST Command | Specifies events to track in the Debug Output Window or in a file specified with SET EVENTTRACKING.
SET EVENTTRACKING Command | Turns event tracking on or off or specifies a text file to which event tracking information is directed.
SET EXACT Command | Specifies the rules Visual FoxPro uses when comparing two strings of different lengths.
SET EXCLUSIVE Command | Specifies whether Visual FoxPro opens table files for exclusive or shared use on a network.
SET FDOW Command | Specifies the first day of the week.
SET FIELDS Command | Specifies which fields in a table can be accessed.
SET FILTER Command | Specifies a condition that records in the current table must meet to be accessible.
SET FIXED Command | Specifies if the number of decimal places used in the display of numeric data is fixed.
SET FULLPATH Command | Specifies if CDX( ), DBF( ), MDX( ), and NDX( ) return the path in a file name.
SET FUNCTION Command | Assigns an expression (keyboard macro) to a function key or key combination.
SET FWEEK Command | Specifies the requirements for the first week of the year.
SET HEADINGS Command | Determines whether column headings are displayed for fields and whether file information is included when TYPE is issued to display the contents of a file.
SET HELP Command | Enables or disables Microsoft Visual FoxPro online Help or specifies a Help file.
SET HOURS Command | Sets the system clock to a 12- or 24-hour time format.
SET INDEX Command | Opens one or more index files for use with the current table.
SET KEY Command | Specifies access to a range of records based on their index keys.
SET KEYCOMP Command | Controls Visual FoxPro keystroke navigation.
SET LIBRARY Command | Opens an external API (application programming interface) library file.
SET LOCK Command | Enables or disables automatic file locking in certain commands.
SET LOGERRORS Command | Determines whether Visual FoxPro sends compilation error messages to a text file.
SET MACKEY Command | Specifies a key or key combination that displays the Macro Key Definition dialog box.
SET MARGIN Command | Sets the left printer margin and affects all output directed to the printer.
SET MARK OF Command | Specifies a mark character for menu titles or menu items, or displays or clears the mark character.
SET MARK TO Command | Specifies a delimiter for the display of date expressions.
SET MEMOWIDTH Command | Specifies the displayed width of memo fields and character expressions.
SET MESSAGE Command | Defines a message for display in the main Visual FoxPro window or in the graphical status bar, or specifies the location of messages for user-defined menu bars and menu commands.
SET MULTILOCKS Command | Determines whether you can lock multiple records using LOCK( ) or RLOCK( ).
SET NEAR Command | Determines where the record pointer is positioned after FIND or SEEK unsuccessfully searches for a record.
SET NOCPTRANS Command | Prevents translation to a different code page for selected fields in an open table.
SET NOTIFY Command | Enables or disables the display of certain system messages.
SET NULL Command | Determines how null values are supported by the ALTER TABLE, CREATE TABLE and INSERT - SQL commands.
SET NULLDISPLAY Command | Specifies the text displayed for null values.
SET ODOMETER Command | Specifies the reporting interval of the record counter for commands that process records.
SET OLEOBJECT Command | Specifies whether Visual FoxPro searches the OLE Registry when an object cannot be located.
SET OPTIMIZE Command | Enables or disables Rushmore Query Optimization.
SET ORDER Command | Designates a controlling index file or tag for a table.
SET PALETTE Command | Specifies whether the Visual FoxPro default color palette is used.
SET PATH Command | Specifies a path for file searches.
SET PDSETUP Command | Loads a printer driver setup or clears the current printer driver setup.
SET POINT Command | Determines the decimal point character used in the display of numeric and currency expressions.
SET PRINTER Command | Enables or disables output to the printer, or routes output to a file, port, or network printer.
SET PROCEDURE Command | Opens a procedure file.
SET READBORDER Command | Determines whether borders are placed around text boxes created with @ ... GET.
SET REFRESH Command | Determines whether and how often a Browse window is updated with changes made to records by other users on the network.
SET RELATION Command | Establishes a relationship between two open tables.
SET RELATION OFF Command | Breaks an established relationship between the parent table in the currently selected work area, and a related child table.
SET REPROCESS Command | Specifies how many times and for how long Visual FoxPro attempts to lock a file or record after an unsuccessful locking attempt.
SET RESOURCE Command | Updates or specifies a resource file.
SET SAFETY Command | Determines whether Visual FoxPro displays a dialog box before overwriting an existing file, or whether table or field rules, default values, and error messages are evaluated when changes are made in the Table Designer or with ALTER TABLE.
SET SECONDS Command | Specifies whether seconds are displayed in the time portion of a DateTime value.
SET SKIP Command | Creates a one-to-many relationship among tables.
SET SKIP OF Command | Enables or disables a menu, menu bar, menu title, or menu item for user-defined menus or the Microsoft Visual FoxPro system menu.
SET SPACE Command | Determines whether a space is displayed between fields or expressions when you use the ? or ?? command.
SET STATUS Command | Displays or removes the character-based status bar.
SET STATUS BAR Command | Displays or removes the graphical status bar.
SET STEP Command | Opens the Trace window and suspends program execution for debugging.
SET STRICTDATE Command | Specifies if ambiguous Date and DateTime constants generate errors.
SET SYSFORMATS Command | Specifies whether Visual FoxPro for Windows system settings are updated with the current Microsoft Windows system settings.
SET SYSMENU Command | Enables or disables the Visual FoxPro system menu bar during program execution, and allows you to reconfigure it.
SET TABLEVALIDATE Command | Specifies the level of table validation to perform.
SET TALK Command | Determines whether Visual FoxPro displays command results.
SET TEXTMERGE Command | Enables or disables the evaluation of fields, variables, array elements, functions, or expressions that are surrounded by text-merge delimiters, and lets you specify text-merge output.
SET TEXTMERGE DELIMITERS Command | Specifies the text-merge delimiters.
SET TOPIC Command | Specifies the Help topic or topics to open when you invoke the Visual FoxPro Help system.
SET TOPIC ID Command | Specifies the Help topic to display when you invoke the Visual FoxPro Help system. The Help topic is based on the topic's context ID.
SET TRBETWEEN Command | Enables or disables tracing between breakpoints in the Trace Window.
SET TYPEAHEAD Command | Specifies the maximum number of characters that can be stored in the type-ahead buffer.
SET UDFPARMS Command | Specifies if Microsoft Visual FoxPro passes parameters to a user-defined function (UDF) by value or by reference.
SET UNIQUE Command | Specifies whether records with duplicate index key values are maintained in an index file.
SET VIEW Command | Opens or closes the Data Session window or restores the Visual FoxPro environment from a view file.
SET VOLUME Command | Maps MS-DOS drive designators (A:, B:, C:, and so on) to volumes or folders in FoxPro for Macintosh.
SET WINDOW of Memo Command | Included for backward compatibility.

See Also

SET VIEW | Data Session Window | SET ALTERNATE Command


SET ALTERNATE Command

Directs screen or printer output created with ?, ??, DISPLAY, or LIST to a text file.

SET ALTERNATE ON | OFF
-or-
SET ALTERNATE TO [FileName [ADDITIVE]]

Parameters

ON
Directs output to the text file.
OFF
(Default) Disables output to the text file.
TO FileName
Creates the text file, which is assigned the default extension .txt unless you include a different extension with the file name.

If you use SET ALTERNATE TO without FileName, the last file you created using SET ALTERNATE TO FileName is closed.

ADDITIVE
Appends output to the end of the file specified with FileName. If you omit ADDITIVE, the contents of the file are overwritten.

See Also

CLOSE | SET PRINTER | ACTIVATE SCREEN Command


SET ANSI Command

Determines how comparisons between strings of different lengths are made with the = operator in Visual FoxPro SQL commands.

SET ANSI ON | OFF

Parameters

ON
Pads the shorter string with the blanks needed to make it equal to the longer string's length.

The two strings are then compared character for character for their entire lengths. Consider this comparison:

'Tommy' = 'Tom'

The result is false (.F.) if SET ANSI is on because when padded, 'Tom' becomes 'Tom ' and the strings 'Tom ' and 'Tommy' don't match character for character.

The == operator uses this method for comparisons in Visual FoxPro SQL commands.

OFF
Specifies that the shorter string not be padded with blanks. (Default)

The two strings are compared character for character until the end of the shorter string is reached. Consider this comparison:

'Tommy' = 'Tom'

The result is true (.T.) when SET ANSI is off because the comparison stops after 'Tom'.

Remarks

SET ANSI determines whether the shorter of two strings is padded with blanks when a SQL string comparison is made. SET ANSI has no effect on the == operator; when you use the == operator, the shorter string is always padded with blanks for the comparison.

SET ANSI is scoped to the current data session.

SET ANSI and the Query Designer Visual FoxPro builds a SELECT - SQL command in the Query Designer when you create a query. When creating Join and Filter conditions, if you choose the Equal or Exactly Like options, the = or == operator is included in the generated SELECT. The SET ANSI setting can affect the results of queries you create and perform in the Query Designer.

String Order In SQL commands, the left-to-right order of the two strings in a comparison is irrelevant — switching a string from one side of the = or == operator to the other doesn't affect the result of the comparison.

See Also

CREATE QUERY | MODIFY QUERY | SELECT – SQL | SET DATASESSION | SET EXACT


SET ASSERTS Command

Specifies if ASSERT commands are evaluated or ignored.

SET ASSERTS ON | OFF

Parameters

ON
Specifies that Visual FoxPro executes ASSERT commands.
OFF
Specifies that Visual FoxPro ignores ASSERT commands.

Remarks

ASSERTS is set to OFF if you choose the Ignore All button in the message box following an assert.

See Also

ASSERT | Setting Asserts | SET Command


SET AUTOINCERROR Command

Specifies whether attempts to update or insert values in a field with automatically incrementing values generate errors.

Note A cursor inherits the current setting of SET AUTOINCERROR when opened. Changing the value of SET AUTOINCERROR during a session does not change the setting for any cursors already opened. To change the setting of an open cursor, use the CURSORSETPROP( ) function.
SET AUTOINCERROR ON | OFF

Parameters

ON
Generates an error when updating or inserting a value in a field that uses automatically incrementing field values. The ON setting is the default for a global or private data sessions.
OFF
Does not generate an error when updating or inserting a value in a field that uses automatically incrementing field values and disregards the value specified for the field, which uses the appropriate incremented value.

Remarks

The OFF setting provides greater utility when using tables that contain autoincrementing fields with certain language operations such as the APPEND FROM and INSERT INTO commands where you need to otherwise specify a fields list and omit those fields that use autoincrementing from the operation.

SET AUTOINCERROR is scoped to the data session.

See Also

Commands | Autoincrementing Field Values in Tables


SET AUTOSAVE Command

Determines whether Visual FoxPro flushes data buffers to disk when you exit a READ or return to the Command window.

SET AUTOSAVE ON | OFF

Parameters

ON
Specifies that buffers be flushed to disk whenever you exit a READ or return to the Command window.
OFF
Specifies that buffers be flushed to disk only if five minutes have elapsed since the last flush occurred, and only when you exit a READ or return to the Command window.

OFF is the default for SET AUTOSAVE.

Remarks

Flushing buffers may reduce the chance of data loss if your computer loses power.

SET AUTOSAVE is scoped to the current data session.

See Also

FFLUSH( ) | FLUSH | SET DATASESSION


SET BELL Command

Turns the computer bell on or off and sets the bell attributes.

SET BELL ON | OFF
-or-
SET BELL TO [cWAVFileName]

Parameters

ON
(Default) Turns the bell on.
OFF
Turns the bell off.
TO cWAVFileName
Specifies a waveform sound to play when the bell is rung. cWAVFileName can include a path to the waveform sound.

Issue SET BELL TO without cWAVFileName to restore the default waveform sound.

Remarks

SET BELL enables or disables the sounding of the bell during editing when you reach the end of a field or enter invalid data.

Example

In the following example, the waveform sound file Ding.wav is played.

SET BELL TO 'C:\WINDOWS\DING.WAV'
?? CHR(7)

See Also

SOUNDEX( ) Function | Sound Player


SET BLOCKSIZE Command

Specifies how Visual FoxPro allocates disk space for the storage of memo fields.

SET BLOCKSIZE TO nBytes

Parameters

nBytes
Specifies the block size in which disk space for memo fields is allocated. If nBytes is 0, disk space is allocated in single bytes (blocks of 1 byte). If nBytes is an integer between 1 and 32, disk space is allocated in blocks of nBytes bytes multiplied by 512. If nBytes is greater than 32, disk space is allocated in blocks of nBytes bytes.

If you specify a block size value greater than 32, you can save substantial disk space.

Remarks

The default value for SET BLOCKSIZE is 64. To reset the block size to a different value after the file has been created, set it to a new value and then use COPY to create a new table. The new table has the specified block size.

SET BLOCKSIZE is scoped to the current data session.

See Also

COPY FILE | MODIFY STRUCTURE | PACK | SET DATASESSION


SET BROWSEIME Command

Specifies if the Input Method Editor is opened when you navigate to a text box in a Browse window.

SET BROWSEIME ON | OFF

Parameters

ON
(Default for Traditional Chinese Windows) Opens the Input Method Editor when you navigate to a text box in a Browse window.
OFF
(Default for Korean Windows) The Input Method Editor isn't opened when you navigate to a text box in a Browse window.

Remarks

SET BROWSEIME corresponds to the Browse IME control check box on the General tab of the Options dialog box.

This command has no effect if you are not working in a double-byte character set (DBCS) environment.

See Also

Entering International Data | IMEMode Property | IMESTATUS( ) | General tab | Options


SET CARRY Command

Determines whether Visual FoxPro carries data forward from the current record to a new record created with INSERT, APPEND, and BROWSE.

SET CARRY ON | OFF
-or-
SET CARRY TO [FieldList [ADDITIVE]]

Parameters

ON
Brings data from all fields in all work areas forward from the current record to a new record.
OFF
(Default) Prevents data from all fields from being passed to a new record.
TO [FieldList [ADDITIVE]]
FieldList specifies the fields from which data is carried forward. Separate the field names with commas.

ADDITIVE specifies that the fields in the field list be added to the current set of fields being carried forward.

Issuing SET CARRY TO implicitly performs SET CARRY ON.

Use SET CARRY TO without FieldList to restore the default setting (all fields are carried forward).

Remarks

Use SET CARRY to enable data to be carried forward from the current record to a new record or to prevent data from being carried forward. Fields that generally remain unchanged during an editing session can be brought forward for each new record. For example, a field containing the current date can be brought forward for each new record so a new date doesn't have to be entered again. Note that the contents of Memo and General type fields are not carried forward.

Modifying the structure of a table with an active SET CARRY TO <fieldlist> calls an implicit SET CARRY TO. This results in the field list containing all of the fields in the table. If you modify the structure of a table, you must reissue the SET CARRY TO <fieldlist> to reset the field list.

SET CARRY affects only the table open in the currently selected work area.

SET CARRY is scoped to the current data session.

See Also

INSERT | SET DATASESSION | APPEND Command | BROWSE Command


SET CENTURY Command

Determines whether Microsoft Visual FoxPro displays the century portion of date expressions and how Visual FoxPro interprets dates that specify only 2 digit years.

SET CENTURY ON | OFF | TO [nCentury [ROLLOVER nYear]]

Parameters

ON
Specifies a four-digit year in a format that includes 10 characters (including date delimiters).
Note To provide year 2000 compliance, it's recommended that you always set SET CENTURY to ON.
OFF
(Default) Specifies a two-digit year in a format that includes eight characters and assumes the twentieth century for date calculations.
TO nCentury
A number from 1 to 99 that specifies the current century. When a date has a two digit year, nCentury determines in which century the year occurs. The ROLLOVER value determines whether the year is in nCentury or the century following nCentury.
ROLLOVER nYear
A number from 0 to 99 that specifies the year equal to and above which is the current century and below which is the next century. The default value for nYear is the last two digits of the current year plus 50 years - if the current year is 1998, nYear is 48, the last two digits of 2048 (1998 + 50).

Note that the rollover value only determines the century for a date entered without a century portion - an ambiguous date format that is not recommended.

For example, if the current year is 1998 and nYear is the default (48), any date entered without a century portion and a year of 48 or greater is considered to be in the current century (the 20th century). Any date entered without a century portion but with a year before 48 is considered to be in the next century (the 21st century).

Remarks

Use SET CENTURY to specify how date variables and functions are displayed.

Issue SET CENTURY TO without any additional arguments to restore the default century to the current century and ROLLOVER to the default value of the current year plus 50 years. In Visual FoxPro 5.0, issuing SET CENTURY TO without any additional arguments sets the century to 19 and ROLLOVER to zero.

SET CENTURY is scoped to the current data session. New data sessions are initialized to the default values as specified above, ignoring the value of SET CENTURY for the current data session.

SET CENTURY TO ROLLOVER is available in Visual FoxPro 5.0 and later, and makes it possible for you to control the assumed year for dates used when the setting is SET CENTURY OFF. It also allows for a rollover value since many applications contain dates that span multiple centuries.

Note SET CENTURY OFF always implies dates in the 20th century. However, the SET CENTURY TO syntax takes precedence over this setting. So, with Visual FoxPro 5.0 and later, the SET CENTURY ON/OFF setting only controls the number of digits displayed.

The value of SET CENTURY TO is scoped to the current data session.

In Visual FoxPro 5.0, issuing SET CENTURY TO without additional parameters sets the century to the current century –1 and rollover to zero if the two-digit year of the system date is less than 50. Century is set to the current century if the two-digit system date is greater than 50. For example, if the current year were 1998, nYear would be 48, the last two digits of 2048 (1998 + 50).

See Also

DATE( ) | SET DATASESSION | SET STRICTDATE | SET SYSFORMATS | YEAR( )


SET CLASSLIB Command

Opens a .vcx visual class library containing class definitions.

SET CLASSLIB TO ClassLibraryName [IN APPFileName | EXEFileName]
   [ADDITIVE] [ALIAS AliasName]

Parameters

TO ClassLibraryName
Specifies the name of the .vcx visual class library to open. If ClassLibraryName does not include a fully qualified path, Visual FoxPro first searches for the visual class library in the default Visual FoxPro directory, and then in the directories in the Visual FoxPro path. The default Visual FoxPro directory is specified with SET DEFAULT, and the Visual FoxPro search path is specified with SET PATH.

Issuing SET CLASSLIB TO without ClassLibraryName closes all open visual class libraries. Use RELEASE CLASSLIB to close an individual visual class library.

IN APPFileName | EXEFileName
Specifies a Visual FoxPro application file (.app) or executable file (.exe) containing the visual class library.
ADDITIVE
Opens the .vcx visual class library without closing any currently open .vcx visual class libraries. If this clause is omitted, all open .vcx visual class libraries are closed.
ALIAS AliasName
Specifies an alias for the visual class library. The visual class library can be referenced by its alias. For example, the following commands open a .vcx visual class library named MyClass, assign it the alias MyCntrls, and then create a control named MyButton.
SET CLASSLIB TO MyClass ALIAS MyCntrls
mMyButton = CREATEOBJ('MyCntrls.MyButton')

Remarks

When CREATEOBJECT( ), ADD OBJECT in DEFINE CLASS, or the AddObject method is issued, Visual FoxPro searches for the class definition defining the object specified in these commands in the following locations and order:

  1. The Visual FoxPro base classes.
  2. Class definitions in memory in the order they are loaded.
  3. Class definitions in the current program.
  4. Class definitions in the .vcx class libraries opened with SET CLASSLIB.
  5. Class definitions in procedure files opened with SET PROCEDURE.
  6. Class definitions in the Visual FoxPro program execution chain.
  7. The OLE Registry if SET OLEOBJECT is set to ON.

If the class definition containing the object cannot be located, Visual FoxPro generates an error message.

Example

The following example uses CREATE CLASSLIB to create a visual class library named myclslib. A class named myform based on the Visual FoxPro Form base class is created and is stored in the myclslib visual class library. SET CLASSLIB is used to open the myclslib visual class library so that classes within it can be used.

CREATE CLASSLIB myclslib     && Creates a new .VCX visual class library
CREATE CLASS myform OF myclslib AS "Form"  && Creates new class
SET CLASSLIB TO myclslib ADDITIVE     && Opens MyClsLib.VCX

See Also

ADD CLASS | AddObject Method | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | MODIFY CLASS | RELEASE CLASSLIB | SET PROCEDURE | SET OLEOBJECT


SET CLOCK Command

Determines whether Visual FoxPro displays the system clock and specifies the clock location on the main Visual FoxPro window.

SET CLOCK ON | OFF | STATUS
-or-
SET CLOCK TO [nRow, nColumn]

Parameters

ON
Displays the clock in the upper-right corner of the main Visual FoxPro window.
OFF
(Default) Removes the clock from the status bar or from the main Visual FoxPro window.
STATUS
Displays the clock in the graphical status bar. Issue SET STATUS BAR ON to display the graphical status bar.
TO [nRow, nColumn]
Using row and column coordinates, specifies where the clock is displayed in the main Visual FoxPro window. Use SET CLOCK TO without the coordinates to display the clock in its default position in the upper-right corner of the main Visual FoxPro window.

If you place the clock in the graphical status bar with SET CLOCK STATUS and you specify a location in the main Visual FoxPro window with TO nRow, nColumn, Visual FoxPro removes the clock from the graphical status bar and places it at the location you specify.

See Also

SET BRSTATUS | SET HOURS | SET STATUS


SET COLLATE Command

Specifies a collation sequence for character fields in subsequent indexing and sorting operations.

SET COLLATE TO cSequenceName

Parameters

cSequenceName
Specifies a collation sequence. The following table lists collation sequence options that are available.
cSequenceName | Language
ARABIC | Arabic
CZECH | Czech
DUTCH | Dutch
GENERAL | English, French, German, Modern Spanish, Portuguese, and other Western European languages
GERMAN | German phone book order (DIN)
GREEK | Greek
HEBREW | Hebrew
HUNGARY | Hungarian
ICELAND | Iceland
JAPANESE | Japanese
KOREAN | Korean
MACHINE | Machine (the default collation sequence for earlier FoxPro versions)
NORDAN | Norwegian, Danish
PINYIN | Simplified Chinese
POLISH | Polish
RUSSIAN | Russian
SLOVAK | Slovak
SPANISH | Traditional Spanish
STROKE | Simplified and traditional Chinese
SWEFIN | Swedish, Finnish
THAI | Thai
TURKISH | Turkish
UNIQWT | Unique Weight

Note When you specify the SPANISH option, "ch" is a single letter that sorts between "c" and "d", and "ll" sorts between "l" and "m". If you specify a collation sequence option as a literal character string, be sure to enclose the option in quotation marks:

SET COLLATE TO "SWEFIN"

MACHINE is the default collation sequence option and is the sequence FoxPro users are familiar with. Characters are ordered as they appear in the current code page.

GENERAL might be preferable for U.S. and Western European users. Characters are ordered as they appear in the current code page. In FoxPro versions earlier than 2.5, you might have used UPPER( ) or LOWER( ) on character fields when you created indexes. In FoxPro versions later than 2.5, you can specify the GENERAL collation sequence option and omit the UPPER( ) conversion instead.

If you specify a collation sequence option other than MACHINE, and if you create an .idx file, a compact .idx is always created.

Use SET("COLLATE") to return the current collation sequence.

If you include the following line in your Visual FoxPro configuration file, a collation sequence is specified when you start Visual FoxPro:

COLLATE = cSequenceName

This is identical to issuing the following command:

SET COLLATE TO cSequenceName

Remarks

SET COLLATE allows you to order tables containing accented characters for any of the supported languages. Changing the setting of SET COLLATE doesn't affect the collating sequence of previously opened indexes. Visual FoxPro automatically maintains existing indexes, providing the flexibility to create many different types of indexes, even for the same field.

For example, if an index is created with SET COLLATE set to GENERAL, and the SET COLLATE setting is later changed to SPANISH, the index retains the GENERAL collation sequence.

SET COLLATE is scoped to the current data session.

When using the SET COLLATE TO command, you may receive the error "Collating sequence <sequencename> is not found." This occurs when you attempt to use a collating sequence that is not supported by the current code page. To prevent this error, you must specify a compatible code page in your Visual FoxPro configuration file. For instance, you may see the error "Collating sequence 'CZECH' is not found" when issuing the command SET COLLATE TO 'CZECH'. To enable support for the Czech collating sequence, add the following line to your config.fpw file and restart Visual FoxPro:

CODEPAGE = 1250

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro in Developing International Applications.

For more information on configuring Visual FoxPro, see Configuring Visual FoxPro and Special Terms for Configuration Files.

See Also

IDXCOLLATE( ) | SET DATASESSION | Code Pages Supported by Visual FoxPro | Special Terms for Configuration Files | SYS(2300) - Add or Remove Code Page | CREATE TABLE - SQL Command | ALTER TABLE - SQL Command | INDEX Command


SET COLOR OF SCHEME Command

Specifies the colors of a color scheme or copies one color scheme to another color scheme.

SET COLOR OF SCHEME nScheme1 TO   [SCHEME nScheme2 | ColorPairList]

Parameters

nScheme1
Specifies the number of the color scheme you want to change. This can be a value from 1 through 24.
Note In Visual FoxPro, color schemes 13 through 15 are reserved for internal use. Do not use these color schemes.
TO [SCHEME nScheme2]
Specifies the number of a color scheme to which color scheme nScheme1 is changed.
TO [ColorPairList]
Specifies up to 10 color pairs you would like to change in your color scheme. You can selectively change colors in a color scheme by including a comma for each color pair that you don't want to change. For example, to change the third color pair in color scheme 1 to bright white and blue and leave the rest of the color settings unchanged, use this command:
SET COLOR OF SCHEME 1 TO , , W+/B*

A color pair can also be specified with a set of six RGB (red, green, and blue) color values separated by commas. To change the third color pair in color scheme 1 to bright white and blue and leave the rest of the color settings unchanged, you can use this command:

SET COLOR OF SCHEME 1 TO , , RGB(255,255,255,0,0,255)

Remarks

Not all interface elements can be controlled by color schemes — system windows, such as the View and Command windows, the system menu bar, and so on are always controlled by the Control Panel color settings. Issuing SET COLOR OF SCHEME nScheme1 TO without including an optional clause restores the colors from the current color scheme.

See Also

CREATE COLOR SET | SET COLOR SET


SET COLOR SET Command

Loads a previously defined color set.

SET COLOR SET TO [ColorSetName]

Parameters

ColorSetName
Specifies the color set to load.

Remarks

You can create color sets with SET COLOR OF SCHEME and save them with CREATE COLOR SET.

If you issue SET COLOR SET without an optional clause, the current color set remains loaded.

See Also

CREATE COLOR SET | SET COLOR OF SCHEME


SET COMPATIBLE Command

Controls compatibility with Microsoft FoxBASE+ and other FoxPro languages.

SET COMPATIBLE FOXPLUS | OFF | DB4 | ON [PROMPT | NOPROMPT]

Parameters

FOXPLUS | OFF
(Default) These two keywords can be used interchangeably. Each allows programs created in FoxBASE+ to run in Microsoft Visual FoxPro without changes.
DB4 | ON
These two keywords can be used interchangeably. Including either keyword affects the behavior of the commands and functions listed below.
PROMPT | NOPROMPT
These options determine whether Visual FoxPro displays a dialog box when you open a dBASE table containing a memo field.

Include the PROMPT option to display the Convert Memos dialog box. If you open a dBASE table containing a memo field, Visual FoxPro by default displays the Convert Memos dialog box, which enables you to convert the dBASE memo file to a Visual FoxPro format. You must convert the memo file to a Visual FoxPro format to open the table in Visual FoxPro. You can later convert the memo file to a dBASE format by including the TYPE FOXPLUS option in the COPY command.

If you include NOPROMPT, the Convert Memos dialog box is not displayed when you open a dBASE table containing a memo field. The dBASE memo file is automatically converted to a Visual FoxPro format.

Remarks

Commands and functions affected by SET COMPATIBLE include LIKE( ), PLAY MACRO, SELECT( ), and STORE (when STORE is used with arrays).

SET COMPATIBLE does not create compatibility with other commands, functions, or features not supported in Visual FoxPro. For example, it does not make it possible for you to open a report form created in other products with the Report Designer.

The following table lists the commands affected by SET COMPATIBLE.

Commands

@ ... GET with a RANGE clause | PLAY MACRO
@ ... SAY with CHR(7) | READ with an @ ... GET VALID clause
@ ... SAY scrolling | Nested READs
@ ... SAY when STATUS is ON | READ
ACTIVATE SCREEN | RUN | !
ACTIVATE WINDOW | SET COLOR TO
APPEND MEMO | SET BORDER
BROWSE | SET FIELDS
DECLARE | SET MESSAGE
DIMENSION | SET MEMOWIDTH
GO | GOTO with SET TALK ON | SET PRINTER TO <file>
FSIZE( ) | STORE
INKEY( ) | SUM
LASTKEY( ) | TRANSFORM( ) with a numeric PICTURE clause
LIKE( ) | SELECT( )
Menu commands | SYS(2001, "COLOR")

See Also

SET KEYCOMP | Backward-Compatible Language Elements


SET CONFIRM Command

Specifies whether the user can exit a text box by typing past the last character in the text box.

SET CONFIRM ON | OFF

Parameters

ON
Specifies that the user cannot exit a text box by typing past the last character in the text box. To exit the text box, the user can press ENTER, TAB, or any of the arrow keys to move from a text box to another control.

SET CONFIRM ON also affects menu items and menu titles created with DEFINE BAR and DEFINE PAD. If the user types the first letter of the menu item or menu title, the item or title is selected but is not chosen. To choose the menu item or title when it is selected, the user should press ENTER or the SPACEBAR.

OFF
Specifies that the user can exit a text box by typing past the last character in the text box. The insertion point, when it reaches the last character in a text box, moves to the next control, and the bell is sounded (if SET BELL is set to ON).

OFF is the default value of SET CONFIRM.

SET CONFIRM OFF also affects menu items and menu titles. If SET CONFIRM is set to OFF, the user can choose an item from a menu or a menu title in a menu bar by pressing the key corresponding to the first letter of the menu item or title. (When SET CONFIRM is set to ON, this action only selects the menu item or title.)

Remarks

SET CONFIRM has no effect on access keys for menu items and menu titles. If a menu item or menu title is created with an access key, the menu item or title can be chosen by pressing the corresponding access key.

You can create text boxes using the Form Designer.

SET CONFIRM is scoped to the current data session.

See Also

TextBox Control | SET DATASESSION | Form Designer


SET CONSOLE Command

Enables or disables output to the main Visual FoxPro window or to the active user-defined window from within programs.

SET CONSOLE ON | OFF

Parameters

ON
(Default) Sends all output to the main Visual FoxPro window or to the active user-defined window.
OFF
Suppresses output to the main Visual FoxPro window or to the active user-defined window.

Remarks

SET CONSOLE is set to ON when you are using Visual FoxPro interactively, and it cannot be changed to OFF from the Command window. You can change the setting to OFF only from within a program.

SET CONSOLE affects some interactive Visual FoxPro dialog boxes. For example, if SET CONSOLE is set to OFF and you issue BROWSE when no table is open, Visual FoxPro displays an error message. If SET CONSOLE is set to ON in the same circumstances, Visual FoxPro displays the Open dialog box.

SET CONSOLE does not affect output from @ ... SAY. Output from @ ... SAY is controlled by the SET DEVICE setting.

Note An error always sets SET CONSOLE to ON.

See Also

SYS( ) | Working with User-Defined Functions


SET COVERAGE Command

Turns code coverage on or off, or specifies a text file to which code coverage information is directed.

SET COVERAGE TO [FileName [ADDITIVE]]

Parameters

TO FileName
Specifies the name of a text file to which code coverage information is directed. Issue SET COVERAGE TO without a file name to close the text file.

If the file you specify does not exist, Visual FoxPro automatically creates and opens it.

ADDITIVE
Appends the code coverage information to the end of the text file specified with FileName. If you omit ADDITIVE, the code coverage information replaces the contents of the text file.

Remarks

You can also set code coverage options in the Coverage dialog box online topic.

For more information about the Visual FoxPro Coverage Profiler, see Coverage Profiler Application.

See Also

_COVERAGE, | SET EVENTTRACKING | Coverage dialog box | Coverage Profiler Application | The Logging of Code Coverage


SET CPCOMPILE Command

Specifies the code page for compiled programs.

SET CPCOMPILE TO [nCodePage]

Parameters

nCodePage
Specifies the compilation code page with nCodePage.

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro in Developing International Applications.

Issue SET CPCOMPILE TO without nCodePage to reset the compilation code page to the current code page. Use CPCURRENT( ) to determine the current code page.

Remarks

Use SET CPCOMPILE to compile programs for a specific code page. The code page you specify with SET CPCOMPILE is used for programs compiled automatically by Visual FoxPro, programs compiled from the Compile dialog, and programs compiled with the COMPILE command. However, you can include the AS clause in the COMPILE command to override the code page you specify with SET CPCOMPILE.

See Also

COMPILE | CPCURRENT( ) | Code Pages Supported by Visual FoxPro


SET CPDIALOG Command

Specifies whether the Code Page dialog box is displayed when a table is opened.

SET CPDIALOG ON | OFF

Parameters

ON
(Default) Displays the Code Page dialog box when you open a table and the following conditions are true:
  • The table is opened exclusively.
  • The table is not marked with a code page.
OFF
Does not display the Code Page dialog box when a table is opened.

Remarks

The Code Page dialog box makes it possible for you to specify a code page for tables created in earlier FoxPro versions and other products that create Visual FoxPro tables. The table is marked with the code page you choose.

When creating an application, issue SET CPDIALOG ON to ensure that the tables included in your application are marked with the proper code page. In your completed application, be sure that SET CPDIALOG is OFF.

You can also interactively specify whether the Code Page dialog box is displayed with the Prompt for Code Page check box in the Data tab of the Options dialog box. The Options dialog box is displayed by choosing Options from the Tools menu.

Note For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro in Developing International Applications.

See Also

CPCURRENT( ) | CPCONVERT( ) | CPDBF( ) | GETCP( ) | USE


SET CURRENCY Command

Defines the currency symbol and specifies its position in the display of numeric, currency, float, and double expressions.

SET CURRENCY TO [cCurrencySymbol]
-or-
SET CURRENCY LEFT | RIGHT

Parameters

cCurrencySymbol
Specifies a character string representing the currency symbol; can be one to nine characters long. Issue SET CURRENCY TO without cCurrencySymbol to reset the currency symbol to the default dollar sign ($).

You can also specify a currency symbol using Alt+nnn. Specify the Euro currency symbol (€) with Alt+0128 if you have installed supporting Windows fonts. You also can set the default currency symbol in the Regional tab of the Options dialog box.

LEFT
(Default) Positions the currency symbol to the left of the currency value.
RIGHT
Positions the currency symbol to the right of the currency value.

Remarks

The currency symbol is displayed in output created with @ ... SAY and in text boxes created with @ ... GET when the $ code is included in the FUNCTION or PICTURE clause.

SET CURRENCY is scoped to the current data session.

Example

The following example displays the DM currency symbol on either side of the currency value. If you use PICTURE to display the currency symbol, be sure to include @ before the dollar sign.

STORE SET('CURRENCY') TO gcCurrPosit
STORE 1234.56 TO gnDollarAmnt
CLEAR
SET CURRENCY TO 'DM'
@ 2,2 SAY gnDollarAmnt PICTURE '@$99,999.99'
IF gcCurrPosit = 'LEFT'
   SET CURRENCY RIGHT
ELSE
   SET CURRENCY LEFT
ENDIF
@ 4,2 SAY gnDollarAmnt FUNCTION '$99,999.99'

See Also

SET DATASESSION | SET DECIMALS | SET SEPARATOR | SET SYSFORMATS


SET CURSOR Command

Determines whether the insertion point is displayed when Visual FoxPro waits for input.

SET CURSOR ON | OFF

Parameters

ON
(Default) Causes the insertion point to be displayed during a pending @ ... GET, @ ... EDIT, WAIT, or INKEY( ).
OFF
Prevents the insertion point from being displayed during a pending @ ... GET, @ ... EDIT, WAIT, or INKEY( ).

Remarks

SET CURSOR, similar to SYS(2002), enables you to turn the insertion point on or off.

See Also

INKEY( ) | SET( ) | SYS(2002) – Turn Insertion Point On or Off | WAIT


SET DATABASE Command

Specifies the current database. SET DATABASE is scoped to the current data session. When one or more databases are open, you can also specify the current database by selecting an open database from the Database drop-down list on the Standard toolbar.

You can have many databases open at the same time, but only one can be the current database. Commands and functions that manipulate open databases, such as ADD TABLE and DBC( ), operate on the current database.

SET DATABASE TO [DatabaseName]

Parameters

DatabaseName
Specifies the name of an open database to make the current database. If you omit DatabaseName, no open database is made the current database. You can specify an empty string for DatabaseName, which is treated as if you omitted DatabaseName.

Remarks

Visual FoxPro might automatically open databases when executing a query or a form.

Example

The following example creates two databases named mydbc1 and mydbc2, and a table named table1. SET DATABASE is used to make mydbc1 the current database, and table1 is added to mydbc1 when it is created. The table is then closed and removed from mydbc1. SET DATABASE is used to make mydbc1 the current database, and ADD TABLE is then used to add the table to mydbc2. RENAME TABLE is used to change the name of the table from table1 to table2.

CREATE DATABASE mydbc1
CREATE DATABASE mydbc2
SET DATABASE TO mydbc1
CREATE TABLE table1 (cField1 C(10), n N(10))  && Adds table to mydbc1
CLOSE TABLES     && A table must be closed to remove it from a database
REMOVE TABLE table1
SET DATABASE TO mydbc2
ADD TABLE table1
RENAME TABLE table1 TO table2

See Also

ADD TABLE | CLOSE DATABASES | DBC( ) | DBGETPROP( ) | DBSETPROP( ) | DELETE DATABASE | DISPLAY TABLES | MODIFY DATABASE | OPEN DATABASE | REMOVE TABLE | SET DATASESSION


SET DATASESSION Command

Activates the specified form's data session.

SET DATASESSION TO [nDataSessionNumber]

Parameters

nDataSessionNumber
Specifies a form's data session to activate. If you omit nDataSessionNumber, data session 1 (the Global data session) is activated.

Remarks

By default, data session 1, the Global data session, is active when you start Visual FoxPro.

A form's DataSession property determines whether the form has its own unique data session when the form is created. If a form's DataSession property is set to true (.T.), the form has its own data session; otherwise, a data session is not created for the form. You can use the form's read-only DataSessionId property to determine the form's data session number.

A data session is closed when the form that created the data session is released.

SET DATASESSION typically is used to debug forms. Care should be taken when issuing this command when a form is active, because tables in non-current datasessions are not accessible.

The following SET commands scope to the current data session:

SET Commands

SET ANSI | SET AUTOSAVE
SET BLOCKSIZE | SET CARRY
SET CENTURY | SET COLLATE
SET CONFIRM | SET CURRENCY
SET DATABASE | SET DATE
SET DECIMALS | SET DELETED
SET DELIMITERS | SET EXACT
SET EXCLUSIVE | SET FIELDS
SET FIXED | SET HOURS
SET LOCK | SET MARK TO
SET MEMOWIDTH | SET MULTILOCKS
SET NEAR | SET NULL
SET POINT | SET REPROCESS
SET SAFETY | SET SECONDS
SET SEPARATOR | SET SYSFORMATS
SET TALK | SET UNIQUE

See Also

AUSED( ) | CREATE FORM | DataSession Property | DataSessionId Property


SET DATE Command

Specifies the format for the display of Date and DateTime expressions.

SET DATE [TO] AMERICAN | ANSI | BRITISH | FRENCH | GERMAN | ITALIAN
 | JAPAN | TAIWAN | USA | MDY | DMY | YMD| SHORT | LONG

Remarks

Here are the settings and the resulting date formats:

Setting | Format
AMERICAN | mm/dd/yy
ANSI | yy.mm.dd
BRITISH/FRENCH | dd/mm/yy
GERMAN | dd.mm.yy
ITALIAN | dd-mm-yy
JAPAN | yy/mm/dd
TAIWAN | yy/mm/dd
USA | mm-dd-yy
MDY | mm/dd/yy
DMY | dd/mm/yy
YMD | yy/mm/dd
SHORT | Short date format determined by the Windows Control Panel short date setting.
LONG | Long date format determined by the Windows Control Panel long date setting.
Note When SET DATE is set to SHORT or LONG, a date before {^1601-01-01} is invalid and generates an error.

The default date setting is AMERICAN.

The SET DATE setting also determines how the date appears in datetime expressions.

If DATE is set to SHORT or LONG, the SET CENTURY, SET MARK, SET HOURS, and SET SECONDS settings are ignored.

SET DATE is scoped to the current data session.

See Also

DATE( ) | DATETIME( ) | SET CENTURY | SET DATASESSION | SET MARK TO | SET SYSFORMATS


SET DEBUGOUT Command

Directs debugging output to a file.

SET DEBUGOUT TO [FileName [ADDITIVE]]

Parameters

FileName
Specifies the name of the file to which debugging output is directed. If the file you specify does not exist, it is automatically created. If the file you specify already exists, its contents are overwritten unless you include the ADDITIVE clause.

Issue SET DEBUGOUT TO to stop direction of debugging output to the file and close the file.

ADDITIVE
Specifies that debugging output is appended to the end of the file specified with FileName.

Remarks

Debugging output that is directed to the file includes ASSERT messages, output from the DEBUGOUT command, and events that are specified with SET EVENTLIST or in the Event Tracking Dialog Box. See the Event Tracking dialog box topic for more information about specifying events to track interactively.

See Also

ASSERT | DEBUG | DEBUGOUT | SET EVENTLIST | SET EVENTTRACKING


SET DECIMALS Command

Specifies the number of decimal places displayed in numeric expressions.

SET DECIMALS TO [nDecimalPlaces]

Parameters

nDecimalPlaces
Specifies the minimum number of decimal places to display. The default is two decimal places. The maximum number of decimal places is 18; the minimum is zero.

Remarks

SET DECIMALS specifies the minimum number of decimal places used to display the results of division, multiplication, and trigonometric and financial functions.

SET DECIMALS is scoped to the current data session.

See Also

SET DATASESSION | SET FIXED | SET SYSFORMATS


SET DEFAULT Command

Specifies the default drive and directory.

SET DEFAULT TO [cPath]

Parameters

cPath
Specifies one of the following:
  • A drive designator.
  • A drive designator with a directory name.
  • A child directory name.
  • Any of the above using Microsoft MS-DOS shorthand notation ( \ or ..).

Remarks

SET DEFAULT changes the default directory to the directory you specify.

Microsoft® Visual FoxPro® searches for a file in the default Visual FoxPro directory. The default directory is the one from which you start Visual FoxPro. However, you can specify a different default directory in your Visual FoxPro configuration file or in a startup program. If Visual FoxPro cannot find a file in the default directory, it then searches the Visual FoxPro path if one has been specified. Use SET PATH to specify the Visual FoxPro path.

If you create a file and don't specify where to place it, the file is placed in the default Visual FoxPro directory.

The SET DEFAULT command is not supported in either single or multithreaded DLL servers. This command changes the default directory of the entire process, so all threads which are part of the process are affected. Use the SET PATH command in DLL servers, in place of CD and CHDIR.

When you quit Visual FoxPro, you are returned to Microsoft® Windows®. When you exit Windows, you are returned to the drive and directory from which you started Windows.

Tip SYS(5) returns the default drive. SYS(2003) returns the default directory with no drive designator. SYS(5) + SYS(2003) returns the default drive and the directory.

You can change the default drive to drive A using either of the following commands:

SET DEFAULT TO A
SET DEFAULT TO A:

You can specify a specific directory:

SET DEFAULT TO A:\sales
SET DEFAULT TO C:\sales\data

You can specify a child directory. If the root directory on drive C is the default Visual FoxPro directory, issue the following command to change the default directory to C:\Sales:

SET DEFAULT TO sales

You can use MS-DOS shorthand notation. If the current directory is C:\Sales\Data, issue the following command to make the root directory the default directory:

SET DEFAULT TO \

You can also move the default directory one directory toward the root directory with the following command:

SET DEFAULT TO ..

See Also

CD | CHDIR | MD | MKDIR | RD | RMDIR | SET PATH | SYS(5) – Default Drive | SYS(2003) – Current Directory


SET DELETED Command

Specifies whether Visual FoxPro processes records marked for deletion and whether they are available for use with other commands.

SET DELETED ON | OFF

Parameters

ON
Specifies that commands that operate on records, including records in related tables, using a scope ignore records that are marked for deletion.
OFF
Specifies that commands that operate on records, including records in related tables, using a scope can access records marked for deletion. (Default)
Note Calling SQL SELECT with SET DELETED OFF includes records fitting the specified criteria in the result set and sets those records as available for processing. That is, SET DELETED OFF is not set for the records in the result set.

Remarks

Queries that use DELETED( ) to test the status of records can be optimized using Rushmore Query Optimization technology if the table is indexed on DELETED( ).

For more information on optimizing queries, see Using Rushmore Query Optimization to Speed Data Access.

You can mark records for deletion by issuing DELETE – SQL or DELETE, or by choosing Delete Records... from the Table menu from within a Browse or Edit window.

You can recall records by issuing RECALL or by choosing Recall Records... from the Table menu from within a Browse or Edit window.

Note SET DELETED is ignored if the default scope for the command is the current record or if you include a scope of a single record. The exception exists with the SEEK command, in which case, SET DELETED is always respected. INDEX and REINDEX always ignore SET DELETED and index all records in the table.

SET DELETED is scoped to the current data session.

See Also

DELETE | DELETE – SQL | DELETED( ) | PACK | RECALL | SET DATASESSION


SET DEVELOPMENT Command

Causes Visual FoxPro to compare the creation date and time of a program with those of its compiled object file when the program is run.

SET DEVELOPMENT ON | OFF

Parameters

ON
(Default) Specifies that Visual FoxPro recompile the source program before it executes if it is more current than its compiled object program. This option ensures that the most current version of a program is executed.
OFF
Specifies that Visual FoxPro not compare the source and compiled versions of the program. If SET DEVELOPMENT is set to OFF, you might not always be executing the most current version of a program.

Remarks

SET DEVELOPMENT needs to be set to ON when programs are modified outside of Visual FoxPro. Using an external editor — for example, a terminate-and-stay-resident (TSR) editor — may require you to issue CLEAR PROGRAM before you execute the modified program. For more information, see CLEAR PROGRAM. Use SET DEVELOPMENT OFF for optimum performance.

When SET DEVELOPMENT is set to ON, program execution can be canceled during a READ. The Cancel command on the Program menu is available when SET DEVELOPMENT is ON and a READ is active. Choosing Cancel during the READ cancels program execution. If SET DEVELOPMENT is set to OFF, the Cancel command on the Program menu is unavailable during a READ.

SET DEVELOPMENT also determines whether the Trace window is opened when an error occurs within a Form that is running. If SET DEVELOPMENT is ON, the Trace window is opened with the program line that caused the error selected. If SET DEVELOPMENT is OFF, the Trace window is not opened when an error occurs in a Form.

See Also

COMPILE | MODIFY COMMAND | MODIFY FILE


SET DEVICE Command

Directs output from @ ... SAY to the screen, a printer, or a file.

SET DEVICE TO SCREEN | TO PRINTER [PROMPT] | TO FILE FileName

Parameters

TO SCREEN
Directs @ ... SAY output to the main Visual FoxPro window or to the active user-defined window.
TO PRINTER [PROMPT]
Directs @ ... SAY output to the printer. A page eject is issued when the coordinates in @ ... SAY specify a location on the page higher than the location specified by the coordinates in the previous @ ... SAY.

You can include the optional PROMPT clause to display a dialog box before printing starts. In this dialog box, the user can adjust printer settings, including the number of copies to print and page numbers. The currently installed printer driver determines which printer settings the user can adjust. Place PROMPT immediately after TO PRINTER.

TO FILE FileName
Specifies a file to which @ ... SAY sends output.

Remarks

@ ... SAY output can be sent to the main Visual FoxPro window, the active user-defined window, the printer, or a file.

See Also

SYS(101) – Device Setting | @ ... SAY Command | PROMPT( ) Function


SET ECHO Command

Opens the Trace window for program debugging. Included for backward compatibility. Use the Trace window instead.

SET ECHO ON | OFF

Parameters

ON
Displays the source code for the program that is executing in the Trace window. The line currently executing is highlighted.
OFF
(Default) Closes the Trace window in FoxPro versions earlier than 2.0. From within a program, the Trace window can be closed with DEACTIVATE WINDOW TRACE.

Remarks

You can also use the Trace window to set breakpoints, which suspend program execution.

For more information about the Trace window, see the Trace Window.

See Also

RESUME | SET STEP | SUSPEND


SET ENGINEBEHAVIOR Command

Enables SQL data engine compatibility with Visual FoxPro 7.0 or Visual FoxPro 8.0.

SET ENGINEBEHAVIOR 70 | 80

Parameters

70
Specifies that Visual FoxPro treats SQL SELECT commands as it did in versions prior to Visual FoxPro 8.0
80
Specifies that Visual FoxPro treats SQL SELECT commands as follows. (Default)
SQL SELECT clause | Behavior
DISTINCT You cannot use the DISTINCT clause with Memo or General fields. Instead, wrap a Memo field inside a function such as PADR( ) or ALLTRIM( ).

For more information, see PADL( ) | PADR( ) | PADC( ) Functions and ALLTRIM( ) Function.
UNION | The UNION clause does not support Memo fields unless the ALL clause is included in the SQL SELECT statement.
GROUP BY The GROUP BY clause does not support Memo or General fields.

The GROUP BY clause must list every field in the SELECT list except for fields contained in an aggregate function, such as the COUNT( ) function. In addition, the GROUP BY clause must also list every field in a HAVING clause except for fields contained in an aggregate function.

For example, the following code raises an error because the field company is not listed in the GROUP BY clause.

SELECT company, country FROM Customer GROUP BY country

You can include an aggregate function in the SELECT list without having it in the GROUP BY clause.

For example, the following code uses the COUNT( ) function on the field company without having the field company in the GROUP BY clause.

SELECT COUNT(company), country FROM Customer GROUP BY country
HAVING A SQL SELECT statement can contain the HAVING clause without the GROUP BY clause as long as the SQL SELECT statement does not contain any aggregate functions.

For example, the following code filters query results by specifying the country field must equal "Sweden".

SELECT customerid FROM customers HAVING country="Sweden"
LIKE SQL SELECT statements do not automatically remove trailing spaces from values compared with the LIKE operation. In versions prior to Visual FoxPro 8.0, both values in the LIKE operation were trimmed from the right prior to evaluation.

For example, the following code assumes that you have a table named table1, and the table has three rows that contain values of "1 ", "12 ", and "123", respectively.

SELECT * FROM table1 WHERE column1 LIKE "1__"

Visual FoxPro version 7.0 and earlier returns one row with the value of "123". Visual FoxPro 8.0 returns three rows with the values, "1 ", "12 ", and "123".

If the beginning of the filter condition matches the pattern of the expression in the LIKE operation, and the rest of the filter condition contains trailing spaces, the LIKE operation ignores the trailing spaces and returns True (.T.). Trailing spaces in the pattern are not ignored.

Remarks

Using SET ENGINEBEHAVIOR set to 70 might lead to ambiguous results from SQL SELECT commands when the DISTINCT and UNION clauses are used with memos and the GROUP BY clause, the HAVING clause without a GROUP BY clause, and when using the LIKE clause.

The scope of SET ENGINEBEHAVIOR is global.

See Also

SET Command Overview | SELECT - SQL Command | Special Terms for Configuration Files | SYS(3099) - SQL Data Engine Compatibility Mode


SET ESCAPE Command

Determines whether pressing the ESC key interrupts program and command execution.

SET ESCAPE ON | OFF

Parameters

ON
(Default) Allows command and program execution to be interrupted when the user presses ESC.

If the user presses ESC during the execution of a command or program while the insertion point is in the Command window, the following message appears:

*** INTERRUPTED ***

If the user presses ESC during command or program execution, processing completes at the current program line, and an alert appears with the following three options:

  • (Default) Choose Cancel to immediately stop program execution and return to the Command window.
  • Choose Suspend to pause program execution and return to the Command window. This option is useful for debugging a program. Choosing Resume from the Program menu or issuing RESUME in the Command window restarts the program at the line at which it was paused.
  • Choose Ignore to continue program execution at the line at which it was paused.
OFF
Prevents command and program execution from being interrupted when the user presses ESC.

See Also

ON ESCAPE | ON KEY LABEL | RESUME Command


SET EVENTLIST Command

Specifies events to track in the Debug Output Window or in a file specified with SET EVENTTRACKING.

SET EVENTLIST TO [EventName1 [, EventName2 ...] [ADDITIVE]]

Parameters

EventName1 [, EventName2 ...]
Specifies the names of the events to track. You can include any number of event names separated by commas.
ADDITIVE
Specifies that the events EventName1, EventName2 ... are added to the set of events currently being tracked. If ADDITIVE is omitted, only the events EventName1, EventName2 ... are tracked.

Remarks

Issue SET EVENTLIST TO without any event names to remove all events from the set of events being tracked. You can also specify events to track in the Event Tracking dialog box.

See Also

SET DEBUGOUT | SET EVENTTRACKING | Event Tracking dialog box


SET EVENTTRACKING Command

Turns event tracking on or off or specifies a text file to which event tracking information is directed.

SET EVENTTRACKING ON | OFF | PROMPT | TO [FileName [ADDITIVE]]

Parameters

ON
Turns event tracking on and directs event tracking information to the text file specified with FileName.
OFF
Turns event tracking off and stops directing event tracking information to the text file.
PROMPT
Displays the Event Tracking dialog box, allowing the user to specify which events are tracked.
TO FileName
Specifies the name of a text file to which event tracking information is directed. SET EVENTTRACKING must be ON to direct event tracking information to a text file. Issue SET EVENTTRACKING TO without a file name to close the text file.

If the file you specify doesn't exist, Microsoft Visual FoxPro automatically creates and opens it.

ADDITIVE
Appends the event tracking information to the end of the text file specified with FileName. If you omit ADDITIVE, the event tracking information replaces the contents of the text file.

Remarks

Use SET EVENTLIST or the Event Tracking dialog box to specify the events that are tracked.

Starting with Visual FoxPro 7, the event log format differs from earlier versions. The new format adds a timestamp (to allow for profiling) to the event information already displayed in each line.

See Also

SET COVERAGE | SET EVENTLIST | Event Tracking dialog box


SET EXACT Command

Specifies the rules Visual FoxPro uses when comparing two strings of different lengths.

SET EXACT ON | OFF

Parameters

ON
Specifies that expressions must match character for character to be equivalent. Any trailing blanks in the expressions are ignored for the comparison. For the comparison, the shorter of the two expressions is padded on the right with blanks to match the length of the longer expression.
OFF
(Default) Specifies that, to be equivalent, expressions must match character for character until the end of the expression on the right side is reached.

Remarks

The SET EXACT setting has no effect if both strings are the same length.

String Comparisons

Visual FoxPro has two relational operators that test for equality. The = operator performs a comparison between two values of the same type. This operator is suited for comparing character, numeric, date, and logical data.

However, when you compare character expressions with the = operator, the results might not be exactly what you expect. Character expressions are compared character for character from left to right until one of the expressions isn't equal to the other, or until the end of the expression on the right side of the = operator is reached (SET EXACT OFF), or until the ends of both expressions are reached (SET EXACT ON).

The == operator can be used when an exact comparison of character data is needed. If two character expressions are compared with the == operator, the expressions on both sides of the == operator must contain exactly the same characters, including blanks, to be considered equal. The SET EXACT setting is ignored when character strings are compared using ==.

The following table shows how the choice of operator and the SET EXACT setting affect comparisons. (An underscore represents a blank space.)

Comparison | = EXACT OFF | = EXACT ON | == EXACT ON or OFF
"abc" = "abc" | Match | Match | Match
"ab" = "abc" | No match | No match | No match
"abc" = "ab" | Match | No match | No match
"abc" = "ab_" | No match | No match | No match
"ab" = "ab_" | No match | Match | No match
"ab_" = "ab" | Match | Match | No match
"" = "ab" | No match | No match | No match
"ab" = "" | Match | No match | No match
"__" = "" | Match | Match | No match
"" = "___" | No match | Match | No match
TRIM("___") = "" | Match | Match | Match
"" = TRIM("___") | Match | Match | Match

SET EXACT is scoped to the current data session.

See Also

SET ANSI | = Command | ON KEY = Command


SET EXCLUSIVE Command

Specifies whether Visual FoxPro opens table files for exclusive or shared use on a network.

SET EXCLUSIVE ON | OFF

Parameters

ON
(The default for the global data session.) Limits accessibility of a table opened on a network to the user who opened it. The table isn't accessible to other users on the network. Unlike FLOCK( ), SET EXCLUSIVE ON also prevents all other users from having read-only access. A file can also be opened on a network for exclusive use by including the EXCLUSIVE clause with the USE command. It isn't necessary to perform record or file locking on a table opened for exclusive use.

Opening a table for exclusive use ensures that the file can't be changed by other users. For some commands, execution isn't possible until a table is opened for exclusive use. These commands are INSERT, INSERT BLANK, MODIFY STRUCTURE, PACK, REINDEX, and ZAP.

OFF
(The default for a private data session.) Allows a table opened on a network to be shared and modified by any user on the network.

For additional information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Remarks

Changing the setting of SET EXCLUSIVE doesn't change the status of previously opened tables. For example, if a table is opened with SET EXCLUSIVE set to ON, and SET EXCLUSIVE is later changed to OFF, the table retains its exclusive-use status.

SET EXCLUSIVE is scoped to the current data session.

See Also

FLOCK( ) | RLOCK( ) | SET DATASESSION | USE


SET FDOW Command

Specifies the first day of the week.

SET FDOW TO [nExpression]

Parameters

nExpression
Specifies the first day of the week. The following table lists the values nExpression can assume and the corresponding first day of the week.
Nexpression | Day of the week
1 | Sunday
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday

If you omit nExpression, the first day of the week is reset to Sunday (1).

Remarks

The first day of the week can also be set with the Week Starts On list box in the Regional tab of the Options dialog.

Example

STORE SET('FDOW') TO gnFdow  && Save current value
SET FDOW TO 1  && Sets first day of the week to Sunday, the default
SET FDOW TO 7  && Sets first day of the week to Saturday
SET FDOW TO &gnFdow  && Restore original day

See Also

CDOW( ) | DAY( ) | DOW( ) | SET FWEEK | SYS( ) Functions Overview | WEEK( )


SET FIELDS Command

Specifies which fields in a table can be accessed.

SET FIELDS ON | OFF | LOCAL | GLOBAL

-Or-

SET FIELDS TO [[FieldName1 [, FieldName2 ...]]
    | ALL [LIKE Skeleton | EXCEPT Skeleton]]

Parameters

ON
Specifies that only the fields in the field list can be accessed.
OFF
(Default) Specifies that all the fields in the current table can be accessed.
LOCAL
Specifies that only the fields in the current work area listed in the fields list can be accessed.
GLOBAL
Specifies that all fields in the field list, including fields in other work areas, can be accessed.

SET FIELDS GLOBAL lets you access fields in other work areas without issuing SET COMPATIBLE TO DB4.

TO [FieldName1 [, FieldName2 ...]]
Specifies the names of fields that can be accessed in the current table. You must include an alias with the field name in the following cases:
  • When the field is in a table that is open in a work area other than the currently selected work area.
  • When the field names are the same in two or more tables.

You can include fields from tables that are open in other work areas if the fields are prefaced with their table aliases. However, these fields cannot be accessed unless you issue SET FIELDS GLOBAL or SET COMPATIBLE DB4.

The field list can contain statements for creating calculated fields. A calculated field contains read-only data created with an expression. This expression can take any form, but it must be a valid FoxPro expression. Calculated fields cannot be accessed unless you issue SET FIELDS GLOBAL or SET COMPATIBLE DB4.

The format of the statement you use to create a calculated field is:

<calculated field name> = <expr>

This example creates a calculated field called LOCATION:

CLOSE DATABASES
USE customer
SET FIELDS TO LOCATION = ALLTRIM(city) + ', ' + state

CITY and STATE are the names of fields from the selected table.

ALL
Allows access to all the fields in the current table.
ALL LIKE Skeleton | EXCEPT Skeleton
You can selectively access fields by including the LIKE or EXCEPT clause or both. If you include LIKE Skeleton, you can access fields that match Skeleton. If you include EXCEPT Skeleton, you can access all fields except those that match Skeleton.

The skeleton Skeleton supports wildcards such as * and ?. For example, to access fields that begin with the letters A and P, issue the following:

SET FIELDS TO ALL LIKE A*,P*

The LIKE clause can be combined with the EXCEPT clause:

SET FIELDS TO ALL LIKE A*,P* EXCEPT PARTNO*

Remarks

SET FIELDS TO is additive — issuing SET FIELDS TO with a field list adds the specified fields to those that are currently accessible.

Issuing SET FIELDS TO implicitly performs SET FIELDS ON. Issuing SET FIELDS TO without any additional arguments implicitly performs SET FIELDS OFF. Issue SET FIELDS TO without including either a field list or ALL to remove all fields from the field list for the current table.

SET FIELDS is scoped to the current data session.

See Also

SET FILTER | SET DATASESSION | SET COMPATIBLE Command


SET FILTER Command

Specifies a condition that records in the current table must meet to be accessible.

SET FILTER TO [lExpression] [IN nWorkArea | cTableAlias]

Parameters

lExpression
Specifies the condition that records must satisfy.

If the current table is indexed on a field or fields specified in lExpression, Rushmore Query Optimization technology can optimize queries based on the field or fields.

IN nWorkArea | cTableAlias
Specifies the work area or table alias affected by the SET FILTER command. Use this clause to specify a work area or a table outside the current work area.

Remarks

Once SET FILTER is issued, only the records that satisfy the condition specified by the logical expression lExpression are available in the table. All commands that access the table respect the SET FILTER condition. A separate filter can be set for every open table.

The condition specified by SET FILTER isn't evaluated until the record pointer is moved in the table.

Issuing SET FILTER TO without lExpression turns off the filter for the current table.

SELECT – SQL does not respect the current filter condition.

See Also

FILTER( ) | SELECT – SQL | Working with Table Aliases


SET FIXED Command

Specifies if the number of decimal places used in the display of numeric data is fixed.

SET FIXED ON | OFF

Parameters

ON
Uses the SET DECIMALS setting to determine the number of decimal places displayed in results. The default number of decimal places is 2.
OFF
(Default) Allows the number of decimal places displayed in results to depend on the specific constants, variables, and operators used in a numeric expression. The contents of fields are displayed with the declared number of decimal places.

Remarks

SET FIXED is scoped to the current data session.

See Also

SET DECIMALS | SET DATASESSION | Numeric Data Type


SET FULLPATH Command

Specifies if CDX( ), DBF( ), MDX( ), and NDX( ) return the path in a file name.

SET FULLPATH ON | OFF

Parameters

ON
(Default) Specifies that CDX( ), DBF( ), MDX( ), and NDX( ) return the drive designator, path, and file name.
OFF
Specifies that only the drive designator and file name are returned.

See Also

CDX( ) | DBF( ) | MDX( ) | NDX( )


SET FUNCTION Command

Assigns an expression (keyboard macro) to a function key or key combination.

SET FUNCTION nFunctionKeyNumber | KeyLabelName TO [eExpression]

Parameters

nFunctionKeyNumber
Specifies the number of the function key assigned to the macro. For example, use SET FUNCTION 2 to specify the F2 function key.
KeyLabelName
Specifies a key combination, including a function key, to which to assign the macro. Visual FoxPro supports key combinations that include function keys. You can use the CTRL or SHIFT key in combination with a function key to create additional programmable keys. For a list of key label expressions, see ON KEY LABEL.
TO [eExpression]
Specifies the series of keystrokes stored to the function key or key combination. Visual FoxPro interprets a semicolon (;) in the expression as a carriage return.

Function key definitions can be cleared with CLEAR MACROS.

See Also

CLEAR MACROS | FKLABEL( ) | FKMAX( ) | ON KEY LABEL


SET FWEEK Command

Specifies the requirements for the first week of the year.

SET FWEEK TO [nExpression]

Parameters

nExpression
Specifies a value, which determines the requirements for the first week of the year. The following table lists the values nExpression can assume and the corresponding requirements for the first week of the year:
nExpression | First week requirement
1 | (Default) The first week contains January 1st.
2 | The larger half (four days) of the first week is in the current year.
3 | The first week has seven days.

If you omit nExpression, the first week of the year is reset to 1 (the first week contains January 1st).

Remarks

The first week of the year can also be set with the First Week of Year list box in the Regional tab of the Options dialog.

Example

STORE SET('FWEEK') TO gnFweek  && Save current value
SET FWEEK TO 1  && First week contains January 1st
SET FWEEK TO 3  && First week has seven days
SET FWEEK TO &gnFweek  && Restore original setting

See Also

CDOW( ) | DAY( ) | DOW( ) | SET FDOW | SYS( ) Functions Overview | WEEK( )


SET HEADINGS Command

Determines whether column headings are displayed for fields and whether file information is included when TYPE is issued to display the contents of a file.

SET HEADINGS ON | OFF

Parameters

ON
(Default) Specifies that the field names are displayed.

If TYPE is issued to display the contents of a file, Visual FoxPro inserts a form feed, the path and name of the file, and the date at the beginning of the displayed output.

OFF
Specifies that the field names are not displayed.

If TYPE is issued to display the contents of a file, Visual FoxPro does not insert additional information about the file at the beginning of the displayed output.

Remarks

SET HEADINGS specifies whether a field name appears as a column heading above each field in the output of AVERAGE, CALCULATE, DISPLAY, LIST, and SUM.

See Also

AVERAGE | CALCULATE | DISPLAY | LIST | SUM | TYPE


SET HELP Command

Enables or disables Microsoft Visual FoxPro online Help or specifies a Help file.

SET HELP ON | OFF

-Or-

SET HELP [TO [FileName]] [COLLECTION [cCollectionURL]] [SYSTEM]

Parameters

ON
(Default) Displays the Help window when you press F1 or issue HELP in the Command window.
OFF
Makes Visual FoxPro online Help unavailable.
TO [FileName]
Specifies a Help file that is displayed when you press F1 or issue HELP. You can specify a .Dbf-style Help file, a Winhelp (.Hlp) file, or an HTML (.Chm) help file.

Beginning with Visual FoxPro 7, if you issue SET HELP TO without including a file name, Visual FoxPro looks for the default help file, foxhelp.chm.

COLLECTION [cCollectionURL]
Specifies the name of an HTML Help collection to be used as Help source.
SYSTEM
Specifies that a collection name is used as the Help source.

Remarks

Use SET HELP to provide a tailored online Help file within a custom application or to switch between the different Help files in Visual FoxPro.

If you perform a complete installation of the MSDN (Microsoft Developer's Network) library, or you perform a custom installation of the MSDN library and you specify to install the Visual FoxPro documentation, the Visual FoxPro Help file, Foxhelp.chm, is installed. The Foxhelp.chm file is installed by default with the Visual FoxPro product.

The following table describes the registry values for Help settings:

Setting | Registry key | Registry value
SET HELP ON | OFF | HelpOn | 0 or 1
SET HELP TO cfilename | HelpTo | cFileName
SET HELP COLLECTION cCollectionURL | HelpCollection | cCollectionURL
SET HELP SYSTEM | HelpSystem | 0 or 1

You can also use the Help File option on the File Locations tab of the Options dialog box to interactively specify a Help file.

See Also

HELP | SET TOPIC


SET HOURS Command

Sets the system clock to a 12- or 24-hour time format.

SET HOURS TO [12 | 24]

Parameters

TO 12
(Default) Specifies a 12-hour format.
TO 24
Specifies a 24-hour format.

Remarks

Use SET HOURS TO without 12 or 24 to return to the default 12-hour format.

TIME( ) always returns a value in 24-hour format and isn't affected by SET HOURS. The value returned by DATETIME( ) is determined by the current SET HOURS setting.

SET HOURS is scoped to the current data session.

See Also

DATETIME( ) | SECONDS( ) | SET CLOCK | SET SYSFORMATS | TIME( )


SET INDEX Command

Opens one or more index files for use with the current table.

SET INDEX TO [IndexFileList | ? ] [ORDER nIndexNumber
 | IDXIndexFileName | [TAG] TagName [OF CDXFileName] [ASCENDING
 | DESCENDING]] [ADDITIVE]

Parameters

IndexFileList
Specifies one or more index files to open. Use commas to separate multiple index files in the list. The index file list can contain any combination of .idx and .cdx index file names; you don't have to include the file name extensions unless another .idx or .cdx file exists with the same name.

The first index file in the index file list becomes the controlling index file, which controls how records are accessed and displayed. The records are displayed and accessed in physical record order if the first index file is a .cdx file and SET ORDER TO TAG has not been issued.

?
Displays the Open dialog box from which you can open a single .idx file.
ORDER nIndexNumber
Specifies a controlling index file or tag. The numeric expression nIndexNumber specifies the index files as they appear in the index file list.

.Idx files are numbered first in the order in which they appear in the index file list. Tags in the structural .cdx file (if one exists) are numbered in the order in which the tags were created. Finally, tags in any independent .cdx files are numbered in the order in which they were created. See SET ORDER for a further discussion of the numbering of index files and tags.

If nIndexNumber is 0, records in the table are displayed and accessed in physical record order, but the index files remain open. ORDER 0 enables you to update open index files while accessing records in physical order. ORDER with no additional arguments is identical to ORDER 0.

Visual FoxPro generates an error message if nIndexNumber is greater than the number of .idx files and .cdx file tags.

ORDER IDXIndexFileName
Specifies an .idx file as the controlling index file.
ORDER [TAG] TagName [OF CDXFileName]
Specifies a tag (TagName) of a .cdx file to be the controlling tag. The tag name can be from the structural .cdx file or any open independent .cdx file.

If tags with the same name exist in open independent .cdx files, use OF CDXFileName to specify the .cdx file the tag is in.

ASCENDING | DESCENDING
Specifies whether table records are displayed and accessed in ascending or descending order. The index files or tags aren't changed in any way; only the order in which the records are displayed and accessed is changed. Include the ASCENDING or DESCENDING clause immediately after the ORDER clause.
ADDITIVE
Specifies that previously opened index files, except for a structural compound index, are left open when you issue SET INDEX to open an additional index file or files for a table. Without ADDITIVE, the previously opened files would be closed.

Remarks

Records in a table that has an index file or files open can be displayed and accessed in an order determined by one of the index files. Both single index (.idx) and compound (.cdx) index files can be opened with SET INDEX. If a table has a structural .cdx file, the file is opened automatically when the table is opened.

Only one .idx file (the controlling index file) or tag from a .cdx file (the controlling tag) controls the order in which records in the table are displayed or accessed. Certain commands (SEEK, for example) use the controlling index file or tag to search for records.

Issuing SET INDEX TO without additional arguments closes all open index files (except a structural .cdx file) in the current work area.

See Also

CLOSE INDEXES | INDEX | SET ORDER | USE


SET KEY Command

Specifies access to a range of records based on their index keys.

SET KEY TO [eExpression1 | RANGE eExpression2 [, eExpression3]]
   [IN cTableAlias | nWorkArea]

Parameters

eExpression1
Allows access to a set of records with identical index keys. eExpression1 is a single index key value. All records with index keys that match eExpression1 are accessible.
RANGE eExpression2 [, eExpression3]
Allows access to a set of records with index keys that fall within a range of index key values. eExpression2 allows access to records with index keys equal to or greater than eExpression2. eExpression3 (preceded by a comma) allows access to records with index keys equal to or less than eExpression3. Including both eExpression2 and eExpression3 (separated by a comma) allows access to records with index keys equal to or greater than eExpression2 and equal to or less than the eExpression3.

For example, the CUSTOMER table includes a character field containing postal codes. If the table is indexed on the postal code field, you can specify a range of postal codes with SET KEY.

In the following example, only records with postal codes falling within the range of 40000 to 43999 appear in a Browse window:

CLOSE DATABASES
USE customer
SET ORDER TO postalcode
SET KEY TO RANGE '40000', '43999'
BROWSE
IN cTableAlias | nWorkArea
Allows access to a range of records for a table open in a specific work area. cTableAlias specifies the work area alias and nWorkArea specifies the work area number. If no table has the alias you specify, Visual FoxPro generates an error message. If you omit the work area alias and number, SET KEY operates on the table in the currently selected work area.

Remarks

Use SET KEY to limit the range of records you can access in a table. The table must be indexed, and the index key value or values you include must be the same data type as the index expression of the master index file or master tag.

Issue SET KEY TO without any additional arguments to restore access to all records in the table.

See Also

INDEX | KEY( ) | SET FILTER


SET KEYCOMP Command

Controls Visual FoxPro keystroke navigation.

SET KEYCOMP TO DOS | WINDOWS

Remarks

SET KEYCOMP determines the keystrokes and keystroke combinations you use to move through the Visual FoxPro interface by accessing controls such as buttons, list boxes, menus, and so on. The effect of SET KEYCOMP depends on the control.

Use SET KEYCOMP when you want to use keystrokes that are familiar to you.

To navigate in Microsoft Windows using MS-DOS keystrokes, issue the following:

SET KEYCOMP TO DOS

You can specify the DOS or WINDOWS (default) option.

You can specify a startup SET KEYCOMP setting in your Visual FoxPro configuration file, Config.fpw. For example, the following line, when placed in your configuration file, has the effect of SET KEYCOMP TO DOS:

KEYCOMP = DOS

This section describes how the DOS and WINDOWS options affect Visual FoxPro.

Default buttons |
DOS | The default button in a dialog box has the focus; its appearance does not change. It is chosen when you press CTRL+ENTER.
WINDOWS | The default button in a dialog box can change appearance when you move among controls. It can be dimmed, or it has the focus (is surrounded by a bold border) to indicate it is the current default. It is chosen when you press ENTER. Pressing ENTER always performs the default button's action.

For an illustration of how the default button changes appearance in a dialog box, issue SET KEYCOMP TO WINDOWS, choose Open from the File menu, and then press TAB to move through the Open dialog box.

Access keys |
DOS | An access key for a control is a single key. If you aren't in a control that has keyboard steering (a combo box or a list box), you can press the access key to choose it.
WINDOWS | An access key for a control can be a single key or a key combination. If the current control has keyboard steering (a combo box or a list box), you can press ALT plus the access key to choose the control. To choose other controls, you can press the access key or ALT plus the access key.
Combo boxes |
DOS | When a combo box has the focus, you can open it by pressing ENTER or the SPACEBAR. Keyboard steering within a combo box is not available until the combo box is open.
WINDOWS | When a combo box has the focus, you can open it by pressing the SPACEBAR, ALT+UP ARROW, or ALT+DOWN ARROW. Keyboard steering within a combo box is available when the combo box has the focus, and when it is open. For example, a selected combo box contains a list of available drives. If drives A, B, and C are available and drive B is currently displayed, you can choose drive C without opening the combo box by pressing C or the DOWN ARROW key. Drive C is chosen and you move to the next control.
Option buttons |
DOS | Press the TAB key when a group of option buttons is selected to move among the option buttons.
WINDOWS | Press the TAB key when a group of option buttons is selected to move from the option buttons to the next control. To move among a set of option buttons, press the UP ARROW and DOWN ARROW keys.
Browse window |
DOS | A field is not selected upon entry into the field.
WINDOWS | A field is automatically selected upon entry into the field.

See Also

SET COMPATIBLE | Automating Keystroke Tasks with Macros


SET LIBRARY Command

Opens an external API (application programming interface) library file.

SET LIBRARY TO [FileName [ADDITIVE]]

Parameters

FileName
Specifies the file name of the API library or procedure file to open.

Visual FoxPro assume an .fll extension for libraries. If the library has an .fll extension, you don't have to include the extension with the file name. If a library has an extension other than .fll, you must include the extension with the file name.

Caution When using SET LIBRARY, be aware of the following:
  • You cannot use API libraries built for one platform on another platform. For example, libraries created for FoxPro for MS-DOS cannot be used in Visual FoxPro; libraries created for Visual FoxPro cannot be used in FoxPro for MS-DOS.
  • You cannot use API libraries built for one version on another version. For example, you cannot use libraries built for FoxPro version 2.6 in Visual FoxPro. You must recompile and link.

Visual FoxPro assumes a .prg extension for a procedure file.

When you execute a procedure with DO ProcedureName, Visual FoxPro searches for the procedure in the following files in this order:

  • The file containing DO ProcedureName.
  • A procedure file opened with SET PROCEDURE (if one is set).
  • The programs in the execution chain. Visual FoxPro searches program files beginning with the most recently executed program and continuing back to the first executed program.
  • A procedure file opened with SET LIBRARY (if one is set).
  • A stand-alone program file. If Visual FoxPro finds a program file with the same name as the file name specified with DO, the program is executed. If it doesn't find a matching program file name, Visual FoxPro generates an error message.
ADDITIVE
Opens additional API libraries. Include ADDITIVE after the file name in successive SET LIBRARY commands.

Visual FoxPro ignores ADDITIVE when you use SET LIBRARY to open a procedure file.

Remarks

Use SET LIBRARY to open external Application Program Interface (API) libraries or a procedure file.

API routine libraries extend the capabilities of the Visual FoxPro language and user interface. Once an external API library is opened, you can use the API functions as if they were Visual FoxPro functions. Use DISPLAY STATUS or LIST STATUS to display the library's available functions.

You can use existing API libraries or create your own API libraries.

In Visual FoxPro, the preferred way to register functions in shared libraries is to use the DECLARE - DLL command.

To remove all API libraries from memory, use SET LIBRARY TO without including FileName or ADDITIVE. To remove an individual library from memory, use RELEASE LIBRARY LibraryName.

If you specify a procedure file, the procedures within the procedure file are made available to all programs and are also available interactively through the Command window.

Note The ability of Visual FoxPro to open a procedure file with SET LIBRARY provides compatibility with dBASE IV. Using SET LIBRARY to open a procedure file will close all open API libraries. Using SET LIBRARY to open API libraries will close a procedure file opened with SET LIBRARY. Use SET PROCEDURE to open a procedure file and prevent API libraries from being closed.

For additional information about procedure files, see PROCEDURE and SET PROCEDURE.

See Also

CALL | DISPLAY STATUS | LIST | LOAD | RELEASE LIBRARY Command


SET LOCK Command

Enables or disables automatic file locking in certain commands.

SET LOCK ON | OFF

Parameters

ON
Specifies that the commands listed below automatically lock the table when they execute. This provides read-only access to other users on the network and ensures that you are using the most current data.
OFF
(Default) Enables shared access of tables with commands listed below. Use SET LOCK OFF if you don't need the most current information from a table.

Remarks

Visual FoxPro doesn't place a lock on a file when executing commands that require read-only access to a table. These commands include the following:

Commands |
AVERAGE | JOIN (both files)
CALCULATE | LIST
COPY TO | LABEL
COPY TO ARRAY | REPORT
COUNT | SORT
DISPLAY (with a scope) | SUM
INDEX | TOTAL

While they are executed, these commands don't change the contents of a table, and access to the table is available to other users on the network. Thus, the table can be changed while you are executing one of these commands. For example, you might begin printing a report by using REPORT before another user changes a record included in the report. Your report now contains outdated information.

SET LOCK is scoped to the current data session.

See Also

FLOCK( ) | LOCK( ) | RLOCK( ) | SET DATASESSION | SET MULTILOCKS


SET LOGERRORS Command

Determines whether Visual FoxPro sends compilation error messages to a text file.

SET LOGERRORS ON | OFF

Parameters

ON
(Default) Specifies that a compilation error message log file be created with the same name as the compiled program and an .err extension. If a log file with the same name already exists, it is overwritten.
OFF
Specifies that a compilation error message log file is not created when a program is compiled.

Remarks

Use SET LOGERRORS to save compilation error messages to a text file when programs are compiled.

If a log file exists with the same name as the compiled program, and if the program compiles without error, the log file is deleted.

See Also

COMPILE | SYS(2018) - Error Message Parameter | SET CPDIALOG Command


SET MACKEY Command

Specifies a key or key combination that displays the Macro Key Definition dialog box.

SET MACKEY TO [KeyLabelName]

Parameters

KeyLabelName
Specifies the key or key combination that displays the Macro Key Definition dialog box. See ON KEY LABEL for the key labels to use.

Remarks

Use SET MACKEY to change the default key combination for displaying the Macro Key Definition dialog box. Choose Macros from the Tools menu to display this dialog box.

See Also

CLEAR | ON KEY LABEL | PLAY MACRO | RESTORE MACROS | SAVE MACROS


SET MARGIN Command

Sets the left printer margin and affects all output directed to the printer.

SET MARGIN TO nColumns

Parameters

nColumns
Specifies the left margin in columns. The default is 0 columns; the maximum is 256.

Remarks

If you use SET MARGIN to adjust the left margin, the value specified with SET MARGIN is stored to the system variable _PLOFFSET. You can also set the left margin by storing a value directly to _PLOFFSET.

The value of the system variable _LMARGIN also affects the left margin setting.

Note The left margin setting specified in SET MARGIN doesn't affect reports created with the Report Designer and then run with REPORT. Although _PLOFFSET is adjusted during the running of a report created with the Report Designer, it is reset to its original value after the report is run. The Left Margin setting in the Page Setup dialog box of the Report Designer determines the offset from the left edge of the paper. Choose Page Setup from the File menu to display the Page Setup dialog when the Report Designer is open.

See Also

_LMARGIN | _PLOFFSET | _RMARGIN


SET MARK OF Command

Specifies a mark character for menu titles or menu items, or displays or clears the mark character.

SET MARK OF MENU MenuBarName1
   TO lExpression1-or-SET MARK OF POPUP MenuName1
   TO lExpression3-or-SET MARK OF BAR nMenuItemNumber OF MenuName2
   TO lExpression4

Parameters

MENU MenuBarName1
Specifies the name of the menu bar for which the mark character is specified, displayed or cleared.
  • TO lExpression1 Displays or clears the mark character for every menu title on the menu bar. If the logical expression lExpression1 evaluates to true (.T.), the mark character is displayed beside every menu title. The mark character is cleared from every menu name if lExpression1 evaluates to false (.F.).
POPUP MenuName1
Specifies the name of the menu for which the mark character is specified, displayed, or cleared.
  • TO lExpression3 Displays or clears the mark characters for all the menu items. If lExpression3 evaluates to true (.T.), the mark characters are displayed. If lExpression3 evaluates to false (.F.), the mark characters are cleared.
BAR nMenuItemNumber OF MenuName2
Specifies the number of the menu item (and the name of the menu containing the menu item) for which the mark character is specified, displayed, or cleared.
  • TO lExpression4 Displays or clears the mark character for the menu item. If lExpression4 evaluates to true (.T.), the mark character is displayed. If lExpression4 evaluates to false (.F.), the mark character is cleared.

Remarks

You cannot specify a mark character for menu titles or menu items. The mark character is always a check mark. However, you can use SET MARK OF to display or clear the check mark for menu titles or menu items.

You cannot mark menu items created with any of the DEFINE POPUP PROMPT clauses (FIELD, FILES, or STRUCTURE).

Use MRKPAD( ) to determine if a menu title has a mark character displayed, and use MRKBAR( ) to determine if a menu item has a mark character displayed.

For an example using SET MARK OF, see CNTBAR( ).

See Also

CNTBAR( ) | CNTPAD( ) | DEFINE BAR | DEFINE MENU | DEFINE PAD | DEFINE POPUP | MRKBAR( ) | MRKPAD( )


SET MARK TO Command

Specifies a delimiter for the display of date expressions.

SET MARK TO [cDelimiter]

Parameters

cDelimiter
Specifies the character you want to use as the date delimiter.

Remarks

SET MARK TO specifies the character that separates the month, day, and year in displayed dates.

Use SET MARK TO without cDelimiter to reset the delimiter to the default forward slash ( / ).

SET MARK TO is scoped to the current data session.

See Also

SET DATASESSION | SET DATE | SET SYSFORMATS


SET MEMOWIDTH Command

Specifies the displayed width of memo fields and character expressions.

SET MEMOWIDTH TO nColumns

Parameters

nColumns
Specifies a width between 8 and 8192 columns. The default width for output is 50 columns. If you issue SET COMPATIBLE ON or SET COMPATIBLE DB4, the default width is changed to 80 columns. If you specify a value for nColumns greater than 8192, width is set to 8192.

Remarks

SET MEMOWIDTH specifies the width of output sent to the main Microsoft Visual FoxPro window or a user-defined window by commands such as ? | ??, DISPLAY, or LIST. It affects the output width of memo fields and character expressions longer than 254 characters. It also affects the values returned by the ATCLINE( ), ATLINE( ), MEMLINE( ), and MLINE( ) functions.

Note that for ? and ?? the displayed width will not exceed 256 characters.

If output is directed to the main Visual FoxPro window, the width of the output is determined by the font for the main Visual FoxPro window. If output is directed to a user-defined window, the width of the output is determined by the font for the user-defined window.

SET MEMOWIDTH is scoped to the current data session.

See Also

ATCLINE( ) | ATLINE( ) | MEMLINES( ) | MLINE( ) | SET DATASESSION


SET MESSAGE Command

Defines a message for display in the main Visual FoxPro window or in the graphical status bar, or specifies the location of messages for user-defined menu bars and menu commands.

SET MESSAGE TO [cMessageText]-or-SET MESSAGE TO [nRow [LEFT | CENTER
 | RIGHT]]-or-SET MESSAGE WINDOW [WindowName]

Parameters

TO [cMessageText]
Specifies the message to display.
TO [nRow [LEFT | CENTER | RIGHT]]
Specifies the placement of messages in the main Visual FoxPro window. nRow specifies the row on which messages are displayed. If nRow is 0, no messages are displayed.

LEFT, CENTER, and RIGHT specify the horizontal screen placement of messages.

Visual FoxPro ignores a message location specified with SET MESSAGE when the graphical status bar is displayed.

WINDOW [WindowName]
Specifies the window in which messages are displayed. To remove a message from the window and display it on the screen, issue SET MESSAGE WINDOW.

Remarks

SET MESSAGE lets you create a message. It also lets you specify where to display messages created with DEFINE BAR, DEFINE MENU, DEFINE PAD, or DEFINE POPUP.

By default, messages are placed on the last line of the main Visual FoxPro window if the character-based status bar is displayed. If the graphical status bar is displayed, messages are placed in the status bar.

The SET MESSAGE line is reset to the last line of the main Visual FoxPro window whenever SET DISPLAY is issued.

SET MESSAGE TO without any arguments places messages in the graphical status bar.

See Also

SET DISPLAY | SET STATUS | SET STATUS BAR


SET MULTILOCKS Command

Determines whether you can lock multiple records using LOCK( ) or RLOCK( ).

SET MULTILOCKS ON | OFF

Parameters

ON
Allows you to attempt locking a set of records. Include a set of record numbers in LOCK( ) or RLOCK( ) to try to lock multiple records.
OFF
(Default) Allows you to attempt locking a single record with LOCK( ) or RLOCK( ).

Remarks

When a table is opened for shared use on a network, you can attempt to lock more than one record in a table file. The SET MULTILOCKS setting determines whether you can attempt to lock either a single record or a set of records. Records can be locked with the LOCK( ) or RLOCK( ) function.

Note Switching SET MULTILOCKS from ON to OFF or from OFF to ON implicitly issues UNLOCK ALL — all record locks in all work areas are released.

SET MULTILOCKS is scoped to the current data session.

MULTILOCKS must be ON to before row or table buffering can be enabled with CURSORSETPROP( ). See CURSORSETPROP( ) for additional information about row and table buffering.

If you select the Enable Data Buffering check box in the Work Area Properties dialog box (which is displayed when you choose the Properties button in the Data Session window), MULTILOCKS is automatically set to ON for the current data session. However, clearing the Enable Data Buffering check box does not set MULTILOCKS to OFF for the current data session.

For more information about record and file locking and sharing tables on a network, see the LOCK( ) and RLOCK( ) functions, and Programming for Shared Access.

See Also

CURSORSETPROP( ) | LOCK( ) | RLOCK( ) | SET DATASESSION


SET NEAR Command

Determines where the record pointer is positioned after FIND or SEEK unsuccessfully searches for a record.

SET NEAR ON | OFF

Parameters

ON
Positions the record pointer on the closest matching record if a record search using FIND or SEEK is unsuccessful. With this setting, RECNO( ) returns the record number of the closest matching record, FOUND( ) returns false (.F.), and EOF( ) returns false (.F.).
OFF
(Default) Positions the record pointer at the end of the table if a record search using FIND or SEEK is unsuccessful. With this setting, RECNO( ) returns the number of records in the table plus 1, FOUND( ) returns false (.F.), and EOF( ) returns true (.T.).

Remarks

A search is unsuccessful when no record meets the search criteria.

Issuing RECNO( ) with an argument of 0 returns the record number of the closest matching record if a search is unsuccessful, regardless of the setting of SET NEAR.

SET NEAR is scoped to the current data session.

See Also

EOF( ) | FIND | FOUND( ) | RECNO( ) | SEEK | SET DATASESSION


SET NOCPTRANS Command

Prevents translation to a different code page for selected fields in an open table.

SET NOCPTRANS TO [FieldName1 [, FieldName2 ...]]

Parameters

TO [FieldName1 [, FieldName2 ...]]
Specifies the fields that should not be translated to another code page.

Issue SET NOCPTRANS TO without a set of fields to return to the default translation (established by the CODEPAGE configuration item) for all character and memo fields in a table. Use SET("NOCPTRANS") to return the fields specified in the last SET NOCPTRANS command you issued. Use the CHR( ) function to ensure that individual characters don't get translated.

Remarks

Because Microsoft Visual FoxPro can be configured to automatically translate character and memo fields into other code pages, the SET NOCPTRANS command is available to prevent the automatic translation of fields containing binary data. For example, a memo field may contain a Microsoft Word document. When you access the Word document, you would like the document in its original, untranslated form. Use SET NOCPTRANS to specify that the memo field not be translated.

You don't need to use SET NOCPTRANS to access binary data if the character or memo field containing the binary data has not been translated. You can ensure that character and memo fields are not translated by omitting the CODEPAGE configuration item from your Visual FoxPro configuration file.

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro in Developing International Applications.

See Also

CPCONVERT( ) | CPCURRENT( ) | CPDBF( ) | MODIFY COMMAND | MODIFY FILE


SET NOTIFY Command

Enables or disables the display of certain system messages. The following are examples of system messages affected by SET NOTIFY:

  • "Expression is valid" in the Expression Builder dialog box
  • "Do Canceled," which appears when program execution is canceled
SET NOTIFY [CURSOR] ON | OFF

Parameters

CURSOR
Specifies whether data-related messages should appear in the status bar.
ON
Enables the display of certain system messages. (Default)
OFF
Disables the display of certain system messages.

Remarks

System messages display in the graphical, not character-based, status bar at the bottom of the main Visual FoxPro window.

When SET NOTIFY CURSOR is set to OFF, Visual FoxPro suppresses all data-related messages from displaying in the status bar. These messages include alias, data source, record pointer, record count and exclusive/record unlocked status.

The setting of SET NOTIFY CURSOR does not affect SET NOTIFY.

You can use the SET("NOTIFY",1) function to return the current value of SET NOTIFY CURSOR.

See Also

SET MESSAGE | SET( ) Function | WAIT | UIEnable Event


SET NULL Command

Determines how null values are supported by the ALTER TABLE, CREATE TABLE and INSERT - SQL commands.

SET NULL ON | OFF

Parameters

ON
Specifies that all columns in a table created with ALTER TABLE and CREATE TABLE will allow null values. You can override null value support for columns in the table by including the NOT NULL clause in the columns' definitions.

Also, specifies that INSERT - SQL will attempt to insert null values into any columns not included in the INSERT - SQL VALUE clause. INSERT - SQL can successfully insert null values only into columns that allow null values.

Note If you add support for null values to one or more columns in a table, the limit on the number of columns for that table is reduced from 255 to 254.
OFF
(Default) Specifies that all columns in a table created with ALTER TABLE and CREATE TABLE will not allow null values. You can designate null value support for columns in ALTER TABLE and CREATE TABLE by including the NULL clause in the columns' definitions.

Also specifies that INSERT - SQL will insert blank values into any columns not included in the INSERT - SQL VALUE clause.

Remarks

SET NULL affects only how null values are supported by ALTER TABLE, CREATE TABLE and INSERT - SQL. Other commands are unaffected by SET NULL. SET NULL is scoped to the current data session.

Example

The following example demonstrates how SET NULL affects support for null values. The first table, employee, is created with SET NULL ON, so its fields support null values. REPLACE is used to place a null value in the cLastName field. The second table, staff, is created with SET NULL OFF, so its fields do not support null values. REPLACE is used to place zero in the cLastName field.

CLOSE DATABASES
SET NULL ON        && Fields will support null values
CREATE TABLE employee (cLastName C(20), ySalary Y(12,2))
APPEND BLANK       && Add a new blank record
REPLACE cLastName WITH .NULL.  && cLastName supports null values

SET NULL OFF       && Fields will not support null values
CREATE TABLE staff (cLastName C(20), ySalary Y(12,2))
APPEND BLANK       && Add a new blank record
REPLACE cLastName WITH 0   && Doesn't support null values

See Also

ALTER TABLE | CREATE TABLE | INSERT - SQL | ISNULL( ) | NVL( ) | SET DATASESSION


SET NULLDISPLAY Command

Specifies the text displayed for null values.

SET NULLDISPLAY TO [cNullText]

Parameters

cNullText
Specifies the text that is displayed for null values. If cNullText is omitted, the default null value text, .NULL., is restored and displayed for null values.

Remarks

By default, Visual FoxPro displays .NULL. for null values in objects, Browse windows, DISPLAY output, LIST output, and so on. Use SET NULLDISPLAY to change the default null value text to a different character string. SET NULLDISPLAY changes the default null value text for all objects for which the NullDisplay property is the empty string.

Use the NullDisplay property to change the default null value text to a different character string for an individual object.

See Also

CREATE TABLE - SQL, | SQL NullDisplay Property | SET NULL Command


SET ODOMETER Command

Specifies the reporting interval of the record counter for commands that process records.

SET ODOMETER TO [nRecords]

Parameters

TO [nRecords]
Specifies the reporting interval in number of records. The value of nRecords can range from 1 to 32,767 records. The default value is 100 records.

Remarks

Use SET ODOMETER to change the interval at which commands display information about the number of records processed.

For example, COPY TO displays the number of records that are copied to a new file while the command is executing. The record counter can be turned off by issuing SET TALK OFF.

See Also

SET TALK | _TALLY | COPY TO


SET OLEOBJECT Command

Specifies whether Visual FoxPro searches the registry when an object cannot be located.

SET OLEOBJECT ON | OFF

Parameters

ON
(Default) Specifies that Visual FoxPro searches the registry when an object cannot be located.
OFF
Specifies that Visual FoxPro does not search the registry when an object cannot be located.

Remarks

When an object is created with CREATEOBJECT( ) or GETOBJECT( ), Visual FoxPro searches for the object in the following locations and order:

  1. The Visual FoxPro base classes.
  2. Class definitions in memory in the order they are loaded.
  3. Class definitions in the current program.
  4. Class definitions in the .vcx class libraries opened with SET CLASSLIB.
  5. Class definitions in procedure files opened with SET PROCEDURE.
  6. Class definitions in the Visual FoxPro program execution chain (For Details, See DO Command).
  7. The registry.

When Visual FoxPro searches for an object, the registry is searched last. Visual FoxPro loads COM object support before it searches the registry, increasing the amount of memory required by Visual FoxPro and reducing the amount of memory available to other applications.

If you are developing an application that does not require COM support, issue SET OLEOBJECT OFF to prevent Visual FoxPro from searching the registry when an object cannot be located.

SET OLEOBJECT does not affect COM objects in Forms or General fields. Visual FoxPro always loads COM object support when a Form containing a COM object is opened for modification or is instantiated, or a table with a general field is opened.

Because GETOBJECT( ) activates a COM object, Visual FoxPro generates an error when GETOBJECT( ) is issued and SET OLEOBJECT is OFF.

See Also

CREATEOBJECT( ) | GETOBJECT( ) | DO Command


SET OPTIMIZE Command

Enables or disables Rushmore Query Optimization.

SET OPTIMIZE ON | OFF

Parameters

ON
(Default) Enables Rushmore optimization.
OFF
Disables Rushmore optimization.

Remarks

Visual FoxPro uses a technology called Rushmore Query Optimization to optimize data retrieval. Table commands that support a FOR clause use Rushmore technology to enhance their performance. When you issue a command that is optimizable, Rushmore determines which records match the FOR criterion. The command is executed on records in the table that match the Rushmore recordset.

In rare cases, you should disable Rushmore optimization. If a command that benefits from Rushmore optimization modifies a query's index keys, the Rushmore recordset may become outdated. You can disable Rushmore optimization to ensure that you have the most current information from the table.

You can use SET OPTIMIZE to globally enable or disable Rushmore technology. Every command that uses Rushmore has a NOOPTIMIZE clause you can include to disable Rushmore optimization for the command.

For more information, see Using Rushmore Query Optimization to Speed Data Access.

Below are the commands whose performance is optimized by Rushmore:

Commands |
AVERAGE | INDEX
BLANK | LABEL
BROWSE | LIST
CALCULATE | LOCATE
CHANGE | RECALL
COPY TO | REPLACE
COPY TO ARRAY | REPLACE FROM ARRAY
COUNT | REPORT
DELETE | SCAN
DISPLAY | SORT
EDIT | SUM
EXPORT | TOTAL

See Also

INDEX | SET ORDER | Using Rushmore Query Optimization to Speed Data Access


SET ORDER Command

Designates a controlling index file or tag for a table.

SET ORDER TO [nIndexNumber | IDXIndexFileName | [TAG] TagName
   [OF CDXFileName] [IN nWorkArea | cTableAlias]
   [ASCENDING | DESCENDING]]

Parameters

nIndexNumber
Specifies the number of the controlling index file or tag. nIndexNumber refers to the index files as they are listed in USE or SET INDEX. Open .idx files are numbered first in the order in which they appear in USE or SET INDEX. Tags in the structural .cdx file (if one exists) are then numbered in the order in which they were created. Finally, tags in any open independent .cdx files are numbered in the order in which they were created.

The following example illustrates how different index file types and tags are numbered. (The file names are for illustration only and don't necessarily exist.) A table named video.dbf is opened with three indexes (title.idx, costs.cdx, and rating.idx) in the first work area with this command:

USE video INDEX title.idx, costs.cdx, rating.idx IN 1

The video table has a structural compound index file (video.cdx) with two tags, NUMBERSOLD and YEARSOLD. The structural .cdx file is automatically opened when video is opened.

Since .idx files are numbered first, issue SET ORDER TO 1 to make title.idx the controlling index and SET ORDER TO 2 to make rating.idx the controlling index:

SET ORDER TO 1
Controlling index: C:\FOX30\TITLE.IDX
SET ORDER TO 2
Controlling index: C:\FOX30\RATING.IDX

The tags in video.cdx are numbered next:

SET ORDER TO 3
Controlling index: C:\FOX30\VIDEO.CDX  Tag: NUMBERSOLD
SET ORDER TO 4
Controlling index: C:\FOX30\VIDEO.CDX  Tag: YEARSOLD

Finally, the tags in the independent file, costs.cdx, are numbered:

SET ORDER TO 5
Controlling index: C:\FOX30\COSTS.CDX  Tag: RENTALCOST
SET ORDER TO 6
Controlling index: C:\FOX30\COSTS.CDX  Tag: BUYCOST

nIndexNumber can also be 0. If you issue SET ORDER TO 0, all index files remain open and are updated when records are added, deleted or modified. However, the records in the table are displayed and accessed in record number order and not in an indexed order. Issuing SET ORDER TO without additional arguments is identical to issuing SET ORDER TO 0.

If nIndexNumber is greater than the number of .idx files and .cdx file tags, Visual FoxPro generates an error message.

IDXIndexFileName
Specifies an .idx file as the controlling index file.
[TAG] TagName [OF CDXFileName]
Specifies a tag of a .cdx file as the controlling tag. The tag name can be from a structural .cdx file or any open independent .cdx file.

If identical tag names exist in open independent .cdx files, use OF CDXFileName to specify the .cdx file containing the tag.

Note The .idx file takes precedence if duplicate .idx file and tag names exist.
IN nWorkArea | cTableAlias
Designates a controlling index file or tag for a table open in a work area other than the currently selected work area. nWorkArea specifies the work area number and cTableAlias specifies the alias for a table.
ASCENDING | DESCENDING
Displays and allows access to table records in ascending or descending order. Including ASCENDING or DESCENDING doesn't change the index file or tag in any way.

Remarks

A table can have many index files open simultaneously. However, only one single-index (.idx) file (the controlling index file) or tag from a compound index (.cdx) file (the controlling tag) determines the order in which the records in a table are displayed or accessed. SET ORDER makes it possible for you to designate the controlling index file or tag. Certain commands (SEEK, for example) use the controlling index file or tag to search for records.

You can open index files with a table by including the INDEX clause in the USE command. If a table has an associated structural .cdx file, that file is automatically opened with the table. After a table has been opened, you can open and close index files for the table using SET INDEX.

By default, SET ORDER designates the controlling index or controlling tag for the table open in the currently selected work area.

See Also

INDEX | ORDER( ) | SET INDEX


SET PALETTE Command

Specifies whether the Visual FoxPro default color palette is used.

SET PALETTE ON | OFF

Parameters

ON
(Default) Restores the default Visual FoxPro color palette.
OFF
Replaces the Visual FoxPro default color palette with color palettes from the .bmp graphics and OLE objects.

Remarks

OLE objects and .bmp graphics can contain color palettes that determine how the graphics and objects appear when they are displayed. The color palette of the first graphic or object displayed is used for all subsequent graphics or objects. Since a single color palette is used for all the graphics and objects, the colors of some of the graphics and objects may be changed in an unexpected manner.

The default Visual FoxPro color palette is designed to improve the display appearance of multiple .bmp graphics and OLE objects.

See Also

@ ... SAY | MODIFY GENERAL | SET COLOR TO Command


SET PATH Command

Specifies a path for file searches.

SET PATH TO [Path]

Parameters

TO [Path]
Specifies the directories you want Visual FoxPro to search. Use commas or semicolons to separate the directories.
Note Visual FoxPro will not recognize a path name properly if a disk or directory name contains an exclamation point (!).

On all FoxPro platforms, functions that return path information, such as CURDIR( ), DBF( ), and SYS(2003), use Microsoft MS-DOS path-naming conventions in their return values.

Remarks

Issue SET PATH TO without Path to restore the path to the default directory. Use SET DEFAULT to specify the default directory and CURDIR( ) to return the current default directory.

SET PATH is not scoped to the current data session; changes you make to the default path using the SET PATH command affect all data sessions.

SET PATH is limited to a maximum of 1024 characters.

See Also

CD | CHDIR | GETFILE( ) | LOCFILE( ) | MD | MKDIR | RD | RMDIR | SET DEFAULT | SET DATASESSION


SET PDSETUP Command

Loads a printer driver setup or clears the current printer driver setup.

SET PDSETUP TO [[cPrinterDriverSetup [, Parameter1[, Parameter2 ...]]]
   [WITH Parameter3 [, Parameter4 ...]]]

Parameters

cPrinterDriverSetup
Specifies the name of the printer driver setup to load.

When you load a printer driver setup, the name of the setup is stored in the _PDSETUP system variable, and a special variable array, _PDPARMS, can be created. (_PDPARMS is discussed in detail under the WITH clause in this topic.)

If the printer driver setup name you specify with cPrinterDriverSetup doesn't exist in your resource file, the current printer driver setup application is executed so you can create a setup with this name. If the current printer driver setup application is Genpd.app, the Printer Setup Editing dialog box appears so you can create the setup.

If the setup name begins with a dash (-), the _GENPD program won't be executed, but the name following the dash is stored in _PDSETUP.

If you issue SET PDSETUP TO without cPrinterDriverSetup, the current printer driver setup is cleared, the empty string is stored in _PDSETUP, and the _PDPARMS array is cleared from memory.

Parameter1 [, Parameter2 ...]
Specifies any number of optional parameters. These parameters are passed to the printer setup interface application and can be of any type (character, numeric, logical, and so on). The first line in your printer setup interface application must be an LPARAMETERS or PARAMETERS statement to accept the parameters passed from SET PDSETUP.

If you are using Genpd.app, don't include these optional parameters. Genpd.app doesn't accept parameters passed from SET PDSETUP, so including them generates an error.

WITH Parameter3 [, Parameter4 ...]
Creates the special _PDPARMS printer array. Each parameter you specify with Parameter3, Parameter4, and so forth becomes an element in _PDPARMS. The first parameter (Parameter3) is stored to the first element of _PDPARMS, the second parameter (Parameter4) is stored to the second element, and so on. These parameters may be of any type (character, numeric, logical, and the like).

If you are using Genpd.app, any parameters you include are overwritten by the application.

Remarks

In Visual FoxPro, a printer driver setup is used when you print character-based reports created in FoxPro for MS-DOS.

A printer driver setup consists of a combination of settings, including the printer driver program and information such as page orientation, default font size and font style, margins, and so on. Printer driver setups are stored in your FoxPro for MS-DOS resource file, FoxUser.dbf, and can be created interactively and assigned a name in the Printer Setup Editing dialog box.

A printer driver setup can also be loaded or cleared with the _PDSETUP system variable.

When you issue SET PDSETUP, the current printer setup interface application is executed. The interface application is passed the name of the printer driver setup included in SET PDSETUP. The interface application can also be specified with the _GENPD system variable. The default interface application is Genpd.app, the printer setup interface application included with FoxPro for MS-DOS.

See Also

_GENPD | _PDRIVER | _PDSETUP | SET PRINTER


SET POINT Command

Determines the decimal point character used in the display of numeric and currency expressions.

SET POINT TO [cDecimalPointCharacter]

Parameters

cDecimalPointCharacter
Specifies the character for the decimal point.

Remarks

Use SET POINT to change the decimal point from the default, which is a period (.). Issue SET POINT TO without cDecimalPointCharacter to reset the decimal point to a period. Although you can set the displayed decimal point to a different character, you must use a period as the decimal point in calculations.

SET POINT is scoped to the current data session.

Example

gnX = 1.25
gcNewPoint = '_'
SET POINT TO gcNewPoint
? gnX
SET POINT TO      && Reset the decimal point to a period (.)
? gnX

See Also

SET DATASESSION | SET DECIMALS | SET FIXED | SET SEPARATOR | SET SYSFORMATS


SET PRINTER Command

Enables or disables output to the printer, or routes output to a file, port, or network printer.

SET PRINTER ON [PROMPT] | OFF

-or-

SET PRINTER FONT cFontName [, nFontSize]
   [STYLE cFontStyle]-or-SET PRINTER TO [FileName [ADDITIVE] | PortName]

-or-

SET PRINTER TO [DEFAULT | NAME WindowsPrinterName]

-or-

SET PRINTER TO NAME \\ServerName\PrinterName

Parameters

ON [PROMPT]
Enables output to the printer. Output formatted with @ ... SAY isn't routed to the printer when SET PRINTER is set to ON. Use SET DEVICE TO PRINTER to direct output from @ ... SAY to the printer.

You can include PROMPT to display a dialog box before printing starts. In this dialog box you can adjust printer settings. The currently installed printer driver determines which printer settings you can adjust.

OFF
(Default) Disables output to the printer.
FONT cFontName [, cFontSize]
Specifies a default font for printer output. cFontName specifies the name of the font, and cFontSize specifies the point size. For example, the following command specifies 16-point Courier font as the default printer font:
SET PRINTER FONT 'Courier', 16

If the font you specify is not available, a font with similar font characteristics is substituted.

STYLE cFontStyle
Specifies a default font style for printer output. If you omit the STYLE clause, the normal font style is used.

If the font style you specify is not available, a font style with similar characteristics is substituted.

The font styles you can specify with cFontStyle are as follows:

Character | Font style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
– Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, the following command specifies 16-point Courier Bold Italic:

SET PRINTER FONT 'Courier', 16 STYLE 'BI'
TO [FileName [ADDITIVE] | PortName]
Specifies a file or port to which output is directed.

In Visual FoxPro, use SET PRINTER TO NAME instead to specify a printer.

FileName specifies a file name to which output is directed. If you include ADDITIVE, output is appended to the existing contents of the file. If you omit ADDITIVE, the existing contents of the file are overwritten.

PortName sends output to a different local printer.

TO [DEFAULT | NAME WindowsPrinterName]
Sends printer output to the default Windows printer or to a specific Windows printer. Windows printer names are stored in Win.ini.

You can use GETPRINTER( ) or APRINTERS( ) to determine the names of the currently installed printers. For example, the following command displays the Windows Print Setup dialog box and makes printer you select the printer to which printed output is directed:

SET PRINTER TO NAME GETPRINTER( )
TO NAME \\ServerName\PrinterName
Supported only under Windows NT 4.0 or later. Spools printer output to a network printer.

ServerName is the network name assigned to your print server. This name is assigned by the network administrator and must be unique.

PrinterName is a name assigned to the printer and is also assigned by the network administrator.

Remarks

Use SET PRINTER TO with the specified arguments to direct output to a file, a port for a different local printer, or a network printer.

Use SET PRINTER TO without an argument to reset output to the default MS-DOS PRN print utility.

When you direct output to a network printer, output prints or collects in a print spooler until a new SET PRINTER command is issued. For additional information about printing on your network, consult your network documentation.

Note This command does not function in Unattended Server Mode.

See Also

APRINTERS( ) | GETPRINTER( ) | PRINTSTATUS( ) | SET DEVICE


SET PROCEDURE Command

Opens a procedure file.

SET PROCEDURE TO [FileName1 [, FileName2, ...]] [ADDITIVE]

Parameters

FileName1 [, FileName2, ...]
Specifies the sequence in which files are to be opened. SET PROCEDURE can take more than one file name, making it possible for you to open several procedure files at once. This option makes it possible for you to create stand-alone libraries of functions and specify them separately.
ADDITIVE
Opens additional procedure files without closing currently open procedure files.

Remarks

Issuing SET PROCEDURE TO without any file names closes all open procedure files. Use RELEASE PROCEDURE to close individual files.

When you execute a procedure, the procedure files are searched if the procedure isn't located in the currently executing program.

For more information about procedure files, see PROCEDURE and DO.

See Also

PROCEDURE | RELEASE PROCEDURE | LIST PROCEDURES Command


SET READBORDER Command

Determines whether borders are placed around text boxes created with @ ... GET.

SET READBORDER ON | OFF

Parameters

ON
Places a single-line border around all text boxes created with @ ... GET. If SET READBORDER is set to ON when the first text box is created, all subsequent text boxes created in the same READ level also have borders.
OFF
(Default) Specifies that a border isn't placed around text boxes created with @ ... GET. If SET READBORDER is set to OFF when the first text box is created, all subsequent text boxes created in the same READ level do not have borders.

Remarks

SET READBORDER specifies whether single-line borders are placed around text boxes created with @ ... GET.

Example

In the following example, the first three text boxes created with @ ... GET have borders. The third text box has a border, even though SET READBORDER was SET to OFF before it was created. The fourth text box does not have a border, since READBORDER was SET to OFF and it is encompassed in a different READ from the first three text boxes.

SET READBORDER ON
@ 2,2 GET gnW DEFAULT 1   && 1st READ
@ 4,2 GET gnX DEFAULT 1   && 1st READ
SET READBORDER OFF
@ 6,2 GET gnY DEFAULT 1   && 1st READ
READ
@ 8,2 GET gnZ DEFAULT 2   && 2nd READ
READ

See Also

READ | READ EVENTS | @ ... GET - Text Boxes Command


SET REFRESH Command

Determines whether and how often a Browse window is updated with changes made to records by other users on the network.

SET REFRESH TO nSeconds1 [, nSeconds2]

Parameters

TO nSeconds1 [, nSeconds2]
Specifies whether and how often updates are made. nSeconds1 specifies the number of seconds between updates to a Browse or memo-editing window. nSeconds1 can be a value from 0 to 3,600; the default value is 0 seconds. When nSeconds1 is a nonzero value and other users change records you are viewing, those records are updated when the refresh interval elapses. The records you are viewing aren't updated if nSeconds1 is 0.

Microsoft Visual FoxPro buffers portions of tables in memory on your workstation. nSeconds2 specifies how often these local data buffers are updated with current data from the network. nSeconds2 is the number of seconds between data buffer updates. You can specify a value between 0 and 3,600; the default value is 5. The buffers are never refreshed if nSeconds2 is set to 0.

If you specify a value for nSeconds1 other than 0 but don't include nSeconds2, nSeconds2 is set to the same value as nSeconds1. However, nSeconds2 is set to 5 if you specify 0 for nSeconds1 and don't include nSeconds2.

Performance can be improved by increasing the value of nSeconds2.

Remarks

Because tables can be opened for shared use on a network, it is possible that records you are viewing in a Browse window are being edited by other users on the network.

SET REFRESH affects records displayed in a Browse window opened with BROWSE, CHANGE, or EDIT. Memo fields opened for editing in a Browse window are also updated.

SET REFRESH can also be used to specify how often data buffered locally on your workstation is updated.

See Also

BROWSE | CHANGE | EDIT | MODIFY MEMO


SET RELATION Command

Establishes a relationship between two open tables.

SET RELATION TO [eExpression1 INTO nWorkArea1 | cTableAlias1
   [, eExpression2 INTO nWorkArea2 | cTableAlias2 ...]
   [IN nWorkArea | cTableAlias] [ADDITIVE]]

Parameters

eExpression1
Specifies the relational expression that establishes a relationship between the parent and child tables. The relational expression is usually the index expression of the controlling index of the child table.

The index for the child table can be a single-entry (.idx) index, a multiple-entry structural compound (.cdx) index, or an independent compound index. If the index is compound, specify the proper index tag to order the child table. SET ORDER can be used to specify the index tag that orders the child table.

For example, consider the customer and orders tables described in the Remarks section below. Suppose the child orders table has been indexed and ordered on the customer number with this command:

SET ORDER TO TAG cust_id

To relate the customer and orders tables on customer number, select the work area containing the customer parent table or include the IN clause to specify the parent table's work area or alias, and issue SET RELATION, specifying the index expression with the following relational expression:

SET RELATION TO cust_id INTO orders

The child table must be indexed unless the relational expression is numeric. Visual FoxPro displays an error message if you issue SET RELATION with a non-numeric relational expression and the child table isn't ordered with an index.

If eExpression1 is numeric, it is evaluated when the record pointer in the parent table is moved. The record pointer in the child table is then moved to record number eExpression1.

INTO nWorkArea1 | cTableAlias1
Specifies the work area number (nWorkArea1) or table alias (cTableAlias1) of the child table.
eExpression2 INTO nWorkArea2 | cTableAlias2 ...
Specifies a relational expression (eExpression2) and a child table or tables to establish an additional relationship between the parent table and child tables. From a single SET RELATION command, you can create multiple relations between a single parent table and various child tables. Precede each relation by a comma.

nWorkArea2 specifies a work area number and cTableAlias2 specifies a table alias for the child table.

IN nWorkArea
Specifies the work area of the parent table.
IN cTableAlias
Specifies the alias of the parent table.

The IN clause makes it possible for you to create a relationship without first selecting the parent table's work area. If you omit nWorkArea and cTableAlias, the parent table must be open in the currently selected work area.

ADDITIVE
Preserves all existing relationships in the current work area and creates the specified relationship. If you omit ADDITIVE, any relationships in the current work area are broken and the specified relationship is created.

Remarks

Before you can establish a relationship, one table (the parent table) must be open, and the other table (the child table) must be open in another work area.

Related tables typically have a common field. For example, suppose a table named customer contains customer information. It has fields for name, address, and a unique customer number. A second table named orders contains order information. It too has a field for the customer number, along with fields for dates and shipping information.

SET RELATION relates these two tables on their common field — the customer number field. To set the relation, the child table must be indexed on the common field. After you set the relation, whenever you move the record pointer to a record with a given customer number in the parent customer table, the record pointer in the child orders table moves to the record with the same customer number. If a matching record can't be found in the child table, the record pointer in the child table is positioned at the end of the table.

Issue SET RELATION TO with no arguments to remove all relationships in the currently selected work area. SET RELATION OFF can be used to remove a specific parent-child relationship.

See Also

INDEX | RELATION( ) | SET ORDER | SET RELATION OFF | SET SKIP | TARGET( )


SET RELATION OFF Command

Breaks an established relationship between the parent table in the currently selected work area, and a related child table.

SET RELATION OFF INTO nWorkArea | cTableAlias

Parameters

INTO nWorkArea | cTableAlias
Specifies the child table's work area number or table alias.

See Also

RELATION( ) | SELECT | SET RELATION | SET SKIP | TARGET( )


SET REPROCESS Command

Specifies how many times and for how long Visual FoxPro attempts to lock a file or record after an unsuccessful locking attempt.

SET REPROCESS TO nAttempts [SECONDS] [SYSTEM] | TO AUTOMATIC [SYSTEM]

Parameters

TO nAttempts [SECONDS]
Specifies the number of times Visual FoxPro attempts to lock a record or file after an initial unsuccessful attempt. The default value is 0, the maximum value is 32,000.

SECONDS specifies that Visual FoxPro attempts to lock a file or record for nAttempts seconds. It's available only when nAttempts is greater than zero.

For example, if nAttempts is 30, Visual FoxPro attempts to lock a record or file up to 30 times. If you also include SECONDS (SET REPROCESS TO 30 SECONDS), Visual FoxPro continuously attempts to lock a record or file for up to 30 seconds.

A system message ("Waiting for lock ... ") appears if SET STATUS is set to ON.

If an ON ERROR routine is in effect and attempts by a command to lock the record or file are unsuccessful, the ON ERROR routine is executed. However, if a function attempts the lock, an ON ERROR routine isn't executed and the function returns false (.F.).

If an ON ERROR routine isn't in effect, a command attempts to lock the record or file, and the lock can't be placed, an appropriate alert appears (for example, "Record is in use by another"). If a function attempts to place the lock, the alert isn't displayed and the function returns false (.F.).

If nAttempts is 0 (the default value) and you issue a command or function that attempts to lock a record or file, Visual FoxPro tries to lock the record or file indefinitely. Visual FoxPro displays the system message, "Attempting to lock... Press Escape to Cancel," while attempting to lock the record or file. The lock is placed and the system message is cleared if the record or file becomes available for locking while you wait. If a function attempted to place the lock, the function returns true (.T.).

If you press ESC in response to the system message, an appropriate alert appears (for example, "Record is in use by another"). If a function attempts to place the lock, the alert isn't displayed and the function returns false (.F.).

If an ON ERROR routine is in effect and a command is attempting to lock the record or file, the ON ERROR routine takes precedence over additional attempts to lock the record or file. The ON ERROR routine is immediately executed. Visual FoxPro does not attempt additional record or file locks and does not display the system message.

If nAttempts is –1, Visual FoxPro attempts to lock the record or file indefinitely. You can't cancel the locking attempts by pressing the ESC key, and an ON ERROR routine isn't executed.

Setting nAttempts to -2 is equivalent to using the TO AUTOMATIC clause.

Visual FoxPro displays the "Waiting for lock ... " system message only if SET STATUS is set to ON.

If a lock has been placed by another user on the record or file you are attempting to lock, you must wait until the user releases the lock.

TO AUTOMATIC
Specifies that Visual FoxPro attempts to lock the record or file indefinitely (equivalent to setting nAttempts to –2). This clause is similar to setting nAttempts to -1, except that it includes the facility to quit the attempt to lock a record or file.

The "Attempting to lock ... Press Escape to Cancel" system message appears while Visual FoxPro attempts to lock the record or file. The lock is placed and the system message is cleared if the record or file becomes available for locking while you wait. If a function is used to place the lock, the function returns true (.T.).

If an ON ERROR routine isn't in effect and you press ESC in response to the system message, an appropriate alert appears (for example, "Record is in use by another"). If a function attempts to place the lock, the alert isn't displayed and the function returns false (.F.).

If an ON ERROR routine is in effect and ESC is pressed, the ON ERROR routine is executed. If a function attempts to place the lock, an ON ERROR routine isn't executed and the function returns false (.F.).

SYSTEM
Specifies that SET REPROCESS applies to the system data session, which controls Tables used internally, such as a database, FoxUser, .scx files, and so on.

For more information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Remarks

The first attempt to lock a record or file isn't always successful. Frequently, a record or file is locked by another user on the network. SET REPROCESS determines whether Visual FoxPro makes additional attempts to lock the record or file when the initial attempt is unsuccessful. You can specify either how many times additional attempts are made or for how long the attempts are made. An ON ERROR routine affects how unsuccessful lock attempts are handled.

SET REPROCESS is scoped to the current data session. SET REPROCESS SYSTEM is scoped to the system data session.

Note Changes made in the Data tab of the Tools Options Dialog box affect only the current session.

Example

SET ("REPROCESS")      && Returns the current session setting
SET("REPROCESS",1)   && Returns the system session setting

* In the config.fpw file, the following code changes the default session.
REPROCESS = 100

See Also

FLOCK( ) | SET DATASESSION | Programming for Shared Access


SET RESOURCE Command

Updates or specifies a resource file. The resource file is a Visual FoxPro table that contains information on system and user-defined resources such as keyboard macros, preferences, system window locations and sizes, diary entries, and so on.

SET RESOURCE ON | OFF

-or-

SET RESOURCE TO [FileName]

Parameters

ON
Specifies that changes made to the Visual FoxPro environment are saved to the resource file. (Default)
OFF
Specifies that changes made to the Visual FoxPro environment are not saved to the resource file.
TO [FileName]
Specifies that changes made to the Visual FoxPro environment are saved to a resource file (FileName) other than the default FoxUser.dbf resource file.

Issue SET RESOURCE TO without a resource file name to open the default FoxUser.dbf resource file. Issuing SET RESOURCE TO performs an implicit SET RESOURCE ON.

See Also

SYS(2005) - Current Resource File | Resource Files in Applications


SET SAFETY Command

Determines whether Visual FoxPro displays a dialog box before overwriting an existing file, or whether table or field rules, default values, and error messages are evaluated when changes are made in the Table Designer or with ALTER TABLE.

SET SAFETY ON | OFF

Parameters

ON
(Default) Specifies that a dialog box is displayed before you overwrite an existing file. The dialog box gives you the option of overwriting the existing file.

For the Table Designer, specifies that table or field rules, default values, and error messages are evaluated when you save changes to a table's structure. Data validation occurs for new or modified validation rules after you save the table structure changes. If a validation rule contains a UDF (user-defined function), the UDF isn't evaluated and the validation rule is ignored.

For ALTER TABLE, table or field rules, default values, and error messages are evaluated when ALTER TABLE changes the table's structure. Data validation occurs for new or modified validation rules when ALTER TABLE changes the table's structure. If a validation rule contains a UDF (user-defined function), the UDF isn't evaluated and the validation rule is ignored.

OFF
Specifies that a dialog box isn't displayed before an existing file is overwritten. Note that for in-process .dll automation servers the default setting of SET SAFETY is OFF.

For the Table Designer, specifies that table or field rules, default values, and error messages are not evaluated when you save changes to a table's structure. However, data validation occurs for new or modified validation rules after you save the table structure changes.

For ALTER TABLE, table or field rules, default values, and error messages are not evaluated when ALTER TABLE changes the table's structure. Data validation does not occur for new or modified validation rules after ALTER TABLE changes the table's structure.

Remarks

SET SAFETY is scoped to the current data session.

See Also

ALTER TABLE - SQL | MODIFY STRUCTURE | SET DATASESSION | SET TALK


SET SECONDS Command

Specifies whether seconds are displayed in the time portion of a DateTime value.

SET SECONDS ON | OFF

Parameters

ON
(Default) Specifies that seconds are displayed in DateTime values.
OFF
Specifies that seconds are not displayed in DateTime values.

Remarks

SET SECONDS is scoped to the current data session.

Example

The following example demonstrates the effect of the SET SECONDS setting on the time value returned by DATETIME( ). When SET SECONDS is ON, the time value is displayed with the seconds portion. When SET SECONDS is OFF, the time value is displayed without the seconds portion.

SET SECONDS ON
CLEAR
? DATETIME( )  && Displays time value with the seconds portion

SET SECONDS OFF  && Displays time value without the seconds portion
? DATETIME( )

See Also

CTOT( ) | DATE( ) | DATETIME( ) | DTOT( ) | HOUR( ) | MINUTE( ) | SEC( ) | SECONDS( ) | SET SECONDS | TIME( )


SET SEPARATOR Command

Included for backward compatibility. Use the Digit grouping symbol setting of the Windows Regional Options Control Panel instead.


SET SKIP Command

Creates a one-to-many relationship among tables.

SET SKIP TO [TableAlias1 [, TableAlias2] ...]

Parameters

TO TableAlias1 [, TableAlias2] ...
Specifies the aliases of multiple child tables. These are used to create a one-to-many relationship with a parent table. Use commas to separate the aliases. In commands that support a scope (DISPLAY, LIST, and so on), records in the parent table are repeated for each corresponding record in the child table.

Use SET SKIP TO without additional arguments to remove the one-to-many relationship from the parent table open in the currently selected work area. Any one-to-one relationships remain in effect. One-to-one relationships can be removed with SET RELATION TO.

Remarks

Using SET RELATION, you can establish relations between tables open in different work areas. When the record pointer is moved in the parent table, the record pointer in the child table moves to the first corresponding record. The relational expression in SET RELATION determines where the record pointer moves in the child table. A one-to-one relation is created — for each record in the parent table, the record pointer moves to the first matching record in the child table. If a matching record can't be found in the child table, the record pointer in the child table moves to the end of the table.

Frequently, a child table contains multiple records that correspond to one record in the parent table. SET SKIP lets you establish a one-to-many relationship between one record in the parent table and multiple records in the child table. When you skip through the parent table, the record pointer remains on the same parent record until the record pointer moves through all related records in the child table.

To establish a one-to-many relationship, first create the relationship between the parent and child table with SET RELATION. Then, issue SET SKIP to create a one-to-many relationship.

Example

This example below finds all occurrences in three tables where each item in the first field are the same. It does this by using scanning the first table, which has a relation into a second, which table has a relation into a third. The first table then does a SET SKIP for the other two tables. A SET SKIP on the second table has no effect. It affects only the table being scanned (replaced, etc.). In the example, eight matches are found.

CLOSE DATABASES
* Creates parent table with values a and b in Name field
CREATE TABLE Parent FREE (Name C(1), Val C(10))
INSERT INTO Parent VALUES ('a', 'Parent.a1')
INSERT INTO Parent VALUES ('b', 'Parent.b1')

SELECT 0     && Child1 will have two a's and two b's
CREATE TABLE Child1 FREE (Name1 C(1), Val C(10))
INSERT INTO Child1 VALUES ('a', 'Child1.a1')
INSERT INTO Child1 VALUES ('b', 'Child1.b1')
INSERT INTO Child1 VALUES ('b', 'Child1.b2')
INSERT INTO Child1 VALUES ('a', 'Child1.a2')
INDEX ON Name1 TAG tagName   && The tag name is irrelevant

SELECT 0  && Child2 will have two a's and two b's
CREATE TABLE Child2 FREE (Name2 C(1), Val C(10))
INSERT INTO Child2 VALUES ('b', 'Child1.b1')
INSERT INTO Child2 VALUES ('b', 'Child1.b2')
INSERT INTO Child2 VALUES ('a', 'Child1.a1')
INSERT INTO Child2 VALUES ('a', 'Child1.a2')
INDEX ON Name2 TAG tagName     && The tag name is irrelevant

SELECT Child1
SET RELATION TO Name1 INTO Child2
SELECT Parent
SET RELATION TO Name INTO Child1
SET SKIP TO Child1, Child2 && Parent gets both skips.
           && Otherwise, only four record triplets
           && would be listed.
SCAN ALL  && There will be eight triplets: four a's and four b's
   ? Parent.Val, Child1.Val, Child2.Val
ENDSCAN

See Also

RELATION( ) | SET RELATION | SKIP


SET SKIP OF Command

Enables or disables a menu, menu bar, menu title, or menu item for user-defined menus or the Microsoft Visual FoxPro system menu.

SET SKIP OF MENU MenuBarName1 lExpression1

-Or-

SET SKIP OF PAD MenuTitleName OF MenuBarName2 lExpression2

-Or-

SET SKIP OF POPUP MenuName1 lExpression3

-Or-

SET SKIP OF BAR nMenuItemNumber | SystemItemName OF MenuName2
   lExpression4

Parameters

MENU MenuBarName1 lExpression1
Enables or disables the Visual FoxPro system menu bar or user-defined menu bar created with DEFINE MENU. For example, the Visual FoxPro system menu bar _MSYSMENU can be disabled with this command:
SET SKIP OF MENU _MSYSMENU .T.

It can be enabled with this command:

SET SKIP OF MENU _MSYSMENU .F.
PAD MenuTitleName OF MenuBarName2 lExpression2
Enables or disables a Visual FoxPro system menu title or a user-defined menu title created with DEFINE PAD. For example, the Visual FoxPro Edit menu title can be disabled with this command:
SET SKIP OF PAD _MSM_EDIT OF _MSYSMENU .T.

The menu title can be enabled with this command:

SET SKIP OF PAD _MSM_EDIT OF _MSYSMENU .F.
POPUP MenuName1 lExpression3
Enables or disables a Visual FoxPro system menu or a user-defined menu created with DEFINE POPUP. For example, the Visual FoxPro Edit menu can be disabled with this command:
SET SKIP OF POPUP _MEDIT .T.

The menu can be enabled with this command:

SET SKIP OF POPUP _MEDIT .F.
BAR nMenuItemNumber | SystemItemName OF MenuName2 lExpression4
Enables or disables a menu item on a Visual FoxPro system menu or a user-defined menu item created with DEFINE BAR. For example, the New command on the Visual FoxPro File menu can be disabled with this command:
SET SKIP OF BAR _MFI_NEW OF _MFILE .T.

where SystemItemName specifies the menu command _MFI_NEW, MenuName2 specifies the menu _MFILE, and lExpression4 specifies the logical expression .T.. The menu command can be enabled with this command:

SET SKIP OF BAR _MFI_NEW OF _MFILE .F.

Use nMenuItemNumber to specify a menu item created with DEFINE BAR.

Remarks

For a complete listing of the internal names of Visual FoxPro system menu components, see System Menu Names. You can also use SYS(2013) to return the system menu internal names.

If the logical expression lExpression evaluates to true (.T.), the menu, menu bar, menu name, or menu item included in SET SKIP OF is disabled, appears dimmed, and can't be selected. If lExpression evaluates to false (.F.), the menu, menu bar, menu name, or menu item is enabled and can be selected.

See Also

CREATE MENU | DEFINE BAR | DEFINE MENU | DEFINE PAD | DEFINE POPUP | System Menu Names Overview | SKPBAR( )


SET SPACE Command

Determines whether a space is displayed between fields or expressions when you use the ? or ?? command.

SET SPACE ON | OFF

Parameters

ON
(Default) Inserts a space between fields and expressions.
OFF
Removes all spaces between fields or expressions and runs them together.

See Also

? | ?? | SPACE( ) Function | DISKSPACE( ) Function


SET STATUS BAR Command

Displays or removes the graphical status bar.

SET STATUS BAR ON | OFF

Parameters

ON
(Default) Issue SET STATUS BAR ON to display the graphical status bar.
OFF
Issue SET STATUS BAR OFF to remove the graphical status bar.

See Also

SET STATUS | StatusBarText Property | StatusBar Property


SET STATUS Command

Displays or removes the character-based status bar.

SET STATUS ON | OFF

Parameters

ON
If SET STATUS is ON, the character-based status bar is displayed showing the name of the program currently executing (if any) the alias of the active table, the current record pointer position, the number of records in the table, and the state of the Insert, NumLock and CapsLock keys. The record or file lock status is also shown in the status bar when the table is opened for shared use. The status bar is updated each time you execute a command that changes status information.
OFF
(Default) Issue SET STATUS OFF to remove the status bar.

See Also

SET STATUS BAR | StatusBarText Property | NUMLOCK( ) Function | CAPSLOCK( ) Function


SET STEP Command

Opens the Trace window and suspends program execution for debugging.

SET STEP ON

Parameters

ON
Opens the Trace window and suspends program execution.

Remarks

SET STEP is used to debug programs. You can insert SET STEP ON in a program at the point where you'd like to execute individual commands.

For information about the Trace Window, see Testing and Debugging Applications .

You can pass parameters to a program and then trace its execution by following these steps:

  1. Open the Trace window.
  2. From the Trace window's Program menu, choose Open and select the program to trace.
  3. Set a breakpoint on the first executable line of the program.
  4. In the Command window, DO the program WITH the parameters.

See Also

SET ECHO | Trace Window | Testing and Debugging Applications


SET STRICTDATE Command

Specifies if ambiguous Date and DateTime constants generate errors.

SET STRICTDATE TO [0 | 1 | 2]

Parameters

0
Specifies that strict date format checking is off. This setting provides compatibility with earlier versions of Visual FoxPro. 0 is the default setting for the Visual FoxPro runtime and ODBC driver. When STRICTDATE is set to 0, invalid Date and DateTimes evaluate to the empty date.
1
Specifies that all Date and DateTime constants be in the strict date format. Any Date or DateTime constant that is not in the strict format or evaluates to an invalid value generates an error, either during compilation, at runtime, or during an interactive Visual FoxPro session. 1 is the default setting for an interactive Visual FoxPro session.
2
Identical to setting STRICTDATE to 1, but also generates a compilation error (2033 – CTOD and CTOT can produce incorrect results) whenever CTOD( ) and CTOT( ) functions appear in code.

Because the values returned by CTOD( ) and CTOT( ) rely on SET DATE and SET CENTURY to interpret the date string they contain, they are prone to year 2000 noncompliance errors. Use DATE( ) and DATETIME( ) with the optional numeric arguments to create Date and DateTime constants and expressions.

This setting is most useful during debugging sessions to trap for code that may contain year 2000 compliance errors.

Remarks

Note that the StrictDateEntry property isn't affected by the setting of SET STRICTDATE.

See Also

COMPILE | CTOD( ) | CTOT( ) | SET LOGERRORS | StrictDateEntry Property


SET SYSFORMATS Command

Specifies whether Visual FoxPro for Windows system settings are updated with the current Microsoft Windows system settings.

SET SYSFORMATS ON | OFF

Parameters

ON
Specifies that the Visual FoxPro system settings are updated when the Windows system settings are changed. SET SYSFORMAT ON is identical to choosing the Use System Settings check box on the International tab of the Options dialog. Note that issuing SET SYSFORMAT ON changes the SET DATE setting to SHORT.

The settings are used for the duration of the current data session, or, if issued during the default data session, for the duration of the Visual FoxPro session.

OFF
(Default) Specifies that the Visual FoxPro system settings are not updated when the Windows system settings are changed. The Visual FoxPro default settings are not restored.

Remarks

The Windows system settings are specified in International option of the Windows Control Panel.

When SET SYSFORMATS is ON, the following SET commands can be used to override the current system settings. However, changing the Windows system settings when SET SYSFORMATS is ON overrides these SET commands:

  • SET CENTURY
  • SET CURRENCY
  • SET DATE
  • SET DECIMALS
  • SET HOURS
  • SET MARK TO
  • SET POINT
  • SET SEPARATOR

When Visual FoxPro is started, the Visual FoxPro system settings are the default settings of these SET commands. To use the Windows system settings when Visual FoxPro is started, place the following line in your Visual FoxPro Config.fpw configuration file:

SYSFORMATS = ON

SET SYSFORMATS is scoped to the current data session.

See Also

SET CENTURY | SET CURRENCY | SET DATASESSION | SET DATE | SET DECIMALS | SET HOURS | SET MARK TO | SET POINT | SET SEPARATOR


SET SYSMENU Command

Enables or disables the Visual FoxPro system menu bar during program execution, and allows you to reconfigure it.

SET SYSMENU ON | OFF | AUTOMATIC | TO [MenuList] | TO [MenuTitleList]
   | TO [DEFAULT] | SAVE | NOSAVE

Parameters

ON
Enables the main Visual FoxPro menu bar during program execution when Visual FoxPro is waiting for keyboard input during commands such as BROWSE, READ, and MODIFY COMMAND.
OFF
Disables the main Visual FoxPro menu bar during program execution.
AUTOMATIC
Makes the main Visual FoxPro menu bar visible during program execution. The menu bar is accessible and menu items are enabled and disabled as appropriate for the current command.

AUTOMATIC is the default setting.

TO [MenuList]TO [MenuTitleList]
Specifies a subset of menus or menu titles for the main Visual FoxPro menu bar. The menu or menu title list can contain any combination of menus or menu titles separated by commas. The internal names for the menus and menu titles are listed in the System Menu Names topic.

For example, the following command removes all menus from the main Visual FoxPro menu bar except the File and Window menus:

SET SYSMENU TO _MFILE, _MWINDOW

Use RELEASE BAR to specify the menu items available in the menus.

TO [DEFAULT]
Restores the main menu bar to its default configuration. If you have modified the main menu bar or its menus, issue SET SYSMENU TO DEFAULT to restore it. You can specify a default configuration with SET SYSMENU SAVE.
SAVE
Makes the current menu system the default configuration. If you modify the menu system after issuing SET SYSMENU SAVE, you can restore the previous configuration by issuing SET SYSMENU TO DEFAULT.
NOSAVE
Resets the menu system to the default Visual FoxPro system menu. However, the default Visual FoxPro system menu is not displayed until you issue SET SYSMENU TO DEFAULT.

Remarks

SET SYSMENU controls the main Visual FoxPro menu bar during program execution and lets you selectively remove menu titles and menus from and restore them to the main Visual FoxPro menu system.

Issuing SET SYSMENU TO without additional arguments disables the main Visual FoxPro menu bar.

See Also

System Menu Names | POP MENU | PUSH MENU | RELEASE | SYS(2013) – System Menu Name String


SET TABLEVALIDATE Command

Specifies the level of table validation to perform.

You can use SET TABLEVALIDATE when you want a lower level of table integrity checking than the default setting.

SET TABLEVALIDATE TO [nLevel]

Parameters

nLevel
Specifies the table validation level. If omitted, the default value of nLevel is 3.

The following table lists the values for nLevel.

nLevel | Description
0 | Does not perform table validation.
1 Validate record count when opening a table.
Note The table (.dbf) file header is locked during validation. This can result in decreased scalability when tables are opened as shared, for example, by calling USE tableName SHARED, or when calling a SQL SELECT, INSERT, UPDATE, or DELETE command for an unopened table, and SET EXCLUSIVE is OFF.
2 | Validate record count when appending or inserting records and writing them to disk.
3 | Validate as described by nLevel=1 and nLevel=2. (Default)

Remarks

SET TABLEVALIDATE does not have repair functionality; it performs only integrity checks as specified by nLevel.

SET TABLEVALIDATE does not affect temporary files or cursors; that is, table validation is not performed.

You can use SET TABLEVALIDATE in Config.fpw as follows:

TABLEVALIDATE = nLevel

See Also

SET Command Overview | USE Command | SELECT - SQL Command | INSERT - SQL Command | UPDATE - SQL Command | DELETE - SQL Command | Programming for Shared Access


SET TALK Command

Determines whether Visual FoxPro displays command results.

SET TALK ON | OFF | WINDOW [WindowName] | NOWINDOW

Parameters

ON
(Default) Allows talk to be sent to the main Visual FoxPro window, the system message window, the graphical status bar, or a user-defined window. If SET TALK is set to OFF and is then changed to ON, the talk is directed to the same location it was sent to before you issued SET TALK OFF.
OFF
Prevents talk from being sent to the main Visual FoxPro window, the system message window, the graphical status bar, or a user-defined window. Note that for in-process .dll automation servers the default setting of SET TALK is OFF.
WINDOW [WindowName]
WindowName specifies a user-defined window to which talk is directed. You must create the user-defined window before directing talk to it. Talk is directed to the Visual FoxPro system window if the window you specify doesn't exist.
NOWINDOW
Directs talk to the main Visual FoxPro window.

Remarks

Some table processing commands return information, or "talk," about their status while they execute. These commands include:

Commands

APPEND FROM | PACK
AVERAGE | REINDEX
CALCULATE | REPLACE
COPY TO | SELECT - SQL
COUNT | SORT
DELETE | SUM
INDEX | TOTAL

Talk can be directed to the main Visual FoxPro window, the graphical status bar, or a user-defined window. Talk can also be turned off.

The SET TALK reporting interval can be specified with SET ODOMETER. The default value for SET ODOMETER is 100. Note that execution speed can be degraded when SET TALK is set to ON, because the main Visual FoxPro window or user-defined window must be frequently updated. If you just need the total number of records processed by a command, you can issue SET TALK OFF and display the _TALLY system variable once the command has completed executing.

SET TALK is scoped to the current data session.

See Also

DEFINE WINDOW | SET DATASESSION | SET NOTIFY | SET ODOMETER | SYS(103) - Talk Setting | _TALLY


SET TEXTMERGE Command

Enables or disables the evaluation of fields, variables, array elements, functions, or expressions that are surrounded by text-merge delimiters, and lets you specify text-merge output.

SET TEXTMERGE [ON | OFF] [TO [FileName] MEMVAR VarName [ADDITIVE]]
   [WINDOW WindowName] [SHOW | NOSHOW]

Parameters

ON
Specifies that any fields, variables, array elements, functions, or expressions surrounded by the text-merge delimiters be evaluated and output when placed after \ or \\, or between TEXT and ENDTEXT.

The following short program example demonstrates how the contents of the variable gcTodayDate and the DATE( ) and TIME( ) functions are evaluated when SET TEXTMERGE is set to ON. The variable gcTodayDate, DATE( ), and TIME( ) are evaluated because they are enclosed by the text-merge delimiters and SET TEXTMERGE is set to ON.

CLEAR
SET TALK OFF
STORE 'Today is: ' TO gcTodayDate
SET TEXTMERGE ON
\<<gcTodayDate>>
\\<<DATE( )>>
\The time is:
\\ <<TIME( )>>

Here is the output from the program above when run on January 1:

Today is: 01/01/98
The time is: 10:55:19
OFF
(Default) Specifies that any fields, variables, array elements, functions, or expressions be literally output along with the text-merge delimiters surrounding them. Note the difference in output when SET TEXTMERGE is set to OFF in the previous example:
CLEAR
SET TALK OFF
STORE 'Today is: ' TO gcTodayDate
SET TEXTMERGE OFF
\<<gcTodayDate>>
\\<<DATE( )>>
\The time is:
\\ <<TIME( )>>

Here is the output from this program:

<<gcTodayDate>><<DATE( )>>
The time is: <<TIME( )>>
TO [FileName]
Specifies that output from \, \\, and TEXT ... ENDTEXT be directed to a text file in addition to the main Visual FoxPro window, which is the default. You can also direct the output to a text file by including FileName. If a file with that name doesn't exist, a new file is created. If a file with the same name already exists and SET SAFETY is set to ON, you are given the option of overwriting the existing file.

The text file is opened as a low-level file, and its file handle is stored to the _TEXT system variable. You can close the file by issuing SET TEXTMERGE TO without additional arguments. If the file handle of another file was previously stored in _TEXT, that file is closed.

MEMVAR VarName
Specifies a variable to contain data from TEXTMERGE output.

Because SET TEXTMERGE is a global setting and can span several procedures or methods, it is possible for MEMVAR VarName to lose scope. The command will function even when the variable is out of scope, but will return no content. You can control scooping of MEMVAR VarName by declaring the variable PUBLIC or PRIVATE.

This clause can also create recursive behavior, which you can control with the SET TEXTMERGE TO command, as in the following example:

USE LABELS
STORE "" to myVar, myVar2

SET TEXT ON NOSHOW
SET TEXTMERGE TO MEMVAR myVar && TEXTMERGE begins on the next line.

\Hey Now
\<<date()>>

SCAN
   \  <<name>>
ENDSCAN

* Remove comments from SET TEXTMERGE TO line to eliminate recursive
* error with myVar and myVar2.
* SET TEXTMERGE TO

TEXT TO myVar2
<b> Here's some HTML. </b>
This is HTML
   <<date()>>
ENDTEXT

SET TEXTMERGE OFF
USE

CLEAR
? myVar  && But has also stored the TEXTMERGE contents to variables
? myVar2
ADDITIVE
Specifies that output from \, \\, and TEXT ... ENDTEXT be appended to an existing file or memory variable.

For more information on directing text-merge output to a file, see _TEXT.

WINDOW WindowName
Specifies that output from \, \\, and TEXT ... ENDTEXT be directed to a user-defined window rather than the main Visual FoxPro window, which is the default. WindowName specifies the name of the window to which you want to direct output. The window must be created with DEFINE WINDOW before output can be sent to it. The window doesn't have to be active or visible.
SHOW | NOSHOW
(Default) SHOW displays text-merge output.

NOSHOW suppresses display of text-merge output.

By default, output generated by \, \\, and TEXT ... ENDTEXT is sent to the main Visual FoxPro window or an active user-defined window.

Remarks

The \, \\, and TEXT ... ENDTEXT commands are used to merge text with the contents of tables, variables, array elements, and the results of functions and expressions. If a field, variable, array element, function, or expression is surrounded by text-merge delimiters (by default, << and >>), it can be evaluated and merged with text. This text-merge capability lets you produce letters, programs, and templates that create programs.

SET TEXTMERGE determines how fields, variables, array elements, functions, or expressions surrounded by text-merge delimiters are evaluated. It also lets you direct text-merge output to the main Visual FoxPro window, a user-defined window, or a file.

Memo fields can be used to nest merged text. If a memo field contains field names, variables, array elements, functions, or expressions surrounded by the current text-merge delimiters, these are evaluated and output with the contents of the memo field. The memo field name must also be enclosed in text-merge delimiters.

See Also

\ | \\ | _PRETEXT | SET TEXTMERGE DELIMITERS | TEXTMERGE( ) Function | _TEXT | TEXT ... ENDTEXT


SET TEXTMERGE DELIMITERS Command

Specifies the text-merge delimiters.

SET TEXTMERGE DELIMITERS [TO cLeftDelimiter [, cRightDelimiter]]

Parameters

TO cLeftDelimiter [, cRightDelimiter]
Specifies the delimiters. If you specify only one delimiter with cLeftDelimiter, both the left and right delimiters are set to cLeftDelimiter. If you specify both delimiters with cLeftDelimiter and cRightDelimiter, the left delimiter is set to cLeftDelimiter and the right delimiter is set to cRightDelimiter.

Remarks

With SET TEXTMERGE DELIMITERS, you can specify a set of text-merge delimiters other than the default delimiters, which are double angle brackets (<< and >>). The current delimiters can be displayed with DISPLAY STATUS.

If you issue SET TEXTMERGE DELIMITERS without any additional arguments, the default delimiters are restored.

For more information about text-merge delimiters, see SET TEXTMERGE.

See Also

\ | \\ | _PRETEXT | SET TEXTMERGE | _TEXT


SET TOPIC Command

Specifies the Help topic or topics to open when you invoke the Visual FoxPro Help system.

SET TOPIC TO [cHelpTopicName | lExpression]

Parameters

cHelpTopicName
Specifies the name of the Help topic you want to display.
lExpression
A logical expression that is the basis for opening a specific topic or topics.

Remarks

For more information on creating your own Help system, see Creating Help.

See Also

HELP | SET HELP | SET TOPIC ID


SET TOPIC ID Command

Specifies the Help topic to display when you invoke the Visual FoxPro Help system. The Help topic is based on the topic's context ID.

SET TOPIC ID TO nHelpContextID

Parameters

nHelpContextID
Specifies the Help topic to display, based on a numerical context ID. nHelpContextID is a context number in the MAP section of the Help project file.

See Also

HELP | SET HELP | SET TOPIC


SET TRBETWEEN Command

Enables or disables tracing between breakpoints in the Trace Window.

SET TRBETWEEN ON | OFF

Parameters

ON
Specifies that every line of program code be displayed and highlighted in the Trace window as it is executed. Issuing SET TRBETWEEN ON is identical to enabling the Trace Between Breaks command in the Trace window's Program menu.
OFF
(Default) Specifies that only the last line at which program execution was paused be highlighted in the Trace window. Issuing SET TRBETWEEN OFF is identical to disabling the Trace Between Breaks command.

Remarks

The Trace window displays the source code for a program as the program executes. The executing program line is highlighted. When the Trace window is open, you can set breakpoints that cause program execution to stop.

The Trace window can also be opened by issuing ACTIVATE WINDOW TRACE, SET ECHO ON, or SET STEP ON.

See Also

ACTIVATE WINDOW | SET ECHO | SET STEP


SET TYPEAHEAD Command

Specifies the maximum number of characters that can be stored in the type-ahead buffer.

SET TYPEAHEAD TO nCharacters

Parameters

nCharacters
Specifies the maximum number of characters to store in the type-ahead buffer.

No characters are held in the type-ahead buffer if you issue SET TYPEAHEAD TO 0. This statement deactivates INKEY( ) and ON KEY.

Remarks

The type-ahead buffer can store as many as 32,000 characters until they are ready to be processed. The default value for SET TYPEAHEAD is 20.

See Also

INKEY( ) | ON KEY | TYPE Command


SET UDFPARMS Command

Specifies if Microsoft Visual FoxPro passes parameters to a user-defined function (UDF) by value or by reference.

SET UDFPARMS TO VALUE | REFERENCE

Parameters

TO VALUE
Specifies that a variable be passed to a user-defined function by value. When a variable is passed by value, the variable's value can be changed in the user-defined function, but the variable's original value in the calling program isn't changed.
TO REFERENCE
Specifies that a variable be passed to a user-defined function by reference. When a variable is passed by reference and the user-defined function changes the value of the passed variable, the variable's original value in the calling program is also changed.

Remarks

By default, variables are passed to a user-defined function by value. (Variables passed to procedures with DO ... WITH are passed by reference.)

You can force parameters to be passed to a UDF by value or reference, regardless of the setting of SET UDFPARMS. Enclose a variable in parentheses to force the variable to be passed by value. Preface the variable with an @ symbol to force the variable to be passed by reference.

Tip Entire arrays can be passed to a procedure or user-defined function. The entire array is passed if you issue SET UDFPARMS TO REFERENCE or preface the array name with @. The first element of the array is passed by value if you issue SET UDFPARMS TO VALUE or enclose the array name by parentheses. Array elements are always passed by value.

Example

The following example illustrates the difference between passing variables by value and by reference.

*** Pass variable by value ***
CLEAR
SET TALK OFF
WAIT 'Press a key to pass by value' WINDOW
SET UDFPARMS TO VALUE
STORE 1 TO gnX

*** The value of gnX is unchanged ***
@ 2,2 SAY 'UDF value: ' + STR(plusone(gnX))
@ 4,2 SAY 'Value of gnX: ' + STR(gnX)

*** Pass variable by reference ***
WAIT 'Press a key to pass by reference' WINDOW
CLEAR
SET UDFPARMS TO REFERENCE
STORE 1 TO gnX
*** The value of gnX is changed ***
@ 2,2 SAY 'UDF value: ' + STR(plusone(gnX))
@ 4,2 SAY 'Value of X: ' + STR(gnX)
SET UDFPARMS TO VALUE

*** This is a UDF that adds one to a number ***
FUNCTION plusone
PARAMETER gnZ
gnZ = gnZ + 1
RETURN gnZ
*** End of UDF ***

The following is the above example with variables passed by value and reference through the use of parentheses and @, respectively.

*** Pass variable by value ***
CLEAR
SET TALK OFF
WAIT 'Press a key to pass by value' WINDOW
STORE 1 TO gnX
@ 2,2 SAY 'UDF value: ' + STR(plusone((gnX)))
@ 4,2 SAY 'Value of gnX: ' + STR(gnX)

*** Pass variable by reference ***
WAIT 'Press a key to pass by reference' WINDOW
CLEAR
STORE 1 TO gnX
@ 2,2 SAY 'UDF value: ' + STR(plusone(@gnX))
@ 4,2 SAY 'Value of gnX: ' + STR(gnX)

*** This is a UDF that adds one to a number ***
FUNCTION plusone
PARAMETER gnZ
gnZ = gnZ + 1
RETURN gnZ
*** End of UDF ***

See Also

DO | LPARAMETERS | PARAMETERS | PARAMETERS( ) | PROCEDURE


SET UNIQUE Command

Specifies whether records with duplicate index key values are maintained in an index file.

SET UNIQUE ON | OFF

Parameters

ON
Specifies that any record with a duplicate index key value not be included in the index file. Only the first record with the original index key value is included in the index file.
OFF
(Default) Specifies that records with duplicate index key values be included in the index file.

Remarks

An index file retains its SET UNIQUE setting when you issue REINDEX. For more information, see INDEX and REINDEX.

SET UNIQUE is scoped to the current data session.

See Also

INDEX | REINDEX | SET DATASESSION


SET VIEW Command

Opens or closes the Data Session window or restores the Visual FoxPro environment from a view file.

SET VIEW ON | OFF
-or-
SET VIEW TO FileName | ?

Parameters

ON
Opens the Data Session window.
OFF
(Default) Closes the Data Session window.
TO FileName
Restores the Visual FoxPro environment to the state it was in when the view file specified with FileName was created. View files are created with CREATE VIEW.
?
Displays the Open dialog box, from which you can open a view file.

Remarks

For more information on view files, see CREATE VIEW.

See Also

CREATE VIEW | SET | Data Session Window


SHOW MENU Command

Displays one or more user-defined menu bars without activating them.

SHOW MENU MenuBarName1 [, MenuBarName2 ...] | ALL   [PAD MenuTitleName]
   [SAVE]

Parameters

MenuBarName1 [, MenuBarName2 ...]
Specifies the name of one or more menu bars to display.
ALL
Displays all currently defined menu bars.
PAD MenuTitleName
Specifies a menu title to be highlighted on a menu bar.
SAVE
Retains an image of the specified menu bars without activating them. You can clear the menu bar images with CLEAR.

Remarks

The menu bars are displayed but cannot be used. Before they can be displayed, you must first create the menu bars with DEFINE MENU.

Example

CLEAR
DEFINE MENU mnuExample BAR AT LINE 2
DEFINE PAD padConv OF mnuExample PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD padCard OF mnuExample PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
SHOW MENU mnuExample

See Also

ACTIVATE MENU | CREATE MENU | DEFINE MENU


SHOW POPUP Command

Displays one or more menus defined with DEFINE POPUP without activating them.

SHOW POPUP MenuName1 [, MenuName2 ...] | ALL    [SAVE]

Parameters

MenuName1 [, MenuName2 ...]
Specifies the name of one or more menus to display.
ALL
Displays all currently defined menus.
SAVE
Retains an image of the specified menus without activating them. The menu images can be cleared with CLEAR.

Remarks

The menus are displayed but cannot be used. Before they can be shown, the menus must first be created with DEFINE POPUP.

See Also

ACTIVATE POPUP | DEFINE POPUP | DEACTIVATE POPUP Command | CLEAR Commands


SHOW WINDOW Command

Displays one or more user-defined windows or Visual FoxPro system windows without activating them.

SHOW WINDOW WindowName1 [, WindowName2 ...] | ALL | SCREEN
   [IN [WINDOW] WindowName3   [REFRESH]   [TOP | BOTTOM | SAME]   [SAVE]

Parameters

WindowName1 [, WindowName2 ...]
Specifies the name of one or more windows to display.
ALL
Displays all user-defined windows.
SCREEN
Displays the main Visual FoxPro window when it is hidden. You can also choose Screen from the Window menu to display the main Visual FoxPro window. You can hide the main Visual FoxPro window by clicking its close box or issuing DEACTIVATE WINDOW SCREEN, HIDE WINDOW SCREEN, or RELEASE WINDOW SCREEN.
IN [WINDOW] WindowName3
Displays the window inside a parent window specified with WindowName3. The window does not assume the characteristics of the parent window. A window displayed inside a parent window cannot be moved outside the parent window. If the parent window is moved, the child window moves with it.

The parent window specified with WindowName3 must first be created with DEFINE WINDOW.

IN SCREEN
Explicitly displays the window in the main Visual FoxPro window instead of in another window. Windows are placed in the main Visual FoxPro window by default.
REFRESH
Redraws a Browse window. This option is useful on a network to ensure that you are browsing the most current version of a table. The work area for the Browse window table is selected.

Memo-editing windows are refreshed with changes made to the memo field by other users on a network. SET REFRESH determines the interval between memo-editing-window refreshes. Refer to SET REFRESH for additional information on how data is refreshed in tables opened for shared use on a network.

TOP
Places the specified window in front of all other windows.
BOTTOM
Places the specified window behind all other windows.
SAME
Places the specified window back into a stack of windows in the same position the window occupied before it was deactivated. SAME affects only windows that have been previously displayed or activated and then cleared from the main Visual FoxPro window with DEACTIVATE WINDOW.
SAVE
Keeps an image of the window in the main Visual FoxPro window or in another window after the window is released. Normally, windows are removed from the main Visual FoxPro window after they are released. The window image can be cleared from the main Visual FoxPro window or a window with CLEAR.

Remarks

SHOW WINDOW controls the display and front-to-back screen placement of windows. If a window is hidden or has not been activated, SHOW WINDOW displays the window without activating it. If one or more windows are currently displayed, SHOW WINDOW lets you change the front-to-back order of the windows.

You can also display system windows, such as the Command window.

In Visual FoxPro, you can use SHOW WINDOW to display the Visual FoxPro toolbars. Use HIDE WINDOW to remove a toolbar from the FoxPro window. Toolbars must be active before they can be displayed. The following table lists the Visual FoxPro toolbars names to use in SHOW WINDOW and HIDE WINDOW. Enclose the toolbar name in quotation marks.

Toolbar Names |  |
Color Palette | Layout | Report Designer
Database Designer | Print Preview | Standard
Form Controls | Query Designer | View Designer
Form Designer | Report Controls |

To show a system window, enclose the entire system window name in quotation marks.

You cannot specify where output is directed to user-defined windows with SHOW WINDOW. Use ACTIVATE WINDOW to direct output to a user-defined window created with DEFINE WINDOW.

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the SHOW WINDOW command.

Example

The following example, a window named wOutput1 is created and displayed. Since SHOW WINDOW is used to display the window, output cannot be directed to the window until it is activated.

CLEAR
DEFINE WINDOW wOutput1 FROM 2,1 TO 13,75 TITLE 'Output' ;
   CLOSE FLOAT GROW ZOOM
SHOW WINDOW wOutput1

See Also

ACTIVATE WINDOW | DEFINE WINDOW | CLEAR Commands


SIZE POPUP Command

Changes the size of a menu created with DEFINE POPUP.

SIZE POPUP MenuName TO nRow1, nColumn1 | BY nRow2, nColumn2

Parameters

MenuName
Specifies the name of the menu whose size you want to change.
TO nRow1, nColumn1
Changes the size of a menu to a specific size. nRow1 and nColumn1 specify the new row and column coordinates, respectively, of the lower-right corner of the menu.
BY nRow2, nColumn2
Changes the size of a menu relative to its current size. nRow2 and nColumn2 specify the change in size of the menu in rows and columns, relative to the current row and column coordinates of the lower-right corner of the menu.

Remarks

If a user-defined menu has been created, its size can be changed; it doesn't have to be active or visible.

Example

This example creates a menu containing files with a .PRG extension and moves, enlarges, and shrinks the menu before closing it.

CLEAR
DEFINE POPUP popMovIn FROM 2,2 TO 7, 14 PROMPT FILES LIKE *.PRG ;
   TITLE 'Programs'
ACTIVATE POPUP popMovIn NOWAIT
=CHRSAW(2)
MOVE POPUP popMovIn BY 5,5     && Move popup down
=CHRSAW(2)
SIZE POPUP popMovIn BY 5,5  && Enlarge the popup
=CHRSAW(2)
SIZE POPUP popMovIn BY -5,-5  && Shrink the popup
=CHRSAW(2)
MOVE POPUP popMovIn BY -5,-5  && Move popup up
=CHRSAW(2)
DEACTIVATE POPUP popMovIn
RELEASE POPUP popMovIn

See Also

ACTIVATE POPUP | CLEAR Commands | DEFINE POPUP Command


SIZE WINDOW Command

Changes the size of a window created with DEFINE WINDOW or a Visual FoxPro system window.

SIZE WINDOW WindowName TO nRow1, nColumn1 | BY nRow2, nColumn2

Parameters

WindowName
Specifies the name of the window whose size you want to change.

To change the size of a system window, enclose the entire system window name in quotation marks. For example, to increase the size of the Command window by 1 row and 1 column, issue the following command:

SIZE WINDOW 'Command Window' BY 1,1

You can only change the size of the Command, Debug, and Trace windows.

TO nRow1, nColumn1
Changes the size of a window to a specific size. nRow1 and nColumn1 specify the new row and column coordinates, respectively, of the lower-right corner of the window relative to the upper-left corner of the window.
BY nRow2, nColumn2
Changes the size of a window relative to its current size. nRow2 and nColumn2 specify the change in size of the window in rows and columns, relative to the current row and column coordinates of the lower-right corner of the window.

Remarks

If a user-defined window has been created, its size can be changed; it doesn't have to be active or visible.

See Also

ACTIVATE WINDOW | DEFINE WINDOW | ZOOM WINDOW


SKIP Command

Moves the record pointer forward or backward in a table.

SKIP   [nRecords]   [IN nWorkArea | cTableAlias]

Parameters

nRecords
Specifies the number of records to move the record pointer.

Issuing SKIP without nRecords advances the record pointer to the next record. The record pointer moves toward the end of the file nRecords records if nRecords evaluates to a positive number. The record pointer moves toward the beginning of the file nRecords records if nRecords evaluates to a negative number.

If the record pointer is positioned on the last record of a table and SKIP with no arguments is executed, RECNO( ) returns a value 1 greater than the number of records in the table and EOF( ) returns true (.T.). If the record pointer is positioned on the first record of a table and SKIP –1 is executed, RECNO( ) returns 1 and BOF( ) returns true (.T.).

IN nWorkArea | cTableAlias
Moves the record pointer in a table in a specific work area. nWorkArea specifies the work area number and cTableAlias specifies a table or work area alias.

Remarks

If the table has a master controlling index tag or index file, SKIP moves the record pointer to the record determined by the index sequence.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens Customer table
CLEAR

SKIP 4 IN 'customer'
? RECNO('customer')  && Displays 5
GO BOTTOM
SKIP -5
? RECNO( )

See Also

GO | GOTO | SET SKIP | CLEAR Commands


SORT Command

Sorts records in the currently selected table and outputs the sorted records to a new table.

SORT TO TableName ON FieldName1 [/A | /D] [/C]
   [, FieldName2 [/A | /D] [/C] ...]   [ASCENDING | DESCENDING]
   [Scope] [FOR lExpression1] [WHILE lExpression2]
   [FIELDS FieldNameList   | FIELDS LIKE Skeleton
   | FIELDS EXCEPT Skeleton]   [NOOPTIMIZE]

Parameters

TableName
Specifies the name of the new table containing the sorted records. Visual FoxPro assumes a .dbf file name extension for tables. A .dbf extension is automatically assigned if the file name you include doesn't have an extension.
ON FieldName1
Specifies the field in the currently selected table on which the sort is based. The contents and data type of the field determine the order of the records in the new table. By default, the sort is done in ascending order. You can't sort on memo or general fields.

The following example sorts a table on the cust_id field. The customer table is opened and sorted, creating a new table named temp. The records in temp are ordered by the cust_id field.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens Customer table
CLEAR
LIST FIELDS company, cust_id NEXT 3
SORT TO temp ON cust_id
USE temp
LIST FIELDS company, cust_id NEXT 3
WAIT WINDOW 'Now sorted on CUST_ID' NOWAIT

You can include additional field names (FieldName2, FieldName3) to further order the new table. The first field FieldName1 is the primary sort field, the second field FieldName2 is the secondary sort field, and so on.

[/A | /D] [/C]
For each field you include in the sort, you can specify an ascending or descending sort order. /A specifies an ascending order for the field. /D specifies a descending order. /A or /D can be included with any type of field.

By default, the field sort order for character fields is case sensitive. If you include the /C option after the name of a character field, case is ignored. You can combine the /C option with the /A or /D option. For example, /AC or /DC.

In the following example, a new table named clients is created. The orders table is sorted on the order_date field in ascending order and the freight field in descending order.

USE orders
SORT TO clients ON order_date/A,freight/D
ASCENDING
Specifies an ascending order for all fields not followed by /D.
DESCENDING
Specifies a descending order for all fields not followed by /A.

If you omit either ASCENDING or DESCENDING, the sort order is ascending by default.

Scope
Specifies a range of records to sort. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

The default scope for SORT is ALL records.

FOR lExpression1
Specifies that only the records in the current table for which the logical condition lExpression1 evaluates to true (.T.) are included in the sort. Including FOR lets you conditionally sort records, filtering out undesired records.

Rushmore Query Optimization optimizes a SORT ... FOR command if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

A discussion of expressions that Rushmore can optimize appears in Optimizing Applications.

WHILE lExpression2
Specifies a condition whereby records from the current table are included in the sort for as long as the logical expression lExpression2 evaluates to true (.T.).
FIELDS FieldNameList
Specifies fields from the original table to include in the new table that SORT creates. If you omit the FIELDS clause, all fields from the original table are included in the new table.
FIELDS LIKE Skeleton
Specifies that fields from the original table that match the field skeleton Skeleton are included in the new table that SORT creates.
FIELDS EXCEPT Skeleton
Specifies that all fields except those that match the field skeleton Skeleton are included in the new table that SORT creates.

The field skeleton Skeleton supports wildcards. For example, to specify that all fields that begin with the letters A and P are included in the new table, use the following:

SORT TO mytable ON myfield FIELDS LIKE A*,P*

The LIKE clause can be combined with the EXCEPT clause:

SORT TO mytable ON myfield FIELDS LIKE A*,P* EXCEPT PARTNO*
NOOPTIMIZE
Disables Rushmore optimization of SORT.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

One or more specified fields in the current table determine the order in which the records appear in the new table.

Caution Be sure you have enough disk space for the new table and the temporary work files created during the sort. The disk space needed to perform a sort can be as much as three times the size of the source table. The amount of available disk space can be determined with DISKSPACE( ) and SYS(2020). If you run out of disk space during a sort, Visual FoxPro displays an error message, and the temporary work files are deleted.

Character-type fields that contain numbers and spaces might not sort in the order you expect. Numeric fields fill from right to left, with empty spaces to the left. In contrast, character fields fill from left to right, with empty spaces to the right.

For example, if two records in a table contain a character field with 1724 in one record and 18 in the other, and the table is sorted on this field in ascending order, the record containing 1724 appears before the record containing 18. This is because Visual FoxPro reads each character in the character fields from left to right, and because 17 (in 1724) is less than 18 (in 18), it puts 1724 first. To avoid this problem, always precede lower numbers with leading zeros (0018) or make the field numeric.

See Also

COPY FILE | DISKSPACE( ) | INDEX | SYS(2020) - Default Disk Size


STORE Command

Stores data to a variable, to an array, or to an array element.

STORE eExpression TO VarNameList | ArrayNameList-or-
VarName | ArrayName = eExpression

Parameters

eExpression
Specifies an expression whose value is stored to the variable, array, or array element. If the variable doesn't exist, it is created and initialized to eExpression. An array must be previously defined with DIMENSION. STORE replaces the value in an existing variable, array, or array element with the new value.
VarNameList
Specifies a list of variables or array elements to which eExpression is stored. Separate the names or array elements with commas.
ArrayNameList
Specifies a list of names of existing arrays to which eExpression is stored. Separate array names with commas.

STORE initializes every element in the arrays to the specified value if SET COMPATIBLE is OFF. STORE stores the specified value to memory variables of the specified names if SET COMPATIBLE is ON, overwriting any existing arrays that have those names.

Remarks

An alternative to STORE is the equal sign (=) assignment operator. The variable, array, or array element must be on the left side of the equal sign and its value on the right side.

Dates can be stored directly to variables, arrays, or array elements by using braces:

STORE {^1998-12-25} TO gdXMas

The maximum number of variables or arrays you can create is listed in the System Capacities topic. The limit can be increased or decreased in your Visual FoxPro configuration file. For more information on configuring Visual FoxPro, refer to Configuring Visual FoxPro.

Example

STORE DATE( ) TO gdDate
STORE 50 TO gnNumeric
STORE 'Hello' TO gcCharacter
STORE .T. TO glLogical
STORE $19.99 TO gyCurrency

DIMENSION gaMyArray(2,2)
SET COMPATIBLE OFF
STORE 2 TO gaMyArray

CLEAR
DISPLAY MEMORY LIKE g*

See Also

DIMENSION | SET COMPATIBLE | System Capacities | Configuring Visual FoxPro


SUM Command

Totals all or specified numeric fields in the currently selected table.

SUM [eExpressionList]   [Scope] [FOR lExpression1] [WHILE lExpression2]
   [TO MemVarNameList | TO ARRAY ArrayName]   [NOOPTIMIZE]

Parameters

eExpressionList
Specifies one or more fields or field expressions to total. If you omit the field expression list, all numeric fields are totaled.
Scope
Specifies a range of records to include in the total. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST. For more information on scope clauses, see Scope Clauses.

The default scope for SUM is ALL records.

FOR lExpression1
Specifies that only the records for which the logical condition lExpression1 evaluates to true (.T.) are included in the total. Including FOR makes it possible for you to conditionally total records, filtering out undesired records.

Rushmore Query Optimization optimizes a SUM ... FOR command if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information on Rushmore optimization, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records from the current table are included in the total for as long as the logical expression lExpression2 evaluates to true (.T.).
TO MemVarNameList
Stores each total to a variable. If you specify a variable in MemVarNameList that doesn't exist, Visual FoxPro automatically creates it. Separate the variable names in the list with commas.
TO ARRAY ArrayName
Stores totals to a variable array. If the array you specify in SUM doesn't exist, Visual FoxPro automatically creates it. If the array exists and is too small to contain all the totals, the size of the array is automatically increased to accommodate the totals.
NOOPTIMIZE
Disables Rushmore optimization of SUM.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Example

The following example displays the totals of the in_stock and on_order fields in the products table, along with a sum of the two totals.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE products  && Opens Products table

SUM in_stock, on_order, in_stock+on_order ;
   TO gnInStock, gnOnOrder, gnUnits

CLEAR
?
? 'Total in stock : ', gnInStock  && Displays 3119.00
? 'Total on order:  ', gnOnOrder  && Displays 780.00
? 'Total # units :  ', gnUnits  && Displays 3899.00

See Also

Commands | AVERAGE | CALCULATE | COUNT | SET OPTIMIZE | Using Rushmore Query Optimization to Speed Data Access


SUSPEND Command

Pauses program execution and returns to interactive Visual FoxPro.

SUSPEND

Remarks

While a program is paused, you can execute intervening commands, check variable values, open the Trace and Debug windows, and so on.

All variables created while the program is paused are PRIVATE.

Use RESUME to restart execution of a suspended program. Program execution continues with the line following the line containing SUSPEND.

See Also

CANCEL | RESUME | PRIVATE


TEXT ... ENDTEXT Command

Sends lines of text specified by TextLines to the current output device. Visual FoxPro sends lines of text to the current output device until it encounters an ENDTEXT statement or until the program ends.

The current output device can include the main Visual FoxPro window, a user-defined window, a printer, a text file, or a low-level file.

TEXT [TO VarName [ADDITIVE] [TEXTMERGE] [NOSHOW] [PRETEXT eExpression]]
   TextLines
ENDTEXT

Parameters

TextLines
Specifies text to send to the current output device. TextLines can consist of text, memory variables, array elements, expressions, functions or any combination of these.
Note Visual FoxPro evaluates expressions, functions, memory variables, and array elements specified with TextLines only if you set SET TEXTMERGE to ON and enclose them with the delimiters specified by SET TEXTMERGE DELIMITERS. If SET TEXTMERGE is OFF, Visual FoxPro outputs expressions, functions, memory variables, and array elements as string literals along with their delimiters.

For example, Visual FoxPro evaluates and outputs the current date when you specify the DATE( ) function as TextLines only if SET TEXTMERGE is ON, and TextLines contain the function and the appropriate delimiters, such as <<DATE( )>>. Otherwise, if SET TEXTMERGE is OFF, Visual FoxPro outputs <<DATE( )>> as a string literal.

If you place comments within TEXT...ENDTEXT or after the single backslash character (\) or double backslash characters (\\), Visual FoxPro outputs the comments.

TO VarName
Specifies the memory variable name to use for passing the contents of the TEXT...ENDTEXT. This variable can already exist.

If the variable has not yet been declared, Visual FoxPro automatically creates it as a private variable. The TO clause operates regardless of how SET TEXTMERGE is set. If SET TEXTMERGE is set to a file, and the TO statement is included, Visual FoxPro outputs both the file and variable.

ADDITIVE
Determines whether the contents of the TO variable are overwritten or added to existing contents.
Note If the contents of TO VarName is not a string, Visual FoxPro always overwrites the contents in VarName.
TEXTMERGE
Enables evaluation of contents surrounded by delimiters without setting SET TEXTMERGE to ON.
NOSHOW
Disables display of the text merge to the screen.
PRETEXT eExpression
Specifies a character string to insert before each line of the text merge contents between TEXT...ENDTEXT or a numeric expression.

The following table describes behaviors of the PRETEXT clause depending on the expression specified by eExpression.

eExpression PRETEXT behavior
Character expression Insert the expression before each line of the text merge contents appearing between the TEXT...ENDTEXT statement. When using PRETEXT with TEXT...ENDTEXT, eExpression is limited to a maximum length of 255 characters.

eExpression overrides the contents of the _PRETEXT system variable. When eExpression contains an expression that needs to be evaluated, for example, a user-defined function (UDF), Visual FoxPro evaluates it only once when the TEXT command first appears.
Numeric expression Specify additive flag values to determine behavior for the text merge contents appearing between the TEXT...ENDTEXT statement.

For example, a value of 7 specifies that Visual FoxPro eliminate all white space including spaces, tabs, and carriage returns. A value falling outside of the range of 0-7 produces an error.

Note Specifying a value of zero does not eliminate white space.

When eExpression is a numeric expression, you can use the _PRETEXT system variable to insert additional text after Visual FoxPro eliminates white space.

The following table lists numeric additive flags that you can use in eExpression to specify additional behavior.

Value (Additive) | Description
1 | Eliminate spaces before each line.
2 | Eliminate tabs before each line.
4 | Eliminate carriage returns, for example, blank lines, before each line.
Note Unlike the _PRETEXT system variable, the PRETEXT clause does not have global scope and applies only to the TEXT...ENDTEXT statement in which it appears.

Characters removed using the PRETEXT clause apply only to text within the TEXT...ENDTEXT statement and not to evaluated text merged from cExpression. In the following example, the spaces in the memory variable, myvar, are not removed when merged with the text in TEXT...ENDTEXT:

myvar = "   AAA"
TEXT TO x NOSHOW ADDITIVE TEXTMERGE PRETEXT 7
Start Line
<<myvar>>
      BBB
   CCC
ENDTEXT

Remarks

By default, TEXT ... ENDTEXT sends output to the main Visual FoxPro window or the active window. To suppress output to the main Visual FoxPro window or the active window, issue SET CONSOLE OFF. To send output to a printer or a text file, use SET PRINTER. To send output from TEXT ... ENDTEXT to a low-level file that you created or opened using FCREATE( ) or FOPEN( ), store the file handle returned by FCREATE( ) or FOPEN( ) to the _TEXT system variable, which you can use to direct output to the corresponding low-level file.

Note The text merge process usually includes any white space that might appear before each line in a TEXT...ENDTEXT statement. However, the inclusion of white space might cause the text merge to fail, for example, when XML is used in a Web browser. You must remove such white space to avoid incorrectly formatted XML.

Example

Example 1

The following example demonstrates creating a low-level file called myNamesFile.txt and storing its file handle in the _TEXT system variable. The program exits if the myNamesFile.txt file cannot be created.

Visual FoxPro opens the customer table and outputs the names of the first ten contacts to myNamesFile.txt. Visual FoxPro outputs the text and results of the functions to the text file. The example uses MODIFY FILE to open myNamesFile.txt.

CLEAR
CLOSE DATABASES
SET TALK OFF
SET TEXTMERGE ON
STORE FCREATE('myNamesFile.txt') TO _TEXT
IF _TEXT = -1
   WAIT WINDOW 'Cannot create an output file. Press a key to exit.'
   CANCEL
ENDIF

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer

TEXT
         CONTACT NAMES
   <<DATE( )>>    <<TIME( )>>
ENDTEXT
WAIT WINDOW 'Press a key to generate the first ten names.'
SCAN NEXT 10
   TEXT
      <<contact>>
   ENDTEXT
ENDSCAN
CLOSE ALL
MODIFY FILE myNamesFile.txt
ERASE myNamesFile.txt

Example 2

The following example shows a custom procedure that uses TEXT...ENDTEXT to store an XML DataSet to a variable. In the example, all spaces, tabs, and carriage returns are eliminated.

PROCEDURE myProcedure
   DO CASE
   CASE nValue = 1
      TEXT TO myVar NOSHOW TEXT PRETEXT 7
         <?xml version="1.0" encoding="utf-8"?>
         <DataSet xmlns="http://tempuri.org">
         <<ALLTRIM(STRCONV(leRetVal.item(0).xml,9))>>
         </DataSet>
      ENDTEXT
   OTHERWISE
   ENDCASE
ENDPROC

See Also

FOPEN( ) | _PRETEXT | SET TEXTMERGE | SET TEXTMERGE DELIMITERS | _TEXT


TOTAL Command

Computes totals for numeric fields in the currently selected table.

TOTAL TO TableName ON FieldName   [FIELDS FieldNameList]   [Scope]
   [FOR lExpression1]   [WHILE lExpression2]   [NOOPTIMIZE]

Parameters

TableName
Specifies the name of the table that will contain the totals. If the specified table does not exist, Visual FoxPro creates it. If the table exists and SET SAFETY is ON, Visual FoxPro asks if you would like to overwrite the existing table. If SET SAFETY is OFF, you are not prompted, and the output table is overwritten.
FieldName
Specifies the field on which the totals are grouped. The table must be sorted on this field, or an open index or index tag must have this field as its key expression.
FIELDS FieldNameList
Specifies the fields to be totaled. Separate the field names in the list with commas. If you omit the FIELDS clause, all numeric fields are totaled by default.
Scope
Specifies a range of records to total. The default scope for TOTAL is ALL records. The scope clauses are: ALL, NEXT nRecords, RECORD nRecordNumber, and REST.

For more information on scope clauses, see Scope Clauses.

FOR lExpression1
Specifies a condition whereby only the records that satisfy the logical condition lExpression1 are included in the totals.

Rushmore Query Optimization optimizes a query created with TOTAL ... FOR if lExpression1 is an optimizable expression. For best performance, use an optimizable expression in the FOR clause.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

WHILE lExpression2
Specifies a condition whereby records from the current table are included in the totals for as long as the logical expression lExpression2 evaluates to true (.T.).
NOOPTIMIZE
Disables Rushmore optimization of TOTAL.

For more information, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Remarks

The table in the currently selected work area must be sorted or indexed. A separate total is calculated for each set of records with a common field value or unique index key value. The results are placed into records in a second table. One record is created in the second table for each common field value or unique index key value.

Numeric overflow can occur if the numeric fields in the second table are not wide enough to contain the totals. Visual FoxPro conserves the most significant portions of the totals when numeric overflow occurs. When a field is too small to accept a total:

  • Decimal places are truncated, and the remaining decimal portion of the total is rounded.
  • If the total still does not fit, scientific notation is used if the total field contains seven or more digits.
  • Finally, asterisks replace the field contents.

See Also

AVERAGE | CALCULATE | INDEX | SORT | SUM


TRY...CATCH...FINALLY Command

Provides a structure to handle errors and exceptions that can occur while running a block of code. For general information about structured error handling, see Structured Error Handling.

TRY
     [ tryCommands ]
[ CATCH [ TO VarName ] [ WHEN lExpression ]
     [ catchCommands ] ]
[ THROW [ eUserExpression ] ]
[ EXIT ]
[ FINALLY
     [ finallyCommands ] ]
ENDTRY

Parameters

TRY
Indicates the beginning of the TRY...CATCH...FINALLY structure.
tryCommands
Specifies statements where an error might occur.

If an error occurs, Visual FoxPro stores a reference to an Exception object specified by the VarName memory variable in the TO VarName clause. Program execution then proceeds directly to the CATCH statements. If no error occurs, program execution proceeds to the FINALLY statements.

CATCH
Indicates the beginning of a CATCH block, which handles the appropriate error. You can specify a CATCH statement without arguments, which evaluates to CATCH WHEN .T. (True).

A CATCH statement is called only when an error occurs in the TRY block for that method, and the code in the method causes the exception. If another method called from within the TRY block causes an error, the Error event for that method handles the error. This behavior occurs because the other method could have been either called directly or from a different method that does not contain a TRY...CATCH...FINALLY structure. The following example illustrates this behavior:

x=NEWOBJECT("myClass")
x.myMethod()

DEFINE CLASS myClass AS Session OLEPUBLIC
   PROCEDURE myMethod
      myMethod3()         && Error event handles errors.
      TRY
         THIS.myMethod2()
         myMethod3()      && CATCH handles this error.
      CATCH TO oErr
         ? "Catch:",oErr.ErrorNo
      FINALLY
      ENDTRY
   ENDPROC

   PROCEDURE myMethod2
      x=y   && The y variable does not exist. Error event
            && handles this error.
   ENDPROC

   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:",nError
   ENDPROC
ENDDEFINE

PROCEDURE myMethod3
   x = y
ENDPROC
TO VarName
Specifies an optional memory variable that stores a reference to an Exception object, which is automatically created if an error occurs in the TRY block. VarName can only be a simple memory variable, not an object property reference.

You can explicitly set VarName to any value in the TRY...CATCH...FINALLY structure. The value does not change as long as another CATCH statement does not run, which resets VarName to NULL.

VarName can have local, public, or private scope, which depends on how the variable was previously declared. If VarName has not been previously declared, it has private scope. The Exception object created has the same scope as VarName. When VarName goes out of scope, is released, or is reset, the Exception object is also released.

When a CATCH TO VarName clause executes, Visual FoxPro always sets the VarName to a new Exception object regardless of its previous setting, though VarName retains its scope. Therefore, the contents of VarName are always overwritten regardless of what it previously referenced.

If a WHEN clause exists, and it evaluates to False (.F.), Visual FoxPro releases the Exception object and resets the VarName to NULL. You can test whether VarName is set to a type or to NULL by using the VARTYPE() function.

WHEN lExpression
Specifies an optional expression that is evaluated when the program encounters the CATCH statement. The expression must evaluate to True (.T.) for the corresponding catchCommands to run.

The lExpression parameter can contain a reference to the VarName Exception object so that you can query the resulting error and handle it accordingly.

catchCommands
Specifies statements to run when the program encounters the corresponding CATCH statement.
THROW [ eUserExpression ]
Creates a new Exception object to be caught by a CATCH statement. The eUserExpression parameter specifies an expression of any type and sets the UserValue property for the Exception object. Usually, you use a THROW clause in a CATCH block to escalate an error or exception to a higher-level error handler. You can pass an object of any type because Exception UserValue stores only the object reference.

When you use the THROW clause with eUserExpression, Visual FoxPro sets the Exception object's ErrorNo property value to 2071, which corresponds to the error, User Thrown Error (Error 2071). If you omit eUserExpression, Visual FoxPro escalates the original Exception object, if it exists. If the Exception object does not exist, Visual FoxPro throws a new Exception object with an ErrorNo property value of 2071.

Note You should pass a value for eUserExpression, which sets the UserValue property for the Exception object, because it allows you to chain multiple Exception objects. For more information about chaining Exception objects, see the Example section.

If you do not include eUserExpression, and the THROW clause escalates the Exception object to an outer TRY...CATCH block, the same Exception object is caught by the outer TRY...CATCH block. Values returned by the ERROR(), MESSAGE( ), and AERROR( ) functions might not always be reliable when used in a structured exception handler, so, instead, you should use the Exception object.

You can call THROW from any code block in a TRY...CATCH...FINALLY structure. However, you can use THROW anywhere in code where an error handler exists to catch the exception. You cannot call THROW from the Command window.

Caution Calling the THROW command outside the TRY...CATCH...FINALLY structure and without an appropriate error handler causes your program to quit.

If an outer TRY...CATCH statement is in effect when THROW is called from a CATCH or FINALLY block, Visual FoxPro assigns VarName in the CATCH TO clause to the object reference for the Exception object generated by the thrown exception. If no outer TRY...CATCH statement is in effect, Visual FoxPro escalates the exception to an ON ERROR or Error event, if one exists; otherwise, Visual FoxPro calls its system error handler.

Note Runtime applications should properly wrap a THROW statement with an outer TRY...CATCH...FINALLY structure.

If you wish to rethrow the original exception that was caught by the CATCH TO VarName clause, you can call THROW VarName to rethrow the exception.

Note Rethrowing the original exception produces another new Exception object, at the outer CATCH statement, that has a UserValue property containing an object reference to the original exception.

Visual FoxPro disregards any THROW statements appearing in a CATCH WHEN eExpression clause.

If THROW encounters an error when evaluating an expression, Visual FoxPro escalates the error in the usual way.

EXIT
Include in a TRY, CATCH, or FINALLY block to immediately break out of a code block.

If EXIT appears in the TRY or CATCH block, the program resumes execution at the FINALLY statement, if one exists. If EXIT appears in the FINALLY block or if FINALLY does not exist, the program resumes execution immediately following the ENDTRY statement.

FINALLY
Indicates the beginning of the FINALLY block, which you use to clean up any resources allocated by the TRY block and always runs except when the CANCEL and QUIT commands are used.

For more information about commands you can use in the TRY...CATCH...FINALLY structure, see Structured Error Handling.

finallyCommands
Specifies statements to run in the FINALLY block after either finding no errors in the TRY block or running statements in a CATCH block.
ENDTRY
Indicates the end of the TRY...CATCH...FINALLY structure. Each TRY...CATCH...FINALLY structure must end with an ENDTRY keyword. As with other Visual FoxPro control statements, you can add comments prefaced by double ampersand (&&) characters after this ENDTRY.

If you do not include the ENDTRY statement at the end of the TRY...CATCH...FINALLY structure, Visual FoxPro generates an error when you compile your code. Although you can still execute code with compile errors, you should not do so in this scenario because it causes Visual FoxPro to stop responding.

Remarks

Like other error handling in Visual FoxPro, exceptions that occur in TRY...CATCH...FINALLY exception handlers set the SET CONSOLE command to ON. For more information, see SET CONSOLE Command.

You cannot explicitly transfer program execution to a CATCH or FINALLY code block.

Visual FoxPro determines scope for variables on a procedural, not block, basis. That is, variables declared in a TRY block are visible from a FINALLY block within the same TRY...CATCH...FINALLY structure. However, in a nested structure, variables that are declared in a TRY, CATCH, or FINALLY block have local scope.

You should not initialize variables or set up critical code inside the TRY block because the code is not guaranteed to run. If an error occurs at a particular line of code in the TRY block, all subsequent lines in the TRY block do not run.

Any errors that occur in an object's Error event must be handled by the object and are not escalated to an ON ERROR routine or TRY...CATCH...FINALLY handler. However, you can use a TRY...CATCH...FINALLY structure in the Error event to catch errors from an Error event. For more information, see Error Event.

Using the COMRETURNERROR() function in a CATCH block ends all further processing and returns control of the program directly to the Component Object Model (COM) client. Therefore, if you have a FINALLY block, it does not run. For more information, see COMRETURNERROR( ) Function.

Avoid using the SET TEXTMERGE TO MEMVAR command within a TRY...CATCH...FINALLY structure because the memory variable will be lost if an error occurs in the statement.

You can use the SYS(2410) - Error Handler function in your TRY...CATCH...FINALLY code to determine a course of action, for example, by using a DO CASE structure, depending on the type of handler that handles the exception. For more information, see SYS(2410) - Error Handler.

You can use TRY...CATCH...FINALLY to handle errors that occur in menu and timer events and with commands such as ON KEY LABEL if the structure is properly wrapped. The following example illustrates how the READ EVENTS command retains control of the program within the TRY...CATCH...FINALLY structure so that you trap menu events. Error trapping is controlled by the position of TRY...CATCH...FINALLY on the call stack.

TRY
   DO myMenu.mpr
   DO FORM myForm
   myForm.AddObject("tm1","mytimer")
   READ EVENTS
CATCH TO oException
   IF oException.ErrorNo = 1
ENDIF
FINALLY
   CLEAR EVENTS
ENDTRY

For more information, see READ EVENTS Command and ON KEY LABEL Command.

Visual FoxPro supports Set Next Statement debugging functionality only within a single code block. For example, when executing code in a TRY block, you can use Set Next Statement only to another line within the TRY block. You cannot jump to another line of code in a CATCH or FINALLY block. For more information, see Debugger Keyboard Shortcuts and Menus.

Visual FoxPro generates the appropriate messages under the following conditions:

  • A mismatch or error occurs with the TRY...CATCH...FINALLY structure.
  • An unhandled exception occurs.
  • A command that is not permitted for a specific block appears in a TRY, CATCH, or FINALLY block. For more information, see Structured Error Handling.
  • A user-thrown error occurs.

Example

The following example illustrates how to nest TRY...CATCH statements, use the THROW clause, and handle Exception objects.

LOCAL x AS Integer, y AS Integer, result AS Integer
LOCAL oErr AS Exception, oErr1 AS Exception
TRY
   x = 1
   TRY
      USE nothing
      GO TOP
      y = nothing.col1
   CATCH TO oErr
      oErr.UserValue = "Nested CATCH message: Unable to handle"
      ?[: Nested Catch! (Unhandled: Throw oErr Object Up) ]
      ?[  Inner Exception Object: ]
      ?[  Error: ] + STR(oErr.ErrorNo)
      ?[  LineNo: ] + STR(oErr.LineNo)
      ?[  Message: ] + oErr.Message
      ?[  Procedure: ] + oErr.Procedure
      ?[  Details: ] + oErr.Details
      ?[  StackLevel: ] + STR(oErr.StackLevel)
      ?[  LineContents: ] + oErr.LineContents
      ?[  UserValue: ] + oErr.UserValue
      THROW oErr
   FINALLY
      ?[: Nested FINALLY executed ]
      IF USED("nothing")
         USE IN nothing
      ENDIF
   ENDTRY
   result = x-y
CATCH TO oErr1
   ?[: Outer CATCH! ]
      ?[  Outer Exception Object: ]
      ?[  Error: ] + STR(oErr1.ErrorNo)
      ?[  LineNo: ] + STR(oErr1.LineNo)
      ?[  Message: ] + oErr1.Message
      ?[  Procedure: ] + oErr1.Procedure
      ?[  Details: ] + oErr1.Details
      ?[  StackLevel: ] + STR(oErr1.StackLevel)
      ?[  LineContents: ] + oErr1.LineContents
      ?[  ->UserValue becomes inner exception THROWn from nested TRY/CATCH ]
      ?[     Error: ] + STR(oErr1.UserValue.ErrorNo)
      ?[     Message: ] + oErr1.UserValue.Message
      ?[     Procedure: ] + oErr1.UserValue.Procedure
      ?[     Details: ] + oErr1.UserValue.Details
      ?[     StackLevel: ] + STR(oErr1.UserValue.StackLevel)
      ?[     LineContents: ] + oErr1.UserValue.LineContents
      ?[     UserValue: ] + oErr1.UserValue.UserValue
   result = 0
FINALLY
   ?[: FINALLY statement executed ]
ENDTRY
RETURN result

The following example shows how you might want to chain Exception objects:

TRY
   TRY
      x=y      && The y variable does not exist and causes an error.
   CATCH TO oException2
      THROW CREATEOBJECT("myException")
   ENDTRY
CATCH TO oException1
ENDTRY

? 2, oException2.ErrorNo, oException2.UserValue
? 1, oException1.ErrorNo, oException1.UserValue.UserValue

DEFINE CLASS myException AS Exception
UserValue = "My custom error handler"
PROCEDURE Init
   STRTOFILE("An error occurred at: " + TRANSFORM(DATETIME());
 + CHR(13),"c:\errs.log",.T.)
ENDPROC
ENDDEFINE

See Also

Commands | Exception Class | UserValue Property | VARTYPE( ) Function | ErrorNo Property | ERROR( ) Function | MESSAGE( ) Function | AERROR( ) Function | SYS(2018) - Error Message Parameter


TYPE Command

Displays the contents of a file.

TYPE FileName1   [AUTO]   [WRAP]
   [TO PRINTER [PROMPT] | TO FILE FileName2]   [NUMBER]

Parameters

FileName1
Specifies the name of the file to display. The name must include a file extension.
AUTO
Turns automatic indentation on. When you also include WRAP, TYPE automatically indents wrapped text in each paragraph by the same amount it indents the first line of the paragraph. For example:
  • Wrapped lines are aligned with the tab when a paragraph begins with a tab.
  • Wrapped lines are aligned with the tab when a paragraph begins with a number (or other text) followed by a tab and text.
  • Wrapped lines are indented by the same amount as the first line when the first line of a paragraph is indented with spaces.
WRAP
Enables word wrap so that a word that is too long to fit at the end of a line is automatically moved to the next line.
TO PRINTER [PROMPT]
Directs output to the printer.

You can include the optional PROMPT clause to display a print dialog before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName2
Directs output to the file specified with FileName2.
NUMBER
Places line numbers at the beginning of each line in the output.

Remarks

TYPE displays the contents of files. This display can be directed to the main Visual FoxPro window, the active user-defined window, a printer, or another file.

When SET HEADINGS is ON, Visual FoxPro inserts a form feed, the path and name of the file, and the date at the beginning of output produced with TYPE. If SET HEADINGS is OFF, this information isn't included.

In FoxPro for MS-DOS, if a printer driver setup is loaded and you direct output from TYPE to a file or a printer, TYPE displays the file contents using the settings from the printer driver setup.

See Also

SET HEADINGS | WordWrap | PROMPT( ) | Type Property


UNLOCK Command

Releases a record lock, multiple record locks, or a file lock from a table, or releases all record and file locks from all open tables.

UNLOCK    [RECORD nRecordNumber]   [IN nWorkArea | cTableAlias]   [ALL]

Parameters

RECORD nRecordNumber
Releases the record lock on record number nRecordNumber. You can specify 0 for nRecordNumber to unlock a table header locked with LOCK(0) or RLOCK(0).

Issuing UNLOCK RECORD nRecordNumber for a record in a table with a file lock releases the file lock.

IN nWorkArea | cTableAlias
Releases a record lock (or locks) or a file lock from a table in a specific work area. nWorkArea specifies a work area number and cTableAlias specifies a table alias. If you don't include nWorkArea or cTableAlias, UNLOCK releases a record lock (or locks) or a file lock from the table in the currently selected work area.
ALL
Releases all record and file locks in all work areas.

For more information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Remarks

Record and file locks can be removed from a table only by the user who issued the locks. UNLOCK cannot unlock a table opened for exclusive use.

A record lock (or locks) or a file lock is released from the table in the current work area if you issue UNLOCK without any additional arguments.

If relations are established between tables, releasing a record lock (or locks) or a file lock from one of the tables doesn't release locks from the related records or files. You must explicitly release the record or file locks in each of the related files. You can release all locks on any related tables by issuing UNLOCK ALL (this also releases locks in unrelated files).

Example

CLOSE DATABASES
SET REPROCESS TO 3 AUTOMATIC
STORE '1,2,3,4' TO gcRecList     && Lock records 1 through 4
gcOldExc = SET('EXCLUSIVE')     && Save the EXCLUSIVE setting
SET EXCLUSIVE OFF  && Allow sharing of tables

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
SELECT 0
USE employee  && Opens Employee table

? LOCK('1,2,3,4', 'customer')  && Lock the first 4 records in customer
? RLOCK(gcRecList, 'employee') && Lock the first 4 records in employee

UNLOCK IN customer
UNLOCK IN employee
SET EXCLUSIVE &gcOldExc  && Restore original EXCLUSIVE setting

See Also

FLOCK( ) | LOCK( ) | RLOCK( ) | Programming for Shared Access


UPDATE - SQL Command

Updates records in a table with new values.

UPDATE [DatabaseName1!]TableName1 SET Column_Name1 = eExpression1
   [, Column_Name2 = eExpression2 ...]
   WHERE FilterCondition1 [AND | OR FilterCondition2 ...]

Parameters

[DatabaseName1!]TableName1
Specifies the table in which records are updated with new values.

DatabaseName1! specifies the name of a non-current database containing the table. You must include the name of the database containing the table if the database is not the current one. Include the exclamation point (!) delimiter after the database name and before the table name.

SET Column_Name1 = eExpression1 [, Column_Name2 = eExpression2
Specifies the columns that are updated and their new values. If you omit the WHERE clause, every row in the column is updated with the same value.
WHERE FilterCondition1 [AND | OR FilterCondition2 ...]]
Specifies the records that are updated with new values.

FilterCondition specifies the criteria that records must meet to be updated with new values. You can include as many filter conditions as you like, connecting them with the AND or OR operator. You can also use the NOT operator to reverse the value of a logical expression, or use EMPTY( ) to check for an empty field.

Remarks

UPDATE - SQL can only update records in a single table. Note that subqueries are supported in UPDATE – SQL.

You can determine the number of records updated by checking the value of the _TALLY system variable immediately after the UPDATE - SQL command.

Unlike REPLACE, UPDATE - SQL uses record locking when updating multiple records in a table opened for shared access. This reduces record contention in multiuser situations, but may reduce performance. For maximum performance, open the table for exclusive use or use FLOCK( ) to lock the table.

Example

The following example opens the customer table in the testdata database. UPDATE -SQL is used to set all of the values in the maxordamt field to 25.

CLOSE DATABASES

OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table

* Set and display amounts for customers
UPDATE customer SET maxordamt = 25
BROWSE FIELDS company,maxordamt

See Also

DELETE - SQL | GATHER | INSERT - SQL | REPLACE | SCATTER | _TALLY


USE Command

Opens a table and its associated index files, or a SQL view.

USE [[DatabaseName!]Table | SQLViewName | ?]
   [IN nWorkArea | cTableAlias]   [ONLINE]   [ADMIN]   [AGAIN]
   [NOREQUERY [nDataSessionNumber]]   [NODATA]   [INDEX IndexFileList | ?
   [ORDER [nIndexNumber | IDXFileName   | [TAG] TagName [OF CDXFileName]
      [ASCENDING | DESCENDING]]]]   [ALIAS cTableAlias]   [EXCLUSIVE]
   [SHARED]   [NOUPDATE]   [CONNSTRING cConnectionString | (m.nStatementHandle) ]

Parameters

[DatabaseName!]TableName
Specifies the name of the table to open. Because spaces are significant in file names in Microsoft Windows 98 and later, avoid using extraneous spaces in TableName. If a table name contains spaces, enclose the table name in quotation marks (" " or ' ').

To open a table not in the current database, qualify the table name with the database name, using an exclamation point (!) to separate the database and tables names. If you don't qualify a table with a database name, Microsoft Visual FoxPro can open tables only in the current database. If the database name or table name or both contains spaces, enclose the database and table name in quotation marks (" " or ' ').

Note Visual FoxPro will not recognize a path name properly if a disk or directory name actually contains an exclamation point (!).
SQLViewName
Specifies the name of a SQL view in the current database to open. A SQL view is created with CREATE SQL VIEW. SQLViewName can also be the name of an offline view created with CREATEOFFLINE( ).
?
Displays the Use dialog, from which you can choose a table to open.
IN nWorkArea
Specifies the work area in which the table is opened. You can close a table in a specific work area by issuing USE with the IN clause and the work area number.

The IN clause supports 0 as a work area. Including 0 opens a table in the lowest available work area. For example, if tables are open in work areas 1 through 10, the following command opens the customer table in work area 11:

USE customer IN 0
IN cTableAlias
Specifies that the table is opened in the work area of a table that is currently open. The alias of the open table is specified with cTableAlias.

If you omit nWorkArea and cTableAlias, the table is opened in the currently selected work area.

ONLINE
Opens an offline view created with CREATEOFFLINE( ). You can specify the name of the offline view in SQLViewName. You can use TABLEUPDATE( ) to update data on the server.

The offline view must be opened exclusively. Before opening the offline view with USE, include the EXCLUSIVE clause in USE or SET EXCLUSIVE to ON.

You cannot open or close an offline view in ONLINE mode from within a transaction.

ADMIN
Opens an offline view created with CREATEOFFLINE( ) but does not update the data on the server with the changes made to the offline view. Opening an offline view with the ADMIN keyword allows you to make changes to the offline view without updating the data on the server.

You cannot open or close an offline view in ADMIN mode from within a transaction.

AGAIN
To open a table concurrently in multiple work areas, you can do one of the following:
  • Select another work area and issue USE with the table name and the AGAIN clause.
  • Issue USE with the table name and the AGAIN clause, and specify a different work area with the IN clause.

When you open a table again in another work area, the table in the new work area takes on the attributes of the table in the original work area. For example, if a table is opened for read-only or exclusive access and is opened again in another work area, the table is opened for read-only or exclusive access in the new work area.

Index files opened for the original table are available for the table you open again if you don't open indexes when you open the table again. The index order is set to 0 in the work areas where the table is opened again.

You can open indexes that weren't opened with the original table. This sets the index order to 0 for the original table.

A table opened again is assigned the default alias of the work area. You can include an alias every time you open a table in multiple work areas as long as the aliases are unique.

In Visual FoxPro for Windows, opening a table again in another work area doesn't consume an additional file handle.

NOREQUERY [nDataSessionNumber]
Specifies that data from a remote SQL view is not downloaded again. NOREQUERY is available only for SQL views and is typically used when you open a SQL view again by including the AGAIN clause. Including the NOREQUERY clause increases performance for large data sets because the data does not need to be downloaded again.

nDataSessionNumber can be included to specify that data for a remote SQL view in a specific data session isn't downloaded again. If nDataSessionNumber is omitted, data isn't downloaded for the view open in the current data session.

For additional information about the NOREQUERY clause, see Creating Views.

NODATA
Specifies that only the structure of a SQL view is downloaded. The SQL view's data isn't downloaded. NODATA provides the fastest method for determining a SQL view's structure.

For additional information about the NODATA clause, see Creating Views.

INDEX IndexFileList
Specifies a set of indexes to open with the table. If a table has a structural compound index file, the index file is automatically opened with the table.

IndexFileList can contain any combination of names of single-entry .idx and compound .cdx index files. You don't have to include the file name extensions for index files unless an .idx and a .cdx index file in the index file list have the same name.

The first index file named in the index file list is the master controlling index file, which controls how records in the table are accessed and displayed. However, if the first index file is a .cdx compound index file, records in the table are displayed and accessed in physical record order.

INDEX ?
Displays the Open dialog with a list of available index files to choose from.
ORDER [nIndexNumber]
Specifies a master controlling single-entry .idx index file or compound .cdx index file tag other than the first index file or index tag specified in IndexFileList.

.Idx index files are numbered first, in the order in which they appear in the index file list. Tags in the structural compound index file (if one exists) are then numbered in the order in which the tags were created. Finally, tags in any independent compound index files are numbered in the order in which they were created. You can also use SET ORDER to specify the controlling index file or tag. See SET ORDER for a further discussion of the numbering of index files and tags.

If nIndexNumber is 0, records in the table are displayed and accessed in physical record order, and the indexes remain open. Including ORDER 0 enables open index files to be updated while presenting the file in record number order. Including ORDER without nIndexNumber is identical to including ORDER 0.

ORDER [IDXFileName]
Specifies a single-entry .idx index file as the master controlling index file.
ORDER [TAG TagName] [OF CDXFileName]
Specifies a master controlling tag in a compound .cdx index file. The tag name can be from the structural compound index file or any open compound index file. If identical tag names exist in open compound index files, include OF CDXFileName and specify the name of the compound index file containing the desired tag.
ASCENDING
Specifies that the table records are accessed and displayed in ascending order.
DESCENDING
Specifies that the table records are accessed and displayed in descending order.

Including ASCENDING or DESCENDING doesn't change the index file or tag; it alters only the order in which records are displayed and accessed.

ALIAS cTableAlias
Creates an alias for the table. You can refer to a table by its alias in commands and functions that require or support an alias.

When a table is opened, it is automatically assigned an alias, which is the table name if ALIAS isn't included. You can create a different alias for the table by including ALIAS and a new alias. In Visual FoxPro, an alias can contain up to 254 letters, digits or underscores and must begin with a letter or an underscore. In other FoxPro versions, an alias can contain up to 10 letters, digits or underscores and must begin with a letter or an underscore.

A default alias is assigned automatically if you use AGAIN to open a single table simultaneously in multiple work areas and you don't specify an alias when you open the table in each work area.

A default alias is also assigned if a conflict occurs. For example:

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
ACTIVATE WINDOW View  && Open the Data Session Window
USE customer ALIAS orders IN 1     && Alias is ORDERS
USE orders IN 3     && Conflict; alias is C
EXCLUSIVE
Opens a table for exclusive use on a network. For more information on the exclusive use of tables, see SET EXCLUSIVE.
SHARED
Opens a table for shared use on a network. SHARED allows you to open a table for shared use even when EXCLUSIVE is set ON.
NOUPDATE
Prevents changes to the table and its structure.
CONNSTRING cConnectionString | (m.nStatementHandle)
Specifies a connection string for the ODBC data source. The cConnectionString parameter can represent parameters normally passed using either SQLCONNECT( ) or SQLSTRINGCONNECT( ). The m.nStatementHandle parameter specifies a memory variable representing an existing statement handle from an existing connection.

When you use cConnectionString, Visual FoxPro passes the connection string to the remote view that you specify with SQLViewName, which then uses the connection string to connect to the specified data source instead of using any previously defined connection string. Passing an empty string ("") displays the ODBC Data Source dialog box and makes it possible for the user to select a data source.

Note If you specify incomplete data in the connection string, the data source displays a login dialog box for any needed login information. If you omit the optional CONNSTRING cConnectionString clause, the remote view uses the currently defined default connection. For more information about data source connection strings, see your ODBC driver documentation.

Visual FoxPro supports overriding the default connection for a remote view and requires the m.nStatementHandle parameter for supporting shared connections.

Remarks

If you issue USE without a table name, and a table file is open in the currently selected work area, Visual FoxPro closes the table. Visual FoxPro also closes a table when another table is opened in the same work area. You cannot have more than one table open in a work area at one time.

Example

The following example opens three tables in three different work areas. The Data Session window is opened to show where the tables are open and to show the alias for each table.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
ACTIVATE WINDOW View

USE customer IN 0  && Opens Customer table
USE employee IN 0  && Opens Employee table
USE products IN 0  && Opens Products table

See Also

CREATE | CREATE SQL VIEW | CREATE TABLE - SQL | CREATEOFFLINE( ) | DBF( ) | INDEX | USED( ) | Creating Views | SET EXCLUSIVE


VALIDATE DATABASE Command

Ensures that the locations of tables and indexes in the current database are correct.

VALIDATE DATABASE [RECOVER] [NOCONSOLE]
   [TO PRINTER [PROMPT] | TO FILE FileName]

Parameters

RECOVER
Displays dialogs that make it possible for you to locate tables and indexes that are not in the locations contained in the database. Beginning with Visual FoxPro 7, the RECOVER clause is supported in programs.
NOCONSOLE
Suppresses error message output to the main Visual FoxPro window or to the active user-defined window.
TO PRINTER [PROMPT]
Directs error message output from VALIDATE DATABASE to a printer.

PROMPT displays a Print dialog box before printing starts. Place the PROMPT keyword immediately after TO PRINTER.

TO FILE FileName
Directs error message output to the file specified with FileName. If the file already exists and SET SAFETY is ON, you are asked if you want to overwrite the file.

Remarks

VALIDATE DATABASE ensures that the database contains the proper locations of tables and indexes, that tables in the database contain the proper fields, and that index tags in the database exist.

VALIDATE DATABASE operates on the current database. The database must be opened for exclusive use by including the EXCLUSIVE keyword when you issue OPEN DATABASE.

Example

The following example opens the testdata database and uses VALIDATE DATABASE to ensure that the locations of tables and indexes in the database are correct.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'Data\') && Sets path to database
OPEN DATABASE testdata EXCLUSIVE && Open testdata database

VALIDATE DATABASE

See Also

CREATE DATABASE | MODIFY DATABASE | OPEN DATABASE | USE


WAIT Command

Displays a message and pauses Visual FoxPro execution until the user presses a key or clicks the mouse.

WAIT [cMessageText] [TO VarName] [WINDOW [AT nRow, nColumn]] [NOWAIT]
   [CLEAR | NOCLEAR] [TIMEOUT nSeconds]

Parameters

cMessageText
Specifies a custom message to display.

You can use any valid Visual FoxPro function, object, or data type instead of cMessageText. If the function you use evaluates to a noncharacter value, Visual FoxPro automatically uses the TRANSFORM( ) function to provide the character equivalent. In the following example, a character type date is returned and passed to WAIT WINDOW:

WAIT DATE() WINDOW AT 20,20 TIMEOUT 10

If you omit cMessageText, Visual FoxPro displays the default message. If cMessageText is an empty string (""), Visual FoxPro does not display a message and waits until a key is pressed before continuing program execution.

TO VarName
Saves the key pressed to a variable or an array element.

If the variable or an array element you specify with VarName does not exist, it is created. The empty string is stored in VarName if you press ENTER or a nonprintable key or key combination, or click the mouse.

WINDOW
Displays the message in a system message window located in the upper-right corner of the main Visual FoxPro window. The window can be temporarily hidden by pressing the CTRL or SHIFT key.

Beginning with Visual FoxPro 7, core font attributes including font name, font size and font style are derived from the font characteristics specified in the Appearance tab of the Windows Display Control Panel.

AT nRow, nColumn
In Visual FoxPro, specifies the position of the message window on the screen.
NOWAIT
Continues program execution immediately after the message is displayed.

The program does not wait for the message to be removed from the main Visual FoxPro window, but continues executing on the program line immediately following the program line containing WAIT NOWAIT.

If you omit NOWAIT, program execution pauses until the message is removed from the main Visual FoxPro window by pressing a key or clicking the mouse.

CLEAR
Removes a Visual FoxPro system window or a WAIT message window from the main Visual FoxPro window from within a program.

For example, talk from indexing, sorting, and so on is directed to a Visual FoxPro system window if you issue SET TALK WINDOW. The window can be removed interactively if you press a key or move the mouse. Issue WAIT CLEAR to remove the window from within a program.

NOCLEAR
Specifies that a WAIT message window remains on the main Visual FoxPro window until WAIT CLEAR or another WAIT WINDOW command is issued, or a Visual FoxPro system message is displayed.
TIMEOUT nSeconds
Specifies the number of seconds that can elapse without input from the keyboard or the mouse before the WAIT is terminated. nSeconds specifies the number seconds, the fractional seconds that are permitted, that elapse. If TIMEOUT is not the last clause in WAIT, Visual FoxPro generates a syntax error message.

Remarks

If a WAIT message is displayed in Visual FoxPro for Windows, pressing the SHIFT or CTRL keys hides all windows including the WAIT message.

See Also

Commands | TRANSFORM( ) Function | ACCEPT | CLEAR | ReadTimeout


WITH ... ENDWITH Command

Specifies multiple properties for an object.

WITH ObjectName
   [.cStatements]
ENDWITH

Parameters

ObjectName
Specifies the name of the object. ObjectName can be the name of the object or a reference to the object.
.cStatements
cStatements can consist of any number of Microsoft Visual FoxPro commands used to specify properties for ObjectName. Place a period before cStatement to denote that it is a property of ObjectName.

Remarks

WITH ... ENDWITH provides a convenient way to specify a number of properties for a single object. Note that you can also execute methods from within a WITH ... ENDWITH structure.

Example

The following example creates a custom class name Employee. After the Employee class has been created with CREATEOBJECT( ), WITH ... ENDWITH is used to set multiple properties for the class. The properties values are then displayed.

moemployee = CREATEOBJECT('employee')

WITH moemployee
   .First_Name = 'John'
   .Last_Name = 'Smith'
   .Address = '16 Maple Lane'
   .HireDate = {^1998-02-16}
ENDWITH

CLEAR
? moemployee.First_Name + ' '
?? moemployee.Last_Name
? moemployee.Address
? moemployee.HireDate

DEFINE CLASS employee AS CUSTOM
      First_Name = SPACE(20)
      Last_Name = SPACE(20)
      Address = SPACE(30)
      HireDate = {  -  -  }
ENDDEFINE

See Also

:: Scope Resolution Operator | ADD CLASS | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | GETOBJECT( ) | MODIFY CLASS | RELEASE CLASSLIB | SET CLASSLIB


ZAP Command

Removes all records from a table, leaving just the table structure.

ZAP   [IN nWorkArea | cTableAlias]

Parameters

IN nWorkArea
Specifies the work area of the table in which all records are removed.
IN cTableAlias
Specifies the alias of the table in which all records are removed.

If you omit nWorkArea and cTableAlias, all records are removed in the table in the currently selected work area.

Remarks

Issuing ZAP is equivalent to issuing DELETE ALL followed by PACK, but ZAP is much faster.

If SET SAFETY is ON, Microsoft Visual FoxPro asks if you would like to remove the records from the current table.

Issuing ZAP does not cause a Delete trigger to occur. For more information about creating triggers for a table, see CREATE TRIGGER.

Caution Records zapped from the current table cannot be recalled.

See Also

CREATE TRIGGER | DELETE | PACK


ZOOM WINDOW Command

Changes the size and position of a user-defined window or a Visual FoxPro system window.

ZOOM WINDOW WindowName MIN | MAX | NORM
   [AT nRow1, nColumn1 | FROM AT nRow1, nColumn1
   [SIZE AT nRow2, nColumn2 | TO nRow2, nColumn2]]

Parameters

WindowName
Specifies the name of the window whose size you want to change.
MIN
Reduces the window to minimum size.

In Visual FoxPro for Windows, the window is reduced to an icon.

All system windows can be reduced to a minimum size in Visual FoxPro for Windows. Visual FoxPro system windows must be open in the main Visual FoxPro window or a user-defined window before they can be minimized.

A user-defined window can be minimized after it is defined. It doesn't have to be activated before you change its size.

MAX
Expands a window to fill the main Visual FoxPro window, the Windows desktop, or a user-defined window. If a child window is placed in a parent window and the child window is maximized, it fills the parent window. If any of the additional ZOOM WINDOW clauses (AT, SIZE, TO, or FROM) are included with MAX, MAX is ignored.

Only user-defined windows defined with ZOOM can be expanded to maximum size.

NORM
Returns a window to its original size after it has been minimized or maximized. NORM can also be used to move a window without changing its size. Use ZOOM WINDOW NORM without any additional clauses to return a minimized or maximized window to its original size and location.
AT nRow1, nColumn1 | FROM nRow2, nColumn2
You can specify the placement of a window by including the AT or FROM clause.

ZOOM WINDOW WindowName NORM AT AT nRow1, nColumn1 restores a minimized or maximized window to its original size and places it at the specific location. The AT nRow1, nColumn1 coordinates specify where the upper-left corner of the window is placed. A window's location can also be changed with MOVE WINDOW.

In Visual FoxPro for Windows, if NORM is included, the upper-left corner of the window is placed in the main Visual FoxPro window at the location specified with AT nRow1, nColumn1. If MIN is included, AT and FROM are ignored and the window is displayed as an icon in the lower portion of the main Visual FoxPro window. If MAX is included, AT and FROM are ignored and the window is expanded to fill the main Visual FoxPro window.

In Visual FoxPro for Windows, if the window is created with the IN DESKTOP clause, the upper-left corner of the window is placed in the Windows desktop at the location specified with AT nRow1, nColumn1. If MIN is included, AT and FROM are ignored and the window is displayed as an icon in the lower portion of the Windows desktop. If MAX is included, AT and FROM are ignored and the window is expanded to fill the Windows desktop.

SIZE AT nRow2, nColumn2 | TO nRow2, nColumn2
You can also specify a window size for a window by including SIZE or TO. If SIZE is included, the window size is nRow2 rows high and nColumn2 columns wide. If the TO clause is included, the upper-left corner of the window remains in its current position and the lower-right corner of the window is placed at the position specified with nRow2, nColumn2.

Remarks

In Visual FoxPro for Windows, windows can be reduced to a minimum size, enlarged to fill the entire main Visual FoxPro window, or sized anywhere in between.

If you create a user-defined window with DEFINE WINDOW and the IN DESKTOP clause in Visual FoxPro for Windows, the window you create can be enlarged to fill the entire desktop.

In Visual FoxPro for Windows, windows can be zoomed directly from minimum to maximum size and vice versa.

When zooming a window, you can specify where to place the resized window in the main Visual FoxPro window or a user-defined window.

To zoom a system window, enclose the entire system window name in quotation marks. For example, to maximize the Command window, issue the following command:

ZOOM WINDOW 'Command Window' MAX

You can use ZOOM WINDOW to resize all system windows.

Example

In the following example, a Browse window is opened for the customer table. The Browse window is minimized. The Browse window is then returned to its default size. It is then minimized again at a specific location. The Browse window is then enlarged to a specific size and is maximized.

CLEAR ALL
CLEAR
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\Testdata')
USE customer  && Opens Customer table
BROWSE NORMAL NOWAIT

IF _DOS OR _WINDOWS
   ZOOM WINDOW customer MIN
   WAIT WINDOW TIMEOUT 3 ;
      'MIN clause - This window will timeout. Please wait.'
ENDIF

ZOOM WINDOW customer NORM
WAIT WINDOW TIMEOUT 3 ;
   'NORM clause - This window will timeout. Please wait.'

IF _DOS OR _WINDOWS
   ZOOM WINDOW customer MIN AT 10,10
   WAIT WINDOW TIMEOUT 3 ;
      'MIN AT 10,10 clause - This window will timeout. Please wait.'
ENDIF

ZOOM WINDOW customer NORM AT 1,1 SIZE 22,25
WAIT WINDOW TIMEOUT 3 ;
   'NORM & SIZE clauses - This window will timeout. Please wait.'
ZOOM WINDOW customer NORM FROM 10,10 TO 22,70
WAIT WINDOW TIMEOUT 3 ;
   'NORM & TO clauses - This window will timeout. Please wait.'
ZOOM WINDOW customer MAX
WAIT WINDOW TIMEOUT 3 'MAX clause - This window will timeout. Please wait.'
CLEAR ALL

See Also

ACTIVATE WINDOW | DEFINE WINDOW | SIZE WINDOW


Objects, Collections, and Classes

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

Application Object

B

C

CheckBox Control

Collection Class

Column Object

ComboBox Control

CommandButton Control

CommandGroup Control

Container Object

Control Object

Coverage Engine Object

Cursor Object

CursorAdapter Class

Custom Object

D

DataEnvironment Object

DataObject Object

E

EditBox Control

Empty Class

Exception Class

F

Fields Collection (XMLTable)

File Object

Files Collection

Form Object

FormSet Object

FoxCode Object Reference

G

Grid Control

H

Header Object

Hyperlink Object

I

Image Control

J

K

L

Label Control

Line Control

ListBox Control

M

Member Classes

N

O

Objects Collection

OLE Bound Control

OLE Container Control

OptionButton Control

OptionGroup Control

P

Page Object

PageFrame Control

Project Object

ProjectHook Object

Projects Collection

Q

R

Relation Object

S

Separator Object

Server Object

Servers Collection

Session Object

Shape Control

Spinner Control

T

Tables Collection (XMLAdapter)

TextBox Control

THIS Object Reference

THISFORM Object Reference

THISFORMSET Object Reference

Timer Control

ToolBar Object

U

V

Visual FoxPro Foundation Classes A-Z

W

X

XMLAdapter Class

XMLField Class

XMLTable Class

Y

Z

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


Application Object

An object created for each instance of Visual FoxPro that exposes a set of Visual FoxPro properties and methods.

Application.PropertyName[ = eValue]
-or-
Application.Method

Parameters

PropertyName
Specifies a property for the application object.
eValue
Specifies a value for the property.
Method
Specifies a method to execute for the application object.

Remarks

Visual FoxPro is an automation server, allowing other applications such as Microsoft Excel or Visual Basic to remotely start and manipulate Visual FoxPro through properties and methods. The Application object is also available from within an instance of Visual FoxPro.

The syntax used by an application to create an instance of an automation server such as Visual FoxPro is typically unique to the application. Consult the application's documentation for the proper syntax to create an instance of an automation server and then manipulate the instance through the properties and methods.

The Objects Collection can be accessed through the Application object.

Example

You can start another instance of Visual FoxPro from within Visual FoxPro with the following command:

oNewInstance = CREATEOBJECT('VisualFoxPro.Application')

A new instance of Visual FoxPro is not visible when it is created; the following command makes the new instance visible:

oNewInstance.Visible = .T.

See Also

Application Object Properties, Methods and Events | CREATEOBJECT( ) | _VFP System Variable | Objects Collection

Applies To: Projects Collection


Application Object Properties, Methods, and Events

Properties

ActiveForm Property | ActiveProject Property | Application Property
AutoYield Property | Caption Property | DefaultFilePath Property
EditorOptions Property | FullName Property | Height Property
HWND Property | LanguageOptions Property | Left Property
Name Property | Objects Collection | OLERequestPendingTimeout Property
OLEServerBusyRaiseError Property | OLEServerBusyTimeout Property | Parent Property
ProcessID Property | Projects Collection | ServerName Property
StartMode Property | StatusBar Property | ThreadID Property
Top Property | Version Property | VFPXMLProgID Property
Visible Property | Width Property |

Methods

DataToClip Method | DoCmd Method | Eval Method
Help Method | Quit Method | RequestData Method
SETVAR Method |  |

See Also

_VFP System Variable | Objects Collection | Application Object | Visual FoxPro Framework Application Object | Projects Collection


CheckBox Control

Creates a check box.

CheckBox

Remarks

A check box is used to switch between three states, True (.T.), False (.F.) and Null (.NULL.).

The three possible states for a check box are determined by the Value property.

Display | Value property
 | 0 or .F.
 | 1 or .T.
 | 2 or .NULL.

Setting the Value property to .NULL., or 2, allows the application user to refrain from selecting or not selecting the check box. The check box initially appears selected and dimmed; however, the application user can still clear and then select the check box. You can provide this behavior to allow the application user to decline from selecting the check box. The user can return the check box to the original null state after interacting with the check box by pressing CTRL+0.

The Value property of the check box reflects the data type of the last assignment. If you set the property to True (.T.) or False (.F.), the type is Logical until you set the property to a numeric value. If you set the ControlSource property of the check box to a logical field in a table, the check box is displayed as selected when the value in the current record is True (.T.), as not selected when the value in the current record is False (.F.), and as selected and dimmed if the value in the current record is Null (.NULL.).

Tip If the ControlSource property is a field in a table that does not accept a .NULL. value, then pressing CTRL+0 will generate an error.

Use the Caption property to specify the text that appears next to a check box. Use the Picture property to specify a picture for a check box.

For additional information about CheckBox controls, see Using Check Boxes.

See Also

CheckBox Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


CheckBox Control Properties, Methods, and Events

Properties

Alignment | Application | AutoSize
BackColor | BackStyle | BaseClass
Caption | Centered | Class
ClassLibrary | ColorScheme | ColorSource
Comment | ControlSource | DisabledBackColor
DisabledForeColor | DisabledPicture | DownPicture
DragIcon | DragMode | DynamicFontBold
DynamicFontItalic | DynamicFontStrikethru | DynamicFontUnderline
Enabled | FontBold | FontCharSet
FontCondense | FontExtend | FontItalic
FontName | FontOutline | FontShadow
FontStrikethru | FontUnderline | ForeColor
Height | HelpContextID | Left
MouseIcon | MousePointer | Name
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData | Parent | ParentClass
Picture | PicturePosition | ReadOnly
RightToLeft | SpecialEffect | StatusBarText
Style | TabIndex | TabStop
Tag | TerminateRead | Themes
ToolTipText | Top | Value
Visible | WhatsThisHelpID | Width

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
ErrorMessage | GotFocus | Init
InteractiveChange | KeyPress | LostFocus
Message | MiddleClick | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | ProgrammaticChange
RightClick | UIEnable | Valid
When |  |

See Also

CheckBox Control | Using Controls | Caption Property


Class Browser Object Members

You can use the names in this table to reference the object members of the Class Browser. The table order reflects the order the member object appears in the Class Browser window. The reference to the Class Browser window itself is _oBrowser.

Class Browser object | Object name
Class description edit box | edtClassDesc
Class member edit box | edtMemberDesc
Open command button | cmdOpen
Add Additional File command button | cmdAdd
View Class Code command button | cmdExport
Find command button | cmdFind
New Class command button | cmdSubclass
Rename command button | cmdRename
Redefine command button | cmdRedefine
Remove command button | cmdRemove
Clean Up Library command button | cmdCleanup
Class Icon image | imgClassIcon
Class Icon button | cmdClassIcon
Type label for the Type combo box | lblClassType
Type combo box | cboClassType
Class List 3D effect control | txtClassList3D
Class List OLE container | oleClassList
Member List OLE container | oleMembers
Member List 3D effect control | txtMembers3D
Object Member list box | lstMembers*
Methods list box | lstClassList*
Class Description edit box | edtClassDesc
Member Description edit box | edtMemberDesc

* These objects exist only when lOutlineOCX is False (.F.).

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Properties | Class Browser Window | Customizing the Class Browser | Initial Values of Class Browser Properties


Column Object

Creates a Column object in a Grid control. A grid column can contain data from a field in a table or the value of an expression. A column can also contain controls.

Grid.Column

Remarks

To specify the data appearing in the column, use the column's DataSource property.

You can specify the number of columns in a grid with the grid's ColumnCount property.

You can add controls to a column in a grid by using the AddObject method in the Init event of the form that contains the grid. To set the active control in the grid's column, use the column's CurrentControl property. To specify the source of the control's data, set the control's ControlSource property.

Note You cannot access headers and controls for a column until the Init event for the grid occurs.

For additional information about creating columns in a grid, see Grid Control and Using Controls.

Hiding Columns To hide a column in a grid, set the Visible property for the column to False (.F.). You can still set the Value property of any control in the column. For example, you can still change the value of Column.Text1.Value by specifying a new value, even when the column is hidden.

Visual FoxPro processes uncommitted changes in a hidden column as usual and at the appropriate time according to BufferMode property of the form. For example, hiding a column does not cause nor prevent pending updates from being committed to that column.

When you hide a column that has focus, focus does not automatically move from the hidden column to the next or previous column. In essence, no column has focus. If you want to move focus to another cell, column, or control, you must manually move the focus, for example, by pressing the TAB key or using the mouse.

When you hide all columns in a grid, only the record-pointer portion of the grid along the left side remains visible.

Setting the AllowAutoColumnFit property and using the AutoFit method does not affect hidden columns. For more information, see AllowAutoColumnFit Property and AutoFit Method.

See Also

Column Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | Header Object


Column Object Properties, Methods, and Events

Properties

Alignment | Application | BackColor
BaseClass | Bound | Class
ClassLibrary | ColumnOrder | Comment
ControlCount | Controls | ControlSource
CurrentControl | DynamicAlignment | DynamicBackColor
DynamicCurrentControl | DynamicFontBold | DynamicFontItalic
DynamicFontName | DynamicFontOutline | DynamicFontShadow
DynamicFontSize | DynamicFontStrikeThru | DynamicFontUnderline
DynamicForeColor | DynamicInputMask | Enabled
FontBold | FontCharSet | FontCondense
FontExtend | FontItalic | FontName
FontOutline | FontShadow | FontSize
FontStrikeThru | FontUnderline | ForeColor
Format | HeaderClass | HeaderClassLibrary
InputMask | Movable | Name
Objects | Parent | ParentClass
ReadOnly | Resizable | SelectOnEntry
Sparse | StatusBarText | Tag
ToolTipText | Visible | Width

Methods

AddObject | AddProperty | AutoFit
Move | ReadExpression | ReadMethod
Refresh | RemoveObject | ResetToDefault
SaveAsClass | SetAll | SetFocus
WriteExpression | WriteMethod | ZOrder

Events

Destroy | Error | Init
MouseEnter | MouseLeave | MouseMove
MouseWheel | Moved | Resize

See Also

Column Object | ColumnCount Property | Grid Control | Using Controls


Collection Class

You can use collections to group a set of related items, usually objects, which can be of any type. Collections provide a mechanism for working with objects stored in containers and include standard ways for accessing and iterating through objects in a collection. The Collection class functions as a true container class, even though it does not include the AddObject method like the Form and PageFrame classes.

The Collection class is a base class that you can subclass in program (.prg) or visual class library (.vcx) files.

Collection

Remarks

The position of an item in a collection can vary and change when changes occur in the collection.

Collections support the enumerations of items performed with the FOR EACH command based on the position of items. You can control the position of these items by using the eBeforeItem or eAfterItem parameters associated with the Add method for collection objects. You can use an index value of 1, or one-based enumeration, to refer to the first item in a collection, or you can use a key value by setting the KeySort property. Collections are one-based for consistency and compatibility with other internal Visual FoxPro collections.

Make sure that either all the items in a collection have keys or none of them have keys. Deciding whether all items have keys or do not have keys provides more efficient item searching when using the Item method for collection objects and the FOR EACH command.

You can use a collection in a Visual FoxPro Component Object Model (COM) server that other COM Servers can access.

You can hide the Add and Remove methods for collection objects from public use by subclassing the collection object and marking the subclassed members as Hidden or Protected. If you do so, you need to add the collection members in the Init event or via some other method.

Items that are added to collections have the same scope as any other memory variable.

Because Collection objects support default methods, for example, Item (Collection Class), you need to be aware of the search order for these methods. A Collection object method takes precedence over a standard user-defined function (UDF) call. The following list shows the order in which Visual FoxPro searches for a function name:

  • Visual FoxPro native function
  • Collection object default method
  • UDF defined in the local program (.prg) file
  • UDF defined in calling program (.prg) files
  • Named program in the application (.app or .exe) file
  • Named program along the SET PATH list

When Visual FoxPro releases a collection, which contains object references, it also releases any objects in the collection if they are not referenced elsewhere. Make sure to release objects and any references to those objects from a collection before removing them completely from memory.

Visual FoxPro does not support intrinsic type safety. Therefore, to enforce type safety with collections, you must provide it for the class.

Example

At run time, the following example creates forms and a collection, adds forms to the collection using the Collection class Add method, displays the name of each form in the collection, and displays the number of forms in the collection:

loForm1 = CREATEOBJECT("Form")
loForm2 = CREATEOBJECT("Form")
loCol = CREATEOBJECT("Collection")
loCol.Add(loForm1)
loCol.Add(loForm2)
FOR EACH loObj IN loCol
   ? loObj.Name
ENDFOR
? loCol.Count

The following example defines a Form class which adds text boxes, buttons objects, and a collection to the form. When added to the form at run time, the collection class adds all the objects on the form to itself. The example then iterates through the collection to adjust the position of the control and prints its name to the screen.

LOCAL loForm, loItem, lnTop
loForm = CREATEOBJECT("myForm")
lnTop=0
FOR EACH loItem IN loForm.myCollection
   TRY
      loItem.Top = lnTop
      lnTop=lnTop+20
      ? loItem.Name
   CATCH
   ENDTRY
ENDFOR
loForm.Show(1)

DEFINE CLASS myForm AS Form
   AllowOutput=.F.
   AutoCenter=.T.
   ADD OBJECT myTextBox1 AS TextBox
   ADD OBJECT myTextBox2 AS TextBox
   ADD OBJECT myButton1 AS CommandButton
   ADD OBJECT myButton2 AS CommandButton
   ADD OBJECT myCollection AS col1
ENDDEFINE

DEFINE CLASS col1 AS Collection
   PROCEDURE Init
      FOR i = 1 TO THISFORM.Objects.Count
         THIS.Add(THISFORM.Objects(m.i))
      ENDFOR
   ENDPROC
ENDDEFINE

For other examples using the Add, Remove, and Item methods of the Collection class, see Add Method (Collection Class), Remove Method (Collection Class), and Item Method (Collection Class).

See Also

Objects, Collections, and Classes | Collection Object Properties, Methods, and Events | FOR EACH ... ENDFOR Command | Automation and COM Servers


Collection Object Properties, Methods, and Events

Properties

BaseClass | Class | ClassLibrary
Count | Comment | KeySort
Name | Parent | ParentClass
Tag |  |

Methods

Add (Collection Class) | AddProperty | GetKey
Item (Collection Class) | ReadExpression | ReadMethod
Remove (Collection Class) | ResetToDefault | SaveAsClass
WriteExpression | WriteMethod |

Events

Destroy Error Init

See Also

Collection Class


ComboBox Control

Creates a combo box.

ComboBox

Remarks

When selected, the ComboBox control opens, displaying a list of items from which you can choose one. A ComboBox control combines the features of a TextBox control and a ListBox control. You can enter information in the text box portion or select an item from the list box portion of the control.

Note You can show or hide the item list of a ComboBox control by pressing Alt+Down Arrow when the control is selected.

The backslash ("\") is treated as a special character when used in the expression for an item. The following rules apply for this character

  • You can disable an item in a list box or combo box by adding a single backslash to the beginning of the expression.
  • Any multiple of two backslashes used in the expression is displayed as a single backslash. For example, one or two backslashes used together display as one, and three or four backslashes together display as two. The following example code contains a list box item containing a Universal Naming Convention (UNC) path. The code displays in the list box as \\MyServer\MyMachine\MyFolder.
    MyForm.List1.AddItem("\\\\MyServer\\MyMachine\\MyFolder")
  • If the expression begins with multiple backslashes, the item is not disabled. If you want to disable an item that begins with multiple backslashes, add a backslash and a close bracket (]) to the beginning of the item. For example, the following would disable the UNC path item in the list box.
    MyForm.List1.AddItem("\]\\\MyServer\\MyMachine\\MyFolder")
  • To include a separator line use a backslash followed by a hyphen as the item to add to the list box. For example, the following code adds a separator line to a list box.
    MyForm.List1.AddItem("\-")

The Style property determines the ComboBox control type. If the Style property is set to 0, a drop-down ComboBox control is created. If the Style property is set to 2, a drop-down list box is created.

You can also use an ActiveX control that adds extra characteristics, such as a checkbox to the listview or treeview controls.

For additional information about ComboBox controls, see Form Designer and Using Controls.

See Also

ComboBox Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


ComboBox Control Properties, Methods, and Events

Properties

Alignment | Application | BackColor
BaseClass | BorderColor | BorderStyle
BoundColumn | BoundTo | Class
ClassLibrary | ColorScheme | ColorSource
ColumnCount | ColumnLines | ColumnWidths
Comment | ControlSource | DisabledBackColor
DisabledForeColor | DisabledItemBackColor | DisabledItemForeColor
DisplayCount Property | DisplayValue | DragIcon
DragMode | Enabled | FirstElement
FontBold | FontCharSet | FontCondense
FontExtend | FontItalic | FontName
FontOutline | FontShadow | FontSize
FontStrikeThru | FontUnderline | ForeColor
Format | Height | HelpContextID
HideSelection | IMEMode | IncrementalSearch
InputMask | ItemBackColor | ItemData
ItemForeColor | ItemIDData | ItemTips
Left | List | ListCount
ListIndex | ListItem | ListItemID
Margin | MaxLength | MouseIcon
MousePointer | Name | NewIndex
NewItemID | NullDisplay | NumberOfElements
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData Property | OLEDropMode | OLEDropTextInsertion
Parent | ParentClass | Picture
PictureSelectionDisplay | ReadOnly | RightToLeft
RowSource | RowSourceType | Selected
SelectedBackColor | SelectedForeColor | SelectedID
SelectedItemBackColor | SelectedItemForeColor | SelectOnEntry
SelLength | SelStart | SelText
Sorted | SpecialEffect | StatusBarText
Style | TabIndex | TabStop
Tag | Text Property | TerminateRead
Themes | ToolTipText | Top
TopIndex | TopItemID | Value
Visible | WhatsThisHelpID | Width

Methods

AddItem | AddListItem | AddProperty
Clear | CloneObject | Drag
IndexToItemID | ItemIDToIndex | Move
OLEDrag | ReadExpression | ReadMethod
Refresh | RemoveItem | RemoveListItem
Requery | ResetToDefault | SaveAsClass
SetFocus | SetViewPort | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

Events

Click | DblClick | Destroy
DownClick | DragDrop | DragOver
DropDown | Error | ErrorMessage
GotFocus | Init | InteractiveChange
KeyPress | LostFocus | Message
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | ProgrammaticChange | RangeHigh
RangeLow | RightClick | UIEnable
UpClick | Valid | When

See Also

ComboBox Control | Form Designer | Using Controls


CommandButton Control

Creates a single command button.

CommandButton

Remarks

A command button is typically used to start an event that performs an action such as closing a form, moving to a different record, printing a report, and so on. Use the CommandGroup control to create a set of command buttons that you can manipulate individually or as a group.

Use the Caption property to specify the text that appears on a command button. Use the Picture property to specify a picture for a command button.

You can choose a command button by clicking it, and, if the Default property is set to True (.T.), by pressing the ENTER key when the command button is selected. If the Cancel property of the command button is set to True (.T.), you can choose the command button by pressing the ESC key.

For additional information about command buttons, see Form Designer and Using Controls.

Example

The following example demonstrates how command buttons can be added to a form. The Caption property is used to specify the text on the command buttons and the text indicating each button's access key sequence. The Cancel property is used to specify a button that is chosen when you press ESC.

The AddObject method is used to add three command buttons to the form, allowing you to change the direction in which a Line control slants or to close the form.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS CommandButton  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

CommandButton Control Properties, Methods and Events | CommandGroup Control | CREATE CLASS | CREATE FORM | DEFINE CLASS


CommandButton Control Properties, Methods, and Events

Properties

Application | AutoSize | BackColor
BaseClass | Cancel | Caption
ClassLibrary | Class | ColorScheme
ColorSource | Comment | Default
DisabledBackColor | DisabledForeColor | DisabledPicture
DownPicture | DragIcon | DragMode
Enabled | FontBold | FontCharSet
FontCondense | FontExtend | FontItalic
FontName | FontOutline | FontShadow
FontSize | FontStrikeThru | FontUnderline
ForeColor | Height | HelpContextID
Left | MouseIcon | MousePointer
Name | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData Property | OLEDropMode
ParentClass | Parent | Picture
PicturePosition | RightToLeft | SpecialEffect
StatusBarText | Style | TabIndex
TabStop | Tag | TerminateRead
Themes | ToolTipText | Top
Visible | VisualEffect Property | WhatsThisHelpID
Width | WordWrap |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

Events

Click | Destroy | DragDrop
DragOver | Error | ErrorMessage
GotFocus | Init | KeyPress
LostFocus | Message | MiddleClick Event
MouseDown | MouseEnter | MouseLeave
MouseMove | MouseUp | MouseWheel
OLECompleteDrag | OLEDragDrop | OLEDragOver
OLEGiveFeedBack | OLESetData | OLEStartDrag
RightClick | UIEnable | Valid
When |  |

See Also

CommandButton Control | CommandGroup Control | Form Designer | Using Controls


CommandGroup Control

Creates a group of command buttons.

CommandGroup

Remarks

Use the CommandGroup control to create a set of command buttons that you can manipulate individually or as a group. Use the CommandButton control to create an individual command button.

Use the ButtonCount property to specify the number of command buttons in the group, and the Caption property to specify a label for the command button group.

For additional information about command button groups, see the Form Designer topic and Using Controls.

See Also

CommandGroup Control Properties, Methods and Events | CommandButton Control | CREATE CLASS | CREATE FORM | DEFINE CLASS


CommandGroup Control Properties, Methods, and Events

Properties

Application | AutoSize | BackColor
BackStyle | BaseClass | BorderColor
BorderStyle | ButtonCount | Buttons
Class | ClassLibrary | ColorSource
Comment | ControlSource | DragIcon
DragMode | Enabled | Height
HelpContextID | Left | MemberClass
MemberClassLibrary | MouseIcon | MousePointer
Name | Objects | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData Property
OLEDropMode | Parent | ParentClass
SpecialEffect | StatusBarText | TabIndex
Tag | TerminateRead | Themes
ToolTipText | Top | Value
Visible | WhatsThisHelpID | Width

Methods

AddObject | AddProperty | CloneObject
Drag | Move | NewObject
OLEDrag | ReadExpression | ReadMethod
Refresh | RemoveObject | ResetToDefault
SaveAsClass | SetAll | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

Events

Click | DblClick | DragDrop
DragOver | Error | ErrorMessage
Init | InteractiveChange | Message
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | ProgrammaticChange | RightClick
UIEnable | Valid | When

See Also

CommandGroup Control | CommandButton Control


Container Object

Creates an object that can contain other objects.

Container

Remarks

Container objects can contain other objects and allow access to the objects contained within them. For example, if you create a container object that contains two list boxes and two command buttons, and then add the container object to a form, the list boxes and command buttons can be manipulated at design time and at run time.

For more information about container objects and how they differ from other objects and controls, see Object-Oriented Programming.

See Also

Container Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Container Object Properties, Methods, and Events

Properties

ActiveControl | Application | BackColor
BackStyle | BaseClass | BorderColor
BorderWidth | Class | ClassLibrary
ColorSource | Comment | ControlCount
Controls | DragIcon | DragMode
Enabled | ForeColor | Height
HelpContextID | Left | MouseIcon
MousePointer | Name | Objects
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData Property | OLEDropMode | Parent
ParentClass | Picture | SpecialEffect
StatusBarText | TabIndex | TabStop
Tag | ToolTipText | Top
Visible | WhatsThisHelpID | Width

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
GotFocus | Init | LostFocus
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | Moved | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | Resize
RightClick | UIEnable |

Methods

AddObject | AddProperty | Drag
Draw | Move | NewObject
OLEDrag | ReadExpression | ReadMethod
Refresh | RemoveObject | ResetToDefault
SaveAsClass | SetAll | SetFocus
ShowWhatsThis | WriteExpression | Zorder

See Also

Container Object | Objects Collection


Control Object

Creates a control object that can contain other protected objects.

Control

Remarks

Control objects can contain other objects, but, unlike container objects, do not allow access to the objects contained within them. For example, if you create a control object that consists of two ListBoxes and two CommandButtons, and then add the control object to a form, the ListBoxes and CommandButtons cannot be manipulated individually at design time or at run time.

For more information about control objects and how they differ from other objects and controls, see Object-Oriented Programming.

See Also

Control Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | ListBox Control | CommandButton Control


Control Object Properties, Methods, and Events

Properties

ActiveControl | Application | BackColor
BackStyle | BaseClass | BorderColor
BorderWidth | Class | ClassLibrary
ColorSource | Comment | ControlCount
Controls | DragIcon | DragMode
Enabled | ForeColor | Height
HelpContextID | Left | MouseIcon
MousePointer | Name | Objects
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData Property | OLEDropMode | Parent
ParentClass | Picture | SpecialEffect
StatusBarText | TabIndex | TabStop
Tag | ToolTipText | Top
Visible | WhatsThisHelpID | Width

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
GotFocus | Init | LostFocus
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | Moved | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | Resize
RightClick | UIEnable |

Methods

AddProperty | Drag | Draw
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | ZOrder |

See Also

Control Object


Coverage Engine Object

Category | Reporting
Class | cov_engine
Class Library | coverage.vcx
Base Class | formset
Parent Class | scov_formset

This formset is not a subclass of _formset, therefore the Coverage Profiler runs in Visual FoxPro 5.0 and later.

Remarks

This class is subclassed from the Visual FoxPro formset class. Though it provides no visible components, it provides the datatsession of a formset class and includes provisions for feedback on coverage log processing through WAIT WINDOW NOWAIT, MESSAGEBOX( ), and subclasses of MSComDlg.CommonDialog. This formset has one member, a toolbar, that remains hidden while providing a container for custom objects, such as CusRegistry or Dialog subclasses. Cov_standard, a subclass of cov_engine, provides a sample user interface, the Coverage Profiler Application. You can subclass either cov_engine or cov_standard to fit your requirements.

aAddIns array Property

This one-dimensional array holds a list of registered add-in files.

Default .F. (the array will be dimensioned [1])

aFileTypes array Property

This two-dimensional array holds a list of the file types (extensions) the Coverage Profiler handles. The first column holds the extension listed in the coverage text log (such as .fxp or .vct). The second column holds the extension of the matching source code file (such as .prg or .vcx) that the Coverage Profiler must locate to analyze the code. This array is filled at startup by the FillFileTypeArray( ) method.

Default .F. (the array will be dimensioned [1, 2])

cAddIn Property

Specifies the add-in last run successfully. At startup this property can be set by an add-in passed to the Coverage Profiler application as a parameter and run in the Init. Otherwise, if add-in file names have been stored to the registry previously, this property is filled using the aAddIns array.

Default ""

cBaseFontName Property

Specifies a base font name for any interface elements. The default for this attribute when no preference has been saved to the registry is the #DEFINE constant COV_DEFAULT_BASE_FONTNAME in COV_TUNE.H.

Default MS Sans Serif

cBaseMonoFontName Property

Specifies a base font name for any interface elements that require a monospaced font.

The default for this attribute when no preference has been saved to the registry is, first, any Visual FoxPro resource file entry for MODIFY COMMAND window preferences. Otherwise, the coverage engine looks for a Visual FoxPro registry entry for the Trace window. If one of these is not found, the coverage engine uses the #DEFINE constant COV_DEFAULT_MONO_FONTNAME in COV_TUNE.H.

Default Courier New

cCovFilesAlias Property

Specifies the name of the cursor holding names of source files the Coverage Profiler should not locate and analyze. The engine fills this cursor with a set of file names using the CreateCoverageFileNameCursor( ) and FillCoverageFileNameCursor( ) methods. You can use the coverage engine abstract AdjustCoverageFileNameCursor( ) method to add file names to the set.

Default IgnoredFiles

cDefaultWritePath Property

Specifies the path to cSourceFile. Supplies the default path for any file output of the Coverage Profiler.

Default ""

cMarkExecuted Property

Specifies the character(s) that marks lines of code that executed according to the current coverage log. Although this property defaults to an empty string, the engine uses the SetMarks( ) procedure to adjust the length of cMarkExecuted and cMarkNotExecuted to equal lengths so the appearance of marked code is unspoiled. At startup, therefore, cMarkExecuted's value is SPACE(4), to match the default length of cMarkNotExecuted.

Default ""

cMarkNotExecuted Property

Specifies the character(s) that marks lines of code not run during the current coverage log.

Default |+SPACE(3)

cSavedSkipFiles Property

Specifies the name of the table (.dbf) file that contains the list of source files skipped during coverage analysis.

Default ""

cSavedTargetDBF Property

Specifies the name of the table (.dbf) file that contains the coverage results.

Default ""

cSkippedAlias Property

Specifies the name of the cursor which holds names of source files the Coverage Profiler could not locate or analyze. The engine fills this cursor using the CreateSkippedCursor( ) method and saves it to disk using the SaveSkippedCursor( ) method.

Default SkippedFiles

cSourceAlias Property

Specifies the name of the source which holds the appended and processed records stored by the coverage text log. The engine creates this cursor in the CreateSourceCursor( ) method and provides the abstract AdjustSourceCursor( ) method so you can add fields, index tags, and so on. Then the engine fills the cursor with records from the text log in the FillSourceCursor( ) method.

Default FromLog

cSourceFile Property

Specifies the name of the file to be analyzed. You can specify this value as the first parameter of the DO (_COVERAGE) WITH command.

Default ""

cSuspendedLog Property

Specifies the name of the current coverage log (SET(COVERAGE)) if the Coverage Profiler suspends coverage data logging. This property is set with the SuspendCoverage( ) method.

Default ""

cTargetAlias Property

Specifies the target cursor which holds the names of classes, source file names, coverage-marked procedure source code, and coverage statistics. The engine creates this cursor in the CreateTargetCursor( ) method and provides the abstract AdjustTargetCursor( ) method so you can add fields, tags, and so on. Then the coverage engine locates and analyses source code in the FillTargetCursor( ) method.

Default MarkedCode

iLenExecuting

Specifies the length of the field in the source work file that contains information about the object and method name that is running covered lines of code when the #DEFINE COV_TOPSPEED in COV_TUNE.H is false (.F.). You can decrease the default value, with care, if your fully-qualified object names and method names are short and if you want to conserve the disk space used by the Profiler work files. See COV_TUNE.H for more information about this value. See Conserving Disk Space During Coverage Runs for more information on using iLenExecuting.

Default 115

iLenDuration

Specifies the length, including decimal places, of the numeric field in the source file.

Default 8 (in Visual FoxPro versions 5.0 and 6.0. Defaults to 11 in later versions.)

iLenHostFile

Default 115

iLenObjClass

Specifies the length of a field in the source and target work files that holds information about the object executing Covered lines of code when the #DEFINE COV_TOPSPEED in COV_TUNE.H is false (.F.). To conserve the disk space used by the Profiler work files, you can decrease the default value, with care, if your object names are short. You can do this even when object names are fully-qualified by their container hierarchy. See COV_TUNE.H for more information about this value. See Conserving Disk Space During Coverage Runs for more information on using iLenObjClass.

Default 115

lBaseFontBold Property

Specifies a base font attribute (bold) for any displayed characters.

Default .F.

lBaseFontItalic Property

Specifies a base font attribute (italic) for any displayed characters.

Default .F.

lBaseMonoFontBold Property

Specifies a base font attribute (bold) for any displayed characters that require a monospaced font.

Default .F.

lBaseMonoFontItalic Property

Specifies a base font attribute (italic) for any displayed characters that require a monospaced font.

Default .F.

lError Property

A flag that specifies an error occurred; set by the Error method and checked by critical operations during processing.

Default .F.

lInCoverageFrame Property

Specifies whether the Coverage Profiler opens in the main Visual FoxPro window. The default displays Coverage Profiler elements in a separate window.

Default .F.

lInProfileMode Property

Specifies whether the Coverage Profiler analyzes the coverage log for profiling characteristics. In the default setting, the Coverage Profiler analyses for coverage characteristics.

Default .F.

lMarkAllOnLoad Property

Specifies whether all source code is marked when a target file is loaded. In the default setting, individual source code records are marked one at a time as required by the user.

Default .F.

lSaveFormPositions Property

Specifies whether all forms in the formset receive an instance of cov_SavePosition to handle form positions and size.

Default .F.

lSmartPath Property

Specifies whether the engine retains a reference to directories in which you have located files.

Default .T.

lStartInProfileMode Property

Specifies how the lInProfileMode property is set when each coverage log loads. This value is significant when the property lMarkAllOnLoad is set to true (.T.).

Default .F.

lTurnedOffTrace Property

Specifies whether the Coverage Profiler issued SET TRBETWEEN OFF during processing.

Default .F.

lUsingRegistry Property

Specifies whether user options are saved to and restored from the Microsoft Windows registry.

Default .T.

lUsingStatusBar Property

Determines whether feedback messages during processing are displayed in the status bar or as a WAIT WINDOW NOWAIT message. The status bar is used when the Coverage Profiler runs in the main Visual FoxPro window or in Unattended mode and STATUS BAR is ON.

Default .F.

lVFP5 Property

Specifies whether the Coverage Profiler is running in Visual FoxPro 5.0.

Default (ATC("FoxPro 05",VERSION( )) > 0)

nBasefontsize Property

Specifies a base font size for any displayed characters.

Default 11 (defaults to 8 in version 5.0 and 6.0)

oFrame Property

Specifies a reference to the Coverage Frame window when the Coverage Profiler exists in a separate window. The engine makes sure this window exists before displaying any related dialog boxes or other elements (including common dialog subclasses, SET TALK display, and so on).

Default .NULL.

AddFormPositionSaver( ) Method

Adds an instance of cov_SavePosition to a form to save and restore form size and position.

AddFormPositionSaver(toForm)

Return Values

None

Parameters

toForm
Specifies that the cov_SavePosition object is saved to a form.

AddPath( ) Method

Extracts directory information to concatenate to SET(PATH).

AddPath(tcFileName)

Return Values

None

Parameters

tcFileName
Specifies a file name.

Remarks

Extracts the directory information from the passed file name, tcFileName, to concatenate into the current SET(PATH).

AddRegisteredAddin( ) Method

Adds file name to the aAddIns array.

AddRegisteredAddin(tcFileToAdd)

Return Values

None

Parameters

tcFileToAdd
Specifies the file to add to the aAddIns array.

Remarks

Adds a file name, TcFileToAdd, to the aAddIns array when called by the RunAddIn( ) method after an add-in runs successfully.

AdjustCoverageFilenameCursor( ) Method

Enables adding files to cursor list of unanalyzed files.

AdjustCoverageFilenameCursor(tcTarget)

Return Values

NOT THIS.lReturn

Parameters

tcTarget
Specifies the name of the cursor you want to modify.

Remarks

Makes it possible for you to add files that you do not want analyzed to the cursor's file list when called by the CreateCoverageFilenameCursor( ) method. See the cCovFilesAlias property.

AdjustSourceCursor( ) Method

Abstract method that makes it possible for you to add index tags and custom fields to the source cursor when called by the CreateSourceCursor( ) method.

AdjustSourceCursor(tcSource)

Return Values Values

NOT THIS.lReturn

Parameters

tcSource
Specifies the name of the cursor containing the source records.

AdjustTargetCursor( ) Method

Abstract method called by the CreateTargetCursor( ) method makes it possible for you to add index tags and custom fields to the target cursor.

AdjustTargetCursor(tcTarget)

Return Values Values

NOT THIS.lReturn

Parameters

tcTarget
Specifies the name of the table being modified.

ClearStatus( ) Method

Removes a message from the status bar or performs a CLEAR WAIT WINDOW command. See lUsingStatusBar property.

ClearStatus( )

Return Values

None

Parameters

None

CreateCoverageFilenameCursor( ) Method

Creates a cursor to hold the names of source files that the Coverage Profiler should not locate and analyze. See the cCovFilesAlias property.

CreateCoverageFileNameCursor( )

Return Values

lReturn AND NOT THIS.lError

Parameters

None

CreateForms( ) Method

At startup, displays the Coverage Profiler window after workfiles have been set up if the coverage engine is not in Unattended mode. In the coverage engine base class, this method creates only the Coverage frame (if the engine is not running in the Visual FoxPro window). Subclasses can augment this method to add their own dialogs.

CreateForms( )

Return Values

None

Parameters

None

CreateSkippedCursor( ) Method

The engine creates this cursor by looking for deleted records in the Source table, because skipped records are deleted when the engine encounters file names that cannot be located or that are in the Ignored Files list during its load of the log file. See the CSkippedAlias property.

CreateSkippedCursor(tcSource, tcSkipped)

Return Values

NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
TcSkipped
Specifies the alias of the cursor containing the skipped records.

CreateSourceCursor( ) Method

Creates a source cursor in the following format:

CREATE CURSOR(cSource) ;
(Duration n(COV_LEN_DURATION,N_COVLOG_PRECISION), ;ObjClass c(COV_LEN_OBJCLASS), ;Executing c(COV_LEN_EXECUTING), ;Procline i, ;Hostfile c(COV_LEN_HOSTFILE), ;Stacklevel I, ;FileType c(4) )

The Stacklevel field is excluded when the value of the lVFP5 property is true (.T.). See COV_TUNE.H for #DEFINE field lengths.

CreateSourceCursor(tcSource)

Return Values

lReturn AND NOT THIS.lError

Parameters

tcSource
Specifies the name of the cursor containing the source records.

CreateTargetCursor( ) Method

Creates a target cursor in the following format:

CREATE CURSOR (cTarget) ;
(Hostfile c(COV_LEN_HOSTFILE), ;ObjClass c(COV_LEN_OBJCLASS), ;FileType c(4), ;Marked   m, ;Profiled m, ;SourceCode m, ;Coverable i, ;Covered i, ;ObjTotal i, ;ObjHits i)

See COV_TUNE.H for #DEFINE field lengths.

CreateTargetCursor(tcSource, tcTarget)

Return Values

NOT THIS.lError

Parameters

tcSource
Specifies the name of the file to analyze.
TcTarget
Specifies the name of the file you want to modify.

Remarks

The target file contains one record for each of the following in the coverage log:

  • An ASCII source file.
  • A class contained in an ASCII source file.
  • A class contained in a .vcx or .scx file.
  • A stored procedure list in a .dbc file.
  • A Data Environment class or other Data Environment member class (such as a cursor) in a .frx or .lbx source file.

DeleteRegisteredAddin( ) Method

Removes a file name from the aAddIns array.

DeleteRegisteredAddin(tcFileToDelete)

Return Values

None

Parameters

tcFileToDelete
Specifies the add-in to remove from the registry.

Remarks

Called by the RunAddIn method after an add-in does not run successfully, whether the Registry is currently in use or not.

DisplayProjectStatistics( ) Method

Enables reporting after project statistics have been gathered in GetProjectStatistics( ).

DisplayProjectStatistics(tcSource, tcTarget, tcProject)

Return Values

NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.
tcProject
Specifies the alias of the project being analyzed.

DoMessage( ) Method

Displays tcMessage.

DoMessage(tcMessage [, tnMessageBoxOptions [, tcMessageBoxTitle]])

Return Values

liReturn

Parameters

tcMessage
Specifies the message that appears in the MESSAGEBOX.
TnMessageBoxOptions
Specifies the MESSAGEBOX nDialogBoxType setting.
TcMessageBoxTitle
Specifies the MESSAGEBOX cTitleBarText setting.
LiReturn
Specifies any return value from MESSAGEBOX( ), or 0 if a WAIT WINDOW executes.

Remarks

If the Coverage Profiler is running in Unattended mode, the message is displayed in a WAIT WINDOW TIMEOUT window so it does not prevent further processing. You can specify the timeout value using COV_TIMEOUT_SECS (a #DEFINE in COV_TUNE.H).

Error( ) Method

Sets the dialog error flag.

Error(nError, cMethod, nLine)

Return Values

None

Parameters

nError
Specifies the Visual FoxPro error number.
CMethod
Specifies the name of the method that caused the error.
NLine
Specifies the line number where the error occurred.

Remarks

Depending on the value of COV_DEBUG (a #DEFINE in COV_TUNE.H), this will display an error MESSAGEBOX and release the engine or display a WAIT WINDOW with error information and invoke the native Visual FoxPro error handler to make it possible for you to cancel, suspend, or ignore the current error.

FillCoverageFileNameCursor( ) Method

Adds files to the list of ignored files.

FillCoverageFileNameCursor( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

CreateCoverageFileNameCursor( ) calls this method to add the names of the coverage engine file set to the group of files that should be ignored during processing. This method is a hard-coded set of INSERTs in the base coverage engine. You can override this set in a subclass designed to read in a set of file names from a text file generated from the Coverage.pjx file list.

FillFileTypeArray( ) Method

Initializes the aFileTypes array with known file extensions. See the aFileTypes property.

FillFileTypeArray( )

Return Values

NOT(EMPTY(THIS.aFileTypes[1,1]) OR THIS.lError)

Parameters

None

FillOneTargetRecord( ) Method

Adds unmarked source code to memo field.

FillOneTargetRecord(tcSource, tcTarget, tlFillingAll)

Return Values

lReturn AND(NOT THIS.lError)

Parameters

tcSource
Specifies the name of the table containing the source records.
TcTarget
Specifies the name of the table being modified.
TlFillingAll
Specifies whether all records are processed in a loop, which changes the user feedback and displayed character handling.

Remarks

Places the unmarked source code for a target record into the appropriate memo field for later marking using a different strategy to find the right code for each type of source code. When COV_TOPSPEED is not #DEFINEd true (.T.), this method also places certain initial statistics into the Target file.

FillSourceCursor( ) Method

APPENDs the coverage log contents to the coverage analysis source file.

FillSourceCursor(tcSource)

Return Values

lReturn

Parameters

tcSource
Specifies the name of the source file.

Remarks

This method calls the SourceAvailable( ) method to eliminate records that refer to source files unavailable for analysis. It marks these records deleted in the source cursor.

FillTargetCursor( ) Method

Calls the FillOneTargetRecord( ) method for all target records in a loop.

FillTargetCursor(tcTarget)

Return Values

(THIS.iTargetReccount > 0 AND NOT THIS.lError)

Parameters

tcTarget
Specifies the target file that receives the processed results.

Remarks

Replicates the ObjHits statistics from the CreateTargetCursor( ) method for additional records referring to the same source files with the target files. See the CreateTargetCursor( ) method.

FilterListByLocation( ) Method

Provides a placeholder for future enhancements.

FilterListByLocation( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

FilterListByLocation( ) can be called either when a log loads or in response to a user action, with or without the Coverage Profiler application. This method is abstract in the engine.

GetAlias( ) Method

Returns the current or default alias of a Coverage Profiler workfile type.

GetAlias(tAlias, tcWhichProp)

Returns

cReturn

Parameters

tAlias
Specifies the alias of a file.
tcWhichProp
Specifies the workfile type (currently, either Source or Target) of the current default.

Remarks

GetAlias( ) returns either a currently used alias or the default alias of one of the Coverage Profiler workfile types. The valid workfile types include the following:

"SOURCE","TARGET","SKIPPED","COVFILES", and "PROJECT"

(The list of types is #DEFINEd in COV_SPEC.H as COV_KNOWN_ALIAS_PROPERTIES.) Each workfile type matches one c…Alias property to specify the default alias for this workfile.

The Coverage Profiler usually has a cursor open using each one of the workfile default aliases. However, the Coverage Profiler is capable of handling many sets of workfiles at the same time, within its data session, as long as you specify separate aliases for each one. The GetAlias( ) method and the system of defined work types, plus c…Alias, properties make it possible for you to have default alias names without the default aliases being hard-coded.

The engine methods that process the workfiles use aliases as parameters, so you can specify which source, target, or other file you are interested in at any time. Because you usually are interested only in one set of workfiles, however, these methods all use the GetAlias( ) methods to specify which alias and workfile default type to seek if you do not pass them a specific alias or aliases.

GetFontsFromUser( ) Method

Creates an instance of a common dialog subclass to ask the user to set font properties. If lUsingOCXs is False (.F.) or there has been an error creating an instance of the common dialog, the method uses the GETFONT( ) method. If the first parameter, tlBaseMonoFont, is True (.T.), the method shows only monospaced fonts and fills the monospaced font attribute properties of the engine. If this parameter is False (.F.), the second set of base font attribute properties is filled from a list of all available screen fonts.

See to the GetResourceLocation( ) method for more information on the lUsingOCXs property.

GetFontsFromUser(tlBaseMonoFont, toMemberHost )

Return Values

lFontChange AND NOT THIS.lError

Parameters

tlBaseMonoFont
Specifies the default monospace font style.
ToMemberHost
Specifies a reference to the current Coverage object.

GetProjectStatistics( ) Method

Creates a cursor containing project information.

GetStatistics(tcSource, tcTarget, tcProject)

Return Values

lReturn

Parameters

tcSource
Specifies the name of the alias containing the source records.
tcTarget
Specifies the name of the alias being modified.
tcProject
Specifies the project containing the source files.

Remarks

The information contained in the cursor is in the following format.

CREATE CURSOR(cProject) ;

(Hostfile c(COV_LEN_HOSTFILE), ;FileType c(4), ;Coverable n(8), ;Covered n(8), ;ObjTotal n(8), ;ObjHits n(8))

GetProjectStatistics( ) creates a header file in this cursor, indicating the project to which this cursor applies and fills this cursor with statistics drawn from the current coverage log that apply to each source file in the project. If necessary, GetProjectStatistics( ) calls MarkOneTargetRecord( ) for any project files that have not yet had their source code marked.

GetRegisteredAddins( ) Method

Fills the aAddIns array and the cAddIn property.

GetRegisteredAddins( )

Return Values

None

Parameters

None

GetRegistryKeyValue( ) Method

Retrieves registry value of user option

GetRegistryKeyValue(tcOption, tDefaultValue, tcPath)

Return Values

vReturn

Parameters

tcOption
Specifies the file type option.
tDefaultValue
Specifies the default registry value.
tcPath
Specifies RegKey.

Remarks

This method, typically used at startup, uses the registry-handling member of the toolbar in the engine formset to get a registry key value for a user option. It converts the registry value to other TYPE( )s as required and compares this TYPE( ) to the passed value, tDefaultValue. It returns the registry value or the default value if the registry value is not found or is of the wrong type.

GetResourceLocation( ) Method

Specifies whether GETFILE( )/ShowOpen( ) strategy or PUTFILE( )/ShowSave( ) strategy is followed.

GetResourceLocation(tcHost, tcTitle, tcCDLFilter, tcFileName, tcWhichDialog, [toMemberHost] )

Return Values

lcFileName

Parameters

tcHost
Specifies the name of the file the method is starting from, usually seeking the matching file name of the uncompiled version of the code. If it is passed, it provides information for the common file dialog .InitDir property.
tcTitle
Specifies the title to use in the dialog or, in the GETFILE( )/PUTFILE( ) version, to use as a WAIT WINDOW NOWAIT prompt. If tcHost also is passed and includes a file name, then this information is added to the dialog title or prompt.
tcCDLFilter
Specifies the file types allowed in the dialog. This parameter is expressed in the format required by the common dialog filter expression. If the GETFILE( )/PUTFILE( ) is called, the method parses the common dialog filter to put it into appropriate format for the two Visual FoxPro functions.
tcFileName
Specifies the default file name to display.
tcWhichDialog
Specifies the GETFILE or PUTFILE.
toMemberHost
Specifies an optional form reference that can be passed to indicate where the dialog is displayed. If toMemberHost is not passed, the file dialog will display relative to the Coverage frame (if the Coverage frame exists) or to the first form in the formset collection (if the Coverage Profiler is in the Visual FoxPro window).

Remarks

Adds a member of the appropriate common dialog subclass (depending on the value of tcWhichDialog) if this is the first call. The dialog subclasses differ in how they set various flags.

Note This method provides for additional dialog subclasses, showing a Help file or print dialog, to be instantiated and used in the future.

If a common dialog subclass or .ocx-related error occur in the Coverage Profiler, this method sets the lUsingOCXs property to false (.F.) and uses GETFILE( )/PUTFILE( ).

You can set the #DEFINE COV_USE_OCXS if you prefer to default to the native Visual FoxPro functions even if there are no OCX errors.

GetTableName( ) Method

Generates file names for unattended operation.

GetTableName(tcWhichSuffix)

Return Values

cLogfileStem+SUFFIX[+n]+.dbf

Parameters

tcWhichSuffix
Specifies which file extension to use.

Remarks

This method allows the coverage engine to generate file names with which to save its work to disk without overwriting existing files. Generally it just supplies file name defaults, but in Unattended mode, this method creates the file names without user intervention. Each method that saves a file to disk calls GetTableName( ) with a specific suffix; for example, in the SaveSkippedCursor:

cDBFName = ; THIS.GetTableName(COV_SKIPFILEDBF_SUFFIX)

GetTableName( ) uses the path and stem of the current log file name (THIS.cSourceFile) and attaches the appropriate suffix to this stem plus a digit, followed by the DBF extension. For example, Testlog.txt would produce TESTLOG_SKIP1.DBF in the previous example.

GetTableName( ) then increments the digit if the generated file name exists, until it finds a name that does not exist.

The default suffixes are #DEFINEs in COV_TUNE.H.

LockScreens( ) Method

Freezes or releases LockScreen properties and MousePointer properties for all members of _Screen during various long procedures.

LockScreens(tlOn)

Return Values

Logical. .T.

Parameters

tlOn
Specifies whether to lock the Lockscreen and MousePointer properties.

MarkAllTargetRecords( ) Method

Calls the MarkOneTargetRecord( ) method for all target records in a loop. Can be called because lMarkAllOnLoad is true (.T.) or because the coverage engine is in Unattended mode.

MarkAllTargetRecords(tcSource, tcTarget)

Return Values

NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.

MarkCodeLine( ) Method

Creates a marked-up version of a line of code, plus coverage statistics.

MarkCodeLine(tcLine, tiExecuted, tnFirst, tnAverage)

Return Values

CMarkedLine

Parameters

tcLine
Specifies the line of code.
tiExecuted
Specifies the number of times tcLine was run.
tnAverage
Specifies the average length of time to run.

Remarks

In Coverage mode, MarkCodeLine( ) marks code as "Executed" if tiExecuted is a positive number and "not Executed" if tiExecuted is 0. In Profile mode, MarkCodeLine( ) marks coverage statistics appropriately for the line. In either mode, MarkCodeLine( ) marks code as uncoverable (preceded by spaces) if tiExecuted is .NULL.

MarkOneTargetRecord( ) Method

Determines the marked status of the current line.

MarkOneTargetRecord(tcSource, tcTarget, tlFillingAll)

Return Values

lReturn AND (NOT THIS.lError)

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the record being modified.
tlFillingAll
Specifies whether other target records are being processed. If all records are processed in a loop, then the user feedback and handling of displayed characters changes.

Remarks

Determines whether the current target record, tcTarget, is already marked in the current coverage mode and, if not, passes the relevant information to the MarkTargetCoverage( ) method for processing.

MarkTargetCoverage( ) Method

Marks up a copy of the source and REPLACEs a memo field in the target file.

MarkTargetCoverage(tcSource, tcTarget)

Return Values

NOT (EMPTY(cMemo) OR THIS.lError)

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.

Remarks

MarkTargetCoverage( ) creates a marked-up version of tcSource and REPLACEs a memo field in the target file, tcTarget, (whether the code is for a class or a full procedure file).

To perform this action, the method starts with the sourcecode memo. The memo field REPLACEd depends on whether Coverage Profiler is marking Profiler or Coverage information, because the Target record retains both sets of marked-up code. This method parses the source code and evaluates its statistics line by line. By default, this method calls the MarkCodeLine( ) method to mark each line when it has the appropriate statistics. However, the way this method marks the code line is #DEFINEd as COV_MARK_CODE_LINE in COV_TUNE.H, not directly implemented as a call to the MarkCodeLine( ) method. This makes it possible for you to replace the call to the MarkCodeLine( ) method with a different marking system. A second #DEFINE, COV_TOPSPEED, in COV_TUNE.H also makes it possible for you to switch the MarkCodeLine( ) call to a simpler, in-line marking system for fastest response time.

MarkTargetCoverage( ) evaluates each line to find out whether it was executed, how many times it was executed, and its execution timings (first and average) when in Profile mode. However, many lines are considered uncoverable in Coverage Profiler. These lines, such as comments, DEFINE CLASS and ELSE/Otherwise statements, and lines within TEXT … ENDTEXT, do not appear in coverage logs, because they are not executable.

Note Other uncoverable code lines include #DEFINE statements, empty lines, continuations of executing lines, and parameter lines.

This method sets the number of times these lines run to .NULL. These lines are not considered when Coverage Profiler compiles statistics. In addition, lines broken by continuation symbols (semicolons) are considered as a single line of code and marked only on the last line.

OrderListByTime( ) Method

Provides a placeholder for future enhancements and subclasses.

OrderListByTime( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

OrderListByTime( ) is abstract in the engine.

PassedProperParams( ) Method

PassedProperParams(tcFile, tlUnattended, tcAddIn)

Return Values

lReturn

Parameters

tcFile
Specifies the name of the log file.
tlUnattended
Specifies whether to run in Unattended mode.
tcAddIn
Specifies the add-in file name(s).

Remarks

Test at startup to determine whether passed parameters are appropriate to the class. If any passed parameters are not appropriate TYPE( ), provides a MESSAGEBOX showing what parameters may be passed and RETURNs false (.F.), preventing any further coverage processing, as well as the creation of an instance of the class.

This method uses a MESSAGEBOX for feedback and stops processing even if the Coverage Profiler is starting up in Unattended mode. If you are setting up the Coverage Profiler for automated testing, be sure your calling program sends correct parameters or the analysis will not proceed.

RestoreCoverage( ) Method

Resumes coverage logging from suspended operation.

RestoreCoverage( )

Return Values

None

Parameters

None

Remarks

If the Coverage Profiler previously suspended coverage logging, this method gives the user a chance to resume coverage logging when the Coverage Profiler releases. The user can choose to overwrite this previous log, append new log entries to it, or not resume coverage logging at that time.

RunAddin( ) Method

Runs an add-in file.

RunAddin(tcAddin)

Return Values

lReturn AND NOT THIS.lError

Parameters

tcAddin
Specifies the name of the file to run.

Remarks

RunAddin( ) runs a file (.scx, .fxp, .app, .prg, .qpx, .qpr, .mpx, or .mpr) that adds functionality to the Coverage object. If you do not pass a file name, RunAddin( ) runs the file specified by the cAddIn property.

The tcAddin file must accept an object reference, because the file is run by passing a reference to the coverage form, as in the following examples (depending on the file type):

DO (cFileName) WITH THIS
DO FORM (cFileName) WITH THIS

SaveFormsetAttributes( ) Method

Saves general frame and formset characteristivs to the registry as Profiler ends.

SaveFormsetAttributes( )

Return Values

None

Parameters

None

SaveOptionsToRegistry( ) Method

Saves current user values to the registry.

SaveOptionsToRegistry( )

Return Values

lSuccess

Parameters

None

Remarks

SaveOptionsToRegistry( ) can be called any time the user's current values should be saved to the registry. It saves the following user preferences:

Work options group
lStartInProfileModelSmartPathlMarkAllOnLoadcMarkExecutedcMarkNotExecutedlRegisterAddIn
UI options group
Font name, size, italic, bold for base monospace font

There are a few registry settings not saved by this method, because they have to be done at specific moments during the life of the engine. These are:

Coverage or the main Visual FoxPro frame (must be done when the user makes a choice and will be in effect next session but does not correspond to or affect any of the coverage property values for this session).

Registered add-ins (this array is manipulated over the life of the session, and the full set of file names it contains is saved to the registry at the end of the session).

SaveSkippedCursor( ) Method

Saves the skipped files cursor to disk.

SaveSkippedCursor(tcSkipped)

Return Values

RETURN NOT THIS.lError

Parameters

tcSkipped
Specifies the cursor containing skipped records.

Remarks

Saves the skipped files cursor to disk if it contains any records and places the name of the table on disk in the cSavedSkipFiles property. See the cSkippedAlias and cSavedSkipFiles properties.

SaveTargetToDisk( ) Method

Saves output file, including marked-up code and statistics, to disk.

SaveTargetToDisk(tcTarget)

Return Values

lReturn and NOT THIS.lError

Parameters

tcTarget
Specifies the name of the modified table saved to disk.

SetFontValues( ) Method

Sets up initial font attribute values using registry key values and other defaults.

SetFontValues( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

See cBaseFontName and cBaseMonoFontName for information on how the coverage engine derives these defaults.

SetFormsetAttributes( ) Method

Reads and restores general frame and formset characteristics.

SetFormsetAttributes( )

Return Values

None

Parameters

None

Remarks

Reads and restores general frame and formset characteristics from the registry as Profiler starts.

SetLogFile( ) Method

Attempts to set up a file for analysis.

SetLogFile(tcFile)

Return Values

lReturn

Parameters

tcFile
Specifies the name of the file to analyze.

Remarks

If you pass no string value, the SET COVERAGE value is used. If there is no current log file, the method prompts for a file name. If a log file can be set successfully, the method returns .T. If the user designates no log file, the method returns. F. If no new log is specified, the Coverage Engine returns to the currently loaded log, if one is loaded, or releases, if no log is loaded.

SetMarks( ) Method

Synchronizes and returns the values of cMarkExecuted and cMarkNotExecuted.

SetMarks( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

Synchronizes the lengths of cMarkExecuted and cMarkNotExecuted and returns the values of either or both properties to a default if they are not character-type or both properties are empty. If user options are not available from the registry, this method gets defaults from the #DEFINE values, COV_DEFAULT_MARKNOTEXECUTED and COV_DEFAULT_MARKEXECUTED, which you can set in COV_TUNE.H. A third #DEFINE, COV_DEFAULT_MARKSPACING, makes sure there is space between the marks and the line of code.

SetRegisteredAddins( ) Method

Saves the file names in the aAddIns array to registry values.

SetRegisteredAddins( )

Return Values

None

Parameters

None

SetRegistryKeyValue( ) Method

Sets a registry key value from a user option.

SetRegistryKeyValue(tcWhichOption, tValue)

Return Values

NOT THIS.lError

Parameters

tcWhichOption
Specifies the user option to be accessed.
tValue
Specifies the value of tcWhichOption.

Remarks

SetRegistryKeyValue( ) uses the registry-handling member of the toolbar in the engine formset to set a registry key value from a user option. It converts all values to string type before sending them to the registry-handler to apply to the registry.

SetUIFonts( ) Method

Provides font preferences.

SetUIFonts( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

Abstract in the engine, called by SetUiOptions, SetUIFonts( ), makes it possible for the user font preferences saved in the various Base and BaseMont font properties to be applied to appropriate displayed characters .

SetUIOptions( ) Method

Sets UI options and defaults.

SetUIOptions( )

Return Values

lReturn and NOT THIS.lError

Parameters

None

Remarks

Sets up initial UI options according to user preferences or defaults after initial setup of workfiles. This group of options includes fonts and the array of registered add-ins. It is required for UI display and user interaction with the workfiles, after they have been processed.

SetUIToShowCode( ) Method

Enables display of current target record in new log.

SetUIToShowCode(tcTarget)

Return Values

NOT THIS.lError

Parameters

tcTarget
Specifies the name of the table being modified.

Remarks

Abstract in the engine, called at the end of SetupWorkFiles( ) to allow UI to show current Target record in the newly loaded log.

SetUIToShowFileStates( ) Method

Enables reporting of log loading status.

SetUIToShowFileStates(tcSource, tcTarget)

Return Values

NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.

Remarks

Abstract in the engine, called at the end of SetupWorkFiles( ) to allow UI to indicate success or failure or current attempt to load a log.

SetUpWorkFiles( ) Method

Sets and validates a coverage log.

SetupWorkFiles(tcLogFile, tcSource, tcTarget)

Return Values

lReturn AND NOT THIS.lError

Parameters

TcLogFile
Specifies the name of the text log to analyze.
tcSource
Specifies the name of the file to use as source.
tcTarget
Specifies the name of the cursor being modified.

Remarks

SetUpWorkFiles( ) sets and validates a coverage log and then creates and fills the source and target work files for this text log. If the user choice is the same as the log file currently loaded, the method asks the user whether the log should be reloaded and analyzed. It makes sure the log is not open in a text window before loading the log. If the user specifies lMarkAllOnLoad, it marks all records in the current mode (Coverage or Profile) after successfully filling the target file with source code entries. If Coverage Profiler is in Unattended mode, it marks all records in both Coverage and Profile mode after successfully filling the target file. If the load succeeds, this method also sets the cDefaultWritePath to mark the path of the text log and the cSourceFile property to hold the name of this text log.

SetWorkOptions( ) Method

Sets initial user defined options.

SetWorkOptions( )

Return Values

NOT THIS.lError

Parameters

None

Remarks

SetWorkOptions( ) sets up initial options according to user preferences or defaults before initial setup of workfiles. This group of options includes coverage marks and initial coverage mode and is required for processing the workfiles.

ShowProjectStatistics( ) Method

Runs coverage analysis figures against a Visual FoxPro project.

ShowStatistics(tcSource, tcTarget, tcProject)

Return Values

lReturn AND NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.
tcProject
Specifies the project containing tcSource.

Remarks

ShowProjectStatistics( ) calls GetProjectStatistics( ) and DisplayProjectStatistics( ) to run coverage analysis figures against a specific Visual FoxPro project set of files.

ShowStatistics( ) Method

Abstract in the base engine.

ShowStatistics( )

Return Values

NOT THIS.lError

Parameters

None

ShowStatus( ) Method

Places a message in the status bar or a WAIT WINDOW. See lUsingStatusBar property.

ShowStatus(cMessage)

Parameters

cMessage
Specifies the message to display in the status bar or WAIT WINDOW

SourceAvailable( ) Method

Replaces the current Source log compiled file name with the full path name of the file holding the uncompiled source code.

SourceAvailable( )

Return Values

lReturn

Parameters

None

Remarks

SourceAvailable( ) calls GetSourceLoc( ) if necessary to locate uncompiled source code. If the lSmarthPath property is true (.T.), it uses AddPath( ) to adjust SET (PATH) as the user specifies directories in which to find source files. RETURNs false (.F.) if the source file is on the Ignored Files list, if the file is of an unknown type, or if the uncompiled source code cannot be found.

SourceFileIsLog( ) Method

Checks the file name held in the cSourceFile property for valid coverage log format.

SourceFileIsLog( )

Return Values

lReturn

Parameters

None

SuspendCoverage( ) Method

Sets the cSuspendedLog property to the name of the current log.

SuspendCoverage( )

Return Values

None

Parameters

None

Remarks

Sets cSuspendedLog to the name of the current log and temporarily stops Visual FoxPro from writing this log, in one of the following cases:

  • The passed file name is the same as the current coverage log.
  • No file name is passed and the engine defaults to analyzing the current coverage log.

ToggleCoverageProfileMode( ) Method

Marks all target records in the new mode

ToggleCoverageProfileMode(tcSource, tcTarget)

Return Values

RETURN NOT THIS.lError

Parameters

tcSource
Specifies the name of the table containing the source records.
tcTarget
Specifies the name of the table being modified.

Remarks

If the lMarkAllOnLoad property is true (.T.), marks all target records in the new mode.

cSavedStackXML Property

Holds the name of the saved Coverage stacklevel analysis in XML form, after this file has been saved to disk. Set back to default ("") when you load a new log.

lStackXMLExtendedTree Property

If .T., then it generates more extensive StackXML, so profiling of each branch can assess effects of args and other factors for different invocations of a module. Defaults to .F. but if COV_LOAD_STACK_FROM_DBF is .T., then this more extensive XML is generated always.

ShowStackXML( )

ShowStackXML(tclog)

Returns

Logical. .T. if successful.

Parameters

tcLog
Specifies the name of the log file.

Remarks

ShowStackXML( ) calls GetStackXML(tcLog) and DisplayStackXML(tcXMLFile) to run coverage analysis figures against a specific Visual Foxpro project set of files. The tcLog argument is ignored if DEFINEd COV_LOAD_STACK_FROM_DBF is .T.

GetStackXML( ) Method

Generates Stack Analysis XML from tcLog.

GetStackXML(tclog)

Returns

Logical. .T. if successful.

Parameters

tcLog
Specifies the name of the log file.

Remarks

This function defaults to current Coverage source log. The tcLog argument is ignored if DEFINEd COV_LOAD_STACK_FROM_DBF is .T.

DisplayStackXML( ) Method

Displays XML file.

DisplayStackXML(tcXMLFile)

Returns

Logical. .T. if no error occurs.

Defaults to the current Stack Analysis filename indicated by the cSavedStackXML property.

Remarks

This method is similar to DisplayProjectStatistics, except that, instead of being abstract in the engine, cov_engine.DisplayStackXML performs a ShellExecuteA

ToggleStackXMLExtendedTree( ) Method

Toggles .lStackXMLExtendedTree.

ToggleStackXMLExtendedTree( )

Returns

Logical. .T. if no error occurs.

Parameters

None

Remarks

Designed to be augmented in subclasses to reflect this switch in the UI, change default XSLT on this basis, and so on. This method is similar to ToggleCoverageProfileMode.

*.cStackXSLT Property

Holds filename providing default XSL Transformation stylesheet to be applied by default to the generated Stack XML analysis document, when TransformStackXML is called.

*.TransformStackXML( ) Method

TransformStackXML(tcXSLT, tcXMLIn, tcXMLOut, tlNoShow)

Returns

Returns .T. if successful.

Parameters

tcXSLT
Specifies the name of the XSL file.
tcXMLIn
Specifies the name of the XML input file.
tcXMLOut
Specifies the name of the XML output file.
tlNoShow
Specifies whether to call DisplayStackXML.

Remarks

Applies tcXSLT (default to .cStackXSLT) to tcXMLIn (default .cSavedStackXML, GetStackXML( ) called if empty). Saves result to tcXMLOut (defaults to tcXMLIn-based generated name w/ HTM ext). If ! tlNoShow, calls DisplayStackXML( ).

See Also

Coverage Profiler Application


Cursor Object

Created when a table or view is added to the data environment for a form, form set, or report.

Cursor

Remarks

The cursor object makes it possible for you to specify or determine properties for the table or view when the form, FormSet or report is run.

Note that setting a cursor object property at run time generates an error (with the exception of the Filter and Order properties, which can be set at run time). For a new property setting to take effect, you must call the CloseTables and OpenTables methods for the data environment. Also, if you change the Order property at run time of a cursor that is involved in a one-to-many relationship, the one-to-many relationship is broken.

See Also

Cursor Object Properties, Methods and Events | DataEnvironment Object | Relation Object | Setting the Data Environment


Cursor Object Properties, Methods, and Events

Properties

Alias | Application | BufferModeOverride
CursorSource | Comment | Database
Exclusive | Filter | Name
NoDataOnLoad | Order | ReadOnly
Tag |  |

Events

Destroy Error Init

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | WriteExpression |

See Also

Cursor Object | CURSORGETPROP( ) Function | DataEnvironment Object | Relation Object


CursorAdapter Class

Supports handling a wide range of data sources as native Visual FoxPro cursors. These data source types include the following:

  • Native
  • Open Database Connectivity (ODBC)
  • ActiveX Data Object (ADO)
  • Extensible Markup Language (XML)
CursorAdapter

Remarks

The cursor opened by a CursorAdapter object is always a buffered cursor and defaults to Optimistic Row Buffering.

For more detailed information about the CursorAdapter class, see Data Access Management Using CursorAdapters.

See Also

Objects, Collections, and Classes | CursorAdapter Object Properties, Methods, and Events | Cursor Object | Relation Object | TABLEUPDATE( ) Function


CursorAdapter Object Properties, Methods, and Events

The following properties, methods, and events support extended cursor functionality and the use of data sources at the data environment and CursorAdapter level.

Properties

Alias | AllowDelete | AllowInsert
AllowSimultaneousFetch | AllowUpdate | Application
BaseClass | BatchUpdateCount | BreakOnError
BufferModeOverride | Class | ClassLibrary
Comment | CompareMemo | ConversionFunc
CursorSchema | CursorStatus | DataSource
DataSourceType | DeleteCmd | DeleteCmdDataSource
DeleteCmdDataSourceType | FetchAsNeeded | FetchMemo
FetchSize | Flags | InsertCmd
InsertCmdDataSource | InsertCmdDataSourceType | KeyFieldList
MaxRecords | Name | Parent
ParentClass | Prepared | SelectCmd
SendUpdates | Tables | Tag
UpdateCmd | UpdateCmdDataSource | UpdateCmdDataSourceType
UpdatableFieldList | UpdateGram | UpdateGramSchemaLocation
UpdateNameList | UpdateType | UseDeDataSource
UseMemoSize | WhereType |

Methods

AddProperty | Attach | AutoOpen
CursorAttach | CursorDetach | CursorFill
CursorRefresh | ReadExpression | ReadMethod
ResetToDefault | WriteExpression |

Events

AfterCursorAttach | AfterCursorClose | AfterCursorDetach
AfterCursorFill | AfterCursorRefresh | AfterCursorUpdate
AfterDelete | AfterInsert | AfterUpdate
BeforeCursorAttach | BeforeCursorClose | BeforeCursorDetach
BeforeCursorFill | BeforeCursorRefresh | BeforeCursorUpdate
BeforeDelete | BeforeInsert | BeforeUpdate
Destroy | Error | Init

See Also

CursorAdapter Class


Custom Object

Creates a custom, user-defined object.

Custom

Remarks

A custom, user-defined class can be created with DEFINE CLASS, or with the Class Designer. Issue CREATE CLASS to display the class designer.

Custom, user-defined classes are classes with properties, events, and methods, but with no visual representation. The same general rules that apply to defining other types of classes apply to defining custom classes.

See Object-Oriented Programming for additional information about creating custom objects as non-visual classes.

See Also

Custom Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Custom Object Properties, Methods, and Events

Properties

Application | BaseClass | Class
ClassLibrary | Comment | ControlCount
Controls | Height | HelpContextID
Left | Name | Objects
Parent | ParentClass | Picture
Tag | Top | WhatsThisHelpID
Width |  |

Events

Destroy Error Init

Methods

AddObject | AddProperty | NewObject
ReadExpression | ReadMethod | RemoveObject
ResetToDefault | SaveAsClass | ShowWhatsThis
WriteExpression Method | WriteMethod Method |

See Also

Custom Object | Object-Oriented Programming | CREATE CLASS | CREATE FORM | DEFINE CLASS |CursorToXML( ) Function


DataEnvironment Object

Created when you create a form, form set, or report. A DataEnvironment object functions as a container for the Cursor, CursorAdapter, and Relation objects associated with the form, form set, or report.

Note You can set only the following DataEnvironment properties at run time: DataSource, DataSourceType, InitialSelectedAlias, Name, OpenViews, and Tag. For a new property setting to take effect, you must call the CloseTables and OpenTables methods for the DataEnvironment object. Setting any other DataEnvironment properties at run time generates an error.
DataEnvironment

Remarks

You can define and subclass the DataEnvironment class. From a form, you can save the existing data environment as a visual class library (.vcx) file by selecting the form, choosing Save As Class from the File menu, and selecting DataEnvironment. All DataEnvironment properties, methods, and events are available as appropriate in the Properties window after you open the Class Designer. However, you can access the Data Environment Designer only from the Form Designer, not from the Class Designer.

At design time, you can add a preexisting DataEnvironment class to a form from a class library toolbar or in code using the AddObject method. However, Visual FoxPro considers the DataEnvironment class added in either manner as a member class, not a native data environment.

You can use the Form DEClass and DEClassLibrary properties to specify and load an external DataEnvironment class at design time or run time. Visual FoxPro supports the DEClass and DEClassLibrary properties for form (.scx), visual class library (.vcx), and program (.prg) files but not for form sets or in the Report Designer.

For more information, see the DEClass and DEClassLibrary properties. For more information about the data environment for forms and form sets, see Creating Forms.

See Also

Objects, Collections, and Classes | DataEnvironment Object Properties, Methods and Events | Form Object | AddObject Method | Cursor Object | CursorAdapter Class


DataEnvironment Object Properties, Methods, and Events

Properties

Application | AutoCloseTables | AutoOpenTables
Comment | DataSource | DataSourceType
InitialSelectedAlias | Name | Objects
OpenViews | Tag |

Events

AfterCloseTables | BeforeOpenTables | Destroy
Error | Init |

Methods

AddObject | AddProperty | CloseTables
OpenTables | ReadExpression | ReadMethod
RemoveObject | ResetToDefault | SaveAsClass
WriteExpression |  |

See Also

DataEnvironment Object | Creating Forms


DataObject Object

Container for data being transferred from an OLE drag source to an OLE drop target. Available at run time only.

oDataObject

Remarks

The DataObject object is a container for data being transferred from an OLE drag source to an OLE drop target, and exists only for the duration of an OLE drag-and-drop event. The DataObject object cannot be created programmatically and references to it become invalid once the OLE drag-and-drop operation is complete. The DataObject is passed as the oDataObject parameter in the OLEDragDrop, OLEDragOver, OLESetData, and OLEStartDrag events.

The DataObject can store multiple sets of data, each in a different format. Use the GetFormat and GetData methods to determine the data formats and data on the DataObject. Use the SetFormat, SetData, or ClearData methods to add data formats and data to the DataObject, or clear all data formats and data from the DataObject.

See Also

DataObject Object Properties, Methods and Events | OLE Drag-and-Drop Overview | OLEDragDrop Event | OLEDragOver Event | OLESetData Event | OLEStartDrag Event


DataObject Object Properties, Methods, and Events

Methods

ClearData | SetData
GetData | SetFormat
GetFormat |

See Also

DataObject Object | OLE Drag-and-Drop Overview | OLEDragDrop Event | OLEDragOver Event | OLESetData Event | OLEStartDrag Event


EditBox Control

Creates an edit box.

EditBox

Remarks

Use the EditBox control for editing a Character-type variable, array element, field, or memo field.

All standard Visual FoxPro editing features, such as cut, copy, and paste, are available for the edit box. The text in the edit box scrolls vertically and words are wrapped horizontally.

For additional information about creating edit boxes, see Using Controls.

See Also

EditBox Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


EditBox Control Properties, Methods, and Events

Properties

AddLineFeeds | Alignment | AllowTabs
Application | BackColor | BackStyle
BaseClass | BorderColor | BorderStyle
ClassLibrary | Class | ColorScheme
ColorSource | Comment | ControlSource
DisabledBackColor | DisabledForeColor | DragIcon
DragMode | EnableHyperlinks | Enabled
FontBold | FontCharSet | FontCondense
FontExtend | FontItalic | FontName
FontOutline | FontShadow | FontSize
FontStrikeThru | FontUnderline | ForeColor
Format | Height | HelpContextID
HideSelection | IMEMode | IntegralHeight
Left | Margin | MaxLength
MouseIcon | MousePointer | Name
NullDisplay | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData Property | OLEDropMode
OLEDropTextInsertion | ParentClass | Parent
PasswordChar | ReadOnly | RightToLeft
ScrollBars | SelectedBackColor | SelectedForeColor
SelectOnEntry | SelLength | SelStart
SelText | SpecialEffect | StatusBarText
TabIndex | TabStop | Tag
TerminateRead | Text | ToolTipText
Top | Value | Visible
WhatsThisHelpID | Width |

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
ErrorMessage | GotFocus | Init
InteractiveChange | KeyPress | LostFocus
Message | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | ProgrammaticChange
RightClick | UIEnable | Valid
When |  |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

See Also

EditBox Control


Empty Class

Creates an empty class that instantiates and releases quickly for use with business objects.

Empty

Remarks

The Empty class is only available within a program (.prg) file and cannot be defined in a visual class library (.vcx) class library.

The Empty base class contains no intrinsic properties, methods or events. You cannot subclass or add custom methods and events to the Empty class. However, at run time, you can add custom properties using the ADDPROPERTY( ) function or the SCATTER NAME...ADDITIVE command.

The Empty class is typically used in the following scenarios:

  • When adding properties to or removing properties from a running instance of the class using the ADDPROPERTY( ) and REMOVEPROPERTY( ) functions.
  • When using the SCATTER...NAME command with the ADDITIVE clause to populate contents from the current record.

See Also

Objects, Collections, and Classes | ADDPROPERTY( ) Function | REMOVEPROPERTY( ) Function | SCATTER Command


Exception Class

When an error occurs in the TRY block within a TRY...CATCH...FINALLY error handling structure, Visual FoxPro creates an Exception object automatically and uses the VarName memory variable specified in the CATCH TO clause to store a reference to the exception. The THROW command also generates an Exception object. However, if no TRY...CATCH...FINALLY structure traps the thrown exception, Visual FoxPro escalates the exception another error handler or Visual FoxPro's global error handler.

You can define and subclass the Exception class.

Exception

Remarks

Visual FoxPro supports the Exception class only in program (.prg) files.

Exception objects do not support all the various error information, including Component Object Model (COM), Open Database Connectivity (ODBC), and database triggers, that you can usually obtain from the AERROR() function. However, you can access AERROR() information inside the TRY...CATCH block.

Example

oError = CREATEOBJECT("exception")

See Also

Objects, Collections, and Classes | Exception Object Properties, Methods, and Events | TRY...CATCH...FINALLY Command | Structured Error Handling


Exception Object Properties, Methods, and Events

All properties, methods, and events for Exception objects are read/write at run time.

Properties

BaseClass | Class | ClassLibrary
Comment | Details | ErrorNo
LineContents | LineNo | Message
Name | Parent | ParentClass
Procedure | StackLevel | Tag
UserValue |  |

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | SaveAsClass | WriteExpression
WriteMethod |  |

Events

Destroy Error Init

See Also

Exception Class | TRY...CATCH...FINALLY Command | Structured Error Handling


Fields Collection (XMLTable)

Each XMLTable object contains, at most, a single Fields collection containing XMLField objects. Each XMLField represents the structure of a field that is meaningful to Visual FoxPro.

When an XMLAdapter object analyzes XML by executing its LoadXML or Attach methods, it factors the contained XML schema into one or more XMLTable objects and corresponding XMLField objects. Visual FoxPro translates the XML schema for each field, creates corresponding XMLField objects, and adds them to the XMLTable Fields collection.

XMLTable.Fields

See Also

Objects, Collections, and Classes | XMLTable Object Properties, Methods, and Events | XMLAdapter Class | LoadXML Method | Attach Method | XMLTable Class | XMLField Class


File Object

Instantiated when a file is added to a project.

File

Remarks

A file object is created and instantiated for each file added to a project. A file object provides an object reference to the file in the project, and allows you to determine information about the file and manipulate it through the File object properties and methods.

A project's files collection is composed of all the file objects in the project.

Note that a file object is a COM object, so assigning a file object reference to a memory variable creates a memory variable of class "Unknown Type."

See Also

File Object Properties, Methods and Events | Files Collection | Adding Files to a Project


File Object Properties, Methods, and Events

Properties

CodePage | Description | Exclude
FileClass | FileClassLibrary | LastModified
Name | ReadOnly | SCCStatus
Type |  |

Methods

AddToSCC | CheckIn | CheckOut
GetLatestVersion | Modify | Remove
RemoveFromSCC | Run | UndoCheckOut

See Also

File Object | Files Collection | Adding Files to a Project


Files Collection

A collection of file objects in a project.

Files

Remarks

The files collection consists of all the files in a project. Each file is an object that can be manipulated with the file object properties and methods.

Files in a file collection can be referenced by index number or name. For example, the following code opens the file that was first added to a project:

_VFP.ActiveProject.Files(1).Modify( )

The following code opens an editing window for Main.prg:

_VFP.ActiveProject.Files('Main.prg').Modify( )

Note that it isn't necessary to include the path with a file name.

For more information about the files collection and projects, see Project Manager Hooks under Application Development and Developer Productivity.

See Also

Files Collection Properties, Methods and Events | File Object | Project Manager Hooks | Application Development and Developer Productivity


Files Collection Properties and Methods

Properties

Count

Methods

Add Item

See Also

Files Collection | File Object | Project Manager Hooks | Application Development and Developer Productivity


Form Object

Creates a form to which you can add controls.

Form

Remarks

Forms have properties that determine their appearance, such as position, size, and color, and their behavior, for example, whether they are sizable. You can also use the Form Designer to design a form.

Forms can respond to events initiated by a user or triggered by the system. For example, you can write code in a form's Click event procedure that changes the color of the form when you click it. You can use methods to manipulate forms. For example, you can use the Move method to change a form's location and size. From within a program, you can use the Hide and Show methods to make forms transparent or visible at run time.

For additional information about creating Forms, see Creating Forms.

See Also

Form Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | FormSet Object | DataEnvironment Object


Form Object Properties, Methods, and Events

Properties

ActiveControl | ActiveForm | AllowOutput
AlwaysOnBottom | AlwaysOnTop | Application
AutoCenter | BackColor | BaseClass
BindControls | BorderStyle | BufferMode
Caption | Class | ClassLibrary
ClipControls | Closable | ColorSource
Comment | ContinuousScroll | ControlBox
ControlCount | Controls | CurrentX
CurrentY | DataEnvironment | DataSession
DataSessionID | DefOLELCID | DEClass
DEClassLibrary | Desktop | DrawMode
DrawStyle | DrawWidth | Enabled
FillColor | FillStyle | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderline | ForeColor | HalfHeightCaption
Height | HelpContextID | HScrollSmallChange
hWnd | Icon | KeyPreview
Left | LockScreen | MacDesktop
MaxButton | MaxHeight | MaxLeft
MaxTop | MaxWidth | MDIForm
MinButton | MinHeight | MinWidth
MouseIcon | MousePointer | Movable
Name | Objects | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData
OLEDropMode | Parent | ParentClass
Picture | ReleaseType | RightToLeft
ScaleMode | ScrollBars | ShowInTaskbar
ShowTips | ShowWindow | SizeBox
TabIndex | TabStop | Tag
Themes | TitleBar Property | Top
ViewPortHeight | ViewPortLeft | ViewPortTop
ViewPortWidth | Visible | VScrollSmallChange
WhatsThisButton | WhatsThisHelpID | Width
WindowType | WindowState | ZoomBox

Methods

AddObject | AddProperty | Box
Circle | Cls | Draw
Hide | Line | Move
NewObject | OLEDrag | Point
Print | PSet | ReadExpression
ReadMethod | Refresh | Release
RemoveObject | ResetToDefault | SaveAs
SaveAsClass | SetAll | SetViewPort
Show | ShowWhatsThis | TextHeight
TextWidth | WhatsThisMode | WriteExpression
WriteMethod | ZOrder |

Events

Activate | Click | DblClick
Deactivate | Destroy | DragDrop
DragOver | Error | GotFocus
Init | KeyPress | Load
LostFocus | MiddleClick Event | MouseDown
MouseMove | MouseUp | MouseWheel
Moved | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | Paint | QueryUnload
Resize | RightClick | Scrolled
Unload |  |

See Also

Form Object


FormSet Object

Creates a form set.

FormSet

Remarks

A form set is a container object that contains a set of forms. Form sets are similar to screen sets used in previous FoxPro versions.

For additional information about creating form sets, see Extending Forms with Form Sets.

See Also

FormSet Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | Form Object


FormSet Object Properties, Methods, and Events

Properties

ActiveForm | Application | AutoRelease
BaseClass | Buffermode | Class
ClassLibrary | Comment | DataEnvironment
DataSession | DataSessionID | FormCount
Forms | Name | Objects
Parent | ParentClass | ReadBackColor
ReadCycle | ReadForeColor | ReadLock
ReadMouse | ReadSave | ReadTimeOut
Tag | Visible | WindowList
WindowType |  |

Events

Activate | Deactivate | Destroy
Error | Init | Load
ReadActivate | ReadDeactivate | ReadShow
ReadValid | ReadWhen | Unload

Methods

AddObject | AddProperty | Hide
NewObject | ReadExpression | ReadMethod
Refresh | Release | RemoveObject
ResetToDefault | SaveAs | SaveAsClass
SetAll | Show | WriteExpression
WriteMethod |  |

See Also

FormSet Object | Extending Forms with Form Sets


FoxCode Object Reference

Provides meta-data for use by the scripts contained in the Data field used for custom IntelliSense functionality.

FoxCode.PropertyName[ = eValue]

Parameters

PropertyName
Specifies a property for the object.
eValue
Specifies a value for the property.

Properties

Property | Description
Abbrev | Contents of the Abbrev field
Case | Contents of the Case field
Cmd | Contents of the Cmd field
CursorLocChar | This is a special character denoting the location to place the cursor after script (Default is "~" character)
Data | Contents of the Data field
DefaultCase | Default Case setting of FoxCode as derived from the Version record (Type = "V")
Expanded | Contents of the Expanded field
Filename | Name of file being edited
FullLine | Full text from the line being typed currently
Icon | Icon for use with items array
Items Array for use in populating a dropdown list to be displayed as post script action. Requires ValueType = "L"
Items[1,1] – text to display in list
Items[1,2] – value tip for item

The only required element is the first element for each row in the Items array. By default the array is sorted ascended to allow for incremental seeks. Users can use the ItemSort property to turn this off and use a natural sort of array.
ItemScript | Script for use with items array
ItemSort | Whether to sort items array (default = .T.)
Location Type of editor being edited:
0 – Command Window
1 – Program
8 – Menu Snippet
10 – Code Snippet
12 – Stored Procedure
Menuitem | The menu item selected if user is running script with ValueType="L". Can be used in follow up script.
ParamNum | Parameter number of the function for script call made within a function
Save | Contents of the Save field
Source | Contents of the Source field
Timestamp | Contents of the Timestamp field
Tip | Contents of the Tip field
Type | Contents of the Type field
UniqueId | Contents of the UniqueId field
User | Contents of the User field
UserTyped | Text the user typed. Does not include triggerkey, or any leading spaces or tabs (use FullLine instead for this).
ValueTip | Quick Info tip to display when ValueType = "T"
ValueType Handler for post script action
L – displays a drop-down list populated from the Items array
V – displays Value
T – displays a Quick Info tip from ValueTip

Remarks

The Data field of the FoxCode table generally contains script code to be executed by user-defined IntelliSense scripts. However, it also can be used just to store data used by scripts. This type of metadata is passed automatically to a script by the FoxCode parameter object. This object reference is typically stored in a variable called oFoxcode in IntelliSense scripts.

See Also

Customizing IntelliSense Using FoxCode | Using Scripting in FoxCode.dbf | _FOXCODE System Variable | _Codesense System Variable


Grid Control

Creates a grid.

Grid

Remarks

A grid is a container object that displays data in rows and columns, and is similar in appearance to a Browse window. A grid is also a container object that contains column objects. A column can contain a Header object and controls. Because a grid and its columns, headers, and controls each have their own set of properties, you have complete control over each element of the grid. You can create a grid interactively using the Grid Builder.

For additional information about creating grids, see Using Controls.

Example

The following example places a Grid control on a form. The customer table is opened and its contents are displayed in the grid. The Caption property is used to specify a different header caption (Customer ID) for the CUST_ID field. A command button is placed on the form to close the form.

The SetAll method is used with the DynamicBackColor property to specify the background colors for the records. If the number of a record displayed in the grid is even, the record's DynamicBackColor is white, otherwise its DynamicBackColor is green.

CLOSE ALL  && Close tables and databases
OPEN DATABASE (HOME(2) + 'data\testdata')

USE customer  IN 0  && Opens Customer table

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject('grdGrid1','Grid')  && Add Grid control

frmMyForm.grdGrid1.Left = 25  && Adjust Grid position

frmMyForm.grdGrid1.SetAll("DynamicBackColor", ;
   "IIF(MOD(RECNO( ), 2)=0, RGB(255,255,255) ;
   , RGB(0,255,0))", "Column")  && Alternate white and green records

frmMyForm.grdGrid1.Visible = .T.  && Grid control visible
frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.grdGrid1.Column1.Header1.Caption = 'Customer ID'

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
      CLOSE ALL  && Close table and database
ENDDEFINE

See Also

Grid Control Properties, Methods and Events | Column Object | CREATE CLASS | CREATE FORM | DEFINE CLASS | Header Object


Grid Control Properties, Methods, and Events

Properties

ActiveColumn | ActiveRow | AllowAddNew
AllowAutoColumnFit | AllowCellSelection | AllowHeaderSizing
AllowRowSizing | Application | BackColor
BaseClass | ChildOrder | ClassLibrary
Class | ColumnCount | Columns
Comment | DeleteMark | DragIcon
DragMode | Enabled | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderline | ForeColor | GridLineColor
GridLines | GridLineWidth | HeaderHeight
Height | HelpContextID | HighLight
HighlightBackColor | HighlightForeColor | HighlightStyle
HighLightRow | HighlightRowLineWidth | LeftColumn
Left | LinkMaster | LockColumns
LockColumnsLeft | MemberClass | MemberClassLibrary
MouseIcon | MousePointer | Name
Objects | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData | OLEDropMode
PanelLink | Panel | ParentClass
Parent | Partition | ReadOnly
RecordMark | RecordSource | RecordSourceType
RelationalExpr | RelativeColumn | RelativeRow
RightToLeft | RowColChange | RowHeight
ScrollBars | SelectedBackColor | SelectedForeColor
SelectedItemBackColor | SelectedItemForeColor | SplitBar
StatusBarText | TabIndex | TabStop
Tag | Themes | ToolTipText
Top | Value | View
Visible | WhatsThisHelpID | Width

Methods

ActivateCell | AddColumn | AddObject
AddProperty | AutoFit | CloneObject
DeleteColumn | DoScroll | Drag
GridHitTest | Move | OLEDrag
ReadExpression | ReadMethod | Refresh
RemoveObject | ResetToDefault | SaveAsClass
SetAll | SetFocus | WriteExpression
WriteMethod | Zorder |

Events

AfterRowColChange | BeforeRowColChange | Click
DblClick | Deleted | Destroy
DragDrop | DragOver | Error
Init | KeyPress | MiddleClick Event
MouseDown | MouseEnter | MouseLeave
MouseMove | MouseUp | MouseWheel
OLECompleteDrag | OLEDragDrop | OLEDragOver
OLEGiveFeedBack | OLESetData | OLEStartDrag
Resize | RightClick | Moved
Scrolled | UIEnable | Valid
When |  |

See Also

Grid Control


Header Object

Creates a header for a column in a Grid control. Each column in a grid contains a header. A header displays the caption and an image at the top of a column, and it can respond to events. For additional information about creating headers in grids, see Using Controls.

Header

See Also

Header Object Properties, Methods and Events | Column Object | CREATE FORM | CREATE CLASS | DEFINE CLASS | Grid Control


Header Object Properties, Methods, and Events

Properties

Alignment | Application | BackColor
BaseClass | Caption | Class
ClassLibrary | Comment | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderline | ForeColor | Name
Parent | ParentClass | Picture
StatusBarText | Tag | ToolTipText
WordWrap |  |

Events

Click | DblClick | Destroy
Error | Init | MiddleClick Event
MouseDown | MouseEnter | MouseLeave
MouseMove | MouseUp | MouseWheel
RightClick |  |

Methods

AddProperty | ReadExpression | ReadMethod
Refresh | ResetToDefault | SaveAsClass
WriteExpression | WriteMethod |

Example

The following example uses the Header object with the Caption property to change the caption of the first header in a grid.

A Grid control is placed on a form and the customer table is opened and its contents displayed in the grid. The Header object and the Caption property are used to specify a different header caption (Customer ID) for the first header in the grid.

The SetAll method is used with the DynamicBackColor property to specify the background colors for the records. If the number of a record displayed in the grid is even, the record's DynamicBackColor is white, otherwise its DynamicBackColor is green. A command button is placed on the form to close the form.

CLOSE ALL  && Close tables and databases
OPEN DATABASE (HOME(2) + 'data\testdata')

USE customer  IN 0  && Opens Customer table

frmMyForm = CREATEOBJECT('form')  && Create a form
frmMyForm.Closable = .f.  && Disable the window pop-up menu

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject('grdGrid1','Grid')  && Add Grid control

frmMyForm.grdGrid1.Left = 25  && Adjust Grid position

frmMyForm.grdGrid1.SetAll("DynamicBackColor", ;
   "IIF(MOD(RECNO( ), 2)=0, RGB(255,255,255) ;
   , RGB(0,255,0))", "Column")  && Alternate white and green records

frmMyForm.grdGrid1.Visible = .T.  && Grid control visible
frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.grdGrid1.Column1.Header1.Caption = 'Customer ID'

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
      CLOSE ALL  && Close table and database
ENDDEFINE

See Also

Header Object | HEADER( ) Function | HeaderHeight Property


Hyperlink Object

Creates a Hyperlink object.

Hyperlink

Remarks

A Hyperlink object provides navigational capabilities for Visual FoxPro applications hosted in containers such as Microsoft Internet Explorer.

Note that the Hyperlink object is supported only in Microsoft Internet Explorer. Use the Visual FoxPro Hyperlink Button, Hyperlink Image, or Hyperlink Label foundation classes in the Component Gallery for browser independent navigational capabilities.

See Also

Hyperlink Object Properties, Methods and Events | Hyperlink Button | Hyperlink Image | Hyperlink Label | Component Gallery


Hyperlink Object Properties, Methods, and Events

Properties

Application | BaseClass | Class
ClassLibrary | Comment | Name
Parent | ParentClass | Tag

Events

Destroy Error Init

Methods

AddProperty | SaveAsClass
ResetToDefault | ReadMethod
ReadExpression | WriteExpression

See Also

Hyperlink Object | Hyperlink Button | Hyperlink Image | Hyperlink Label | Component Gallery


Image Control

Creates an Image control that displays a GDI+ compliant picture.

Image

Remarks

An Image control is a graphical control that displays bitmaps that can't be changed directly. However, because an Image control has a full set of properties, events, and methods that other controls have, an Image control can respond to events and can be changed dynamically at run time.

For additional information about creating Images, see Using Controls.

See Also

Objects, Collections, and Classes | Image Control Properties, Methods, and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Image Control Properties, Methods, and Events

Properties

Application | BackStyle | BaseClass
BorderColor | BorderStyle | Class
ClassLibrary | ColorSource | Comment
DragIcon | DragMode | Enabled
Height | HelpContextID | Left
MousePointer | Name | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData Property
OLEDropMode | Parent | ParentClass
Picture | RotateFlip | StatusBarText
Stretch | Tag | Themes
ToolTipText | Top | Visible
WhatsThisHelpID | Width |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | ResetToDefault | SaveAsClass
WriteExpression | WriteMethod | Zorder

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
Init | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | RightClick
UIEnable |  |

See Also

Image Control


Label Control

Creates a label that displays text.

Label

Remarks

A Label control is a graphical control that displays text that can't be changed directly. However, because a Label control has a full set of properties, events, and methods that other controls have, the Label control can respond to events and can be changed dynamically at run time.

To assign an access key to a label, include a backslash and a less-than sign (\<) in the caption immediately preceding the character you want to designate as the access key. When the label is displayed, the character is underlined. Pressing the access key for a label activates the next control in the tab order. Use the TabIndex property to assign a tab order to a label.

Captions are displayed differently depending on the object.

256 is the maximum number of characters for the Caption property for a Label control.

For additional information about creating Label controls, see Using Controls.

See Also

Label Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Label Control Properties, Methods, and Events

Properties

Alignment | Application | AutoSize
BackColor | BackStyle | BaseClass
BorderStyle | Caption | Class
ClassLibrary | ColorScheme | ColorSource
Comment | DisabledBackColor | DisabledForeColor
DragIcon | DragMode | Enabled
FontBold | FontCharSet | FontCondense
FontExtend | FontItalic | FontName
FontOutline | FontShadow | FontSize
FontStrikeThru | FontUnderline | ForeColor
Height | HelpContextID | Left
MouseIcon | MousePointer | Name
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData Property | OLEDropMode | Parent
ParentClass | RightToLeft | StatusBarText
Style | TabIndex | Tag
ToolTipText | Top | Visible
WhatsThisHelpID | Width | WordWrap

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
Init | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | RightClick
UIEnable |  |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | UIEnable | WriteExpression
WriteMethod | ZOrder |

See Also

Label Control | Using Controls | CREATE CLASS | CREATE FORM | DEFINE CLASS


Line Control

Creates a control that displays a horizontal, vertical, or diagonal line.

Line

Remarks

A Line control is a graphical control that displays a horizontal, vertical, or diagonal line that can't be changed directly. However, because a Line control has a full set of properties, events, and methods that other controls have, the Line control can respond to events and can be changed dynamically at run time.

For additional information about creating lines, see the Form Designer topic and Using Controls.

See Also

Line Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Line Control Properties, Methods, and Events

Properties

Application | BaseClass | BorderColor
BorderStyle | BorderWidth | Class
ClassLibrary | ColorSource Property | Comment
DragIcon | DragMode | DrawMode
Enabled | Height | HelpContextID
Left | LineSlant | MousePointer
Name | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData Property | OLEDropMode
Parent | ParentClass | StatusBarText
Tag | ToolTipText | Top
Visible | WhatsThisHelpID | Width

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
Init | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | RightClick
UIEnable |  |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | ResetToDefault | SaveAsClass
WriteExpression | WriteMethod | ZOrder

Example

The following example demonstrates how a Line control can be added to a form and how you can use the LineSlant property to specify the direction in which the line slants.

The AddObject method is used to add a Line control to a form. Three command buttons are added to the form, allowing you to change the direction in which the line slants or to close the form.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

Line Control | Line Method | LineSlant Property


ListBox Control

Creates a list box.

ListBox

Remarks

A list box displays a list of items from which you can select one or more items. A list box is similar to a combo box; however, a combo box initially displays a single item.

The backslash ("\") is treated as a special character when used in the expression for an item. The following rules apply for this character:

  • You can disable an item in a list box or combo box by adding a single backslash to the beginning of the expression.
  • Any multiple of two backslashes used in the expression is displayed as a single backslash. For example, one or two backslashes used together will display as one, and three or four backslashes together will display as two. The following example code contains a list box item containing a Universal Naming Convention (UNC) path. The code would display in the list box as \\MyServer\MyMachine\MyFolder.
    MyForm.List1.AddItem("\\\\MyServer\\MyMachine\\MyFolder")
  • If the expression begins with multiple backslashes, the item is not disabled. If you want to disable an item that begins with multiple backslashes, add a backslash and a close bracket (]) to the beginning of the item. For example, the following would disable the UNC path item in the list box:
    MyForm.List1.AddItem("\]\\\MyServer\\MyMachine\\MyFolder")
  • To include a separator line, use a backslash followed by a hyphen as the item to add to the list box. For example, the following code adds a separator line to a list box:
    MyForm.List1.AddItem("\-")

You can also use an ActiveX control that adds extra characteristics, such as a CheckBox, to the ListView or TreeView controls.

For additional information about creating ListBox controls, see Form Designer and Using Controls.

See Also

ListBox Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


ListBox Control Properties, Methods, and Events

Properties

Application | BaseClass | BorderColor
BoundColumn | BoundTo | Class
ClassLibrary | ColorScheme | ColorSource
ColumnCount | ColumnLines | ColumnWidths
Comment | ControlSource | DisabledBackColor
DisabledForeColor | DisabledItemBackColor | DisabledItemForeColor
DisplayValue | DragIcon | DragMode
Enabled | FirstElement | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderLine | Height | HelpContextID
IncrementalSearch | IntegralHeight | ItemBackColor
ItemData | ItemForeColor | ItemIDData
ItemTips | Left | List
ListCount | ListIndex | ListItem
ListItemID | MouseIcon | MousePointer
MoverBars | MultiSelect | Name
NewIndex | NewItemID | NullDisplay
NumberOfElements | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData Property | OLEDropMode
Parent | ParentClass | Picture
RightToLeft | RowSource | RowSourceType
Selected | SelectedID | SelectedItemBackColor
SelectedItemForeColor | Sorted | SpecialEffect
StatusBarText | TabIndex | TabStop
Tag | TerminateRead | Themes
ToolTipText | Top | TopIndex
TopItemID | Value | Visible
WhatsThisHelpID | Width |

Methods

AddItem | AddListItem | AddProperty
Clear | CloneObject | Drag
IndexToItemID | ItemIDToIndex | Move
MoveItem | OLEDrag | ReadExpression
ReadMethod | Refresh | RemoveItem
RemoveListItem | Requery | ResetToDefault
SaveAsClass | SetFocus | WriteExpression
WriteMethod | ZOrder |

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
ErrorMessage | GotFocus | Init
InteractiveChange | KeyPress | LostFocus
Message | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | OnMoveItem
ProgrammaticChange | RangeHigh | RangeLow
RightClick | UIEnable | Valid
When |  |

Example

The following example creates a ListBox control. The source of the items that appear in the list box is an array specified with the RowSourceType and RowSource properties.

The MultiSelect property for the list box is set to true (.T.), allowing you to make multiple selections from the list. The item or items you choose are displayed by using the ListCount, Selected, and List properties (which determine the number of items in the list and the items you chose).

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
NEXT

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" Command button
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add ListBox control

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Array containing listbox items

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

ListBox Control | ListCount Property | Form Designer | Using Controls


Member Classes

You can define and create subclasses for member objects of certain container objects. The following table lists these members and their parent containers:

Member | Container
Page | PageFrame
CommandButton | CommandGroup
OptionButton | OptionGroup
Column | Grid
Header | Column

Using member classes, you can define consistent behavior for all members of a specific class. For example, you can define a particular behavior in the Activate event of a Page class to be used in a specific PageFrame class or object. All member pages for that page frame inherit the same code or behavior.

To set the default custom class for member objects, set the MemberClassLibrary and MemberClass properties for the PageFrame, CommandGroup, OptionGroup, and Grid container classes. These properties specify the member class and class library you want to use. When these properties are set, new member objects inherit from the specified member class. For Column objects, use the HeaderClassLibrary and HeaderClass properties to specify a custom Header class.

Caution Do not change the Name property for a member class in a program (.prg) -based class definition at design time. Doing so can result in generating the message, "Class definition name is not found."

Remarks

In general, member objects must be contained within a parent container object to be used visually. Parent containers can contain only member objects. For example, a Page object must be in a PageFrame object to display on a Form object and a PageFrame object must have at least one Page object to be visible on a Form object. There are two exceptions:

  • You can use command buttons in other containers without requiring a CommandGroup.
  • Column objects can contain other controls but only one Header.

Member objects exist only as children of the parent container, which contains only members belonging to a specific base class. For example, the existence of a Page object requires the prior existence of its parent PageFrame container object. A PageFrame object can contain only pages and not command buttons.

You can associate an event when adding a new member object using the member object's count property _ASSIGN method. The member object's Init event occurs when member objects are added. However, you cannot pass parameters to the Init event of a newly created member object because members are created dynamically when the parent container's count property changes. If you need to pass parameters, you can use the container's AddObject method.

Note On an .scx form, if you add instantiation code to the member class's Init event, Visual FoxPro disregards that code and only the Init code for the member class definition runs. However, with visual class library (.vcx) forms, Visual FoxPro creates a true subclass. You can safely add instantiation code for other events such as Click.

Any property values accessed in the member class's Init event belong to those of the original member class. Any values that might have been overridden in the subclass are applied after instantiating the member class.

These behaviors apply only to .scx forms. After the Init event occurs, the member class is treated the same on .scx and .vcx forms.

See Also

Objects, Collections, and Classes | Page Object | PageFrame Control | CommandButton Control | CommandGroup Control | OptionButton Control | OptionGroup Control | Grid Control | Column Object | Header Object | MemberClass Property| MemberClassLibrary Property | HeaderClass Property | HeaderClassLibrary Property | Init Event | AddObject Method


Objects Collection

An array to access objects in an Application object.

ApplicationObject.Objects(nIndex)

Property Values

nIndex
Uniquely identifies an object in the Application object. Note that nIndex might not correspond to the order in which the objects were created.

Remarks

The Objects collection can be used to determine the current objects for an Application object. The Column, CommandGroup, Container, Control, Custom, DataEnvironment, Form, FormSet, Grid, Page, PageFrame, OptionGroup, and Toolbar objects have collections, and these collections may appear in the Debug window.

See Also

Forms Property

Applies To: Application Object | _VFP System Variable | _SCREEN System Variable | Column Object | CommandGroup Control | Container Object | Control Object | Custom Object | DataEnvironment Object | Form Object | FormSet Object | Grid Control | OptionGroup Control | Page Object | PageFrame Control | ToolBar Object


OLE Bound Control

Creates an OLE bound control.

OLEBoundControl

Remarks

On a form or report, an OLE bound control lets you display the contents of an OLE object (such as from Microsoft Word or Microsoft Excel) in a General field of a table.

Unlike OLE container controls, insertable OLE objects do not have their own set of events. Also, OLE bound controls, unlike OLE container controls, are bound to a General field in a Visual FoxPro table.

For additional information about OLE objects in Visual FoxPro, see Adding OLE.

See Also

OLE Bound Control Properties, Methods and Events | APPEND GENERAL | CREATE FORM | CREATE CLASS | CREATEBINARY( ) | DEFINE CLASS | MODIFY GENERAL | OLE Container Control


OLE Bound Control Properties, Methods, and Events

Properties

Application | AutoActivate | AutoSize
BaseClass | ClassLibrary | Class
Comment | ControlSource | DocumentFile
DragIcon | DragMode | Enabled
Height | HelpContextId | HostName
Left | MousePointer | Name
Object | OLEClass | OLELCID Property
OLETypeAllowed | ParentClass | Sizable
StatusBarText | Stretch | TabIndex
TabStop | Tag | ToolTipText
Top | Visible | WhatsThisHelpID
Width |  |

Events

Destroy | DragDrop | DragOver
Error | GotFocus | Init
LostFocus | Moved | Resize
UIEnable |  |

Methods

AddProperty | CloneObject | DoVerb
Drag | Move | Refresh
ResetToDefault | SaveAsClass | SetFocus
ZOrder |  |

See Also

OLE Bound Control | OLE Container Control


OLE Container Control

Creates an OLE container control.

OLEControl

Remarks

An OLE container control lets you add OLE objects to your applications. OLE objects include ActiveX Controls (.ocx files) and insertable OLE objects created in other applications such as Microsoft Word and Microsoft Excel. Unlike ActiveX Controls (.ocx files), insertable OLE objects do not have their own set of events. OLE container controls, unlike OLE bound controls, are not bound to a General field in a Visual FoxPro table.

Note that the type of ActiveX control placed in an OLE container control determines the properties, events, and methods available for the ActiveX control

For additional information about OLE objects in Visual FoxPro, see Adding OLE.

See Also

OLE Container Control Properties, Methods and Events | ActiveX Controls Overview | APPEND GENERAL | CREATE FORM | CREATE CLASS | CREATEBINARY( ) | DEFINE CLASS | MODIFY GENERAL | OLE Bound Control


OLE Container Control Properties, Methods, and Events

Properties

Align | Application | AutoActivate
AutoSize | AutoVerbMenu | BaseClass
Cancel | Class | ClassLibrary
Comment | ControlSource | Default
DocumentFile | DragIcon | DragMode
Enabled | Height | HelpContextID
HostName | Left | MouseIcon
MousePointer | Name | Object
OLEClass | OLELCID | OLETypeAllowed
Parent | ParentClass | Sizable
Stretch | TabIndex | TabStop
Tag | Top | Visible
WhatsThisHelpID | Width |

Events

Destroy | DragDrop | DragOver
Error | GotFocus | Init
LostFocus | Moved | Resize
UIEnable |  |

Methods

AddProperty | CloneObject | DoVerb
Drag | Move | Refresh
ResetToDefault | SaveAsClass | SetFocus
ShowWhatsThis | Zorder |

Example

The following example adds an OLE Container control to a form, and uses the OleClass and DocumentFile properties to specify Microsoft Excel as the Automation server and a Microsoft Excel worksheet as the file to edit.

The DocumentFile property specifies a worksheet named Book1.xls in the EXCEL directory on drive C. This example will not work properly if the file and directory specified in the DocumentFile property do not exist; it may be necessary to modify the DocumentFile property to specify an existing directory and worksheet file.

* The DoVerb method is used to activate the worksheet for editing.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject("oleObject","oleExcelObject")  && Add OLE object

frmMyForm.cmdCommand1.Visible=.T.  && Display the "Quit" Command button

frmMyForm.oleObject.Visible=.T.  && Display the OLE control
frmMyForm.oleObject.Height = 50  && OLE control height

frmMyForm.Show  && Display the Form

frmMyForm.oleObject.DoVerb(-1)  && -1 for Edit

READ EVENTS  && Start event processing

DEFINE CLASS oleExcelObject as OLEControl
   OleClass ="Excel.Sheet"  && Server name
   DocumentFile = "C:\EXCEL\BOOK1.XLS"  && This file must exist
ENDDEFINE

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

OLE Container Control | Adding OLE


OptionButton Control

Creates a single option button.

OptionButton

Remarks

A single option button can be added only to a group of option buttons.

For more information about creating a group of option buttons, see the OptionGroup Control and Using Controls.

See Also

OptionButton Control Properties, Methods and Events | CREATE FORM | CREATE CLASS | DEFINE CLASS | OptionGroup Control


OptionButton Control Properties, Methods, and Events

Properties

Alignment | Application | AutoSize
BackColor | BackStyle | BaseClass
Caption | Class | ClassLibrary
ColorScheme | ColorSource | Comment
ControlSource | DisabledBackColor | DisabledForeColor
DisabledPicture | DownPicture | DragIcon
DragMode | Enabled | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderLine | ForeColor | Height
HelpContextID | Left | MousePointer
Name | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData | OLEDropMode
Parent | ParentClass | Picture
PicturePosition | RightToLeft | SpecialEffect
StatusBarText | Style | TabIndex
TabStop | Tag | TerminateRead
Themes | ToolTipText | Top
Value | Visible | WhatsThisHelpID
Width |  |

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
ErrorMessage | GotFocus | Init
KeyPress | LostFocus | Message
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | RightClick | Valid
When |  |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | WriteExpression
WriteMethod | ZOrder |

See Also

OptionButton Control | Setting Option Button Properties


OptionGroup Control

Creates a group of option buttons.

OptionGroup

Remarks

Option button groups are containers that contain option buttons. A group of option buttons makes it possible for you to make a choice from a set of buttons. Choosing an option button makes your choice current and releases a previous choice. A bullet next to the option button indicates the current choice. For example, option buttons can be used to direct output to a file, a printer, or a window.

For additional information about creating groups of option buttons, see Using Controls.

See Also

OptionGroup Control Properties, Methods and Events | CREATE FORM | CREATE CLASS | DEFINE CLASS | OptionButton Control


OptionGroup Control Properties, Methods, and Events

Properties

Application | AutoSize | BackColor
BackStyle | BaseClass | BorderColor
BorderStyle | ButtonCount | Buttons
Class | ClassLibrary | Comment
ColorSource Property | ControlSource | DragIcon
DragMode | Enabled | Height
HelpContextID | Left | MemberClass
MemberClassLibrary | MouseIcon | MousePointer
Name | Objects | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData Property
OLEDropMode | Parent | ParentClass
SpecialEffect | StatusBarText | TabIndex
Tag | TerminateRead | Themes
ToolTipText | Top | Value
Visible | WhatsThisHelpID | Width

Methods

AddObject | AddProperty | CloneObject
Drag | Move | OLEDrag
ReadExpression | ReadMethod | Refresh
RemoveObject | ResetToDefault | SaveAsClass
SetAll | WriteExpression | WriteMethod
ZOrder |  |

Events

Click | DblClick | DragDrop
DragOver | Error | ErrorMessage
Init | InteractiveChange | Message
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | ProgrammaticChange | RightClick
UIEnable | Valid | When

Example

The following example creates an OptionGroup control and places the control on a form. The OptionGroup control has three buttons, and depending on the option button you click, a circle, ellipse, or square is displayed. The Buttons and Caption properties are used to specify the text displayed next to each option button.

The Shape control is used to create the circle, ellipse, and square. The OptionGroup control's Click event uses a DO CASE ... ENDCASE structure and the Value property to display the appropriate shape when you click an option button.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

OptionGroup Control | DO CASE ... ENDCASE Command


Page Object

Creates a page in a PageFrame control.

You can use pages to create tabbed forms or dialog boxes. A page frame contains a set of pages. For additional information about creating pages and page frames, see "Adding Page Frames to a Form" in Extending Forms.

Page

Remarks

You can refer to a page in a page frame by name as in the following example:

myFrame.MyPage1

You can also refer to a page by its index number using the PageFrame Pages property. This is consistent with the control collections in other Visual FoxPro containers.

myFrame.Pages(2).Enabled = .T.

This index does not necessarily equal the PageOrder property. You might have three pages with PageOrders of 2, 3, and 5. You can refer to these pages as follows:

myFrame.Pages(1)
myFrame.Pages(2)
myFrame.Pages(3)

Only the active page is refreshed when the Form Refresh method occurs for the form on which the page is located.

See Also

Page Object Properties, Methods and Events | CREATE FORM | CREATE CLASS | DEFINE CLASS | PageFrame Control


Page Object Properties, Methods, and Events

Properties

ActiveControl | Application | BackColor
BackStyle | BaseClass | Caption
Class | ClassLibrary | ColorSource
Comment | ControlCount | Controls
DragIcon | DragMode | Enabled
FontBold | FontCharSet | FontCondense
FontExtend | FontItalic | FontName
FontOutline | FontShadow | FontSize
FontStrikeThru | FontUnderline | ForeColor
HelpContextID | MouseIcon | MousePointer
Name | Objects | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData
OLEDropMode | PageOrder | Parent
ParentClass | Picture | Tag
ToolTipText | WhatsThisHelpID |

Events

Activate | Click | DblClick
Deactivate | Destroy | DragDrop
DragOver | Error | Init
MiddleClick Event | MouseDown | MouseEnter
MouseLeave | MouseMove | MouseUp
MouseWheel | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | RightClick |

Methods

AddObject | AddProperty | CloneObject
Drag | OLEDrag | ReadExpression
ReadMethod | Refresh | RemoveObject
ResetToDefault | SaveAsClass | SetAll
WriteExpression | WriteMethod | ZOrder

See Also

Page Object | Extending Forms


PageFrame Control

Creates a page frame to contain Page objects.

A page frame is a container object that contains pages, which can contain controls.

Note For a page frame to be visible, it must be added to a form.
PageFrame

Remarks

The page frame defines global characteristics of the page: size and positioning, border style, which page is active, and so on. The page frame determines the location of the pages and how much of each page is visible. Pages are positioned at the top left corner of the page frame. If the page frame is moved, the pages move with the page frame.

A page frame contains individual pages that are named Page1, Page2, Page3, and so on by default.

Note Only the active page is refreshed when the Form Refresh method occurs for the form on which the page is located.

The PageFrame Themes property provides a gradient effect on Page objects, so a label, option button, or similar control with text does not appear correctly if the BackStyle property of the control is set to Opaque. You can remedy this situation by setting BackStyle to Transparent.

For additional information about creating pages and page frames, see "Adding Page Frames to a Form" in Extending Forms.

See Also

PageFrame Control Properties, Methods and Events | CREATE FORM | CREATE CLASS | DEFINE CLASS | Page Object


PageFrame Control Properties, Methods, and Events

Properties

ActivePage | Application | BaseClass
BorderColor | BorderWidth | Class
ClassLibrary | ColorSource Property | Comment
DragIcon | DragMode | Enabled
HelpContextID | Height | Left
MemberClass | MemberClassLibrary | MouseIcon
MousePointer | Name | Objects
OLEDragMode | OLEDragPicture | OLEDropEffects
OLEDropHasData Property | OLEDropMode | PageCount
PageHeight | Pages | PageWidth
Parent | ParentClass | RightToLeft
SpecialEffect | StatusBarText | TabIndex
TabOrientation | Tabs | TabStop
TabStyle | Tag | Themes
ToolTipText | Top | Visible
WhatsThisHelpID | Width |

Methods

AddObject | AddProperty | CloneObject
Drag | Move | OLEDrag
ReadExpression | ReadMethod | Refresh
RemoveObject | ResetToDefault | SaveAsClass
SetAll | WriteExpression | WriteMethod
Zorder |  |

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
Init | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | Moved
OLECompleteDrag | OLEDragDrop | OLEDragOver
OLEGiveFeedBack | OLESetData | OLEStartDrag
Resize | RightClick | UIEnable

See Also

PageFrame Control | Extending Forms


Parent Object Reference

References the container object of a control. Not available at design time; read-only at run time.

Control.Parent

Remarks

Use the Parent keyword to access the properties, methods, or controls of a control's container object. You can also use the Parent object reference to access the container object of a page or form.

The Parent keyword is useful in an application in which you pass controls as arguments. For example, you can pass a control variable to a general procedure and use the Parent object reference to access its container object.

You can also use the Parent object reference for objects in a control class that have been placed on an unknown form.

See Also

BaseClass Property

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container | Control | CursorAdapter Class | Custom | EditBox | Exception Class | Form | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Project Object | ProjectHook Object | Separator | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


Project Object

Instantiated when a project is created or opened, providing programmatic access to project properties and methods.

Project

Remarks

A project object is instantiated when you issue CREATE PROJECT, MODIFY PROJECT, BUILD APP, BUILD DLL, BUILD EXE, BUILD MTDLL, or BUILD PROJECT.

Note that the project object and its properties and methods are not available in the ProjectHook object Init event. Project object property values you set or methods you invoke in the ProjectHook object Init event are ignored.

Note that a project object is a COM object, so assigning a project object reference to a memory variable creates a memory variable of class "Unknown Type."

For more information about projects, see Project Manager Hooks.

See Also

Project Object Properties, Methods, and Events | ActiveProject Property | File Object | Files Collection | Projects Collection | ProjectHook Object | Server Object | Servers Collection


Project Object Properties, Methods, and Events

Properties

Application | AutoIncrement | BaseClass
BuildDateTime | Debug | Encrypted
Files Collection | HomeDir | Icon
MainFile | Name | Parent
ProjectHook | ProjectHookClass | ProjectHookLibrary
SCCProvider | ServerHelpFile | ServerProject
TypeLibCLSID | TypeLibDesc | TypeLibName
VersionComments | VersionCompany | VersionCopyright
VersionDescription | VersionLanguage | VersionNumber
VersionProduct | VersionTrademarks | Visible

Methods

Build | CleanUp | Close
Refresh | SetMain |

See Also

Project Object | ProjectHook Object Properties, Methods, and Events | ProjectHook Object


ProjectHook Object

Instantiated whenever a project is opened, providing programmatic access to project events.

ProjectHook

Remarks

A ProjectHook object is a Visual FoxPro base class that is instantiated by default whenever a project is opened. (You can include the NOPROJECTHOOK clause in CREATE PROJECT and MODIFY PROJECT to prevent a ProjectHook object from being instantiated for the project.)

The ProjectHook object allows programmatic access to events that occur in a project. For example, you can execute code whenever a file is added to a project. Note that you can specify a default project hook class for new projects in the Projects tab, of the Options dialog box or you can specify a default project hook class for an individual project in the Project Information dialog box. At runtime, you can use the ProjectHook property to specify a project hook class for a project as in the following example:

MODIFY PROJECT MyProject
_VFP.Projects('MyProject.pjx').ProjectHook = ;
   NewObject('MyProjectHook', 'MyClass.vcx')

A ProjectHook base class can be created with CREATE CLASS, CREATEOBJECT( ), or NEWOBJECT( ).

For more information about projects, see Project Manager Hooks.

See Also

ProjectHook Object Properties, Methods, and Events | CREATE CLASS | CREATEOBJECT( ) | File Object | Files Collection | NEWOBJECT( ) | ProjectHook Property | Projects Collection | Project Object | Server Object | Servers Collection


ProjectHook Object Properties, Methods, and Events

Properties

Application | BaseClass | Class
ClassLibrary | Comment | Name
OLEDropEffects | OLEDropHasData | OLEDropMode
Parent | ParentClass | Tag

Events

Activate | AfterBuild | BeforeBuild
Deactivate | Destroy | Error
Init | OLEDragDrop | OLEDragOver
OLEGiveFeedBack | QueryAddFile | QueryModifyFile
QueryNewFile Event | QueryRemoveFile | QueryRunFile

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | SaveAsClass | WriteExpression

See Also

ProjectHook Object


Projects Collection

A collection of project objects.

Projects

Remarks

A projects collection provides access to project objects, making it possible for you to manipulate a project and files and servers within the project.

Items in projects collection can be referenced by index number or by name. For example, the following code rebuilds the most recently opened project:

_VFP.Projects(1).Build( )

The following code rebuilds the project named MyProject:

_VFP.Projects('MyProject.pjx').Build( )

For more information about the projects collection, see Project Manager Hooks.

See Also

Projects Collection Properties, Methods, and Events | File Object | Files Collection | Project Object | ProjectHook Object | Server Object | Servers Collection

Applies To: _VFP System Variable | Application Object


Projects Collection Properties, Methods, and Events

Properties

Count

Methods

Item

See Also

Projects Collection


Relation Object

Created when you establish relationships from within the Data Environment Designer for a form, form set, or report.

Relation

Remarks

The Relation object allows you to determine or specify how two tables are related.

Setting a Relation object property at run time generates an error. For a new property setting to take effect, you must call the CloseTables and OpenTables methods for the data environment.

For more information about the data environment for Forms and FormSets, see Setting the Data Environment.

See Also

Relation Object Properties, Methods and Events | Cursor Object | DataEnvironment Object


Relation Object Properties, Methods, and Events

Properties

Application | ChildAlias | ChildOrder
Comment | Name | OneToMany
ParentAlias | RelationalExpr | Tag

Events

Destroy Error Init

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | WriteExpression |

See Also

Relation Object | RELATION( ) Function | Cursor Object | DataEnvironment Object


Separator Object

Creates a Separator object that places space between controls in a toolbar.

Separator

Remarks

Controls in a toolbar are placed immediately next to each other unless you include a Separator between the controls. A Separator is a special object that adds space between the controls and creates a group of controls.

For additional information about creating toolbars and separators, see Designing Menus and Toolbars.

See Also

Separator Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | Toolbar Object


Separator Object Properties, Methods, and Events

Properties

Application | BaseClass | Class
ClassLibrary | Comment | Enabled
Name | Parent | ParentClass
Style | Tag |

Events

Destroy Error Init

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | SaveAsClass | WriteExpression
ZOrder |  |

See Also

Separator Object | CREATE CLASS | CREATE FORM | DEFINE CLASS | Toolbar Object


Server Object

An object reference to a server in a project.

Server

Remarks

A server object is created and instantiated for each server in a project after building an executable file (.exe) or dynamic link library (.dll) from the project. The server object provides an object reference to a server in the project, and makes it possible for you to determine information about the server and manipulate it through the server object properties.

A project's servers collection is composed of all the server objects in the project.

Note that a server object is a COM object, so assigning a server object reference to a memory variable creates a memory variable of class "Unknown Type."

See Also

Server Object Properties, Methods and Events | File Object | Files Collection | Project Object | Projects Collection | ProjectHook Object | Servers Collection


Server Object Properties, Methods, and Events

Properties

CLSID | Description | HelpContextID
Instancing | ProgID | ServerClass
ServerClassLibrary |  |

See Also

Server Object | File Object | Files Collection | Project Object | Projects Collection | ProjectHook Object | Servers Collection


Servers Collection

A collection of server objects.

Servers

Remarks

A Servers collection provides access to server objects, making it possible for you to manipulate servers within the project.

For more information about the servers collection and projects, see Project Manager Hooks.

For information about creating custom Automation servers, see Creating Automation Servers.

See Also

Servers Collection Properties, Methods and Events | File Object | Files Collection | Project Object | Projects Collection | ProjectHook Object | Server Object


Servers Collection Properties, Methods, and Events

Properties

Count

Methods

Item

See Also

Servers Collection | File Object | Files Collection | Project Object | Projects Collection | ProjectHook Object | Server Object


Session Object

Creates a custom, user-defined object that manages its own data session.

DEFINE CLASS ClassName1 AS Session

Remarks

You can create this custom, user-defined class only using the DEFINE CLASS command. You can, however, add this object to a form or other container programmatically.

Custom, user-defined classes are classes with properties, events, and methods, but with no visual representation. The same general rules that apply to defining other types of classes apply to defining custom classes. Use the Session object as efficient memory management and to ensure safe behavior of multiple object instances in multi-tiered applications.

See Object-Oriented Programming for additional information about creating custom objects as non-visual classes.

Beginning with Visual FoxPro 7, the default values for SAFETY, EXCLUSIVE, and TALK are the following:

Setting | Value
EXCLUSIVE | OFF
SAFETY | OFF
TALK | OFF

When the Session object represents a COM Server, all intrinsic properties are treated as private.

See Also

Session Object Properties, Methods and Events | DEFINE CLASS | Object-Oriented Programming | Adding User-Defined Objects to a Form | Commands that Scope to a Data Session


Session Object Properties, Methods, and Events

Events

Destroy Error Init

Methods

AddProperty | ReadExpression | ReadMethod
ResetToDefault | WriteExpression Method |

Properties

Application | BaseClass | Class
ClassLibrary | Comment | DataSession
DataSessionID | Name | Parent
ParentClass | Tag |

See Also

Session Object | DEFINE CLASS | Object-Oriented Programming | Adding User-Defined Objects to a Form | Commands that Scope to a Data Session


Shape Control

Creates a Shape control that displays a box, circle, or ellipse.

Shape

Remarks

A Shape control is a graphical control that displays a box, circle, or ellipse that cannot be changed directly. However, because a Shape control has a full set of properties, events, and methods that other controls have, the Shape control can respond to events and can be changed dynamically at run time.

The Curvature property determines what shape is displayed and can vary from 0 to 99. 0 specifies no curvature and creates square corners; 99 specifies maximum curvature and creates circles and ellipses.

For additional information about creating shapes, see the Form Designer topic and Using Controls.

See Also

Shape Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Shape Control Properties, Methods, and Events

Properties

Application | BackColor | BackStyle
BaseClass | BorderColor | BorderStyle
BorderWidth | Class | ClassLibrary
ColorScheme | ColorSource | Comment
Curvature | DragIcon | DragMode
DrawMode | Enabled | FillColor
FillStyle | Height | HelpContextID
Left | MouseIcon | MousePointer
Name | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData Property | OLEDropMode
Parent | ParentClass | SpecialEffect
Tag | ToolTipText | Top
Visible | WhatsThisHelpID | Width

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
Init | MiddleClick Event | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | RightClick
UIEnable |  |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | ShowWhatsThis | WriteExpression
WriteMethod | ZOrder |

Example

The following example demonstrates how the Shape control can be used to display a circle, ellipse, or square on a form.

A form is created, and a set of option buttons and a command button are placed on the form. When you click one of the option buttons, the corresponding shape is displayed on the form. The Visible property is set to true (.T.) to display a shape; it is set to false (.F.) to hide the shape before another shape is displayed. The Height, Width, and Curvature properties of each shape determine the type of shape (circle, ellipse, or square) created.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS Shape  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS Shape  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS Shape  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

Shape Control | CREATE CLASS | CREATE FORM | DEFINE CLASS


Spinner Control

Creates a spinner.

Spinner

Remarks

A spinner allows a user to choose from a range of numeric values by 'spinning' through the values by clicking the up or down arrows on the spinner or by typing a value into the spinner box.

The KeyBoardHighValue and SpinnerHighValue properties specify the maximum numeric values that can be entered from the keyboard into the spinner box and by clicking the arrow buttons on the spinner.

The KeyBoardLowValue and SpinnerLowValue properties specify the minimum numeric values that can be entered from the keyboard into the spinner box and by clicking the arrow buttons on the spinner.

For additional information about creating spinners, see the Form Designer topic and Using Controls.

See Also

Spinner Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


Spinner Control Properties, Methods, and Events

Properties

Alignment | Application | BackColor
BaseClass | BorderColor | BorderStyle
Class | ClassLibrary | ColorScheme
ColorSource | Comment | ControlSource
DisabledBackColor | DisabledForeColor | DragIcon
DragMode | Enabled | FontBold
FontCharSet | FontCondense | FontExtend
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderline | ForeColor | Format
Height | HelpContextID | HideSelection
Increment | InputMask | KeyboardHighValue
KeyboardLowValue | Left | Margin
MouseIcon | MousePointer | Name
NullDisplay | OLEDragMode | OLEDragPicture
OLEDropEffects | OLEDropHasData | OLEDropMode
OLEDropTextInsertion | Parent | ParentClass
ReadOnly | RightToLeft | SelectedBackColor
SelectedForeColor | SelectOnEntry | SelLength
SelStart | SelText | SpecialEffect
SpinnerHighValue | SpinnerLowValue | StatusBarText
TabIndex | TabStop | Tag
TerminateRead | Text | Themes
ToolTipText | Top | Value
Visible | WhatsThisHelpID | Width

Events

Click | DblClick | Destroy
DownClick | DragDrop | DragOver
Error | ErrorMessage | GotFocus
Init | InteractiveChange | KeyPress
LostFocus | Message | MiddleClick Event
MouseDown | MouseEnter | MouseLeave
MouseMove | MouseUp | MouseWheel
OLECompleteDrag | OLEDragDrop | OLEDragOver
OLEGiveFeedBack | OLESetData | OLEStartDrag
ProgrammaticChange | RangeHigh | RangeLow
RightClick | UIEnable | UpClick
Valid | When |

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

See Also

Spinner Control | CREATE CLASS | CREATE FORM | DEFINE CLASS


Tables Collection (XMLAdapter)

The Tables collection in an XMLAdapter object contains one or more XMLTable objects and describes XML as a Visual FoxPro cursors along with any relational information. To create a new XMLTable object and add it to the Tables collection, or populate the Tables collection with one or more tables, use the XMLAdapter LoadXML, AddTableSchema, or Attach methods.

XMLAdapter.Tables

See Also

Objects, Collections, and Classes | XMLAdapter Object Properties, Methods, and Events | XMLTable Class | AddTableSchema Method

Applies To: XMLAdapter Class


TextBox Control

Creates a text box.

TextBox

Remarks

Creates a text box in which you can edit the contents of a memory variable, array element, or field. All standard Visual FoxPro editing features, such as cut, copy, and paste, are available in the text box. If the text box is used to edit a date or datetime value and the entire value is selected, you can press + or - to increment or decrement the value by one day.

Use the InputMask and Format properties to specify how values are entered and displayed in the text box.

For additional information about creating text boxes, see the Form Designer topic and Using Controls.

See Also

TextBox Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS


TextBox Control Properties, Methods, and Events

Properties

Alignment | Application | BackColor
BackStyle | BaseClass | BorderColor Property
BorderStyle | Century | Class
ClassLibrary | ColorScheme | ColorSource
Comment | ControlSource | DateFormat
DateMark | DisabledBackColor | DisabledForeColor
DragIcon | DragMode | Enabled
EnableHyperlinks | FontBold | FontCharSet
FontCondense | FontExtend | FontItalic
FontName | FontOutline | FontShadow
FontSize | FontStrikeThru | FontUnderline
ForeColor | Format | Height
HelpContextID | HideSelection | Hours
IMEMode | InputMask | IntegralHeight
Left | Margin | MaxLength
MemoWindow | MouseIcon | MousePointer
Name | NullDisplay | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData
OLEDropMode | OLEDropTextInsertion | OpenWindow
Parent | ParentClass | PasswordChar
ReadOnly | RightToLeft | Seconds
SelectedBackColor | SelectedForeColor | SelectOnEntry
SelLength | SelStart | SelText
SpecialEffect | StatusBarText | StrictDateEntry
Style | TabIndex | TabStop
Tag | TerminateRead | Text
Themes | ToolTipText | Top
Value | Visible | WhatsThisHelpID
Width |  |

Events

Click | DblClick | Destroy
DragDrop | DragOver | Error
ErrorMessage | GotFocus | Init
InteractiveChange | KeyPress | LostFocus
Message | MiddleClick | MouseDown
MouseEnter | MouseLeave | MouseMove
MouseUp | MouseWheel | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | ProgrammaticChange
RangeHigh | RangeLow | RightClick
UIEnable | Valid | When

Methods

AddProperty | CloneObject | Drag
Move | OLEDrag | ReadExpression
ReadMethod | Refresh | ResetToDefault
SaveAsClass | SetFocus | ShowWhatsThis
WriteExpression | WriteMethod | ZOrder

See Also

TextBox Control | CREATE CLASS | CREATE FORM | DEFINE CLASS | Form Designer | Using Controls


THIS Object Reference

Provides a reference to the current object in event code or in a class definition.

THIS.PropertyName | ObjectName

Parameters

PropertyName
Specifies a property to set or get for the object.
ObjectName
Specifies an object in the class.

Remarks

THIS provides a convenient way of referring to the current object when writing event-handling programs in a form. For example, this Click Event program for a command button sets the button's caption to the current time:

this.caption = time()

Using THIS instead of explicitly referring to the current object by name (for example, thisform.command1.caption) makes program code portable between objects, because it avoids the object's name, and automatically encapsulates the object's parent class.

THIS also allows you to reference a property or an object in a class definition. Methods in a class definition block can use THIS to specify a property or object that will exist when the class is created.

Because multiple instances of objects share the same method code, THIS always refers to the instance in which the code is executing. If there are multiple instances of an object, and one of the object's methods is called, THIS refers to the correct object.

Example

The following example creates a subclass called MyForm, based on the Form class. A method called ChangeBackColor is created. ChangeBackColor uses THIS to refer to MyForm.

DEFINE CLASS MyForm AS FORM
 CAPTION = "This Form"
 HEIGHT = 15
 WIDTH = 20

 PROCEDURE ChangeBackColor
 PARAMETER NewColor
  THIS.BACKCOLOR = NewColor
 ENDPROC
ENDDEFINE

See Also

THISFORM | THISFORMSET | BackColor, ForeColor Properties | DEFINE CLASS


THISFORM Object Reference

Provides a reference to the current form in form event code or in a class definition.

THISFORM.PropertyName | ObjectName

Parameters

PropertyName
Specifies a property for the form.
ObjectName
Specifies an object in the form.

Remarks

THISFORM provides a convenient way of referring to the current form when writing event-handling programs in a form. For example, this Click Event program for a command button sets the button's caption to the current time:

thisform.command1.caption = time()

Using THISFORM instead of explicitly referring to the current form by name (for example, form1.command1.caption) makes program code portable between forms.

When creating class definitions, THISFORM also provides a means of referring to the current form within a method. THISFORM lets you reference an object on the form or property without using multiple Parent properties.

See Also

THIS | THISFORMSET | Click Event


THISFORMSET Object Reference

Provides a reference to the current form set in event code or in a class definition.

THISFORMSET.PropertyName | ObjectName

Parameters

PropertyName
Specifies a property for the form set.
ObjectName
Specifies an object in the form set.

Remarks

THISFORMSET provides a convenient way of referring to the current form set when writing event-handling programs in a form. Using THISFORMSET instead of explicitly referring to the current form by name (for example, form1.command1.caption) makes program code portable between forms.

When creating class definitions, THISFORMSET also provides a means of referring to the current form set within a method. THISFORMSET lets you reference an object on the form or property without using multiple Parent properties.

See Also

THIS | THISFORM | Object Reference Creation | Programmatic Class Definitions


Timer Control

Creates a timer that can run code at regular intervals.

Timer

Remarks

The Timer control, which is invisible to the user, is useful for background processing. A typical use for the timer is checking the system clock to determine if it is time to run a program or application.

If a Timer control has its Enabled property set to True (.T.) and immediately sets the property False (.F.) after a single execution, it may generate its Timer event multiple times. This occurs when the Interval property is less than or approximately the same as the execution time for the Timer event. This can be corrected by increasing the value of the Interval property or decreasing the execution time of the Timer event.

For additional information about creating timers, see Using Controls.

See Also

Timer Control Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | Form Designer


Timer Control Properties, Methods, and Events

Properties

Application | BaseClass | Class
ClassLibrary | Comment | Enabled
Height | Interval | Left
Name | Parent | ParentClass
Tag | Top | Width

Events

Destroy | Error | Init
Timer |  |

Methods

AddProperty | CloneObject | ReadExpression
ReadMethod | Reset | ResetToDefault
SaveAsClass | WriteExpression | WriteMethod

See Also

Timer Control | CREATE CLASS | CREATE FORM | DEFINE CLASS | Form Designer


ToolBar Object

Creates a custom toolbar.

ToolBar

Remarks

Use the ToolBar object to create your own toolbars for your applications.

The following list describes the properties of a custom toolbar:

  • Toolbars are always on top.
  • Toolbars automatically dock when they are moved to the edge of the main Visual FoxPro window.
  • When toolbars are not docked, they have a half-height title bar.
  • When the size of a toolbar is changed, the controls are arranged to fit.
  • You can move a toolbar by clicking and dragging in any area of the toolbar that is not a control.
  • Many controls placed on the toolbar do not receive the focus when they are chosen.
  • Access keys in controls placed in a toolbar are disabled.

Although any control can be placed on a toolbar, some controls, such as a list box, may be too large to fit properly in a docked toolbar. These controls can be programmatically removed from the toolbar when the toolbar is docked and replaced with a smaller version of the same control or a different control.

For additional information about creating toolbars, see Designing Menus and Toolbars.

Example

The following example demonstrates how you can create a toolbar from the Toolbar class. Visual FoxPro rearranges the buttons when the toolbar is resized. When the ToolBar object is created, Visual FoxPro automatically places the controls from left to right in the order they are added to the class definition, ignoring the controls' Top and Left properties.

PUBLIC tbrDesktop
tbrDesktop = CREATEOBJ('mytoolbar')
tbrDesktop.SHOW

DEFINE CLASS myToolBar  AS Toolbar
   ADD OBJECT btnBold  AS CommandButton
   ADD OBJECT sep1      AS Separator
   ADD OBJECT btnItalics AS CommandButton

   btnBold.HEIGHT = 20
   btnBold.WIDTH = 50
   btnBold.Caption = "Bold"
   btnItalics.HEIGHT = 20
   btnItalics.WIDTH = 50
   btnItalics.Caption = "Italic"
   btnItalics.FontBold = .F.

   LEFT   = 1
   TOP = 1
   WIDTH = 25

   CAPTION = "Desktop Attributes"

   PROCEDURE Activate
   this.btnBold.FontBold = _SCREEN.FONTBOLD
   this.btnItalics.FontItalic = _SCREEN.FONTITALIC
   ENDPROC

   PROCEDURE btnBold.CLICK
   _SCREEN.FONTBOLD = !_SCREEN.FONTBOLD
   This.FontBold =_SCREEN.FONTBOLD
   ENDPROC

   PROCEDURE btnItalics.CLICK
   _SCREEN.FONTITALIC = !_SCREEN.FONTITALIC
   This.FontItalic = _SCREEN.FONTITALIC
   ENDPROC
ENDDEFINE

See Also

ToolBar Object Properties, Methods and Events | CREATE CLASS | CREATE FORM | DEFINE CLASS | Separator Object


ToolBar Object Properties, Methods, and Events

Properties

ActiveControl | Application | BackColor
BaseClass | Caption | Class
ClassLibrary | Comment | ColorSource Property
ControlBox | ControlCount | Controls
DataSession | DataSessionID | Docked
DockPosition | Enabled | ForeColor
Height | HelpContextID | HWnd
KeyPreview | Left | LockScreen
MouseIcon | MousePointer | Movable
Name | Objects | OLEDragMode
OLEDragPicture | OLEDropEffects | OLEDropHasData
OLEDropMode | Parent | ParentClass
ScaleMode | ShowTips | ShowWindow
Sizable | Tag | Themes
Top | Visible | WhatsThisHelpID
Width |  |

Events

Activate | AfterDock | BeforeDock
Click | DblClick | Deactivate
Destroy | DragDrop | DragOver
Error | Init | MiddleClick Event
MouseDown | MouseMove | MouseUp
MouseWheel | Moved | OLECompleteDrag
OLEDragDrop | OLEDragOver | OLEGiveFeedBack
OLESetData | OLEStartDrag | Paint
Resize | RightClick | UnDock

Methods

AddObject | AddProperty | CloneObject
Dock | Hide | Move
NewObject | OLEDrag | ReadExpression
ReadMethod | Refresh | Release
RemoveObject | ResetToDefault | SaveAsClass
SetAll | Show | ShowWhatsThis
WriteExpression Method | ZOrder |

See Also

ToolBar Object | CREATE CLASS | CREATE FORM | DEFINE CLASS | Separator Object | Objects Collection


XMLAdapter Class

XMLAdapter is a "two-way" class. You can import XML and its contained schema to create tables, or you can create and generate XML from tables.

An XMLAdapter object stores object references to XML Schema and Document Object Model (DOM) nodes. It does not store actual XML schema information or content. An XMLAdapter object contains a Tables collection that contains one or more XMLTable objects and describes XML as Visual FoxPro cursors along with any relational information. Each XMLTable object can also contain a child XMLTable, and, at most, a Fields collection with one or more XMLField objects.

Note The XMLAdapter class requires Microsoft XML Core Services (MSXML) 4.0 Service Pack 1 (SP1) or later.

Using the XMLAdapter class, you can perform the following tasks:

  • Interpret the following schema formats when you use the XMLAdapter LoadXML and Attach methods.:
    • W3C XML Schemas (XS), W3C XML Schemas (XS) as used with .NET DataSets and SQL-XML
    • Microsoft XML Data Reduced Schema (XDR) as implemented by SQL-XML
    • ADO Recordset Schemas
      Note The XMLAdapter LoadXML method might not correctly interpret other XML schema formats as produced by other products.
  • Retrieve XML and its associated schema from an XML source. XMLAdapter factors the contained schema into an XMLTable and its corresponding XMLField objects using the XMLAdapter LoadXML or Attach methods.
  • Create a cursor based on the schema and populate it with data represented by an XMLTable object when you use the XMLTable ToCursor method.
  • Represent changes from a .NET DiffGram to local or remote tables when you use the XMLTable ApplyDiffgram method.
  • Add one or more XMLTable objects to the XMLAdapter Tables collection or specify that the XMLAdapter LoadXML, Attach, or AddTableSchema methods perform this for you.
  • Use the XMLAdapter ToXML method to generate an XML document in W3C XML Schema format from one or more cursors or tables referenced by the XMLAdapter object.
XMLAdapter

Remarks

If you use an XMLAdapter object to convert XDR schema to XSD schema, you must change the XMLAdapter XMLNamespace property; otherwise, the XML parser cannot reload the XML. The following example illustrates this scenario:

TEXT TO cXML NOSHOW
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
   xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
   xmlns:rs='urn:schemas-microsoft-com:rowset'
   xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
   <s:ElementType name='row' content='eltOnly'>
      <s:AttributeType name='xmlfield' rs:number='1'
         rs:writeunknown='true' rs:nullable='true'>
   <s:datatype dt:type='number' rs:dbtype='currency' dt:maxLength='8'
      rs:scale='4' rs:precision='6' />
</s:AttributeType>
      <s:extends type='rs:rowbase'/>
   </s:ElementType>
</s:Schema>
<rs:data>
   <z:row xmlfield='12.12'/>
</rs:data>
</xml>
ENDTEXT

CLOSE DATABASES ALL
CLEAR

LOCAL oXMLAdapter as XMLAdapter
oXMLAdapter = NEWOBJECT('XMLAdapter')
oXMLadapter.LoadXML(cXML)
IF oXMLAdapter.Tables.Item(1).Fields.Item(1).DataType <> "Y" THEN
   ? 'Failed'
ELSE
   oXMLAdapter.Tables.Item(1).ToCursor()
   oXMLAdapter.XMLNamespace=""
   oXMLAdapter.ReleaseXML(.F.)
   oXMLAdapter.XMLSchemaLocation='c:\myxmlfile.xsd'
   oXMLAdapter.ToXML('c:\myxmlfile.xml',,.T.)
   oXMLadapter2 = NEWOBJECT('xmladapter')
   oXMLAdapter2.XMLSchemaLocation='c:\myxmlfile.xsd'
   oXMLAdapter2.LoadXML('c:\myxmlfile.xml',.T.,.T.)
ENDIF

When the schema is missing or not available, you can specify a schema that Visual FoxPro can use by setting the XMLAdapter XMLSchemaLocation property. You must specify this property before calling LoadXML. When Visual FoxPro executes LoadXML, Visual FoxPro looks for the schema in the following order:

  • Inline schema
  • External schema as specified in the XML document
  • Schema as specified by the XMLSchemaLocation property

The following code creates an XMLAdapter object with a Tables collection that remains empty until you load valid XML into the XMLAdapter object:

oMyAdapter=CREATEOBJECT("xmladapter")

The XML and XML schema data you retrieve using the XMLAdapter LoadXML method remains in memory until they are replaced by a subsequent call to LoadXML or when they are specifically released when you call the XMLAdapter ReleaseXML method.

Nested Tables The following table describes how XMLAdapter treats nested tables as either individual tables or as a whole table depending on the XML data source.

XML data source | Description
ADO.NET DataSet | XMLAdapter considers each nested table as a separate table, which you can convert to a Visual FoxPro cursor. When the XML schema is analyzed, the XMLAdapter LoadXML and Attach methods create an individual XMLTable object for each nested table and adds it to the Tables collection. You can then use the XMLTable ToCursor, ChangesToCursor, and ApplyDiffgram methods to obtain data for each table.
SQL XML | XMLAdapter considers each nested table as inseparable from the parent table. When data is retrieved, the final result of a join operation between those tables is represented as a single result. If multiple levels of nesting exist, such as a child table containing a child table and so on, this single result contains data from a join operation between all tables in the hierarchy. The XMLAdapter LoadXML and Attach methods create XMLTable objects for all tables. However, only the XMLTable object for the top-level parent table is added to the Tables collection. This XMLTable object represents the parent table and provides access to the single and final result from the join operation through the XMLTable ToCursor method. XMLTable objects for child tables are linked to their parents through the ChildTable and ParentTable properties. However, no way exists to obtain data from individual tables in the chain.

See Also

Objects, Collections, and Classes | XMLAdapter Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | XMLTable Class | Fields Collection (XMLTable) | XMLField Class | LoadXML Method | Attach Method | ToCursor Method | ReleaseXML Method | ApplyDiffgram Method | XMLSchemaLocation Property


XMLAdapter Object Properties, Methods, and Events

Objects and Collections

Tables Collection

Properties

DisableEncode | ForceCloseTag | FormattedOutput
IsDiffGram | IsLoaded | IXMLDomElement
MapN19_4ToCurrency | NoCpTrans | PreserveWhiteSpace
RespectCursorCP | SOM | Unicode
UTF8Encoded | WrapCharInCDATA | WrapMemoInCDATA
XMLConstraints | XMLName | XMLNamespace
XMLPrefix | XMLSchemaLocation |

Methods

AddTableSchema | Attach | LoadXML
ReleaseXML | ToXML |

See Also

XMLAdapter Class


XMLField Class

In an XMLTable object, the Fields collection contain XMLField objects. Each XMLField object represents the structure of a field that is meaningful to Visual FoxPro.

The information in each XMLField object provides the details needed, such as the correct data type, size, and other information, to create each field in the cursor. When Visual FoxPro generates XML from a cursor, XMLField objects provide the information to create the XML document and schema.

XMLField

See Also

Objects, Collections, and Classes | XMLField Object Properties, Methods, and Events | XMLTable Class | Fields Collection (XMLTable)


XMLField Object Properties, Methods, and Events

Properties

Alias | DataType | DisableEncode
FractionDigits | IsAttribute | IsBase64
IsBinary | IsNull | Keyfield
MaxLength | NoCpTrans | Unicode
WrapInCDATA | XMLName | XMLTable
XMLType | XSDfractionDigits | XSDmaxLength
XSDtotalDigits | XSDtype |

See Also

XMLField Class


XMLTable Class

The Tables collection in an XMLAdapter object contains XMLTable objects and describes XML as Visual FoxPro cursors along with any relational information. Each XMLTable object can also contain a child XMLTable and, at most, a Fields collection containing XMLField objects.

XMLTable

Remarks

To retrieve XML and factor the contained XML Schema into an XMLTable and its the corresponding XMLField objects, use the XMLAdapter LoadXML or Attach methods. You can then populate a cursor with data represented by the XMLTable object using the XMLTable ToCursor method. You can manually add an XMLTable object to an XMLAdapter Tables collection, or you can use the XMLAdapter AddTableSchema method to perform the same task.

See Also

Objects, Collections, and Classes | XMLTable Object Properties, Methods, and Events | XMLAdapter Class | Fields Collection (XMLTable) | XMLField Class | LoadXML Method | Attach Method | ToCursor Method | Tables Collection (XMLAdapter) | AddTableSchema Method


XMLTable Object Properties, Methods, and Events

Objects and Collections

Fields Collection

Properties

Alias | ChildTable | ParentTable
XMLAdapter | XMLConstraints | XMLName
XMLNamespace | XMLPrefix |

Methods

ApplyDiffgram ChangesToCursor ToCursor

See Also

XMLTable Class


Visual FoxPro Foundation Classes A-Z

Foundation Classes

About Dialog Box Foundation Class

ActiveX Calendar Foundation Class

Application Registry Foundation Class

Array Handler Foundation Class

Cancel Button Foundation Class

Clock Foundation Class

Common Dialog Box Foundation Class

Common System Folders Foundation Class

Conflict Catcher Foundation Class

Cookies Foundation Class

Cross Tab Foundation Class

Crypto API Foundation Class

Data Edit Buttons Foundation Class

Data Navigation Buttons Foundation Class

Data Navigation Object Foundation Class

Data Session Manager Foundation Class

Data Validation Foundation Class

DBF to HTML Foundation Class

Distinct Values Combo Foundation Class

Error Object Foundation Class

Field Mover Foundation Class

File Version Foundation Class

Filter Dialog Box Button Foundation Class

Filter Dialog Box Foundation Class

Filter Expression Dialog Box Foundation Class

Find (Findnext) Buttons Foundation Class

Find Button Foundation Class

Find Dialog Box Foundation Class

Find Files/Text Foundation Class

Find Object Foundation Class

Font Combobox Foundation Class

Fontsize Combobox Foundation Class

Format Toolbar Foundation Class

FRX to HTML Foundation Class

Get File and Directory Foundation Class

GoTo Dialog Box Button Foundation Class

GoTo Dialog Box Foundation Class

Graph By Record Foundation Class

Graph Object Foundation Class

Help Button Foundation Class

Hyperlink Button Foundation Class

Hyperlink Image Foundation Class

Hyperlink Label Foundation Class

INI Access Foundation Class

Item Locator Foundation Class

Keywords Dialog Box Foundation Class

Launch Button Foundation Class

Locate Button Foundation Class

Lookup Combobox Foundation Class

Mail Merge Object Foundation Class

Messagebox Handler Foundation Class

Microsoft Agent Utility Foundation Class

MouseOver Effects Foundation Class

Mover Foundation Class

Navigation Shortcut Menu Foundation Class

Navigation Toolbar Foundation Class

Object State Foundation Class

ODBC Registry Foundation Class

Offline Switch Foundation Class

OK Button Foundation Class

Output Control Foundation Class

Output Dialog Box Foundation Class

Output Object Foundation Class

Password Dialog Box Foundation Class

Pivot Table Foundation Class

Pool Manager Foundation Class

Preview Report Foundation Class

QBF Foundation Class

Registry Access Foundation Class

Regular Expressions Foundation Class

Resize Object Foundation Class

RTF Controls Foundation Class

Run Form Button Foundation Class

SCX to HTML Foundation Class

SendMail Buttons Foundation Class

SetAllX Extension Foundation Class

Shell Execute Foundation Class

Shortcut Menu Class Foundation Class

Simple Edit Buttons Foundation Class

Simple Navigation Buttons Foundation Class

Simple Picture Navigation Buttons Foundation Class

Sort Dialog Box Button Foundation Class

Sort Dialog Box Foundation Class

Sort Mover Foundation Class

Sort Object Foundation Class

Sort Selector Foundation Class

Sound Player Foundation Class

Splash Screen Foundation Class

SQL Pass Through Foundation Class

Stop Watch Foundation Class

String Library Foundation Class

Super Mover Foundation Class

System Metrics Foundation Class

System Toolbar Foundation Class

Table Mover Foundation Class

Text Preview Foundation Class

Thermometer Foundation Class

Trace Aware Timer Foundation Class

Type Library Foundation Class

URL Combo Foundation Class

URL Open Dialog Box Foundation Class

User Privileges Foundation Class

VCR Buttons Foundation Class

VCR Picture Navigation Buttons Foundation Class

Video Player Foundation Class

Web Browser Control Foundation Class

Window Handler Foundation Class

XML Web Services Foundation Classes

Foundation Class Samples

Add a Data-Bound Calendar Sample

Add Data Lookup Combo Boxes Sample

Add Data Querying to Forms Sample

Add Data Sorting and Filtering to Forms Sample

Add Miscellaneous Form Buttons Sample

Add Navigation to Forms Sample

Add Shortcut Menus to Objects Sample

Add Web Hyperlinks to a Form Sample

Application Error Handling Sample

Create a Visual FoxPro Web Browser Sample

Create Record Bound Graphs Sample

Create Toolbar Control Effects Sample

Display Data Reporting Output Options Sample

Fun with Access/Assign Methods Sample

Fun with OLE Drag and Drop Sample

Generate HTML Sample

Handle Application Environment Tasks Sample

Handle Common Windowing Tasks Sample

Handle Data Conflicts Sample

OLE Drag-and-Drop Data Formats Sample

Retrieve Project Location and Name Sample

Run Word, Excel, and Graph Automation Sample

Track Activities in a Project Sample

Treeview/Listbox Drag and Drop Sample

Use Access/Assign Methods for Polymorphism Sample

Use Array Handling Sample

Use Common Application Dialog Boxes Sample

Use Edit Buttons for a Complex Form Sample

Use Edit Buttons for a Simple Form Sample

Use Mover List Boxes for Selecting Data Sample

Use Progress Thermometer Sample


About Dialog Box Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _aboutbox
Base Class | Form
Class Library | _dialogs.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\dialogs.scx

Remarks

This class is a simple About dialog box template for custom applications. The dialog box includes a button that accesses system information using the Registry class.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form, Visual FoxPro displays the Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer. Specify values for the labels, then save and call the form from your application.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cMSINFODir property | Specifies the path of Msinfo.exe. Default: ""
GetRegisteredCompany method | A stub routine to return the registered company. To use, replace the lblUserCorp.Caption value.
GetRegisteredOwner method | A stub routine to return registered owner. To use, replace the lblUserName.Caption value.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


ActiveX Calendar Foundation Class

Category | Date/Time
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data/Time
Class | _olecalendar
Base Class | OLEcontrol
Class Library | _datetime.vcx
Parent Class | _olecontrol
Sample | ...\Samples\Solution\Ffc\datacal.scx

Remarks

This class uses the ActiveX calendar control that can be bound to a date field for a form or other container.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate Date_column value. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
Date_column property | Specifies a date type field to which to link the calendar. Default: ""
RefreshDisplay method | Updates the calendar display with the value in the column specified in the Date_column property. Syntax: RefreshDisplay( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Application Registry Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _filereg
Base Class | Custom
Class Library | _registry.vcx
Parent Class | registry
Sample | ...\Samples\Solution\WinAPI\regfile.scx

Remarks

This class provides a set of registry functions that return application-specific information such as version and location.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
GetAppPath method | Checks and returns path of the application associated with a particular extension. Syntax: GetAppPath(cExtension, cExtnKey, cAppKey, lServer) Return: GetApplication(cExtnKey, @cAppKey, lServer) Arguments: cExtension Specifies the extension of the application. cExtnKey Specifies the registry key of the application. cAppKey Specifies the application path. lServer Specifies whether the extension is a server application.
GetLatestVersion method | Returns latest version for a specified application. Syntax: Getlatestversion(cClass, cExtnKey, cAppKey, lServer) Return: cExtnKey, @cAppKey, lServer Arguments: cClass Specifies the class key of the application. cExtension Specifies the extension of the application. cExtnKey Specifies the registry key of the application. cAppKey Specifies the application path. lServer Specifies whether the this is a server application.
GetApplication method | Retrieves the application key. Syntax: Getapplication(cExtnKey, cAppKey, lServer) Return: @cAppKey Arguments: cExtension Specifies the extension of the application. cExtnKey Specifies the registry key of the application. cAppKey Specifies the application path. lServer Specifies whether the extension is not a full application.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Array Handler Foundation Class

Category | Data Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _arraylib
Base Class | Custom
Class Library | _utility.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\arrays.scx

Remarks

This class provides methods for handling certain array operations that are not performed by Visual FoxPro array functions, including inserting and deleting specific array elements, and scanning an array by column.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
AColScan method | Scans the column nColumn, of array aSearch for the value specified in sExpr. Syntax: AcolScan(@aSearch, sExpr, nColumn, lRetRow) Return: none Arguments: aSearch specifies the array to analyze. sExpr specifies the expression to seek. nColumn specifies the column of the array in which to seek sExpr. lRetRow specifies whether the method returns the row number in which sExpr was found.
DelAitem method | Deletes an array element. Syntax: DelAitem(@aArray, wziRow) Return: none Arguments: aArray specifies the name of the array being processed. wziRow specifies the item to be deleted.
InsAitem method | Inserts an array element. InsAitem(@aArray, sContents, iRow) Return: none Arguments: aArray specifies the name of the array being processed. sContents specifies a string value to be added to aArray. iRow specifies the row in which to insert the value in sContents.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Cancel Button Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdCancel
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _cmdOK
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class releases a form and discards any outstanding buffered data.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places a button on your form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Clock Foundation Class

Category | Date/Time
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Date/Time
Class | _clock
Base Class | Container
Class Library | _datetime.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Controls\Timer\clock.scx

Remarks

This class is a simple clock control for a form or container.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the object in your form where you can specify the appropriate nTimeFormat value. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
nTimeFormat property | Toggles between short (for 0) and long (for non-zero values) formats as specified in the Control Panel. Default: 0

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Common Dialog Box Foundation Class

Category | System Dialog boxes
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _comdlg
Base Class | Custom
Class Library | _system.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Getfilex.scx

Remarks

You can use system Open and Save file dialog boxes that mimic the latest Windows ones in your applications. For example, you can have a Places bar on the left side of the dialog box.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class, or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aFileNames array | Array of filenames returned from dialog box. Default: .F.
aFileList array | Array of file extension filters passed to dialog box. Default: .F.
cCustomFilter property | Custom filter the user created while using dialog box. Default: none
cDefaultExtension property | Default file extension to display. Default: none
cFileName property | Name of file selected or initially set as default. Default: none
cFilePath property | Path from which files were selected. Default: none
cFileTitle property | File title property of the selected file(s). Default: none
cInitialDirectory property | Initial directory from which to display files. Default: none
cTitleBar property | Caption for dialog box title bar. Default: none
lAllowMultiSelect property | Specifies whether to allow multiple files. Default: .F.
lFileMustExist property | Specifies whether to allow only existing files to be entered. Default: .F.
lHideReadOnly property | Specifies whether to hides read-only files from list. Default: .T.
lNewExplorer | Specifies whether to use new explorer user interface and features such as Places bar. Default: .T.
lNoChangeDir property | Specifies whether to prevent changing of displayed directory. Default: .F.
lNoNetworkButton property | Specifies whether to prevent including a network button in the dialog box. Default: .F.
lNoPlacesBar property | Specifies whether to prevent a Places bar in the dialog box. Default: .F.
lNoValidate property | Specifies that files are not validated in the dialog box. Default: .F.
lSaveDialog box property | Specifies whether to use Save dialog box instead of Open one. Default: .F.
nFileCount property | Specifies the number of files selected from the dialog box. Default: 0
nFilterIndex property | Specifies which of the filters were selected from the dialog box. Default: 0
AddFilter method | Specifies the file extension filters to use when displaying the dialog box. Syntax: AddFilter(cDescription, cSkeleton) Return: none Arguments: cDescription provides a description of the filter. cSkeleton specifies the file extension filter skeleton.
ClearFilters method | Clears all file extension filters. Syntax: ClearFilters( ) Return: none Arguments: cUser specifies name of user to check
ShowDialog box method | Displays dialog box with various options such as filters. Syntax: ShowDialog box( ) Return: none Arguments:
TestDialog box method | Test script for displaying a dialog box. Syntax: TestDialog box( ) Return: none Arguments:

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Common System Folders Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _commonfolder
Base Class | Custom
Class Library | _system.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Logo.scx

Remarks

This class gives you the location of common system windows such as the My Documents folder and the Application Data folder. These are commonly needed in applications that provide Windows 2000 Logo compliancy. See SHGetFolderPath in MSDN for more details.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
GetFolder method | Returns path to specified system folder. Syntax: GetFolder(nFolderID, lCreateNew) Return: name of folder Arguments: nFolderID ID reference to the folder. Refer to the class method for common IDs as specified in SHGetFolderPath in MSDN. lCreateNew specifies whether to create folder when one does not exist

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Conflict Catcher Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _conflicts
Base Class | Form
Class Library | _dataquery.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\Conflicts.scx

Remarks

This class provides a dialog box that displays, conflicting rows encountered during editing sessions under optimistic buffering. The original, current, and new values are presented for resolution. You can use this class with either row or table buffering.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form from the selected class, Visual FoxPro displays the Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer. You need to SET MULTILOCKS ON and enable buffering.

Properties, Events, Methods | Description
CursorAlias property | Specifies the alias to check for conflicts. Default: ""
lAutoCheck property | Specifies whether checking begins on startup. Default: .T.
StartCheck method | Checks for conflicts in the buffered data of the alias. Syntax: StartCheck( ) Return: none Arguments: none
ConflictAlias property | Internal to the class.
lRowConflict property | Internal to the class.
aConflicts[1,0] property | Internal to the class.
NextConflict method | Internal to the class.
CheckSource method | Internal to the class.
Alert method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Cookies Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes \Internet
Class | _cookie
Base Class | Custom
Class Library | _internet.vcx
Parent Class | _custom

Remarks

This is a simple Web class for handling cookies between Web pages. This class is designed primarily for use with Microsoft Internet Information Servers such as FoxISAPI.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form where you can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cCookie property | Name of the current cookie. Default: ""
CookieTable property | Name of the cookies table. Default: Cookies.dbf
DBFAlias property | Alias of the cookies table. Default: ""
MakeCookie method | Generates a unique cookie based on the system datetime. Syntax: MakeCookie( ) Return: none Arguments: none
GetCookie method | Gets a cookie from HTML server. Syntax: GetCookie(cStr) Return: none Arguments: cStr specifies the name of the cookie to be retrieved.
WriteCookieInfo method | Writes the cookie's information to the cookies table. Syntax: WriteCookieInfo( ) Return: none Arguments: none
FixURL method | Reads the URL and evaluates %-markers for reading the cookie. Syntax: FixURL(m.cStr) Return: Arguments: m.cStr specifies the name of the cookie to be retrieved.
GetVal method | Retrieves a value from the target string, cStr. Syntax: GetVal(cStr, cVal) Return: cVal Arguments: cStr specifies the name of the string to be searched for the value, cVal cVal specifies the value to be sought in the string, cStr.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Cross Tab Foundation Class

Category | Automation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Automation
Class | _xtab
Base Class | Custom
Class Library | _utility.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Automate.scx

Remarks

This class uses the Cross-Tab Wizard engine to generate a cross tab report when placed on a form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, Visual FoxPro opens a builder so you can specify the appropriate lDisplayNulls, lTotalRows, nTotalOption, and lBrowseAfter values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cOutfile property | The name of the output file. Default: xtabquery
lCursorOnly property | Specifies whether the input datasource is cursor. Default: .T.
lCloseTable property | Specifies whether to close the source datasource after the cross tab is generated. Default: .T.
lShowThem property | Specifies whether to show thermometer during cross tab generation. Default: .T.
nRowField property | Specifies the field position in the datasource of the cross tab rows. Default: 1
nColField property | Species the field position in the datasource of the cross tab columns. Default: 2
nDataField property | Specifies the field position in the datasource of the cross tab data. Default: 3
lTotalRows property | Specifies whether to total rows in the cross tab output. Default: .F.
nTotalOption property | Specifies the Totaling option to perform 0 = sum 1 = count 2 = % of total. Default: 0
lDisplayNulls property | Specifies whether to display null values in the cross tab output. Default: .F.
lBrowseAfter property | Specifies whether to open a Browse window on the cross tab output. Default: .T.
RunXtab method | Generates a cross tab. Syntax: RunXtab( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Crypto API Foundation Class

Category | System Dialog Boxes
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _cryptapi
Base Class | Custom
Class Library | _crypt.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Crypto.scx

Remarks

This advanced class gives you detailed access to Windows Crypto API routines. You can use it to encrypt information in your applications, including text, files, and data fields. Routines exist for stream, block, symmetrical, private and public key encryption, as well as file signing.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

For information about properties, events, and methods, refer to class and sample for details.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Data Edit Buttons Foundation Class

Category | Data Editing
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | picbtns
Base Class | CommandGroup
Class Library | wizbtns.vcx
Parent Class | txtbtns
Sample | ...\Samples\Solution\Ffc\dataedit.scx

Remarks

This is a complete set of edit buttons that includes Top, Previous, Next, Bottom, Find, Print, Add Delete, Edit, and Save buttons. The Form Wizard uses this class.

You can use this class on simple forms with a single table or for 1-to-Many relationship forms using fields for a parent table and a grid for the child table.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro places the buttons on the form. You can specify a data source and provide input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass. The txtbtns parent class contains additional properties you can set.

Properties, Events, Methods | Description
WizBMPpath property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Data Navigation Buttons Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _datanavbtns
Base Class | Container
Class Library | _datanav.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Forms\single.scx

Remarks

This class is a set of navigation buttons that includes Top, Next, Prev, and Bottom buttons. It also contains the DataChecker class to check for conflicts during navigation betweeen records.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, you should provide input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cSkipTable property | The table within which to move the pointer. Default: ""
lEnableDisableOnInit property | Specifies whether the navigation buttons are enabled when they are first loaded. Default: .T.
RecordPointerMoved method | Called each time the record pointer is moved, providing a new event for the class. Syntax: RecordPointerMoved( ) Return: none Arguments: none
EnableDisableButtons method | Enables or disables buttons based on the record pointer location. Syntax: EnableDisableButtons( ) Return: none Arguments: none
BeforeRecordPointerMoved method | Called before the record pointer is moved to determine if the table contains records. Syntax: BeforeRecordPointerMoved( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Data Navigation Object Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _tablenav
Base Class | Custom
Class Library | _table.vcx
Parent Class | _table
Sample | ...\Samples\Solution\Ffc\datanav.scx

Remarks

This is non-visual navigation object that can be used by other controls to navigate records in a datasource such as a table or view.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro displays the class icon on the form so you can add data navigation objects then reference appropriate class methods on the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
lCycle property | Controls movement when the record pointer reaches the end or beginning of the file. Default: .F.
GoBottom method | Moves record pointer to last record. Syntax: GoBottom( ) Return: none Arguments: none
GoRecord method | Moves record pointer to a specified record number. Syntax: GoRecord( ) Return: none Arguments: tiRecord
GoNext method | Moves the record pointer to the next record using SKIP 1. If this movement positions the pointer at EOF( ), behavior is determined by the lCycle property. Syntax: GoNext( ) Return: none Arguments: none
GoPrevious method | Moves record pointer to the previous record using SKIP –1 if the pointer is not already at BOF( ). If this movement positions the pointer at BOF( ), behavior is determined by the lCycle property. Syntax: GoNext( ) Return: none Arguments: none
GoTop method | Moves record pointer to first record. Syntax: GoTop( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Data Session Manager Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _datassession
Base Class | Custom
Class Library | _app.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\environ.scx

Remarks

This class is used to manage data sessions and handle data updates in all forms or formsets in the current data session. It enables an Application object to easily iterate through sessions to provide Windows-closing behavior during Exit or Shutdown. It also provides generic QueryUnload behavior for forms and formsets, and generic session-wide Update and Revert code. You can use it to evaluate whether any data has been changed in a session before you use your own conflict handling procedure.

This class works with free tables as well as tables in databases. Observe the transactions limit (5).

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
iDataChangedMode property | Specifies the type of data change performed. 0 - Everything changed. 1 - Ignore view fields not in Updatefields list. 2- Ignore views not set to send updates. Default: 0
iSavedSessionID property | Specifies integer value representing the ID of the saved session. Default: 1
lSuccess property | Specifies whether the data operation (update) was successful. Default: .T.
lUseTransactions property | Specifies whether to wrap the updating routine in a transaction. Note Only tables in a database container (.dbc) are affected in transactions. Default: .T.
DataChanged method | Checks if data has changed. Syntax: DataChanged( ) Return: none Arguments: none
DataFlush method | Ensures that the active control will have its current contents "recognized" even if you choose to update from a toolbar button while a grid has the focus. Syntax: DataFlush( ) Return: none Arguments: none
GetActiveControlRef method | Returns the truly active control, loRealActiveControl, in cases where the current active control is a Grid. Syntax: GetActiveControlRef(toActiveControl) Return: loRealActiveControl Arguments: toActiveControl specifies the current control.
GetMessageBoxTitle method | Returns a portion of the titlebar text specifying the name of the message. Syntax: GetMessageBoxTitle( ) Return: cTitlebarText Arguments: none
QueryUnload method | Provides dialog boxes to manage data change decisions. Syntax: QueryUnload(tlDataChangeAlreadyConfirmed, toForm, tlNoShow) Return: liResult Arguments: tlDataChangeAlreadyConfirmed specifies whether data has been changed toForm specifies the form. tlNoShow specifies whether to display the form. liResult specifies the MESSAGEBOX or value.
RestoreSessionID method | Restores the data session. Syntax: RestoreSessionID Return: none Arguments: none
Revert method | Reverts the session to original data. Syntax: Revert(tlUserChoiceAlreadyConfirmed, tlDataChangeAlreadyConfirmed, toForm, tlNoShow) Return: none Arguments: tlUserChoiceAlreadyConfirmed specifies whether to display a confirmation dialog box. tlDataChangeAlreadyConfirmed specifies whether to display a confirmation dialog box. toForm specifies the form. tlNoShow specifies whether to display the form.
SetSessionID method | Sets the data session. Syntax: SetSessionID( ) Return: none Arguments: none
Update method | Updates data. Syntax: Update(tlUserChoiceAlreadyConfirmed, tlDataChangeAlreadyConfirmed, toForm, tlNoShow) Return: none Arguments: tlUserChoiceAlreadyConfirmed specifies whether to display a confirmation dialog box. tlDataChangeAlreadyConfirmed specifies whether to display a confirmation dialog box. toForm specifies the form. tlNoShow specifies whether to display the form.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Data Validation Foundation Class

Category | Data Editing
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _datachecker
Base Class | Custom
Class Library | _datanav.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\conflicts.scx

Remarks

This class traps for data conflicts on buffered data.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, you need to specify the appropriate property values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
HandleRecord method | Compares the current value, old value, and original value on disk of each field, displaying a message box if a change or conflict is detected. Syntax: HandleRecord(lnScope) Return: nReturn Arguments: lnScope specifies the degree of validation: 0 = check for conflicts 1 = check for conflicts and verify changes nReturn specifies the action taken: 0 = No Change 1 = Successful Change 2 = Unable to make change
String method | Called by the HandleRecord method, returns a character equivalent of the passed value. Returns only a notification for memo fields. Syntax: String(luValue) Return: none Arguments: luValue specifies the value to be checked.
VerifyChanges method | Prompts a user to save all changes made to a table or record. Syntax: VerifyChanges( ) Return: none Arguments: none
VerifyEachChange method | Prompts a user to confirm each change made. Syntax: VerifyEachChange( ) Return: none Arguments: none
CheckcConflicts method | Notifies a user when data has changed after record editing started. Syntax: CheckcConflicts( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


DBF to HTML Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _dbf2html
Base Class | Custom
Class Library | _internet.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\dohtml.scx

Remarks

This class converts a Visual FoxPro cursor (.DBF) to HTML. Hooks control the scope, visual layout and HTML generation. For more information on creating web pages from Visual FoxPro tables, see Genhtml.prg.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can accept the current values or specify the appropriate cSource, cOutFile, and nGenOutput values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cSource property | Specifies the source file from which to generate HTML. Default: ""
nGenOutput property | _GENHTML output options. 0 = Generate output file. 1 = Generate and display the output file in the Visual FoxPro editor. 2 = Generate and display the output file in Internet Explorer. 3 = Generate and display the output file after displaying a Save As dialog box 4 = Create PUBLIC _oHTML object and generate a file. 5 = Create a PUBLIC _oHTML object without generating a file. Default: 2
cOutFile property | Specifies the name of the HTML file to output. Default: ""
lAutoNameOutput property | Specifies whether _GENHTML should automatically name the output file based on the source. Default: .T.
lUseCurrentAlias property | Specifies whether to use the current alias as the source. Default: .T.
cScope property | Specifies the scope (for example, NEXT or ALL) for the output. Default: ""
cStyle property | Specifies the visual style as listed in the ID field of Genhtml.dbf. Default: ""
GenHTML method | Generates HTML code by calling the Genhtml.prg program using properties specified in cSource, cOutput, and nGenOutput. Syntax: GenHTML( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Distinct Values Combo Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _cbodistinctvalues
Base Class | ComboBox
Class Library | _dataquery.vcx
Parent Class | _combobox
Sample | ...\Samples\Solution\Ffc\datalook2.scx

Remarks

This class performs a lookup of unique values in the ControlSource field to populate a combobox.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you drop the class on a form, Visual FoxPro places a combobox on the form. You need to specify an appropriate value for the ControlSource property. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Error Object Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _error
Base Class | Custom
Class Library | _app.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\error.scx

Remarks

This class is a generic error handler that works for both object and procedural code. This class is used with an application framework generated by the Application Wizard.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can then specify the appropriate property values and access its functionality from input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
GetMessageBoxTitle method | Returns the truly active control, loRealActiveControl, in cases where the current active control is a Grid. Syntax: GetActiveControlRef(toActiveControl) Return: ERROR_MESSAGEBOX_TITLE_LOC Arguments: none
cCurrentMessage property. | Specifies the error message. Default: ""
cCurrentMethod property | Specifies the method in which the error occurred. Default: ""
iCurrentError property | Specifies the error number. Default: 0
iCurrentLine property | Specifies the line in which the error occurred. Default: 0
cCurrentClass property | Specifies the error classification that the error object specifies for this particular error number. Default: ""
lServer property | Checks _VFP.StartMode to determine whether any sort of modal feedback should be avoided because of the way Visual FoxPro was started. Default: (BETWEEN(_VFP.StartMode,1,3)))
cLogAlias property | Specifies the name of the log alias. Default: ""
cLogDBF property | Specifies the name of log file (DBF) that is built by the _error object. Default: ""
lUserCancelled property | Allows the outside program to perform any necessary cleanup operations before release. Default: .F.
HandleMain method | The routine that handles the error. Syntax: HandleMain(tiError, tcMethod, tiLine) Return: none Arguments: tiError specifies the error number. tcMethod specifies the name of the current method. tiLine specifies the number of the current line.
OKToReport method | Abstract class to evaluate whether to report error. Syntax: OKToReport( ) Return: none Arguments: none
isTrivial method | Specifies whether an error is a trivial error. Syntax:IsTrivial(tlWantDialog box) Return: none Arguments: tlWantDialog box specifies an optional dialog box to display.
isFatal method | Specifies whether an error is a fatal error. Syntax:( ) Return: Arguments: tlWantDialog box specifies an optional dialog box to display.
GetMessageBoxTitle method | This is meant for your subclass or instance to fill out with application-specific information. Syntax: GetMessageBoxTitle( ) Return: none Arguments: none
DisplayErrorLog method | Displays the error log. Syntax: DisplayErrorLog( ) Return: none Arguments: none
OKToContinue method | Evaluates an error to determine whether to continue program execution. Syntax: OKToContinue( ) Return: none Arguments: none
SetLog method | Determines the name of or creates the error log table and alias. Syntax: SetLog( ) Return: cLogAlias The error log table has the following format: CREATE TABLE (THIS.cLogDBF) ; (errstamp t, ; listing m,; usernotes m) Arguments: none
cCurrentErrorParam property | Internal to the class.
aErrorClass[1,3] property | Internal to the class.
aErrors[1,6] property | Internal to the class.
*FillArrays . | Internal to the class.
LogErrorReport method | Internal to the class.
GetErrorAttribute method | Internal to the class
isGoodErrorLog method | Internal to the class.
UserHandlesError method | Internal to the class.
UserCancelled method | Internal to the class.
FillLogRecord method | Internal to the class.
DoErrorLogUI method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Field Mover Foundation Class

Category | Movers
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _fieldmover
Base Class | Container
Class Library | _mover.vcx
Parent Class | _supermover
Sample | ...\Samples\Solution\Ffc\movers.scx

Remarks

This is a super mover list box class that automatically loads fields from the current data source when you drop it on a form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can accept or specify the appropriate SkipGeneral, SkipMemo, and AllowReadOnly values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
AllowReadOnly property | Allows for a read-only datasource. Default: .F.
AutoInit property | Automatically run when loaded. Default: .T.
CurrentAlias property | The current alias determined by ALIAS( ). Default: ""
CurrentDBC property | The current database file. Default: ""
CursorType property | Specifies the type of cursor. 1 = local view 2 = remote view 3 = table Default: 3
DBCTable property | Name of the table in the database. Default: ""
MultiTable property | Specifies whether to support multiple tables. Default: .F.
SkipGeneral property | Specifies whether General fields are included in the list. Default: .F.
SkipMemo property | Specifies whether Memo fields are included in the list. Default: .F.
TableType property | Returns the table type - SYS(2029). Default: 0
AcolScan method | Scans a specific column in the array. Syntax: AcolScan(@wztarr, wztexpr, wztcol) Return: none Arguments: wztarr specifies the array to scan. wztexpr specifies the target expression for which to scan. wztcol specifies the column to scan.
AddToArray method | Adds sContents to the array, aAddToArray, at iRow. Syntax: AddToArray(@aAddToArray, sContents, iRow) Return: none Arguments: aAddToArray specifies the array to which to add an item. sContents specifies the addition to the array. iRow specifies in which array row to insert sContents.
Alert method | Displays a messagebox. Syntax: Alert(pMessage) Return: none Arguments: pMessage specifies the message to be displayed by MESSAGEBOX( ).
FieldChange method | Triggered when fields selected changes. Syntax: FieldChange(nButton) Return: none Arguments: nButton specifies the button pressed.
GetTableData method | Retrieves fields from a table. aWizFlist contains the list of fields, aCalcFields contains the list of calculated fields, aPickFields contains the list of selected fields. Syntax: GetTableData( ) Return: aWizFList, aCalcFields, aPickFields Arguments: none
InitData method | Initializes data. Syntax: InitData( ) Return: none Arguments: none
InitVars method | Initializes variables used by movers. Syntax: InitVars( ) Return: none Arguments: none
JustStem method | Retrieves the filename stem. Syntax: JustStem(m.filename) Return: m.filename Arguments: m.filename specifies the filename from which the stem is extracted.
SetDataProps method | Sets data properties of the data source. Syntax: SetDataProps( ) Return: none Arguments: none
UpdateStatusbar method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples | Super Mover


File Version Foundation Class

Category | File Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _fileversion
Base Class | Custom
Class Library | _utility.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\WinAPI\getver.scx

Remarks

Retrieves information from the version resource of a file and stores it in an array.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
cFileName property | The name of the target file. Default: ""
aVersion[12,0] property | Array containing the file version information. Default: .F.
GetVersion method | Retrieves version information for cFileName. Syntax: GetVersion( ) Return: none Arguments: none
DisplayVersion method | Displays the version information for cFileName. Syntax: DisplayVersion( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Filter Dialog Box Button Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _filterbutton
Base Class | CommandButton
Class Library | _table2.vcx
Parent Class | _dialog boxbutton
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This class is a button that, when clicked, displays a dialog box that enables you to filter data in a particular field.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places a button on the form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
lExprDialog box property | Internal to the class.
cExprClass property | Internal to the class.
cFilterClass property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Filter Dialog Box Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _filterdialog
Base Class | Form
Class Library | _table.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This class is a dialog box that uses an existing filter object to allow you to filter data in a particular field.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form or Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you drop the class on a project or choose Create a new form from the selected class in the shortcut menu, Visual FoxPro displays an Open dialog box so you can specify the name of the form. Then Visual FoxPro creates and opens the form in the Form Designer.

_FilterDialog enables you to use Visual FoxPro expressions to build a complex filter using booleans, nested conditions, and so on, limited to the fields available in currently-open tables. It automatically provides delimiters for various field types. It suggests which expressions might be optimizable by checking available tags on the current table. The field list places "*" in front of field names that have usable index tags.

Like _FilterExpr, _FilterDialog needs at least one open table on which it can set a filter. Unlike _FilterExpr, _FilterDialog is not necessarily modal, however it is modal when _FilterExpr calls it. FilterDialog determines the current table in the Init event. FilterDialog never changes data sessions.

When called by _FilterExpr, _FilterDialog determines what filter the user has already specified in the _FilterExpr edit box and displays that expression as its initial set of conditions. When _FilterDialog is called directly, it checks the current alias for a filter, using SET("FILTER"), and shows any current filter as its initial conditions.

The _FilterDialog SetUpFilter( ) method uses the conditions listed in the dialog box and creates a filter expression, then applies the NORMALIZE( ) function to the expression. The result is stored in the cFilter property. When you click OK, SetupFilter( ) runs. _FilterDialog calls the _FilterExpr.SetFilter method if it is called by an instance of _FilterExpr; otherwise it uses _table to determine if navigation is allowed, sets the filter directly, and refreshes the display if the filter is set.

_FilterDialog is a standalone object and does not require the existence of _FilterExpr to build a filter. However, when called by _FilterExpr, the two dialog boxes work together to build a filter, by specifying an expression in _FilterExpr and by making choices in _FilterDialog. For more information on the Filter Expression class, see _Filter Expression.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cFilter property | Contains the filter expression processed in the SetupFilter method. Default: ""
SetupFilter method | This method takes the conditions listed in the dialog box and creates them into a filter expression, then applies the NORMALIZE( ) function to the expression. Syntax: SetupFilter(tcValue) Return: cFilter Arguments: tcValue specifies an expression to use as the filter. cFilter is the value contained in the cFilter property.
cOldexact property | Internal to the class.
iBact property | Internal to the class.
iQptr property | Internal to the class.
iQuerymax property | Internal to the class.
iSelect property | Internal to the class.
oCaller property | Internal to the class.
aDBFs[1,0] property | Internal to the class.
aTags[1,0] property | Internal to the class.
aQuery[1,0] property | Internal to the class.
aFLDs[1,0] property | Internal to the class.
SetAction method | Internal to the class.
QReset method | Internal to the class.
QSet method | Internal to the class.
FSet method | Internal to the class.
NoBrack method | Internal to the class.
Brackets method | Internal to the class.
SetTags method | Internal to the class.
OnTag method | Internal to the class.
NoTag method | Internal to the class.
EditQuery method | Internal to the class.
SetRowsources method | Internal to the class.
SetInitialQueryParts method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | _Filter Expression


Filter Expression Dialog Box Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _filterexpr
Base Class | Form
Class Library | _table.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This class creates an advanced filter expression dialog box.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form or Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you drop the class on a project or choose Create a new form from the selected class in the shortcut menu, Visual FoxPro displays an Open dialog box so you can specify the name of the form. Visual FoxPro then creates and opens the form in the Form Designer.

_FilterExpr is a modal dialog box that enables you to specify a filter expression, or to construct a filter expression using one of two subsidiary dialog boxes.

The lAdvanced property toggles _FilterExpr between two modes, standard and advanced. In standard mode, the Build expression button uses an instance of the _FilterDialog class to build a simple expression. In advanced mode, the button uses the value in the _GETEXPR system variable.

The cFilter property contains the current contents of the filter expression the user builds. The edit box bound to the cFilter property can contain up to 254 characters.

If _FilterExpr doesn't find a table on which to act, it returns false (.F.) before leaving the Init event; otherwise it restores these settings in its Unload method. When _FilterExpr instantiates, if ALIAS( ) is empty, it looks for an open table in the current data session of the currently selected form or formset.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Descriptionbox b
cFilter property | Contains the filter expression processed in the SetupFilter method. Default: (SPACE(254))
lAdvanced property | This is used to toggle _FilterExpr between two modes, _FilterDialog false (.F) and GETEXPR true (.T.). Default: .F.
iOldSession property | The old data session. Default: 0
iOldSelect property | The old work area. Default: 0
SetFilter method | Sets the value of cFilter. This method is primarily useful when _FilterDialog is called modally to do further work on the expression to be built. Syntax: SetFilter(tcValue) Return: cFilter Arguments: tcValue specifies an expression to use as the filter. cFilter is the filter expression.
SetFilterOnTable method | If the current table allows navigation, this method applies the current filter to the current alias, issues a LOCATE, and then invokes the RefreshLastWindowAfterChange( ) method to get the filter for the next available window in your application. Syntax: SetFilterOnTable( ) Return: none Arguments: none
cFilter_Access method | Internal to the class. Removes carriage returns, line feeds, and tabs from the filter expression and replaces these characters with spaces.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Find (Findnext) Buttons Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _findnextbuttons
Base Class | Container
Class Library | _table.vcx
Parent Class | _findbutton
Sample | ...\Samples\Solution\Ffc\dataqry.scx

Remarks

This class provides a generic find/findnext buttonset.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

When placed on a form or other container, this class locates a record using a Find object based on specified criteria. For details, see Find Button or _findbutton in the _table.vcx class library in the Class Browser.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Find Button


Find Button Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _findbutton
Base Class | Container
Class Library | _table.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\dataqry.scx

Remarks

This class provides a generic Find button, uses the Find object, and locates a record based on specific criteria.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate cFindString, lMatchCase, lSkipMemo, and lWraparound values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cAlias property | Specifies the data source in which to search. Default: ""
cFindString property | Specifies the string for which to search.Default: ""
LFindAgain | Specifies whether the file is traversed to find successive instances of cFindString. Default: .F.
lMatchCase property | Specifies the case-sensitivity of the search. Default: .F.
lSkipMemos property | Specifies whether to ignore Memo fields in the search. Default: .F.
lWrapAround property | Specifies whether to continue searching from the beginning if the end of file (EOF) is reached. Default: .F.
DoFind method | Performs a search. Syntax: DoFind( ) Return: none Arguments: none
SkipField method | Removes the field, tcSkipField from the search. Syntax: SkipField( ) Return: none Arguments: none tcSkipField specifies the field to ignore during the search.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Find Dialog Box Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _finddialog
Base Class | Form
Class Library | _table.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\dataqry.scx

Remarks

This class provides a generic Find dialog box with simple options such as field choice. This class uses the Find object.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form or Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you drop the class on a project or choose Create a new form from the selected class in the shortcut menu, Visual FoxPro displays an Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cAlias property | Specifies the data source in which to search. Default: ""
cFindString property | Specifies the string for which to search. Default: ""
lAdvanced property | Specifies whether to display the advanced options in the dialog box. Default: .F.
lFindAgain | Specifies whether the file is traversed to find successive instances of cFindString. Default: .F.
lMatchCase property | Specifies the case-sensitivity of the search. Default: .F.
lSkipMemos property | Specifies whether to eliminate Memo fields from the search. Default: .F.
lWrapAround property | Specifies whether to continue searching from the beginning if end of file reached. Default: .F.
DOFind method | Prforms a search. Syntax: DoFind( ) Return: none Arguments: none
SkipField method | Removes the field, tcSkipField, from the search. Syntax: SkipField( ) Return: none Arguments: none tcSkipField specifies the field to ignore during the search.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Find Files/Text Foundation Class

Category | File Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _filer
Base Class | Custom
Class Library | _utility.vcx
Parent Class | _custom

Remarks

This wrapper class uses the FILER.DLL COM object to search for files. It is a simplified version of the filer form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate cFileExpression, cSearchPath, cSearchText, lIgnoreCase, lSubFolder, and lWholeWords values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cFileExpression property | Specifies a file skeleton for the search. This expression can include wildcards such as ? and *. Default: ""
cSearchPath property | Specifies the directory in which to begin searching for files. Default: ""
cSearchText property | Specifies the text string to search for within files. Default: ""
lIgnoreCase property | Specifies whether to ignore case during the search. Default: .T.
lPromptDir property | Specifies whether to prompt the user for a search path if none is entered. Default: .T.
lSubFolder property | Specifies whether to search in subfolders for files. Default: .T.
lWholeWords property | Specifies whether to search for whole word matches. Default: .F.
oFiles property | Specifies a collection of files returned by the Find search. Default: .F.
Find method | Searches for files that meet the criteria specified by the properties. Syntax: Find( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Find Object Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _tablefind
Base Class | Custom
Class Library | _table.vcx
Parent Class | _table
Sample | ...\Samples\Solution\Ffc\dataqry.scx

Remarks

This class creates a generic object that locates a record based on specified critereria. The class also provides an optional Find Next method.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify appropriate cFindString, lMatchCase, lSkipMemo, lWrapAround values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cFields property | Specifies the list of fields to search. Default: ""
cFindString property | Specifies the string for which to search. Default: ""
lFindAgain | Specifies whether the file is traversed to find successive instances of cFindString. Default: .F.
lMatchCase property | Specifies whether to use case-sensitivity in the search. Default: .F.
lSkipMemos property | Specifies whether to ignore Memo fields in the search. Default: .F.
lWrapAround property | Specifies whether to continue searching from the beginning if end of file (EOF) is reached. Default: .F.
SkipField method | Removes tcSkipField from the search. Syntax: SkipField( ) Return: none Arguments: none tcSkipField specifies the field to ignore during the search.
aMemos [1] property | Internal to the class. Default: .F.
iMemos property | Internal to the class. Default: 0
cControlCharacter property | Internal to the class. Default: ~

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Font Combobox Foundation Class

Category | Text Formatting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Text Formatting
Class | _cbofontname
Base Class | ComboBox
Class Library | _format.vcx
Parent Class | _combobox
Sample | ...\Samples\Solution\Toolbars\format.scx

Remarks

This class is a combobox that lists available fonts when placed on a form. It is also used by the tbrEditing and rtfControls classes of _format.scx.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places a combobox on the form so you can specify appropriate font values for objects in the active form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Fontsize Combobox Foundation Class

Category | Text Formatting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Text Formatting
Class | _cbofontsize
Base Class | ComboBox
Class Library | _format.vcx
Parent Class | _combobox
Sample | ...\Samples\Solution\Toolbars\format.scx

Remarks

This class is a combobox that lists available font sizes. It is also used by the tbrEditing and RTFControls classes of _format.scx.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places a combobox on the form so you can specify appropriate font size values for objects in the active form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
nSmallestFont property | For scalable fonts, specifies the smallest allowable fontsize. Default: 8
nLargestFont property | For scalable fonts, specifies the largest allowable fontsize. Default: 48

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Format Toolbar Foundation Class

Category | Text Format
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Text Formatting
Class | _tbrediting
Base Class | Toolbar
Class Library | _format.vcx
Parent Class | _toolbars
Sample | ...\Samples\Solution\Toolbars\format.scx

Remarks

This class, when placed on a form, provides a toolbar for applying font formatting to text in the active control.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you add the class to a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
nAppliesTo property | Specifies the scope of the formatting. 1 = apply to the selected control 3 = apply to all controls Default: 1

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


FRX to HTML Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _frx2html
Base Class | Custom
Class Library | _internet.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\dohtml.scx

Remarks

This class converts a Visual FoxPro report (.FRX) to HTML. The class includes properties to control the scope, visual layout and HTML generation. For more information, see Genhtml.prg.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the cSource, cOutFile, nGenOutput, and lAutonameOutput values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods Description
cOutFile property Specifies the name of the HTML file to create.
Default: ""
cSource property Specifies the source file from which to generate HTML.
Default: ""
nGenOutput property _GENHTML output options.
Default: 20 = Generate output file.
1 = Generate and display the output file in the Visual FoxPro editor.
2 = Generate and display the output file in Internet Explorer.
3 = Generate and display the output file after displaying a Save As dialog box
4 = Create a PUBLIC _oHTML object and generate a file.
5 = Create a PUBLIC _oHTML object without generating a file.
lAutoNameOutput property Specifies whether _GENHTML should automatically name the output file based on the source.
Default: .T.
cScope property Specifies the scope (for example, NEXT or ALL) for the output.
Default: ""
cStyle property Specifies the visual style as listed in the ID field of Genhtml.dbf.
Default: ""
GenHTML method Generates HTML code by calling the Genhtml.prg program using properties specified in cSource, cOutput, and nGenOutFile.
Syntax: GenHTML( )
Return: none
Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Get File and Directory Foundation Class

Category | User Interface
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _folder
Base Class | Container
Class Library | _controls.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\getproject.scx

Remarks

This dialog box retrieves both a file and folder name. It is used to create new projects in directories of the same name.

To use, drop the class on a project or form. When you drop the class on a project, you can choose between adding the class or creating a subclass. When you drop the class to a form, Visual FoxPro places the class controls including a Browse button on your form.

Properties, Events, Methods | Description
cLastProjectFile property | Internal to the class.
cExt property | Internal to the class.
TrimFile property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


GoTo Dialog Box Button Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _gotobutton
Base Class | CommandButton
Class Library | _table2.vcx
Parent Class | _dialogbutton
Sample | ...\Samples\Solution\Ffc\Buttons.scx

Remarks

This class creates a button that displays the GoTo dialog box so you can navigate to a specific record.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a form, Visual FoxPro places a button on your form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


GoTo Dialog Box Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigatio n
Class | _gotodialog
Class Library | _table.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\datanav.scx

Remarks

This class creates a GoTo Record dialog box.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you drop the class on a project or choose Create a new form from the selected class in the shortcut menu, Visual FoxPro opens a builder so you can specify the name of the form, then creates and opens the form in the Form Designer.

_GoToDialog is a modal dialog box with a _TableNav member and a spinner to allow the user to specify a record number. When you click OK, the GoToRecord method navigates to the specified record, then runs the RefreshLastWindowAfterChange method to update the display. Note that GoToRecord( ) updates the display even if the table does not permit navigation, in case you revert a change.

_GoToDialog uses _TableNav to determine the current alias at startup. It then sets the spinner SpinnerLowValue and KeyboardLowValue to 1 and SpinnerHighValue and KeyboardHighValue to RECCOUNT( ). It also sets the spinner Value property appropriately.

Properties, Events, Methods | Description
RefreshUIAfterChange method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Graph By Record Foundation Class

Category | Automation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Automation
Class | _graphbyrec
Base Class | Container
Class Library | _utility.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\automate.scx

Remarks

This container class creates graphs at the record level, unlike the AutoGraph class, which creates graphs from an entire Visual FoxPro cursor. The class also includes a set of buttons to navigate between records and dynamically refresh the chart.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, Visual FoxPro opens a builder so you can specify the nChartType and cLblField values for the graph data points and axis labels. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods Description
cLblField property Specifies the caption for the record label.
Default: ""
nChartType property Specifies the chart type. The valid values
are:
1 = Area
2 = Area 3D
3 = Bar
4 = Bar 3D
5 = Column
6 = Column 3D
7 = Pie
8 = Pie 3D
9 = Line
10 = Line 3D

Default: 4
lSeriesByRow property Specifies whether to plot a series by row.
Default: .T.
aDataFields[1] property Specifies the array of data fields to graph.
Default: .F.
SetupGraph method Initializes graph controls.
Syntax: SetupGraph( )
Return: none
Arguments: none
RefreshGraph method Refreshes the graph when the record pointer is moved.
Syntax: RefreshGraph( )
Return: none
Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Graph Object Foundation Class

Category | Automation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Automation
Class | autograph
Base Class | Custom
Class Library | autograph.vcx
Parent Class | automation
Sample | ...\Samples\Solution\Ffc\Automate.scx

Remarks

This custom class generates a chart by automating MS Graph using the core Graph Wizard engine.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the cOutputfile, nChartType, lAddLegend, and lSeriesByRow values. You can also use the autograph class and supply values for fields, chart type, the preview form, and default name in program code. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aDataFields[1,1] property Specifies the name of a numeric field in the target table (the "Y" axis value).
Default: .F.
cCategoryField property Specifies a field in the target table (the "X" axis).
Default: .F.
cOutFile property Name of the output file if any.
Default: ""
cTitle property Title caption of the chart.
Default: ""
lCurrRec property Specifies whether to retain the current record number, if only graphing one
record.
Default:.F.
lAddedData property Flags if data is already added for performance.
Default: .F.
lAddLegend property Adds a legend to the chart.
Default: .T.
lAddTitle property Adds a title to the chart.
Default:.T.
lGraphRecord property Specifies whether to graph the current record. The default graphs the entire cursor.
Default: .F.
lKeepForm property Specifies whether to use the user-supplied form and OLE control.
Default: .F
lSeriesByRow property Plots a series by row or column.
Default: .T.
lShowNulls property Displays null values in the chart.
Default: .T.
lShowWhenDone property Specifies whether to display a preview of the form.
Default: .T.
lUse8Type property Specifies whether to use the nChartType property.
Default: .F.
lUseAutoformat property Use the MS Graph autocharting gallery.
Default:.F.
nAction property Specifies the type of output action:
0 = preview
1 = save to form
2 = save to table
3 = save to query

Default: 1
nChartAutoformat property Chart format for autoformat.
Default: 2
nChartAutoGallery property Gallery chart format for autoformat.
Default: 1
nChartSubType property Sub type of chart.
Default: 1
nChartType property Specifies the chart type. The valid values are:
1 = Area
2 = Bar
3 = Column
4 = Line
5 = Pie
6 = Doughnut
7 = Radar
8 = Scatter
9 = Area 3D
10 = Bar 3D
11 = Column 3D
12 = Line 3D
13 = Pie 3D
-4102 = Pie 3D

Default: 1
nGraphVersion property Version of Graph being used.
Default: 5
cDefNewField property | Internal to the class.
cGraphDBF property | Internal to the class.
cGraphField property | Internal to the class.
cGraphFldCol property | Internal to the class.
cGraphFldRow property | Internal to the class.
cGraphPrevClass property | Internal to the class.
cLastDataCol property | Internal to the class.
cLastDataRow property | Internal to the class.
cOLEServer property | Internal to the class.
cOpenAlias property | Internal to the class.
cOutGenField property | Internal to the class.
GraphPreview property | Internal to the class.
lAutograph property | Internal to the class.
lDontStripLegend property | Internal to the class.
lHadPreview property | Internal to the class.
lReplaceDBF property | Internal to the class.
lStripExcessLegend property | Internal to the class.
nDataCount property | Internal to the class.
nDataSeries property | Internal to the class.
nLastAction property | Internal to the class.
nTotalDataFlds property | Internal to the class.
oGraphRef property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Help Button Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdHelp
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _commandbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class provides a button that, when clicked, displays a Help topic by searching for the HelpContextID specified in the control.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro places a button on your form. You need to provide the appropriate value to replace the default value of HelpContextID. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Hyperlink Button Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _hyperlinkcommandbutton
Base Class | CommandButton
Class Library | _hyperlink.vcx
Parent Class | _commandbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class provides the functionality of the Hyperlink object and launches a Web Browser when you click a button.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the button name and the URL to use. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cTarget property | Specifies the URL to use. Default: ""
GoBack method | Executes a hyperlink jump backward within the history list. Syntax: GoBack( ) Return: none Arguments: none
GoForward method | Executes a hyperlink jump forward within the history list. Syntax: GoForward( ) Return: none Arguments: none
cFrame property | Internal to the class.
cHyperlinkclass property | Internal to the class.
cHyperlinkClassLibrary property | Internal to the class.
cLocation property | Internal to the class.
lFormSynch property | Internal to the class.
lHyperlinkCreated property | Internal to the class.
lNewWindow property | Internal to the class.
lVisited property | Internal to the class.
nVisitedForecolor property | Internal to the class.
oHyperlink property | Internal to the class.
cTarget_assign method | Internal to the class.
Follow method | Internal to the class.
lVisited_assign( ) method | Internal to the class.
nVisitedForecolor_assign( ) method | Internal to the class.
oHyperlink_access( ) method | Internal to the class.
ShowVisitedForecolor( ) method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Hyperlink Image Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _hyperlinkimage
Base Class | Image
Class Library | _hyperlink.vcx
Parent Class | _image
Sample | ...\Samples\Solution\Ffc\hyperlnk.scx

Remarks

This class provides the functionality of the Hyperlink object and launches a Web Browser when you click an image.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the image name and the URL to use. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cTarget property | Specifies the URL to use. Default: ""
GoBack method | Executes a hyperlink jump backward within the history list. Syntax: GoBack( ) Return: none Arguments: none
GoForward method | Executes a hyperlink jump forward within the history list. Syntax: GoForward( ) Return: none Arguments: none
cFrame property | Internal to the class.
cHyperlinkClass property | Internal to the class.
cHyperlinkClassLibrary property | Internal to the class.
cLocation property | Internal to the class.
cTarget_assign method | Internal to the class.
Follow method | Internal to the class.
lFormsSynch property | Internal to the class.
lHyperlinkcreated property | Internal to the class.
lNewWindow property | Internal to the class.
lVisited property | Internal to the class.
oHyperlink property | Internal to the class.
oHyperlink_access method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Hyperlink Label Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _hyperlinklabel
Base Class | Label
Class Library | _hyperlink.vcx
Parent Class | _label
Sample | ...\Samples\Solution\Ffc\hyperlnk.scx

Remarks

This class provides the functionality of the Hyperlink object and launches a Web Browser when you click a label.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the label and the URL (in cTarget) to use. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cTarget property | Specifies the URL to use Default: ""
GoBack method | Executes a hyperlink jump backward within the history list. Syntax: GoBack( ) Return: none Arguments: none
GoForward method | Executes a hyperlink jump forward within the history list. Syntax: GoForward( ) Return: none Arguments: none
cFrame property | Internal to the class.
cHyperlinkClass property | Internal to the class.
cHyperlinkClassLibrary property | Internal to the class.
cLocation property | Internal to the class.
cTarget_assign method | Internal to the class.
Follow method | Internal to the class.
lFormsSynch property | Internal to the class.
lHyperlinkcreated property | Internal to the class.
lNewWindow property | Internal to the class.
lVisited property | Internal to the class.
oHyperlink property | Internal to the class.
oHyperlink_access method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


INI Access Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | oldinireg
Base Class | Custom
Class Library | Registry.vcx
Parent Class | registry

Remarks

This class provides a set of registry functions that access old INI-style file settings.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
GetINIEntry method | Retrieves information from INI entry. Syntax: GetINIEntry(cValue, cSection, cEntry, cINIFile) Arguments: cValue specifies the value to be applied to cEntry. cSection specifies the section of the .ini file in which cEntry occurs. cEntry specifies the item to be assigned cValue. cINIFile specifies the name of the .ini file.
GetINISection method | Retrieves information from INI section. Syntax: GetINISection(@aSections, cSection, cINIFile) Arguments: aSections specifies an array of cSections included in the .ini file. cSection specifies the section of cINIfile file to retrieve. cINIFile specifies the name of the .ini file.
LoadINIFuncs method | Loads functions needed for reading .ini files. Syntax: LoadINIFuncs( ) Return: none Arguments: none
WriteINIEntry method | Writes a specific INI entry. Syntax: WriteINIEntry(cValue, cSection, cEntry, cINIFile) Arguments: cValue specifies the new value. cSection specifies the section of cINIfile file to retrieve. cINIFile specifies the name of the .ini file.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Item Locator Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _locateitem
Base Class | Form
Class Library | _dialogs.vcx
Parent Class | _dialog
Sample | ...\Samples\Solution\Ffc\dialogs.scx

Remarks

This class provides a File Locator dialog box. It is designed to locate a file that your application needs but cannot find.

To use, drop the class on a project or, from the Item Shortcut Menu, select Create Form or Create Form. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you add the class to a form, Visual FoxPro displays an Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer.

In the cDefaultFileName property, specify the file you want to retrieve. If the file is not located, the oLocateItem object opens a GetFile dialog box so you can locate the file.

Properties, Events, Methods | Description
cDefaultFileName property | The name of the file to locate. Default: .NULL.
cFilename property | The file name retrieved from the Locate button. When no file is found, the GetFile dialog box appears. Default: .NULL.
oLocateItem object | An object reference that contains the return value set to the cFileName property. Default: .F.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Keywords Dialog Box Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _keywords
Base Class | Form
Class Library | dialogs.vcx
Parent Class | _dialog
Sample | ...\Samples\Solution\Ffc\dialogs.scx

Remarks

This class creates a dialog box that displays a specified list of keywords, like the Component Gallery keywords dialog box.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you drop the class on a project or choose Create a new form from the selected class in the shortcut menu, Visual FoxPro opens a builder so you can specify the name of the form, then creates and opens the form in the Form Designer.

By default, the dialog box uses the Component Gallery Keywords.dbf file. You can specify your own keywords file in the cTablename property. You can also provide a set of keywords in a comma-delimited list in the cKeywords property.

Properties, Events, Methods | Description
cKeywords property | Specifies a group of space-delimited keywords to seek in the table specified in cTablename. Default: ""
cTablename property | Specifies the name of a table that contains keywords. Default: (IIF(VERSION(2)=0,"",HOME( )+"gallery\")+"keywords.dbf"))
oKeywords object | The object that retrieves the list of keywords set to cKeywords property. Default: .F.
Apply method | Displays the keywords specified by the cKeywords property from the table specified in cTablename. Syntax: Apply( ) Return: none Arguments: none
lAddMode property | Internal to the class.
lUpdated property | Internal to the class.
cLastValue property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Launch Button Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdLaunch
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _commandbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This button launches an application using the RUN command.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate cFileName value. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
cFileName property | Specifies the name of the file to launch. Default: ""

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Locate Button Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _locatebutton
Base Class | CommandButton
Class Library | _table2.vcx
Parent Class | _dialogbutton
Sample | ...\Samples\Solution\Ffc\dataqry.scx

Remarks

This button displays a dialog box to locate a record.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro places a button that opens the Locate dialog box. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Lookup Combobox Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _cbolookup
Base Class | ComboBox
Class Library | _dataquery.vcx
Parent Class | _combobox
Sample | ...\Samples\Solution\Ffc\datalook2.scx

Remarks

This class performs a lookup of values in a field to populate a combobox.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the appropriate Lookup_table, Order_column, Display_column, and Return_column values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
Display_column property | Specifies the column value from the Lookup_table to display in the drop-down list. Default: ""
Lookup_table property | Specifies the table in which to find the column containing the values to display in the drop down list. Default: ""
Return_column property | Specifies the column value (0, 1 or 2) to return to the Value property of the combo box. Default: ""
Order_column property | Specifies the column to order the records displayed in the drop down list (optional). Default: ""

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Mail Merge Object Foundation Class

Category | Automation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Automation
Class | mailmerge
Base Class | Custom
Class Library | mailmrge.vcx
Parent Class | automation
Sample | ...\Samples\Solution\Ffc\Automate.scx

Remarks

This custom class uses the Mail Merge Wizard engine to generate a Microsoft Word Mail Merge document.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, specify the FROM table (cDataPath), the location and version of Word (cExe and cWordVersion), and other appropriate properties values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
aWPMrg[2,0] property | An array of procedures for handling various merge styles. Default: .F.
cDataFile property | A FoxPro 2.6 copy of a Visual FoxPro 3.0 or later table. Default: ""
cDataPath property | Specifies the path to the FROM table. Default: ""
cDataSrc property | Specifies the data source for the ODBC connection. Default: ""
cDocName property | Default: "" Specifies the name of the existing .doc file.
cExe property | Specifies the full path to the Word application. Default: ""
cODBCSource property | Specifies the ODBC connection string. Default: ""
cSaveFile property | Specifies the file for holding merged data. Default: ""
CSQLstmt property | A SQL statement for extracting data. Default: ""
CSQLstmt2 property | Specifies an additional SQL statement, if cSQLStmt is greater than 255 characters (for Word). Default: ""
cWordVersion property | Specifies the version of Word that is installed (for example, '8'). Default: ""
lAlerted property | Specifies whether a failure alert was issued. Default: .F.
lEnglish property | Verifies whether Word recognizes English Word Basic commands. Default: .F.
lHasVerWord property | Verifies the presence of Word. Default: .F.
nNewDoc property | Indicates whether a new document will be used (see Mailmrge.h). Default: 1
nTemplate property | Specifies the main document type. Applies to Word only. See Mailmrge.h. Default: 1
nWordProc property | Specifies the selected word processor. See Mailmrge.h. Default: 1
SysCh property | Specifies a DDE channel. Default: -1
CheckVer method | Verifies the version of Word being used. Internal to the class. Syntax: CheckVer( ) Return: none Arguments: none
GetMSW method | Retrieves the Word command line from the registry. Syntax: GetMSW(m.cversion) Return: the full path to Word Arguments: m.cversion specifies the version of Word being used.
MrgCommaDel method | Generates a comma-delimited text file from data. Syntax: MrgCommaDel( ) Return: a comma-delimited file Arguments: none
MrgWord method | Determines the versions of Word to be used in the merge. Syntax: MrgWord( ) Return: none Arguments: none
MSWerr method | The error handler for use while AppleScript is being run. Syntax: MSWerr( ) Return: none Arguments: none
GetSQLst method | Retrieves the SQL statement for extracting data. Internal to the class. Syntax: GetSQLst( ) Return: none Arguments: none
PrepData method | Determines the kind of data source that is being used for the mail merge and normalizes the data for processing, Internal to the class. Syntax: PrepData( ) Return: none Arguments: none
SaveSQL method | Generates a table of SQL results. Internal to the class. Syntax: SaveSQL( ) Return: none Arguments: none
WzMMData method | Copies data to a text file. Internal to the class. Syntax: WzMMData( ) Return: none Arguments: none
MakeFieldList | Internal to the class.
MailMergeWord8 | Internal to the class.
MailMergeWord6 | Internal to the class.
MSWmldlg | Internal to the class.
Startword | Internal to the class.
MailMergeMacWord6 | Internal to the class.
MMCleanup method | Closes files - Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Messagebox Handler Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _msgbox
Base Class | Custom
Class Library | _dialogs.vcx
Parent Class | _custom

Remarks

This class provides a simple wrapper around the MessageBox function so you can easily display a message box of a specified type with alternate contents.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, specify the appropriate values for the message (cMessage), the type of message box (nType), and other appropriate properties. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cMessage property | Specifies the message box message text. Default: ""
nType property | Specifies the message box type. For options, see MessageBox( ). Default: 48
cTitle property | Specifies the message box title text. Default: _screen.caption
lBeep property | Specifies whether a beep occurs when message box is activated. Default: .F.
Show method | Displays a message box and returns the dialog box result. Syntax: Show(tcMessage, tnType, tcTitle, tlBeep) Return: this.Display( ) Arguments: tcMessage specifies the text that appears in the dialog box. tnType specifies the buttons and icons options, the default button, and the behavior of the dialog box. tcTitle specifies the text that appears in the title bar of the dialog box. tlBeep specifies whether an alert sound accompanies the display of the dialog box.
Set method | Sets the properties for the dialog box message, type, title, and alert sound. Internal to the class. Syntax: Set(tcMessage, tnType, tcTitle, tlBeep, tnParameters) Return: none Arguments: tcMessage specifies the text that appears in the dialog box. tnType specifies the buttons and icons options, the default button, and the behavior of the dialog box. tcTitle specifies the text that appears in the title bar of the dialog box. tlBeep specifies whether an alert sound accompanies display of the dialog box.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Microsoft Agent Utility Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _agent
Base Class | Custom
Class Library | _agent.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Agent.scx

Remarks

This class gives you access to Microsoft Agent API routines so that you can integrate agents (similar to Office Assistants) such as Peedy the parakeet into your application.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
ActiveAgent property | Provides a pointer to the active Agent character object. Default: .F.
AgentControl property | Provides a pointer to the agent object. Default: .F.
ErrorOccurred property | Set to True (.T.) when an error occurs on LOAD. Default: .F.
ErrorState property | Always set to LOAD.
GestureAt method | Causes the active agent to gesture at a given point. Syntax: GestureAt(tnX, tnY, tnCoords, toObj) Return: .F. if there is no ActiveAgent. Arguments: tnX specifies x coordinate. tnY specifies y coordinate. tnCoords whether coordinates are local or world. toObj specifies the object reference for LocalToWorld conversion.
Hide method | Hides the active agent. Syntax: Hide( ) Return: .F. if there is no ActiveAgent. Arguments: none
Interrupt method | Interrupts an animation. Syntax: Interrupt(toRequest) Return: .F. if there is no ActiveAgent. Arguments: toRequest specifies request object.
Load method | Loads an agent character from the specified location (can be a file or URL). Syntax: Load(tcAgentName, tcAgentLocation) Return: .F. if an error occurred. Arguments: tcAgentName specifies name of agent tcAgentLocation specifies the agent file.
LocalToWorld method | Converts local coordinates to world coordinates. Syntax: LocalToWorld(tnAxis, tnPos, toObj) Return: converted value of tnPos. Arguments: tnAxis specifies the axis. tnPos specifies axis coordinate. toObj specifies object to which conversion is relative.
MoveBy method | Moves the active agent by the passed values in the x or y direction. Syntax: MoveBy(tnX, tnY, tnCoords, toObj) Return: .F. if there is no ActiveAgent. Arguments: tnX specifies x coordinate. tnY specifies y coordinate. tnCoords specifies whether coordinates are local or world. toObj object reference for LocalToWorld conversion.
MoveTo method | Moves the default agent or agent passed to the location specificed. Syntax: MoveTo(tnX, tnY, tnCoords, toObj) Return: .F. if there is no ActiveAgent. Arguments: tnX specifies x coordinate. tnY specifies y coordinate. tnCoords specifies whether coordinates are local or world. toObj object reference for LocalToWorld conversion.
Play method | Causes the active agent to play an animation. Syntax: Play(tcAnimation) Return: .F. if there is no ActiveAgent or a Request Object reference. Arguments: tcAnimation specifies animation to play.
SetActiveAgent method | Sets the active agent to the agent with the passed name. Syntax: SetActiveAgent(tcAgentName) Return: .T. if ActiveAgent is set. Arguments: tcAgentName specifies the name of the agent.
Show method | Displays the active agent. Syntax: Show(tnX, tnY, tnCoords, toObj) Return: .F. if there is no ActiveAgent. Arguments: tnX specifies x coordinate tnY specifies y coordinate tnCoords specifies whether coordinates are local or world. toObj object reference for LocalToWorld conversion.
Speak method | Causes the active agent to speak the passed phrase. Syntax: Speak(tcText) Return: .F. if there is no ActiveAgent or a Request Object reference. Arguments: tcText specifies text to speak.
Stop method | Stops a looping animation. Syntax: Stop( ) Return: .F. if there is no ActiveAgent. Arguments:
Wait method | Waits for a request to complete. Syntax: Wait(toRequest) Return: .F. if there is no ActiveAgent. Arguments: toRequest specifies the requesting object.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


MouseOver Effects Foundation Class

Category | User Interface
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _mouseoverfx
Base Class | Custom
Class Library | _ui.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\mousefx.scx

Remarks

This class highlights a control as the mouse is dragged over it.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, specify the appropriate values for the highlight (iHighlightColor and nHighlightWidth), and other appropriate properties, then place a reference to the HighlightMe method in the MouseMove event of the control you want to affect. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
nMargin property | Specifies the border between the control and the highlight. Default: 2
iShadowColor property | Specifies the color code of the shadow. Default: 0
lMouseoverHost property | Specifies whether the mouse is over the mousefx host. Default: .T.
nHighlightWidth property | Specifies the width of the highlight. Default: 2
iHighlightColor property | Specifies the color code of the highlight. Default: 0
CancelHighlight method | Uses the value of lMouseoverHost to determine whether there is a highlighted object requiring change. Sets oCurrentCoolControl to .NULL. and Returns true (.T.) when lMouseOver indicates that the current control has just changed. Your subclasses can check this return value or the state of lMouseOverHost and oCurrentCoolControl to "subtract" their own special effects from cool controls at the appropriate times. Syntax: CancelHighlight (toObject) Return: lChange Arguments: toObject specifies the object affected upon the MouseOver event. lChange specifies whether the current control has already changed.
HighlightMe method | Sets .oCurrentCoolControl, the current control, to the object reference specified by toObject. Returns true (.T.) when it has to act because the current control has just changed. Returns .F. if it doesn't need to act because there is no change in the current control. Your subclasses can use the oCurrentCoolControl property and the return value of this method to decide when they have to act, providing other special effects, perhaps specific for some special classes of "current controls". Syntax: HighlightMe(toObject) Return: lChange Arguments: toObject specifies the object affected upon the MouseOver event. lChange specifies whether the current control has already changed.
oCurrentCoolControl property | Internal to the class. Default: ""

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Mover Foundation Class

Category | Movers
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _mover
Base Class | Container
Class Library | _mover.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\movers.scx

Remarks

When placed on a project or form, this class provides a simple mover list box class with Move and Remove buttons.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class list box controls and move buttons on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aChoices[1,0] property | The array of available choices in the left list box. Default: .F.
aSelections[1,0] property | The array of selected items in the right list box. Default: .F.
UseArrays property | Specifies whether to use arrays for the list boxes. Default: .T.
InitChoices method | Initializes the choices array. Syntax: InitChoices(@aChoices) Return: none Arguments: aChoices specifies an array of initial choices.
InitSelections method | Initializes the selections array. Syntax: InitSelections(@aSelections) Return: none Arguments: aSelections specifies the array of initial selections.
GetSelections method | Retrieves the selected items. Syntax: GetSelections(@aSelections) Return: none Arguments: aSelections specifies the name of the array containing the target selections.
PopList method | The routine to populate list boxes. Syntax: PopList(@aListArray, oLstRef) Return: none Arguments: aListArray specifies the items with which to populate the list. oLstRef is a reference to the control object.
OldlSelectedItem property | Internal to the class.
OldrSelectedItem property | Internal to the class.
SortLeft property | Internal to the class.
Updated property | Internal to the class.
SizeToContainer method | Internal to the class.
ValidItem method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Navigation Shortcut Menu Foundation Class

Category | Menus
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _navmenu
Base Class | Container
Class Library | _table2.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This is a shortcut menu that can be dropped onto a form with items for common data navigation, sorting, filtering and finding options. You call this class from the RightClick event of a form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro prompts you to automatically add the necessary code to implement the shortcut menu. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cClass property | Specifies the class of the dialog box containing the shortcut menu. Default: ""
cClasslib property | Specifies the class library containing the class of the dialog box containing the shortcut menu. Default: ""
DoMenu method . | Runs a menu routine. Syntax: Domenu( ) Return: none Arguments: none
RefreshForm method | Refreshes the active form when data is updated. Syntax: RefreshForm( ) Return: none Arguments: none
DeleteRecord method | Deletes the current record. Syntax: DeleteRecord( ) Return: none Arguments: none
AddRecord method | Adds a new record. Syntax: AddRecord( ) Return: none Arguments: none
DoFilter method | Displays a filter dialog box. Syntax: DoFilter( ) Return: none Arguments: none
DoGoto method | Displays a GoTo dialog box. Syntax: DoGoto( ) Return: none Arguments: none
DoSort method | Displays a Sort dialog box. Syntax: DoSort( ) Return: none Arguments: none
DoDialog method | Displays a dialog box. Syntax: DoDialog( ) Return: none Arguments: none
SetMenu method | Specifies the menu contents through code containing AddMenuBar( ) expressions. Syntax: SetMenu( ) Return: none Arguments: none
DoFilter2 method | Displays an Advanced Filter dialog box. Syntax: DoFilter2( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Navigation Toolbar Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _navtoolbarclass
Base Class | Container
Class Library | _table2.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This class provides a set of data navigation buttons and other controls in a toolbar.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro automatically makes the connections. When you drop the class on a project, you can choose between adding the class or creating a subclass.

This class differs from navigation buttons by providing an output window as well as navigation buttons.

Properties, Events, Methods | Description
oToolbar property | Internal to the class.
cClassLib property | Internal to the class.
cClass property | Internal to the class.
nLastTop property | Internal to the class.
nLastLeft property | Internal to the class.
lDocked property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Object State Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _objectstate
Base Class | Custom
Class Library | _app.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\environ.scx

Remarks

This class determines the state of an object. It saves and/or restores object property settings automatically or explicitly.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aProperties[1,3] property | The array for saving/restoring properties of oObject. Default: .F.
lAutomatic property | Specifies whether oObject properties are saved and restored. If this attribute is true (.T.), the _ObjectState object will restore all the attributes you've saved for its target object when the _ObjectState object is destroyed. Default: .F.
oObject | Reference to the target object whose state is being saved. Default: .NULL.
Restore method | Restores the value of a property for oObject if the value has changed. If tcWhichProperty is not passed, all saved properties of oObject are restored. (This method is called with no argument in the _ObjectState.Destroy( ) event when _ObjectState.lAutomatic is true (.T.). Syntax: Restore(tcWhichProperty) Return: tcSave Arguments: tcWhichProperty specifies the property to be restored. tcSave specifies the value to be restored.
Save method | Saves the current value of a property for oObject. You can use this instead of the tlSave argument of the Set method. Syntax: Save(tcProperty, tcTypeValue) Return: none Arguments: tcProperty specifies the property being accessed. tcTypeValue specifies the value being saved for tcProperty.
Set method | Sets a property to a new value for oObject. Syntax: Set(tcProperty, tvValue, tlSave) Return: Arguments: tcProperty specifies the property to set. tvValue specifies the value tcProperty is to be set to. tlSave specifies whether the current value is retained for later restoration.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


ODBC Registry Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _odbcreg
Base Class | Custom
Class Library | registry.vcx
Parent Class | registry
Sample | ...\Samples\Solution\WinAPI\regodbc.scx

Remarks

This class provides a set of registry functions that return ODBC-specific information such as drivers and data sources.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
LoadODBCFuncs method | Loads the ODBC registry functions. Syntax: LoadODBCFuncs( ) Return: none Arguments: none
GetODBCDrvrs method | Retrieves ODBC drivers. Syntax: GetODBCDrvrs(@aDrvrs, lDataSources) Return: nRetVal Arguments: aDrvrs specifies, in an array, the drivers to retrieve. lDataSources specifies whether to access datasources.
EnumODBCDrvrs method | Enumerates through ODBC drivers. Syntax: EnumODBCDrvrs(@aDrvrOpts, cODBCDriver) Return: aDrvrOpts, m.cSourceKey, HKEY_LOCAL_MACHINE, .F. Arguments: aDrvrOpts specifies available driver options. cODBCDriver specifies the driver name.
EnumODBCData method | Enumerates through ODBC data sources. Syntax: EnumODBCData(@aDrvrOpts, cDataSource) Return: aDrvrOpts, m.cSourceKey, HKEY_CURRENT_USER, .F.) Arguments: aDrvrOpts specifies available driver options. cDataSource specifies the name of the data source.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Offline Switch Foundation Class

Category | Data Editing
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _offline
Base Class | Container
Class Library | _dataquery.vcx
Parent Class | container

Remarks

The Offline switch works in a database containing remote views. This class provides a set of buttons that toggle between use of online and offline data.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class buttons on the form, and opens a builder so you can specify lUseCurrentDBC, lAllViews, lUpdateViews, and lRevertOnFail values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cDatabase property | Specifies the name of the database containing views to take offline. Default: .F.
cViews[1,0] property | Specifies the array of views to process. Default: .F.
lAllViews property | Specifies whether to automatically use all views in the database. Default: .F.
lRevertOnFail property | Secifies whether to revert all views if one fails when going offline. Default: .T.
lUpdateViews property | Specifies whether to update all views when going online. Default: .T.
lUseCurrentDBC property | Specifies whether to use the currently opened database at the start. Default: .T.
GoOffLine method | Takes the views specified in the cViews array offline. Syntax: GoOffline( ) Return: none Arguments: none
GoOnLine method | Takes the views specified in the cViews array online. Syntax: GoOnline( ) Return: none Arguments: none
CheckOffLine method | Checks to see if views are currently online/offline. Syntax: CheckOffline( ) Return: none Arguments: none
Alert method | Displays a message box containing cMessage. Syntax: Alert(cMessage) Return: m.cMessage Arguments: cMessage specifies the text of the alert message.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


OK Button Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdOK
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _commanbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class releases a form and updates any outstanding buffered data.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro places a button on your form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Output Control Foundation Class

Category | Reporting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Output
Class | _outputchoices
Base Class | Container
Class Library | _reports.vcx
Parent Class | _output
Sample | ...\Samples\Solution\Ffc\output.scx

Remarks

This class provides controls that prompt you for a reporting output option. Using the Report object, it also allows you to select which report to print.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Output Dialog Box Foundation Class

Category | Reporting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Output
Class | _outputdialog
Base Class | Form
Class Library | _reports.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\output.scx

Remarks

This class uses the Report object to display a dialog box that prompts the user for a reporting output option.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form, Visual FoxPro opens a builder so you can specify the name of the form, then creates and opens the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cAlias property | Specifies the name of the data source to output. Default: ""
cDestination property | Specifies the list of available destinations that changes dynamically depending on whether cReport, cAlias, or both, contain values. Default: ""
cDisplayFontName property | Specifies the name of an on-screen display of output; for example, when you issue BROWSE or when the _Showtext class is instantiated for text display. Default: .F.
cFieldList property | Specifies a comma-delimited list of fields or expressions. It affects only direct data sources (BROWSEs and LISTs). Default: ""
cHTMLClass property | Specifies an optional HTML class and class library passed to _GENHTML. Default: ""
cHTMLStyleID property | Specifies an optional HTML style passed to _GENHTML. Default: .F.
cReport property | Specifies the name of report or label to output. Default: ""
cScope property | Specifies a valid scope expression for output. Default: .F.
lAddSourceNameToDropdown property | Specifies whether some destinations display in the aDestinations array. Default: .F.
lPreventScopeChanges property | Specifies whether you can change output scope. Default: .F.
lPreventSourceChanges property | Specifies whether source changes for cAlias or cReport are prevented. Default: .F.
cAlias_access method | Internal to the class.
cAlias_assign method | Internal to the class.
cDestination_access method | Internal to the class.
cDestination_assign method | Internal to the class.
cDisplayFontName_access method | Internal to the class.
cDisplayFontName_assign method | Internal to the class.
cFieldList_access method | Internal to the class.
cFieldList_assign method | Internal to the class.
CheckOKButton method | Internal to the class.
cHTMLClass_access | Internal to the class.
cHTMLClass_assign | Internal to the class.
cHTMLStyleID_access | Internal to the class.
cHTMLStyleID_assign | Internal to the class.
cReport_access method | Internal to the class.
cReport_assign method | Internal to the class.
cScope_access method | Internal to the class.
cScope_assign method | Internal to the class.
lAddSourceNameToDropdown_access method | Internal to the class.
lAddSourceNameToDropdown_assign method | Internal to the class.
lPreventScopeChanges_assign method | Internal to the class.
lPreventSourceChanges_access method | Internal to the class.
lPreventSourceChanges_assign method | Internal to the class.
RespondToPermissionForScopeChanges method | Internal to the class.
RespondToPermissionForSourceChanges method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Output Object Foundation Class

Category | Reporting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Output
Class | _output
Base Class | Container
Class Library | _reports.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\output.scx

Remarks

This is a generic reporting object that provides a variety of report source and destination options from reports and labels or directly from a data source.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aDestinations[1,2] property | The array of destinations. Default: .F.
aOptions[1,2] property | The array of destination output options. Default: .F.
cAlias property | Specifies the data source that is used for non-report/label output formats. This property defaults to the current alias, if any. Default: ""
cDestination property | Specifies a list of available destinations that changes dynamically, depending on whether cReport, cAlias, or both contain values. The list of available destinations is stored in the aDestinations array. Default: "PRINTREPORT"
cDisplayFontName property | Specifies an on-screen font for output; for example, when you issue BROWSE or when the _Showtext class is instantiated for text display. Default: Courier New
cFieldList property | Specifies a comma-delimited list of fields or expressions. It affects only direct data sources (BROWSEs and LISTs). Default: ""
cHtmlClass property | Specifies an optional HTML class and class library passed to _GENHTML. Default: ""
cHtmlstyleid property | Specifies an optional HTML style passed to _GENHTML. Default: ""
cOption property | Specifies the list of available options that changes dynamically to fit the current cDestination. Default: WINDEFAULT
cReport property | Specifies a label or report form suitable for Visual FoxPro-formatted output. Default: ""
cScope property | Specifies a macro-expanded string to be added to the command that executes the actual output. It must be a valid scope such as "FOR lExpression". Default: ""
cTextfile property | Specifies the file name for all output destinations that go to disk, which include text files, printer-image files, and export formats. Default: ""
cVFPPrinterName property | Specifies the name of the current Visual FoxPro default printer as distinct from the Windows default printer. Default: ""
lAddSourceNameToDropdown property | Specifies whether some destinations display in the aDestinations array. Default: .T.
lPreventSourceChanges property | Prevents source changes for cAlias or cReport. Default: .F.
CopyTable method | Exports a table. Syntax: CopyTable( ) Return: Arguments:
GenHTML method | Generates HTML code by calling the Genhtml.prg program. Syntax: GenHTML( ) Return: none Arguments: none
Output method | Specifies the main method that is called to generate output based on settings. Syntax: Output(liSelect) Return: Arguments: liSelect specifies the output destination.
OutputToScreen method | Outputs to the screen. Syntax: OutputToScreen( ) Return: none Arguments: none
SetDestinations method | Evaluates the current environment to populate an array of output destinations. Syntax: SetDestinations( ) Return: lSuccess Arguments: none
SetOptions method | Evaluates the current environment to populate an array of options for output destinations. Syntax: SetOptions( ) Return: lSuccess Arguments: none
cAlias_assign method | Internal to the class.
cDestination_assign method | Internal to the class.
cDisplayFontName_assign method | Internal to the class.
cOption_assign method | Internal to the class.
cReport_assign method | Internal to the class.
cScope_assign method | Internal to the class.
cVFPPrinterName_access method | Internal to the class.
lPreventSourceChanges_assign method | Internal to the class.
PrintList method | Internal to the class.
PrintReport method | Internal to the class.
SetOutputPrinter method | Internal to the class.
SetVFPPrinter method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Password Dialog Box Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _login
Base Class | Form
Class Library | _dialogs.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\dialogs.scx

Remarks

This class is a simple password login dialog box for custom applications.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form or Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form from the selected class, Visual FoxPro opens a builder so you can specify the name of the login form, then creates and opens the form in the Form Designer.

Properties, Events, Methods | Description
cAlias property | Specifies the alias of the password table. Default: ""
cFieldName property | Specifies the name of field containing the user name. Default: ""
cPassword property | Specifies the name of the field containing the user password. Default: ""
cTable property | Specifies the name of table containing the user password information. Default: ""

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Pool Manager Foundation Class

Category | Class information
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _poolmanager
Base Class | Custom
Class Library | _poolmanager.vcx
Parent Class | Custom
Sample | ...\Samples\Solution\Ffc\_PoolManager.scx

Remarks

The Pool Manager Foundation Class manages a pool, or collection, of objects from a single class. When you need to use an object repeatedly for a short time, use the Pool Manager class. This class works best if creating an instance of the object takes more time than obtaining an existing instance. This is commonly the case for the following types of classes:

  • Non-lightweight classes like the Visual FoxPro Form class
  • Classes that contain resource-intensive code in the Init event of the form
  • Classes that make use of external resources such as a database connection, automation server, or XML Web service

You can add the Pool Manager class to the Form or Class designers from the Toolbox or to a project. When you add the Pool Manager class to a project, you can add the class or create a subclass.

The Pool Manager class uses the Visual FoxPro Collection base class for storing object references. For more information, see Collection Class.

For more information on using foundation classes, see Guidelines for Using Visual FoxPro Foundation Classes.

Properties, Events, Methods Description
cClass property Name of the pooled class. You can also set this property by passing it as the first parameter when creating the pool manager object.

Default: None
cClassLibrary property Library that contains the pooled class. The cClassLibrary property can point to a visual class library or a program file.

You can change this property by passing it as the second parameter when creating the pool manager object.

Default: None
lRaiseEvent property If True (.T.), raises the ObjectRequested and ObjectReturned events. If you do not need these events to increase performance, set this property to False (.F.).

Default: .T.
nObjectsCreated property Incremented each time an object is created

Default: 0
Get method Returns an object reference to a pooled object. All parameters are passed to the Init event of a newly created object and the ObjectRequested event.

Syntax: Get( Param1, Param2, …)

Return: Object

Arguments: Must pass parameters by value and cannot pass arrays to a pooled object.
Free method Returns an object to the pool, making it available to the next Get method call.

Syntax: Free(@oObject)

Return: None

Arguments: oObject is an object reference previously obtained from the Get method. The object can be passed by reference.
ObjectRequested event Fires when an object is requested.

You can use this event to initialize an object based on the current parameters. When a pooled object binds to this event, the event is raised for every object, not just the object itself.

Syntax: ObjectRequested( oObject, Param1, Param2, …)

Return: None

Arguments: oObject is a reference to the pooled object that is returned to the caller. All parameters from the Get method are passed to this event as additional parameters.
ObjectReturned event Fires when an object is returned to the pool by calling the Free method. When a pooled object binds to this event, the event is raised for every object, not just the object itself.

Syntax: ObjectReturned(oObject)

Return: None

Arguments: oObject is a reference to the pooled object.

See Also

Visual FoxPro Foundation Classes A-Z | Pool Manager Sample | Foundation Class Samples


Pivot Table Foundation Class

Category | Automation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Automation
Class | pivottable
Base Class | Custom
Class Library | pivtable.vcx
Parent Class | automation
Sample | ...\Samples\Solution\Ffc\Automate.scx

Remarks

This Custom class uses the PivotTable Wizard engine to generate an Excel Pivot Table from FoxPro data.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, Visual FoxPro opens a builder so you can specify the cPivFldCol, cPivFldRow, cPivFldPage, cPivFldData, lHasColumnTotals, and lHasRowTotals values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
CheckState property Specifies whether to test the state of
Microsoft Excel through an error routine.
Default: .F.
cOutfile property Specifies the name of the output file.
Default: ""
cPivFldCol property Specifies the name of the field that
identifies each pivot table column.
Default: ""
cPivFldData property Specifies the name of the field reported
as pivot table data.
Default: ""
cPivFldPage property Specifies the name of the field that
determines the pivot table pages.
Default: ""
cPivFldRow property Specifies the name of the field whose
values identify each pivot table row.
Default: ""
lHasColumnTotals property Specifies whether to total columns.
Default: .F.
lHasRowTotals property Specifies whether to total rows.
Default: .F.
nAction property Specifies the output action to perform.
Output action:
1 = Microsoft Excel worksheet
2 = Visual FoxPro form

Default: 1
GetXLPath method Queries the registry for the existence of
Microsoft Excel.
Syntax: GetXLPath( )
Return: none
Arguments: none
MSQueryCheck method Queries the registry for the existence of
MS Query.
Syntax: MSQueryCheck( )
Return: none
Arguments: none
PivotOutput method Creates a Microsoft Excel pivot table
output.
Syntax: PivotOutput( )
Return: none
Arguments: none
aFldList[1,1] property | Internal to the class.
cFormName property | Internal to the class.
cFormSCX property | Internal to the class.
CheckFldLen method | Internal to the class.
GetDOSName method | Internal to the class.
lHasMSQry32 property | Internal to the class.
lHasNoTask property | Internal to the class.
lIsNumeric property | Internal to the class.
SkipError property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Preview Report Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdRunReport
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _commandbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class provides a generic button to run a report directly or through the Output dialog box class.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify the cFileName and lSetCaption values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cDialogClass property | Specifies the output dialog box class. Default: _OutputDialog
cDialogClasslib property | Specifies the output dialog box class library. Default: (IIF(VERSION(2)=0,"",HOME( )+"FFC\")+"_REPORTS.VCX"))
cFilename property | Specifies the name of the form to run. Default: ""
cOutputDialogAlias property | Specifies the name of the output dialog box alias. Default: ""
lOutputDialogPreventScope property | Specifies whether to prevent changing the scope in dialog box. Default: .F.
lOutputDialogPreventSource property | Specifies whether to prevent changing the alias/report in dialog box. Default: .F.
lPromptForReport property | Specifies whether to ask for a report name. Default: .T.
lSetCaption property | Specifies whether caption is automatically based on the value of cFilename. Default:.T.
lUseOutputDialog property | Specifies whether to display the foundation class Output dialog box. Default:.T.
ShowOutputDialog method | Displays the foundation class Output dialog box. Syntax: ShowOutputDialog( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Output Dialog Box


QBF Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _qbf
Base Class | Container
Class Library | _dataquery.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Forms\qbf.scx

Remarks

This class provides a button set for Query-By-Form querying.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the QBF command buttons on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
QBF_Table property | Specifies the table on which to run the query. Default: ""
ParseCondition( )method | Specifies a filter based on a query. Syntax: ParseCondition(cCondition, cControlSource) Return: lcRetCondition Arguments: cControlSource specifies the data bound to the control. cCondition specifies the query expression.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Registry Access Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | registry
Base Class | Custom
Class Library | registry.vcx
Parent Class | registry
Sample | ...\Samples\Solution\WinAPI\regfox.scx

Remarks

This class provides access to information in the Windows Registry.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
CloseKey method | Closes a registry key. Syntax: CloseKey( ) Return: none Arguments: none
DeleteKey method | Deletes a registry key. Syntax: DeleteKey(nUserKey, cKeyPath) Return: none Arguments: nUserKey specifies the Registry User key. cKeyPath specifies the Registry User key path.
DeleteKeyValue method | Deletes a value from a registry key. Syntax: DeleteKeyValue(cOptName, cKeyPath, nUserKey) Return: Arguments: cOptName specifies the name of the Registry key option. cKeyPath specifies the path to the Registry key. nUserKey specifies the User key.
EnumKeys method | Enumerates through a registry key. Syntax: EnumKeys(@aKeyNames) Return: Arguments: aKeyNames specifies the Registry keys to enumerate.
EnumKeyValues method | Enumerates through values of a registry key. Syntax: EnumKeyValues(@aKeyValues) Return: Arguments: aKeyValues specifies the Registry User key values to enumerate.
EnumOptions method | Enumerates through all entries for a key and populates an array with values. Syntax: EnumOptions(@aRegOpts, cOptPath, nUserKey, lEnumKeys) Return: Arguments: aRegOpts specifies the Registry key option. cOptPath specifies the path to the Registry key option. nUserKey specifies the User key ID. lEnumKeys specifies whether to enumerate other options, if they exist.
GetKeyValue method | Returns the value for a key. Syntax: GetKeyValue(cValueName, cKeyValue) Return: Arguments: cValueName specifies the name of the value to retrieve. cKeyValue specifies the value of cValueName.
GetRegKey method | Returns a registry key setting. Syntax: GetRegKey(cOptName, cOptVal, cKeyPath, nUserKey) Return: Arguments: cOptName specifies the name of the Registry key option. cOptVal specifies the value to apply to the option. cKeyPath specifies the Registry key path. nUserKey specifies the User key.
IsKey method | Returns whether a specified key exists. Syntax: IsKey(cKeyName, nRegKey) Return: Arguments: cKeyName specifies the name of the user ley to check, if it exists. nRegKey specifies the Registry key ID
OpenKey method | Opens a registry key. Syntax: Open(cLookUpKey, nRegKey, lCreateKey) Return: Arguments: cLookUpKey specifies the name of the user key for which to search. nRegKey specifies the Registry key ID lCreateKey specifies whether to create a new Registry key if the specified one does not exist.
SetKeyValue method | Sets the value of a registry key. Syntax: SetKeyValue(cValueName, cValue) Return: Arguments: cValueName specifies the name of the value to set. cValue specifies the value to apply to cValueName.
SetRegKey method | Sets the registry key setting. Syntax: SetRegKey(cOptName, cOptVal, cKeyPath, nUserKey) Return: Arguments: cOptName specifies the name of the Registry key option. cOptVal specifies the value to apply to the option. cKeyPath specifies the Registry key path. nUserKey specifies the User key ID.
cAppPathKey property | Internal to the class.
cIniDllFile property | Internal to the class.
cODBCDllFile property | Internal to the class.
cRegDllFile property | Internal to the class.
cVfpOptPath property | Internal to the class.
lCreateKey property | Internal to the class.
lHadError property | Internal to the class.
lLoaddedDlls property | Internal to the class.
lLoadedInis property | Internal to the class.
lLoadedOdbcs property | Internal to the class.
nCurrentKey property | Internal to the class.
nCurrentOS property | Internal to the class.
nUserKey property | Internal to the class.
LoadRegFuncs method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Regular Expressions Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _regexp
Base Class | Custom
Class Library | _regexp.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Regexp.scx

Remarks

Regular expressions are a concise and flexible notation for finding and replacing patterns of text. The Regular Expressions class gives you access to routines for using regular expressions in your applications.

For information about the sample, see Search Text Using Regular Expressions. For general details about regular expressions, you can refer to MSDN.

To use the Regular Expressions Foundation Class, drop the class on a project or form, or from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
Matches array | Specifies the array containing the results of the string test. Default: .F.
Pattern property | Contains the pattern (regular expression). Default: *
Clear method | Clears all values. Syntax: Clear( ) Return: none Arguments:
Execute method | Tests the pattern against the string. Syntax: Execute(tcStr, tlCaseMatters) Return: number of matches Arguments: tcStr specifies string to search. tlCaseMatters specifies whether to ignore case.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Resize Object Foundation Class

Category | User Interface
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _resizable
Base Class | Custom
Class Library | _controls.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Forms\cresize.scx

Remarks

This class causes objects dropped onto a form to resize and move with the Form's Resize event.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, specify the AdjustControls method in the Resize event of the controls on the form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
InitialResize property | Specifies whether controls have been adjusted before. Default: .T.
AdjustControls method | Adjusts the placement and size of contained objects after a Resize event. Syntax: AdjustControls( ) Return: none Arguments: none
Reset method | Resets the Timer control so that it starts counting from 0. Syntax: Reset( ) Return: none Arguments: none
InitialFormHeight property | Internal to the class.
InitialFormWidth property | Internal to the class.
aControlStats[1,5] property | Internal to the class.
AddToArray method | Internal to the class.
SetSize method | Internal to the class.
LoopThroughControls method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


RTF Controls Foundation Class

Category | Text Format
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Text Formatting
Class | _rtfcontrols
Base Class | Container
Class Library | _format.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Toolbars\format.scx

Remarks

This class, when placed on a form, provides controls for applying font formatting to text in the active control.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro places the comboboxes and button controls on the form in the Form Designer.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Run Form Button Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _cmdRunForm
Base Class | CommandButton
Class Library | _miscbtns.vcx
Parent Class | _commandbutton
Sample | ...\Samples\Solution\Ffc\buttons.scx

Remarks

This class provides a generic button to run a form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can specify cFileName, the name of the form you want to run. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
cFilename property | Specifies the name of the form to run. Default: ""
lSetCaption property | Specifies whether the caption is automatically based on the value of cFilename. Default: .T.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


SCX to HTML Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _scx2html
Base Class | Custom
Class Library | _internet.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\dohtml.scx

Remarks

This class converts a Visual FoxPro form (.scx) to HTML. This class provides properties to control the scope, visual layout, and HTML generation. For more information, see Genhtml.prg.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro opens a builder so you can accept the current values or specify the appropriate cSource, cOutFile, and nGenOutput values. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods Description
cOutfile property Specifies the name of the HTML file to
output.
Default: ""
cScope property Specifies the scope (for example, NEXT or
ALL, for the output).
Default: ""
cSource property Specifies the source .scx file from which
to generate the HTML file.
Default: ""
cStyle property Specifies the visual style as listed in the
ID field of Genhtml.dbf.
Default: ""
lAutonameoutput property Specifies whether _GENHTML to
automatically names the output file
based on its source.
Default: .T.
nGenOutput property Specifies the _GENHTML output option.
0 = Generate an output file.
1 = Generate and display an
output file in Visual FoxPro editor.
2 = Generate and display an
output file in Internet Explorer.
3 = Generate and display an
output file after displaying a Save
As dialog box.
4 = Create a PUBLIC _oHTML
object and generate a file.
5 = Create a PUBLIC _oHTML
object without generating a file.

Default: 2
GenHTML method Generates HTML code by calling the
_GENHTML engine using properties
specified in cSource, cOutFile, and
nGenOutput.
Syntax: GenHTML( )
Return: none
Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


SendMail Buttons Foundation Class

Category | Misc Buttons
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _mailbtn
Base Class | Container
Class Library | _miscbtns.vcx
Parent Class | _container
Sample | ...\Samples\Solution\OLE\sendmail.scx

Remarks

This class, which uses the MAPI ActiveX Control, handles sending a mail message from a form. When dropped on a form, it can be used to send the current record directly to your mail application.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a form in a data environment, Visual FoxPro places a button on your form where it will access the current record of the active form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
logSession property | Specifies whether login to mail was successful. Default: .F.
SignOn method | Attempts to login to mail. Syntax: SignOn( ) Return: none Arguments: none
AddTabs method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


SetAllX Extension Foundation Class

Category | Object Extension
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _setallx
Base Class | Custom
Class Library | _setallx.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Setallx.scx

Remarks

The SetAllX class is an extension of the Visual FoxPro SetAll( ) method available on many Visual FoxPro classes. Unlike the Visual FoxPro SetAll( ) method, you can specify a baseclass whose objects are affected.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
Setallx method | Extended version of SetAll( ) method. Syntax: SetAllX(toParent, tcProperty, tcExpr, tcBaseClassList, tlNoContainerMode, tlErrorWait) Return: logical Arguments: toParent provides a reference to the parent object. tcProperty specifies the property to set. tcExpr specifies value of property being set. tcBaseClassList specifies the baseclass that applies the changes. tlNoContainerMode prevents interation through the container tlErrorWait specifies whether to wait for error.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Shell Execute Foundation Class

Category | System utility
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _shellexecute
Class Library | _environ.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Buttons.scx

Remarks

This class enables you to launch an application or document with its associated application from the current application.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
ShellExecute method | Attempts to run the file tcFileName in the directory, tcWorkDir. Syntax: ShellExecute(tcFileName, tcWorkDir, tcOperation) Return: nSuccess Arguments: tcFileName specifies the file to run. tcWorkDir specifies the path to the file to run. tcOperation specifies the operation to perform. nSuccess specifies the failure or the success of the run attempt using one of the following values. 2 = Bad Association (for example, invalid URL) 29 = Failure to load application 30 = Application is busy 31 = No application association Values over 32 represent success, and return an instance handle for the running application.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Shortcut Menu Class Foundation Class

Category | Menus
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Menus
Class | _shortcutmenu
Base Class | Custom
Class Library | _menu.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\newmenu.scx

Remarks

When placed on a project or form, this class dynamically creates shortcut popup menus.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cOnSelection property | Specifies the menu bar selection routine. Default: ""
cMenu property | Specifies the name of the shortcut menu. Default: ""
DeactivateMenu method | Deactivates the existing shortcut menu. Syntax: DeactivateMenu( ) Return: none Arguments: none
ActivateMenu method | Activates the existing shortcut menu. Syntax: ActivateMenu(tcParentMenu) Return: Arguments: tcParentMenu specifies the name of the menu from which the shortcut is activated.
ClearMenu method | Releases the existing shortcut menu. Syntax: ClearMenu( ) Return: none Arguments: none
NewMenu method | Creates a new menu popup for the shortcut menu. Syntax: NewMenu( ) Return: none Arguments: none
AddMenubar method | Adds a new menu bar to the shortcut menu. Syntax: AddMember(tcPrompt, tcOnSelection, tcClauses, tnElementNumber, tlMark, tlDisabled, tlBold) Return: none Arguments: tcPrompt specifies the item label. tcOnSelection specifies the action performed by selecting the item. tcClauses specifies any command clause for the item. tnElementNumber specifies the location of the element in the array. tlMark specifies whether to use the default mark character. tlDisabled specifies whether the menu item is disabled. tlBold specifies whether the item is bold.
AddMenuSeparator method | Adds a separator to the shortcut menu. Syntax: AddMenuSeparator(tnElementNumber) Return: none Arguments: tnElementNumber specifies the position the separator occupies in the menu.
ShowMenu method | Displays the existing shortcut menu. Syntax: ShowMenu( ) Return: none Arguments: none
SetMenu method | Releases the current shortcut menu in order to create a new one. Syntax: SetMenu(toObject) Return: none Arguments: toObject specifies the name of the new shortcut menu.
aMenu[1,0] property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Simple Edit Buttons Foundation Class

Category | Data Editing
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | picformbtns
Base Class | Container
Class Library | wizbtns
Parent Class | gridbtns
Sample | ...\Samples\Solution\Ffc\dataedit2.scx

Remarks

When placed on a project or form, this class provides simple picture Add, Edit, Delete, Duplicate, Save, and Cancel buttons (as used by the Form Wizard). Use for simple forms based on a single table or view. For more information, view gridbtns in the Wizbtns.vcx class library in the Class Browser.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, Visual FoxPro places the class buttons on the form. You can then provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Simple Navigation Buttons Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _nav2Buttons
Base Class | Container
Class Library | _table.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Forms\single.scx

Remarks

When placed on a project or form, this class provides a simple pair of Next and Previous navigation buttons.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the command buttons on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
lCycle property | Specifies whether pointer movement continues when the bottom or top of the file is encountered. Default: .F.
TableNav method | Handles record navigation. Syntax: TableNav(tcAction) Return: none Arguments: tcAction specifies a navigation action such as Next or Previous.
lCycle_access method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Simple Picture Navigation Buttons Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _nav2picbuttons
Base Class | Container
Class Library | _table2.vcx
Parent Class | _nav2buttons
Sample | ...\Samples\Solution\Ffc\datanav.scx

Remarks

When placed on a project or form, this class provides a pair of simple picture Next and Previous navigation buttons. For more details, open _nav2buttons in the _table.vcx class library in the Class Browser.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the command buttons on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Sort Dialog Box Button Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Buttons
Class | _sortbutton
Base Class | CommandButton
Class Library | _table2.vcx
Parent Class | _dialogbutton
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

When placed on a project or form, this class provides a button that displays a dialog box that makes it possible for you to sort data in ascending or descending order on a particular field. For details, open _dialogbutton in the _table2.vcx class library in the Class Browser.

To use, drop the class on a project or form in a data environment or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the button on the form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Sort Dialog Box Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro\Foundation Classes\ Data Query
Class | _sortdialog
Base Class | Form
Class Library | _table2.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This dialog box enables you to perform an ascending or descending data sort on a particular field.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form from the selected class, Visual FoxPro opens a builder so you can specify the name of the form, then creates and opens the form in the Form Designer. You need to provide an indexed table for the Sort dialog box.

Properties, Events, Methods | Description
DoSort method | Makes it possible for you to sort on the current field or to specify the field on which to order a table. Syntax: DoSort( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Sort Mover Foundation Class

Category | Movers
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _sortmover
Base Class | Container
Class Library | _mover.vcx
Parent Class | _mover
Sample | ...\Samples\Solution\Ffc\movers.scx

Remarks

This subclass of the mover list box class, when placed on a form, automatically handles sorting of data.

Properties, Events, Methods | Description
CurrentAlias property | The current alias for field choices. Default: ""
CurrentDBC property | The current database for field choices. Default: ""
MaxFields property | Maximum number of fields allowed. Default: 3
ShowTags property | Specifies whether to show existing index tags in addition to fields. Default: .F.
aTags[1,1] property | Internal to the class.
TagName property | Internal to the class.
UpdateMover | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Mover


Sort Object Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _tablesort
Base Class | Custom
Class Library | _table.vcx
Parent Class | _table
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This class, when placed on a form, enables you to sort a datasource.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
lDescending property | Specifies whether the sort order is ascending or descending. Default: .F.
DoSort method | Makes it possible for you to sort on the current field or to specify the field on which to order a table or alias. Syntax: DoSort([tcField] [,tcAlias] [,tcTag] [,tlDescending]) Return: none Arguments: tcField specifies the field to sort on. tcAlias specifies the alias of the table to sort. tcTag specifies the index tag of the field, tcField. tlDescending specifies whether the sort is a descending sort.
GetSortTag method | Looks for an appropriate tag name by looking at key expressions in the table relevant to the field name. Syntax: Getsorttag(tcField, tcAlias) Return: lcTag Arguments: tcField specifies the field to sort on. tcAlias specifies the alias of the table to sort.
RemoveSort method | Removes the current index tag. Syntax: RemoveSort(tcAlias) Return: none Arguments: tcAlias specifies the alias of the table from which to remove the tag.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Sort Selector Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _sortselect
Base Class | Container
Class Library | _table2.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Ffc\datasort.scx

Remarks

This set of buttons, when placed on a project or form, performs an ascending or descending sort based on the current control.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the buttons on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
DoSort method | Makes it possible for you to sort on the current field or to specify the field on which to order a table. Syntax: DoSort([tcField] [,tcAlias] [,tcTag] [,tlDescending]) Return: none Arguments: tcField specifies the field to sort on. tcAlias specifies the alias of the table to sort. tcTag specifies the index tag of the field, tcField. tlDescending specifies whether the sort is a descending sort.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Sound Player Foundation Class

Category | Multimedia
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Multimedia
Class | _soundplayer
Base Class | Container
Class Library | _multimedia.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Forms\mci_play.scx

Remarks

This class loads and plays a sound file, and provides access to the Media Control Interface (MCI).

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a project, you can choose between adding the class or creating a subclass. When you choose an option from the shortcut menu or drop the class on a form, Visual FoxPro opens a builder so you can specify appropriate cFileName, lAutoOpen, lAutoPlay, lAutoRepeat, and cControlSource values.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cControlSource property | Specifies the source of data to which an object is bound. Default: ""
cFileName property | Specifies the name of the sound file to play. Default: ""
cMCIAlias property | Specifies the alias for the video file when calling MCI commands. If empty, the name of the file is used. Default: ""
cMCIErrorString property | Stores the error string from the last MCI command. Default: ""
lAutoOpen property | Specifies whether the video file specified should be automatically opened when the class is created. Default: .T.
lAutoPlay property | Specifies whether the video file should automatically play after opening. Default: .T.
lAutoRepeat property | Specifies whether video plays continuously. Default: .T.
nMCIError property | Specifies the result of the last MCI command executed. Default: 0
CloseSound method | Closes the loaded sound file and releases its resources. Syntax: CloseSound( ) Return: none Arguments: none
OpenSound method | Opens the sound file. Syntax: OpenSound( ) Return: none Arguments: none
PauseSound method | Pauses the currently playing sound. Syntax: PauseSound( ) Return: none Arguments: none
PlaySound method | Plays the loaded sound file. Syntax:PlaySound( ) Return: none Arguments: none
SetPosition method | Makes it possible for the user to set the position of the media file. Syntax: SetPosition (cPosition) Return: none Arguments: cPosition specifies Start, End, or a number representing milliseconds into the media file.
DoMCI method | Internal to the class.
GetMCIError method | Internal to the class.
ShowMCIError method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Splash Screen Foundation Class

Category | Misc Forms
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _splash
Base Class | Form
Class Library | _dialogs.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\dialogs.scx

Remarks

This class, when placed in an project, provides a simple Splash Screen for custom applications.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Create Form or Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you choose Create a new form from the selected class, Visual FoxPro displays an Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer.

Properties, Events, Methods | Description
nDuration property | Specifies the duration (in seconds) to display the screen. Default: 3

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


SQL Pass Through Foundation Class

Category | Data Query
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Query
Class | _execsp
Base Class | Custom
Class Library | _dataquery.vcx
Parent Class | _custom

Remarks

This class is used for SQL Pass Through and makes it possible for you to execute stored procedures on a host database such as Microsoft SQL Server.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a form, Visual FoxPro places the class icon on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

You need to add code that specifies parameter and connection information so the class can return a result set in a cursor.

Properties, Events, Methods | Description
LUseSQLSyntax | Specifies whether to use Server Exec syntax. Default: .F.
DoSQL method | Runs a SQL Pass Through statement. Syntax: DoSQL( ) Return: none Arguments: none
GetSQL method | Gets results from the SQL Pass Through statement. Syntax: GetSQL( ) Return: none Arguments: none
aParams[1,0] property | Internal to the class.
cCursorName property | Internal to the class.
cSpname property | Internal to the class.
cSQL property | Internal to the class.
hConnectHandle property | Internal to the class.
ProcessError method | Internal to the class.
SetParams method | Internal to the class.
SetSQL method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Stop Watch Foundation Class

Category | Date/Time
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Date/Time
Class | _stopwatch
Base Class | Container
Class Library | _datetime.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Controls\Timer\swatch.scx

Remarks

This class, when placed on a form, provides a stop watch control.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the icon on the form where it will run on the active form. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
Increment method | Increments the stopwatch display. Syntax: Increment( ) Return: none Arguments: none
Reset method | Resets the stopwatch. Syntax: Reset( ) Return: none Arguments: none
Start method | Starts the stopwatch. Syntax: Start( ) Return: none Arguments: none
Stop method | Stops the stopwatch. Syntax: Stop( ) Return: none Arguments: none
UpdateDisplay method | Refreshes the display. Syntax: UpdateDisplay( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


String Library Foundation Class

Category | Data Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _stringlib
Base Class | Custom
Class Library | _utility.vcx
Parent Class | _custom

Remarks

This class removes carriage return and line feed characters from a character string.

Properties, Events, Methods | Description
TrimCRLF method | Trims carriage return and line feed characters from a character string. Syntax: TrimCRLF (tcString, tlTrimLeft, tlTrimRight) Return: none Arguments: tcString specifies the string to trim. tlTrimLeft specifies whether to trim the left side. tlTrimRight specifies whether to trim the right side.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Super Mover Foundation Class

Category | Movers
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _supermover
Base Class | Container
Class Library | _mover.vcx
Parent Class | supermover
Sample | ...\Samples\Solution\Ffc\movers.scx

Remarks

This class, when placed on a form, provides a mover list box with Move, Remove, MoveAll, and RemoveAll buttons.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form in a data environment, Visual FoxPro adds the class list box and button controls to the form in the Form Designer so you can specify appropriate property values.

Properties, Events, Methods | Description
MaxItems property | Specifies the maximum number of items that can be selected. Default: 0
MaxMessage property | Specifies the message to display if maximum number of items is reached. Default: ""

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Mover


System Metrics Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _sysmetrics
Base Class | Custom
Class Library | _system.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Logo.scx

Remarks

Provides access to system metric information that might be useful in your applications as well as necessary for Windows 2000 Logo compliancy. System metrics such as mousewheel present, number of mouse buttons, and number of monitors are provided with the class, but any valid system metric can be queried.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
lMouseWheelPresent property | Returns .T. if MouseWheel is present on mouse.
nMonitors property | Returns the number of monitors attached to system.
nMouseButtons property | Returns the number of mouse buttons on the mouse.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


System Toolbar Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _systoolbars
Base Class | Custom
Class Library | _app.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\environ.scx

Remarks

This class is a manager class that handles and tracks System Toolbars so you can automatically remove the Visual FoxPro system toolbars in your application and later restore them. This class is used with the framework generated by the Application Wizard.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro places the icon on the form. You can then specify the appropriate property values and provide any necessary objects.

If lAutomatic is true (.T.), as in a READEVENTS-type application, the class automatically hides all existing system toolbars when you instantiate it. It then automatically restores the system toolbars hidden when it went out of scope.

You can also call the HideSystemToolbars( ) and ShowSystemToolbars( ) methods manually.

Properties, Events, Methods | Description
lAutomatic property | Automatically hides and restores system toolbars for the application. Default: .F.
aSystemToolbars[1,0] property | The array of system toolbars. Default: .F.
Hidesystemtoolbars method | Manually hides system toolbars for the application. Syntax: Hidesystemtoolbars( ) Return: none Arguments: none
Showsystemtoolbars method | Manually shows system toolbars for the application. Syntax: Showsystemtoolbars( ) Return: none Arguments: none
Initializetoolbararray method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Table Mover Foundation Class

Category | Movers
Default Catalog | Visual FoxPro Catalog\Foundation Classes\User Controls
Class | _tablemover
Base Class | Container
Class Library | _mover.vcx
Parent Class | _fieldmover
Sample | ...\Samples\Solution\Ffc\movers.scx

Remarks

This subclass of the field mover list box class automatically loads tables and fields from the current datasource.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro opens a builder so you can accept or specify the appropriate cDBCTable, cDBCName, SkipGeneral, SkipMemo, AllowReadOnly, and AllowQuery values on the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
AllowQuery property | Specifies whether to allow queries. Default: .F.
AllowViews property | Specifies whether to allow views. Default: .T.
ExclDBF property | Specifies the name of the table to exclude from the list. Default: ""
ViewNoData property | Specifies whether to show view information without retrieving data. Default: .T.
GetDBCAlias method | Retrieves the database file (.dbc) alias. Syntax: GetDBCAlias(cDBC) Return: none Arguments: cDBC specifies the database alias.
GetDBCData method | Retrieves database table fields. Syntax: GetDBCData(cDBCName) Return: data fields Arguments: cDBCName specifies the name of the database.
GetDBCName method | Retrieves the database name. Syntax: GetDBCName( ) Return: none Arguments: none
GetDBCTable method | Retrieves the database table. Syntax: GetDBCTable(cDBCTable) Return: none Arguments: cDBCTable specifies the short name of the table
GetFreeData method | Retrieves free table fields. Syntax: GetFreeData( ) Return: none Arguments: none
MoverRefresh method | Refreshes movers. Syntax: MoverRefresh(lRefresh, lQuickPass, cSaveLstValue) Return: none Arguments: lRefresh specifies whether to repopulate listboxes and popups. lQuickPass specifies whether to restore if the environment is unchanged. cSaveLstValue specifies the value to restore.
OpenTable method | Opens the datasource. Syntax: OpenTable( ) Return: none Arguments: none
UseTable method | Handles what table is opened with USE and whether the table is opened exclusively. Syntax: UseTable(cGetDBF, lUseExcl) Return: none Arguments: cGetDBF specifies the table to use. lUseExcl specifies whether the table is opened exclusively.
ExclusiveSet method | Internal to the class.
RefreshCurrent method | Internal to the class.
TableChange method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Field Mover


Text Preview Foundation Class

Category | Reporting
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Output
Class | _showtext
Base Class | Form
Class Library | _reports.vcx
Parent Class | _form
Sample | ...\Samples\Solution\Ffc\output.scx

Remarks

When used on a project or form, this class provides a simple text editor in a dialog box that also contains buttons to format or save text, and to close the editor.

The main purpose of this class is to provide a controllable preview window to other classes in _reports.vcx. Therefore this dialog box has no button to load a new file (though you can add one in a subclass) and it defaults to read only for its edit box.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. When you choose Create a new form from the selected class, Visual FoxPro opens a builder so you can specify the name of the form, then creates and opens the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cFixedFontName property | The font name for contents of the edit box. Default: Courier New
nFixedFontSze property | The font size for contents of the edit box. Default: 9
cSourceFile property | The name of the source file to view or edit. Default: ""
cTargetFile property | The name of the file to which you save the contents of the edit box. Default: ""
lFixedFontBold property | Specifies a bold font for contents of the edit box. Default: .F.
lFixedFontiItalic property | Specifies an italic font for contents of the edit box. Default: .F.
lSuppressCaptionChange property | Prevents the dialog box caption from changing as the source file changes. This is useful for displaying the contents of a temporary file. Default: .F.
SetFonts method | Applies the current font property characteristics to the edit box displaying the file. Syntax: SetFonts( ) Return: none Arguments: none
GetFixedFont method | Uses a common dialog box to display fonts. Restricted to fixed font items. Syntax: GetFixedFont( ) Return: none Arguments: none
cTargetfile_access method | Internal to the class.
cSourcefile_assign method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Thermometer Foundation Class

Category | User Interface
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Dialogs
Class | _thermometer
Base Class | Form
Class Library | _therm.vcx
Parent Class | _thermometer
Sample | ...\Samples\Solution\Ffc\therm.scx

Remarks

This class, when placed on a form, provides a standard thermometer class.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project. When you drop the class on a project, you can choose between adding the class, creating a subclass, or creating a form. If you choose Create a new form from the selected class, Visual FoxPro displays the Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer. You need to specify appropriate property values in the Update method.

Properties, Events, Methods | Description
cCurrentTask property | Specifies the current task. Default: ""
iBasis property | Specifies the basis for calculating the percentage. Default: 0
iPercentage property | Specifies the percentage completion at which the display updates. Default: 0
iProgress property | Specifies the amount completed(iPercentage). Default: 0
Complete method | Displays 100% complete thermometer. Syntax: Complete(m.cTask) Return: none Arguments: m.cTask specifies what to display when progress is complete.
Update method | Updates the thermometer. Syntax: Update(iProgress, cTask) Return: none Arguments: iProgress specifies the progress increment. cTask specifies the message to be displayed.
cThermRef property | Internal to the class.
ShpThermBarMaxWidth property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Trace Aware Timer Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _traceawaretimer
Base Class | Timer
Class Library | _app.vcx
Parent Class | _timer
Sample | ...\Samples\Solution\Ffc\environ.scx

Remarks

This is an application utility that detects whether the trace window is open and handles debug timing appropriately. Although Visual FoxPro makes it possible for you to skip tracing timer events altogether when debugging, this isn't always an appropriate solution because sometimes the code in timer events is pertinent to what you're trying to debug. Instead, this timer determines whether any of the debugging window is visible and if so, sets a special slow interval.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro places an icon on the form. You can then specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

Properties, Events, Methods | Description
iRegularInterval property | Specifies the standard interval period. Stored during the Init event, and restored during Timer events if you've changed the Interval. Default: 0
iTraceInterval property | Specfies a slower interval period to use while debugging. Default: 10000

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Type Library Foundation Class

Category | File Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _typelib
Base Class | Container
Class Library | _utility.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Winapi\typelib.scx

Remarks

This class uses the TlbInf32 COM component to read type information from type libraries. The main routine ExportTypeLib creates a text file with Type library output.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro places the class icon on the form. You can then specify the appropriate property values on the form in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aTypeAttr[1,0] property | Specifies the array for the TypeAttr structure. Default: .F.
aTypeFuncDesc[1,0] property | Specifies an array for the FuncDesc structure. Default: .F.
aTypeFuncDocs[3,0] property | Specifies an array for function documentation. Default: .F.
aTypeFuncNames[1,0] property | Specifies an array of function names. Default: .F.
aTypeFuncParms[1,0] property | Specifies an array of the function parameters. Default: .F.
aTypeInfoDocs[3,0] property | Specifies an array for TypeInfo documentation. Default: .F.
aTypeLibDocs[3,0] property | Specifies an array for TypeLib documentation. Default: .F.
FuncNamesCount property | Specifies the number of names for TypeInfo function. This is equivalent to total parameters+1. Default: .F.
TypeInfoCount property | Specifies the number of TypeInfos in TypeLib. Default: .F.
TypeInfoIndex property | An index reference to TypeInfo. Default: .F.
TypeLibHandle property | The handle to TypeLib. Default: .F.
TypeLibName property | Specifies the name of the type library. Default: .F.
ExportTypeLib method | Exports contents of a TypeLib to a text file. Syntax: ExportTypeLib(cExportFile, lViewFile) Return: m.exportfile Arguments: cExportFile specifies the file to export. lViewFile specifies whether to open the file in a viewer after export.
GetDataType method | Returns data type of function. Syntax: GetDataType(m.nvt) Return: name of data type Arguments: m.nvt Specifies a data item reference.
GetFuncDesc method | Obtains TypeInfo function info and populates arrays. Syntax: GetFuncDesc(nFuncIndex) Return: TypeInfo arrays, aTypeFuncParms, aTypeFuncNames, aTypeFuncDocs Arguments: nFuncIndex specifies the index of the function.
GetTypeInfo method | Obtains TypeInfo and populates TypeInfo arrays. Syntax: GetTypeInfo(nTypeInfoNum) Return: none Arguments: nTypeInfoNum specifies a reference to the Typeinfo key.
GetTypeLib method | Obtains TypeLib info and populates arrays. Syntax: GetTypeLib( ) Return: none Arguments: none

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


URL Combo Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _urlcombobox
Base Class | Combobox
Class Library | _internet.vcx
Parent Class | _combobox
Sample | ...\Samples\Solution\Ffc\hyperlnk.scx

Remarks

This class, when placed on a form, creates a combo box for entering a Web URL. It launches Internet Explorer and navigates to the site.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a project, you can choose between adding the class or creating a subclass. When you dropn the class on a form, Visual FoxPro opens a builder so you can specify the appropriate cURL, cURLHistoryTable, and iURLHistory values on the form in the Form Designer. You can use the history table to supply one or more start locations for Web navigation.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
cURL property | The current URL. Default: ""
cURLHistoryTable property | Specifies the name of the URL history table that retains previously accessed URLs. Default: (IIF(VERSION(2)=0,"",HOME( ))+"URLHst ry.dbf"))
lInitialized property | Control initialized flag. Default: .F.
lURLHistory property | Saves URL history. Default: .T.
Navigate method | Requests the document based on URL address. Syntax: Navigate( ) Return: none Arguments: none
cHyperlinkClass property | Internal to the class.
cHyperlinkclasslibrary property | Internal to the class.
cTempFilePrefix property | Internal to the class.
lDropDown property | Internal to the class.
lFormNavigate property | Internal to the class.
lGotFocus property | Internal to the class.
lMoveFocus property | Internal to the class.
lRequestOnEnter property | Internal to the class.
oHyperlink property | Internal to the class.
Initialize method | Internal to the class.
oHyperlink_access method | Internal to the class.
OpenURLHistory method | Internal to the class.
ValidURL method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


URL Open Dialog Box Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _openaddressdialog
Basse Class | Form
Class Library | _internet.vcx
Parent Class | _dialog
Sample | ...\Samples\Solution\Ffc\hyperlnk.scx

Remarks

This dialog box, when placed on a form, provides a dropdown that stores the URL history list.

To use, drop the class on a project or, from the Component Gallery Item Shortcut Menu, select Add to Project or Create Form. When you add the class to a project, you can choose between adding the class or creating a subclass, or creating a form. When you create a form, Visual FoxPro displays an Open dialog box so you can specify the name of the form, then creates and opens the form in the Form Designer so you can specify appropriate Target and lShellExecute values.

Properties, Events, Methods | Description
lShellExecute property | Runs the target URL. Default: .T.
Target property | Specifies the name of the target URL. Default: ""
cFileExt property | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


User Privileges Foundation Class

Category | System Utilities
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Utilities
Class | _userpriv
Base Class | Custom
Class Library | _system.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\Logo.scx

Remarks

This class returns the User Access Rights of the currently logged on user. On Windows 2000, this would be Guest, Power User or Administrator. This information is commonly needed in applications that provide Windows 2000 Logo compliancy.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places the class icon on the form. You can specify the appropriate property values and provide any necessary input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
GetUserPriv method | Returns path to specified system folder. Syntax: GetUserPriv(cUser) Return: access of user Arguments: cUser specifies name of user to check.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


VCR Buttons Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _nav4buttons
Base Class | Container
Class Library | _table.vcx
Parent Class | _nav2buttons
Sample | ...\Samples\Solution\Ffc\datanav.scx

Remarks

This set of record navigation buttons is a subclass of _nav2buttons that includes Top, Next, Prev, and Bottom navigation buttons.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, you need to provide appropriate input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


VCR Picture Navigation Buttons Foundation Class

Category | Data Navigation
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Data Navigation
Class | _nav4picbuttons
Base Class | Container
Class Library | _table2.vcx
Parent Class | _nav4buttons
Sample | ...\Samples\Solution\Ffc\datanav.scx

Remarks

This is a set of data navigation buttons that displays VCR pictures on the Top, Next, Previous, and Bottom buttons.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut menu, select Add to Project or Add to Form. When you add the class to a form in a data environment, you need to specify the appropriate input and output objects. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Video Player Foundation Class

Category | Multimedia
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Multimedia
Class | _videoplayer
Base Class | Container
Class Library | multimedia.vcx
Parent Class | _container
Sample | ...\Samples\Solution\Forms\mci_play.scx

Remarks

This class loads and plays a video file, and provides access to the Media Control Interface (MCI).

To use, drop the class on a project or form, or from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you drop the class on a project, you can choose between adding the class or creating a subclass. When you choose an option from the shortcut menu or drop the class on a form, Visual FoxPro opens a builder so you can specify appropriate cFileName, lAutoOpen, lAutoPlay, lAutoRepeat, and cControlSource values.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
AutoOpen property | Specifies whether the video file specified should be automatically opened when the class is created. Default: .T.
AutoPlay property | Specifies whether the video file should automatically play after opening. Default: .T.
AutoRepeat property | If true (.T.), specifies that the video file will play continuously. Default: .T.
cFileName property | Specifies the video file associated with the Video Frame. Default: ""
Controlsource property | Specifies the source of data to which an object is bound. Default: ""
MCIAlias property | Specifies the alias for the video file when calling MCI commands. If empty, the name of the file is used. Default: ""
MCIError property | Specifies the result of the last MCI command executed. Default: 0
MCIErrorString property | Stores the error string from the last MCI command executed. Default: ""
CloseVideo method | Closes the video file and releases all resources. Syntax: CloseVideo( ) Return: none Arguments: none
DoMCI method | Executes an MCI command. Syntax: DoMCI(cMCIcmd) Return: cRetString Arguments: cMCIcmd specifies the command to run.
PauseVideo method | Pauses a currently playing video. Syntax: PauseVideo( ) Return: none Arguments: none
PlayVideo method | Plays the currently loaded video. Syntax: PlayVideo( ) Return: none Arguments: none
SetPosition method | Makes it possible for the user to set the position of the media file. Syntax: SetPosition(cPosition) Return: none Arguments: cPosition specifies Start, End, or a number representing milliseconds into the media file.
GetMCIError method | Internal to the class.
OpenVideo method | Internal to the class.
ShowMCIError method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples | Play Multimedia Files Using MCI Commands


Web Browser Control Foundation Class

Category | Internet
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Internet
Class | _Webbrowser4
Class Library | _webview.vcx
Parent Class | olecontrol
Sample | ...\Samples\Solution\Ffc\Webvwr.scx

Remarks

This subclass of the Microsoft Internet Explorer browser control provides hooks for Visual FoxPro code and can be added to a Visual FoxPro form.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a form, Visual FoxPro places an Internet Explorer logo on your form. You need to specify an appropriate URL in the Navigate method. When you drop the class on a project, you can choose between adding the class or creating a subclass.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
aHistory[1,2] property | URL address history array. Default: .F.
aParam[1,0] property | URL parameters array. Default: .F.
aScripts[1,0] property | Visual FoxPro scripts array. Default: .F.
cAlias property | Returns the table alias of the currently selected. Set automatically when using the OpenTable method. Default: ""
cBeforeURL property | Specifies the current URL before a document is fully retrieved. Default: ""
cBlankHTMLFile property | Specifies a blank .htm file. Default: Blank.htm
cDBF property | Returns the file name of currently selected table. Set automatically when using the OpenTable method. Default: ""
cDBFPath property | Returns the path of the currently selected table. Set automatically when using the OpenTable method. Default: ""
cFilename property | Returns the file name of the current document. Default: ""
cFilepath property | Returns the path of the current document. Default: ""
cLasturl property | Specifies the last URL. Default: ""
cNewURL property | Specifies the URL before the document is fully retrieved. Default: ""
cParam property | Specifies the URL parameter string. Default: ""
cParamdelimiter property | Specifies the URL parameter delimiter character. Default: &
cParseFileExt property | File extension list of the file to parse in pre-processing mode. Default: htm;html;asp
cProgramPath property | Specifies the Web browser control class path. Default: ""
cSourceFile property | Specifies the file name of current document. Default: ""
cSourceFilename property | Specifies the file name of current source document. Default: ""
cSourceFilepath property | Specifies the path of current source document. Default: ""
cSourceHTML property | Specifies the HTML text of the current source document. Default: ""
cSourceURL property | Specifies the URL of the current source document. Default: ""
cTempFilename property | Specifies the file name of the temporary file document. Default: ""
cTempFilePrefix property | Prefix used for the file name of the temporary file document. Default: _temp
cURL property | Current URL. Default: ""
cUserID property | User ID, user defined, not used internally. Default: ""
cUserName property | User name, user defined, not used internally. Default: ""
cVersion property | Specifies the version of the Web browser control subclass. Default: "Web Browser 04.01.0006"
cVFPScript property | Specifies the Visual FoxPro script program file name. Default: ""
cVFPScriptTable property | Specifies the Visual FoxPro script table file name. Default: ""
cVFPSprotocol property | Specifies the default Visual FoxPro script protocol string. Default: vps:
lBlankHTMLStartup property | Specifies whether the browser starts with a blank startup Web page. Default: .F.
lBusy property | Web browser busy mode. Default: .F.
lDebug property | Specifies whether the Web browser runs in Debug mode. Default: .F.
lDesign property | Specifies whether the Web browser runs in design mode. Default: .F.
lDHTML property | Specifies whether the Web browser supports dynamic HTML. Default: .T.
lHistoryEnabled property | Specifies whether URL history tracking is enabled. Default: .F.
lParseSource property | Specifies whether Parse document source mode is enabled. Default: .F.
lRefresh property | Specifies whether the control is refreshed when the Refresh method runs. Default: .F.
lRefreshDeactivate property | Specifies whether auto-execution of the RefreshDeactivate method for the LostFocus event is enabled. Default: .F.
lRefreshMode property | Specifies whether Refresh document mode is enabled. Default: .F.
lRelease property | Specifies whether the object's Release method has been executed and the object is in the process of being released from memory. Default: .F.
lRunCodeMode property | Specifies whether Run code mode is enabled. Default: .F.
lVFPsScript property | Specifies whether Visual FoxPro script mode is enabled. Default: .F.
lViewSourceMode property | Specifies whether View source mode is enabled. Default: .F.
nDataSessionID property | Specifies the data session number of the table alias of the currently selected table that was set automatically when using the OpenTable method. Default: 0
nHistoryCount property | Specifies the length of the URL history array. Default: 0
nParamCount property | Specifies the length of the URL parameter array. Default: .F.
nRecno property | Specifies the current record number of the currently selected table that was set automatically when using the OpenTable method. Default: 0
nScriptCount property | Specifies the length of the Visual FoxPro script array. Default: 0
nUserLevel property | Specifies the user level, user defined, not used internally. Default: 0
oAction property | Specifies the user action object, user defined, not used internally. Default: .NULL.
oHost property | Specifies the host form – equivalent to THISFORM. Default: .NULL.
oSource property | Specifies the source object, user defined, not used internally. Default: .NULL.
oUser property | Specifies the user object, user defined, not used internally. Default: .NULL.
uResult property | Specifies the variant result value. Default: .T.
uReturn property | Specifies the variant return value. Default: .T.
uValue property | Specifies the variant value, user defined, not used internally. Default: .T.
AddProp method | Adds a new property. Syntax: AddProp(tcName, tcProperty, tuValue) Arguments: tcName specifies tcProperty specifies the name of the property.tuValue specifies the value to assign to the property.
BeforeNavigate method | Provides a BeforeNavigate event. Syntax: BeforeNavigate(URL, flags, targetframename, postdata, headers, cancel) Arguments: URL specifies the Web page to use.flags specifies whether to add the resource to the history list, to read or write from the cache, display the resource in a new window or a combination of these. targetframename specifies the name of the target frame. postdata specifies data to send to the HTTP Post transaction. headers specifies the HTTP headers to send. cancel specifies whether navigation was cancelled.
BeforeRetrieval method | Identifies the event to run before retrieval. Syntax: BeforeRetrieval(URL, flags, targetframename, postdata, headers, cancel) Arguments: URL specifies the Web page to use. flags specifies whether to add the resource to the history list, to read or write from the cache, display the resource in a new window or a combination of these. targetframename specifies the name of the target frame. postdata specifies data to send to the HTTP Post transaction. headers specifies the HTTP headers to send. cancel specifies whether navigation was cancelled.
BrowseTable method | Browse the currently selected based on cAlias. Syntax: BrowseTable(tcAlias, tcClauses)
CloseTable method | Close the currently selected based on cAlias. Syntax: CloseTable(tcAlias)
EditScript method | Edit a specific Visual FoxPro script. Syntax: EditScript(tcScriptName) Arguments: tcScriptName specifies the name of the Visual FoxPro script.
EditString method | Opens a string in an edit window. Syntax: EditString(tcString, tcTitle, tlNoEdit) Arguments: tcString specifies the string to edit. tcTitle specifies the name of the edit window. tlNoEdit specifies whether string is editable.
EraseTempFile method | Specifies whether to erase the current temporary file. Syntax: EraseTempFile( ) Return: none Arguments: none
FileToString method | Returns the string contents of a file. Syntax: FileString(tcFileName) Arguments: tcFileName specifies the name of the file from which to extract the string.
FrameBeforeNavigate method | Provides a FrameBeforeNavigate event. Syntax: FrameBeforeNavigate(URL, flags, targetframename, postdata, headers, cancel) Arguments: URL specifies the Web page to use. flags specifies whether to add the resource to the history list, to read or write from the cache, display the resource in a new window or a combination of these. targetframename specifies the name of the target frame. postdata specifies data to send to the HTTP Post transaction. headers specifies the HTTP headers to send. cancel specifies whether navigation was cancelled.
GetHTML method | Returns the HTML of the current document. Syntax: GetHTML(tcName, tcAlias) Arguments: tcName specifies the name of the document to return. tcAlias specifies the alias of cVFPScriptTable.
GetSourceFile method | Returns the file name of the current source document. Syntax: GetSourceFile( ) Arguments: none
GetSourceHTML method | Returns the HTML of the current source document. Syntax: GetSourceHTML( ) Arguments: none
GoBack method | Executes a hyperlink jump backward within the history list. Syntax: GoBack( ) Return: none Arguments: none
GoForward method | Executes a hyperlink jump forward within the history list. Syntax: GoForward( ) Return: none Arguments: none
Msgbox method | Message box handler method. Syntax: Msgbox(tcMessage, tnType,tcTitle) Arguments: tcMessage specifies the message to display. tnType specifies the messagebox type. tcTitle specifies the title of the messagebox.
NavigateComplete method | Provides a NavigateComplete event. Syntax: NavigateComplete(URL) Arguments: URL specifies the Web page to navigate.
NewWindow method | Provides a NewWindow event. Syntax: NewWindow(URL, flags, targetframename, postdata, headers, processed) Arguments: URL specifies the Web page to use. flags specifies whether to add the resource to the history list, to read or write from the cache, display the resource in a new window or a combination of these. targetframename specifies the name of the target frame. postdata specifies data to send to the HTTP Post transaction. headers specifies the HTTP headers to send. cancel specifies whether navigation was cancelled.
OpenTable method | Opens the specified table and activates it as the current table by setting the cAlias property. Syntax: OpenTable(tcFileName, tcAlias, tlExclusive, tcFilter) Arguments: tcFileName specifies the name of the table to open. tcAlias the alias of the table. tlExclusive specifies whether to open the table EXCLUSIVE. tcFilter specifies a filter expression to use.
OpenVFPScript method | Opens the Visual FoxPro script table. Syntax: OpenVFPScript( )
ParseSource method | Parses the source code of the HTML document. Syntax: ParseSource(URL, flags, targetframename, postdata, headers, cancel) Arguments: URL specifies the Web page to use. flags specifies whether to add the resource to the history list, to read or write from the cache, display the resource in a new window or a combination of these. targetframename specifies the name of the target frame. postdata specifies data to send to the HTTP Post transaction. headers specifies the HTTP headers to send. cancel specifies whether navigation was cancelled.
RefreshDeactivate method | Use when losing focus of the Web browser control. Syntax: RefreshDeactivate( ) Arguments: none
RefreshMode method | Set refresh mode. Syntax: Refresh( ) Arguments: none
RefreshSource method | Refresh the source. Syntax: RefreshSource( ) Return: none Arguments: none
ReleaseHost method | Release the host form. Syntax: ReleaseHost( ) Arguments: none
RunAction method | Run action that is a specific method of the object referenced by the oAction property. Syntax: RunAction(tcMethod) Arguments: tcMethod specifies the method to run.
RunCode method | Run a specific block of Visual FoxPro code without compilation. Syntax: RunCode(tcCode) Arguments: tcCode specifies the Visual FoxPro code to run.
RunScript method | Run a specific Visual FoxPro script. Syntax: RunScript(tcScript, tcAlias) Arguments: tcScript specifies the script to run. tcAlias specifies the alias of the file containing tcScript.
SetBusyState method | Set busy state method. Syntax: SetBusyState(tlBusy) Arguments: tlBusy specifies whether a download is in process.
SetParam method | Set URL parameters method. Syntax: SetParam(tcParam) Arguments: tcParam
SkipRecord method | Skip record of currently selected table, based on cAlias. Syntax: SkipRecord(tnRecords) Arguments: tnRecords specifies the number of records to skip.
StringToFile method | Saves string contents to file. Syntax: StringToFile(tcText, tcFileName) Arguments: tcText specifies the text to save. tcFileName specifies the target file.
TrimExt method | Returns a file name without extension. Syntax: TrimExt(tcFileName, tlPlatformType) Return: cFilename Arguments: tcFileName specifies the filename to process. tlPlatformType specifies whether a file is from a DOS or Unix computer.
TrimFile method | Returns the path of the specified file name. Syntax: TrimFile(tcFileName, lPlatType) Arguments: tcFileName specifies the name of the target file. lPlatType specifies whether a file is from a DOS or Unix computer.
TrimPath method | Returns the file name without a path. Syntax: TrimPath(tcFileName, tlTrimExt, tlPlatformType) Arguments: tcFileName specifies name of the file. tlTrimExt specifies whether to remove the extension. tlPlatformType specifies whether a file is from a DOS or Unix computer.
ValidateURL method | Validates the URL. Syntax: ValidateURL(tcURL) Arguments: tcUrl specifies the Web page to validate.
ValidURL method | Returns the validated URL. Syntax: ValidURL(tcURL) Arguments: tcUrl specifies the Web page to return.
VFPS method | Executes a Visual FoxPro script based on the specified URL. Syntax: VFPS(tcCommand) Arguments: tcCommand specifies the Visual FoxPro expression to run.
VFPScript method | Executes a specific Visual FoxPro script. Syntax: VFPScript(tcName, tcAlias, tnCode) Arguments: tcName specifies the name of the file cVFPScript tcAlias specifies the alias of cVFPScriptTable tnCode specifies the Visual FoxPro code to run.
ViewSource method | View the source of the current document. Syntax: ViewSource(tlNoWait, tlNoEdit) Arguments: tlNoWait specifies whether the program pauses while the window displays. tlNoEdit specifies whether the viewed source is editable.
WaitWindow method | Wait window wrapper method. Syntax: WaitWindow(tcText, tlWait) Arguments: tcText specifies the text that displays in the Wait Window. tlWait specifies whether the program pauses while the window displays.
WildcardMatch method | Returns true (.T.) if the wild card string is matched to a specific string. Syntax: WildcardMatch(tcMatchExpList, tcExpressionSearched, tlMatchAsIs) Return: lMatch Arguments: tcMatchExpList specifies the search expression. tcExpressionSearched specifies the target expression tlMatchAsIs specifies whether to enforce an exact string match.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


Window Handler Foundation Class

Category | Application
Default Catalog | Visual FoxPro Catalog\Foundation Classes\Application
Class | _windowhandler
Base Class | Custom
Class Library | _ui.vcx
Parent Class | _custom
Sample | ...\Samples\Solution\Ffc\whandler.scx

Remarks

This general purpose Window Handler class performs several common window operations such as cascading windows.

To use, drop the class on a project or form or, from the Component Gallery Item Shortcut Menu, select Add to Project or Add to Form. When you add the class to a project, you can choose between adding the class or creating a subclass. When you add the class to a form, Visual FoxPro displays the icon on the form so you can specify appropriate properties values its available methods in the Form Designer.

See Guidelines for Using Visual FoxPro Foundation Classes for more information on using foundation classes.

Properties, Events, Methods | Description
IMDIWorkspaceColor property Contains the Windows color for top-level
frame window.
Default: 0
CascadeFormInstances method
Cascades forms.
Syntax: CascadeFormInstances(tcFormName,
tlOmitAutoCenteredForms, tnStartTop,
tnStartLeft, tnStartColumn)
Return: none
Arguments:
tcFormName specifies the form
or _screen in which to cascade forms.
tlOmitAutoCenteredForms specifies
whether to skip cascading for
autocentered forms.
tnStartTop specifies starting top
coordinate.
tnStartLeft specifies starting left
coordinate.
GetCurrentTopFormRef method Returns the current frame window. Use
primarily for top-level form applications.
Syntax: GetCurrentTopFormReference( )
Return: loTopForm
Arguments: none
IMDIWorkspaceColor_access( ) Syntax: IMDIWorkspaceColor_access( )
Return: GetSysColor(12)
Arguments: none
InvokeMenuItemInFrame method Use to invoke menu items in top-level
form applications to access certain
system dialog boxes, such as the Find
dialog box. Also use to implement a
menu item in a dialog box that does
not have a menu.
Syntax: InvokeMenuItemInFrame(tcAction)
Return: none
Arguments:
tcAction specifies navigation action such as NEXT or PREVIOUS.
You can also use the following actions:
UNDO, REDO, CUT, COPY, PASTE,
CLEAR, SELECTALL, FIND, FINDAGAIN,
REPLACE
ShowCurrentTopForm method | Internal to the class.
ShowWindowInFrame method | Internal to the class.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Visual FoxPro Foundation Class Samples


XML Web Services Foundation Classes

The XML Web Service Foundation class libraries, _WS3Utils.vcx and _WS3Client.vcx, contain a collection of classes that serve as the Visual FoxPro XML Web service extensions for Microsoft SOAP Toolkit version 3.0. Use these classes to register XML Web services in compliance with those supported by the Toolkit. You can also publish Visual FoxPro COM Servers (.dll files) as XML Web services using these extensions.

_WS3Utils.vcx Class Library

Class | Description
Olecontrols | Tree view control used by the XML Web Service Builder
Wsbasebuilder | Base form class used by the XML Web Service Builder
Wsbuilder | Initial XML Web Service Builder dialog box
Wsbuilder1 | XML Web Service – Operation Detail dialog box
Wsbuilder2 | XML Web Service – Client Detail dialog box
Wsbuilder3 | XML Web Service – Complex Types dialog box
Wsbuilder4 | XML Web Service – Parameter Values dialog box
Wsconfig | Dialog box used by the Web Services Publisher to specify a URL location for WSDL files
Wsfoxcode | Class used to handle IntelliSense for an XML Web service when accessing in the editing window for a program
Wsmanager | Class called by the XML Web Services pane in the Task Pane Manager to manage XML Web services
Wsphook | Project hook class used by the XML Web Services Publisher to regenerate WSDL files when project is rebuilt
Wspicker | Dialog box for selecting an XML Web service class to insert proxy code. This dialog box opens when you type the characters, ws, in an editing window for a program.
Wsproxy | Class used to generate proxy code when a XML Web service class is dragged and dropped from the Toolbox to an editing window for a program or called by typing the characters, ws, in the editing window.
Wspub | Visual FoxPro XML Web Services Publisher dialog box
Wsreg | Visual FoxPro XML Web Services Registration dialog box
Wstest | Dialog box called from the XML Web Services pane in the Task Pane Manager for testing an XML Web service
Wstool | Visual FoxPro XML Web Services Publisher Advanced dialog box
Wsuddi | Visual FoxPro XML Web Services Registration UDDI Search dialog box
_webservices | Core engine class for publishing and registering XML Web services

_WS3Client.vcx Class Library

Class | Description
Wshandler | Core client class used to communicate with a XML Web service. This class is used in the proxy code generated in the editing window of a program and when visually binding controls to XML Web services on a form.
Colbase | Class from which the XML Web service collection classes are derived
Colclient | Class added to the ColClients clients collection
Colclients | Operation clients collection class
Coloperation | Class added to the Coloperations operations collection
Coloperations | Operations collection class
Colparm | Class added to the Colparms parameters collection
Colparms | Operation parameters collection class
Wsparms | Dialog box that prompts a user to enter parameters for the XML Web service operation call
Wsparmzoom | Zoom dialog box used by the input parameters dialog box

Remarks

In the _WS3Utils.vcx class library, the core engine class, _WebServices, communicates directly with the Toolkit. The _WebServices class contains methods for publishing XML Web services, including those that read type library information from your server and those that generate the necessary XML Web service support files, for example, ASP listener and WSDL service description files. You can also register an external XML Web service using the methods provided.

The _WS3Utils.vcx class library contains other support classes for working with XML Web services. These classes are essentially form classes that assist the user in gathering information for registering and publishing XML Web services. They work in conjunction with the _WebServices class.

In the _WS3Client.vcx class library, the core class for using an XML Web service is WSHandler. This class handles all calls to the SOAP Toolkit 3.0 SOAP Client classes that connect to an XML Web service and call operations.

For more information about using foundation classes, see Guidelines for Using Visual FoxPro Foundation Classes.

See Also

Guidelines for Using Visual FoxPro Foundation Classes | Visual FoxPro Foundation Classes A-Z | Foundation Class Samples


Properties

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

ActiveColumn Property

ActiveControl Property

ActiveForm Property

ActivePage Property

ActiveProject Property

ActiveRow Property

AddLineFeeds Property

Alias Property

Align Property

Alignment Property

AllowAddNew Property

AllowAutoColumnFit Property

AllowCellSelection Property

AllowDelete Property

AllowHeaderSizing Property

AllowInsert Property

AllowOutput Property

AllowRowSizing Property

AllowSimultaneousFetch Property

AllowTabs Property

AllowUpdate Property

AlwaysOnBottom Property

AlwaysOnTop Property

Application Property

AutoActivate Property

AutoCenter Property

AutoCloseTables Property

AutoIncrement Property

AutoOpenTables Property

AutoRelease Property

AutoSize Property

AutoVerbMenu Property

AutoYield Property

B

BackColor, ForeColor Properties

BackStyle Property

BaseClass Property

BatchUpdateCount Property

BindControls Property

BorderColor Property

BorderStyle Property

BorderWidth Property

Bound Property

BoundColumn Property

BoundTo Property

BreakOnError Property

BufferMode Property

BufferModeOverride Property

BuildDateTime Property

ButtonCount Property

Buttons Property

C

Cancel Property

Caption Property

Centered Property

Century Property

ChildAlias Property

ChildOrder Property

ChildTable Property

Class Property

ClassLibrary Property

ClipControls Property

ClosableProperty

CLSID Property

CodePage Property

ColorScheme Property

ColorSource Property

ColumnCount Property

ColumnLines Property

ColumnOrder Property

Columns Property

ColumnWidths Property

Comment Property

CompareMemo Property

ContinuousScroll Property

ControlBox Property

ControlCount Property

Controls Property

ControlSource Property

ConversionFunc Property

Count Property

CurrentControl Property

CurrentX, Current Y Properties

CursorSchema Property

CursorSource Property

CursorStatus Property

Curvature Property

D

Database Property

DataSession Property

DataSessionID Property

DataSource Property

DataSourceType Property

DataType Property

DateFormat Property

DateMark Property

Debug Property

DEClass Property

DEClassLibrary Property

Default Property

DefaultFilePath Property

DefOLELCID Property

DeleteCmd Property

DeleteCmdDataSource Property

DeleteCmdDataSourceType Property

DeleteMark Property

Description Property

Desktop Property

Details Property

DisabledBackColor, DisabledForeColor Properties

DisabledItemBackColor, DisabledItemForeColor Properties

DisabledPicture Property

DisableEncode Property

DisplayCount Property

DisplayValue Property

Docked Property

DockPosition Property

DocumentFile Property

DownPicture Property

DragIcon Property

DragMode Property

DrawMode Property

DrawStyle Property

DrawWidth Property

DynamicAlignment Property

DynamicBackColor, DynamicForeColor Properties

DynamicCurrentControl Property

DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

DynamicFontName Property

DynamicFontOutline Property

DynamicFontShadow Property

DynamicFontSize Property

DynamicInputMask Property

E

EditorOptions Property

Enabled Property

EnableHyperlinks Property

Encrypted Property

ErrorNo Property

Exclude Property

Exclusive Property

F

FetchAsNeeded Property

FetchMemo Property

FetchSize Property

FileClass Property

FileClassLibrary Property

FillColor Property

FillStyle Property

Filter Property

FirstElement Property

Flags Property

FontBold, FontItalic, FontStrikethru, FontUnderline Properties

FontCharSet Property

FontCondense, FontExtend Properties

FontName Property

FontOutline Property

FontShadow Property

FontSize Property

ForceCloseTag Property

Format Property

FormCount Property

FormattedOutput Property

Forms Property

FractionDigits Property

FullName Property

G

GridLineColor Property

GridLines Property

GridLineWidth Property

H

HalfHeightCaption Property

HeaderClass Property

HeaderClassLibrary Property

HeaderHeight Property

Height Property

HelpContextID Property

HideSelection Property

Highlight Property

HighlightBackColor Property

HighlightForeColor Property

HighlightStyle Property

HighlightRow Property

HighlightRowLineWidth Property

HomeDir Property

Hours Property

HostName Property

HScrollSmallChange Property

HWnd Property

I

Icon Property

Increment Property

IncrementalSearch Property

InitialSelectedAlias Property

InputMask Property

InsertCmd Property

InsertCmdDataSource Property

InsertCmdDataSourceType Property

Instancing Property

IntegralHeight Property

Interval Property

IMEMode Property

IsAttribute Property

IsBase64 Property

IsBinary Property

IsNull Property

IsDiffGram Property

IsLoaded Property

ItemBackColor, ItemForeColor Properties

ItemData Property

ItemIDData Property

ItemTips Property

IXMLDomElement Property

J

K

KeyboardHighValue, KeyboardLowValue Properties

KeyField Property

KeyFieldList Property

KeyPreview Property

KeySort Property

L

LanguageOptions Property

Left Property

LeftColumn Property

LineContents Property

LineNo Property

LineSlant Property

LinkMaster Property

List Property

ListCount Property

ListIndex Property

ListItem Property

ListItemID Property

LockColumns Property

LockColumnsLeft Property

LockScreen Property

M

MacDesktop Property

MainFile Property

MapN19_4ToCurrency Property

Margin Property

MaxButton Property

MaxHeight Property

MaxLeft Property

MaxLength Property

MaxRecords Property

MaxTop Property

MaxWidth Property

MDIForm Property

MemberClass Property

MemberClassLibrary Property

MemoWindow Property

Message Property

MinButton Property

MinHeight Property

MinWidth Property

MouseIcon Property

MousePointer Property

Movable Property

MoverBars Property

MultiSelect Property

N

Name Property

NewIndex Property

NewItemID Property

NoCpTrans Property

NoDataOnLoad Property

NullDisplay Property

NumberOfElements Property

O

Object Property

OLEClass Property

OLEDragMode Property

OLEDragPicture Property

OLEDropEffects Property

OLEDropHasData Property

OLEDropMode Property

OLEDropTextInsertion Property

OLELCID Property

OLERequestPendingTimeout Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property

OLETypeAllowed Property

OneToMany Property

OpenViews Property

OpenWindow Property

Order Property

P

PageCount Property

PageHeight Property

PageOrder Property

Pages Property

PageWidth Property

Panel Property

PanelLink Property

Parent Object Reference

ParentAlias Property

ParentClass Property

ParentTable Property

Partition Property

PasswordChar Property

Picture Property

PicturePosition Property

PictureSelectionDisplay Property

Prepared Property

PreserveWhiteSpace Property

Procedure Property

ProcessID Property

ProgID Property

ProjectHook Property

ProjectHookClass Property

ProjectHookLibrary Property

Q

R

ReadCycle Property

ReadLock Property

ReadMouse Property

ReadObject Property

ReadOnly Property

ReadSave Property

ReadTimeout Property

RecordMark Property

RecordSource Property

RecordSourceType Property

RelationalExpr Property

RelativeColumn Property

RelativeRow Property

ReleaseType Property

Resizable Property

RespectCursorCP Property

RightToLeft Property

RotateFlip Property

RowColChange Property

RowHeight Property

RowSource Property

RowSourceType Property

S

ScaleMode Property

SCCProvider Property

SCCStatus Property

ScrollBars Property

Seconds Property

SelectCmd Property

Selected Property

SelectedID Property

SelectedItemBackColor Property

SelectedItemForeColor Property

SelectOnEntry Property

SelLength Property

SelStart Property

SelText Property

SendUpdates Property

ServerClass Property

ServerClassLibrary Property

ServerHelpFile Property

ServerName Property

ServerProject Property

ShowTips Property

ShowInTaskbar Property

ShowWindow Property

Sizable Property

SizeBox Property

SOM Property

Sorted Property

Sparse Property

SpecialEffect Property

SpinnerHighValue, SpinnerLowValue Properties

SplitBar Property

StackLevel Property

StartMode Property

StatusBar Property

StatusBarText Property

Stretch Property

StrictDateEntry Property

Style Property

T

TabIndex Property

Tables Property

TabOrientation Property

Tabs Property

TabStop Property

TabStretch Property

TabStyle Property

Tag Property

TerminateRead Property

Text Property

Themes Property

ThreadID Property

TitleBar Property

ToolTipText Property

Top Property

TopIndex Property

TopItemID Property

Type Property

TypeLibCLSID Property

TypeLibDesc Property

TypeLibName Property

U

Unicode Property

UpdatableFieldList Property

UpdateCmd Property

UpdateCmdDataSource Property

UpdateCmdDataSourceType Property

UpdateGram Property

UpdateGramSchemaLocation Property

UpdateNameList Property

UpdateType Property

UseDeDataSource Property

UseMemoSize Property

UserValue Property

UTF8Encoded Property

V

Value Property

Version Property

VersionComments Property

VersionCompany Property

VersionCopyright Property

VersionDescription Property

VersionNumber Property

VersionProduct Property

VersionTrademarks Property

VFPXMLProgID Property

ViewPortHeight Property

ViewPortLeft Property

ViewPortTop Property

ViewPortWidth Property

VScrollSmallChange Property

View Property

Visible Property

VisualEffect Property

W

WhatsThisButton Property

WhatsThisHelp Property

WhatsThisHelpID Property

WhereType Property

Width Property

WindowList Property

WindowState Property

WindowType Property

WordWrap Property

WrapCharInCDATA Property

WrapInCDATA Property

WrapMemoInCDATA Property

X

XMLAdapter Property

XMLConstraints Property

XMLName Property

XMLNamespace Property

XMLPrefix Property

XMLSchemaLocation Property

XMLTable Property

XMLType Property

XSDfractionDigits Property

XSDmaxLength Property

XSDtotalDigits Property

XSDtype Property

Y

Z

ZoomBox Property


ActiveColumn Property

Returns as an integer the column number that contains the active cell in a Grid control. Not available at design time; read-only at run time.

Grid.ActiveColumn

Remarks

ActiveColumn returns zero if the grid doesn't have the focus.

Example

The following example shows the use of the ActiveColumn Grid property.

m.cTalk=SET("TALK")
SET TALK OFF

PUBLIC oTlb
oTlb = NEWOBJECT("tlbDemo")
oTlb.SHOW

PUBLIC oFrmDemo
oFrmDemo=NEWOBJECT("frmDemo")
oFrmDemo.SHOW

READ EVENTS

RELEASE oTlb
RELEASE oFrmDemo
SET TALK &cTalk

RETURN

DEFINE CLASS tlbDemo AS TOOLBAR

    HEIGHT = 31
    LEFT = 30
    TOP = 30
    WIDTH = 149
    NAME = "tlbDemo"
    CAPTION = "Example"
    CONTROLBOX = .F.

    ADD OBJECT cmdShowColumn AS COMMANDBUTTON WITH ;
        TOP = 5, ;
        LEFT = 5, ;
        HEIGHT = 22, ;
        WIDTH = 100, ;
        CAPTION = "ActiveColumn?", ;
        NAME = "cmdShowColumn"

    ADD OBJECT sepSeparator1 AS SEPARATOR WITH ;
        TOP = 5, ;
        LEFT = 80, ;
        HEIGHT = 0, ;
        WIDTH = 0, ;
        NAME = "sepSeparator1"

    ADD OBJECT cmdExit AS COMMANDBUTTON WITH ;
        TOP = 5, ;
        LEFT = 80, ;
        HEIGHT = 22, ;
        WIDTH = 34, ;
        CAPTION = "Exit", ;
        NAME = "cmdExit"

    PROCEDURE cmdShowColumn.CLICK
        DO ShowColumn
    ENDPROC

    PROCEDURE cmdExit.CLICK
        CLEAR EVENTS
    ENDPROC

ENDDEFINE

DEFINE CLASS frmDemo AS FORM

    CLOSABLE = .F.
    CAPTION = "ActiveColumn Example"
    NAME = "frmDemo"
    LEFT = 60
    TOP = 100

    ADD OBJECT grdNames AS GRID WITH ;
        COLUMNCOUNT = 3, ;
        DELETEMARK = .F., ;
        HEIGHT = 128, ;
        LEFT = 12, ;
        PANEL = 1, ;
        RECORDSOURCE = "names", ;
        SPLITBAR = .F., ;
        TABINDEX = 3, ;
        TOP = 48, ;
        WIDTH = 340, ;
        NAME = "grdNames", ;
        Column1.CONTROLSOURCE = "names.cname", ;
        Column1.WIDTH = 122, ;
        Column1.NAME = "Column1", ;
        Column2.CONTROLSOURCE = "names.nvalue", ;
        Column2.WIDTH = 100, ;
        Column2.NAME = "Column2", ;
        Column3.CONTROLSOURCE = "names.dbirth", ;
        Column3.WIDTH = 122, ;
        Column3.NAME = "Column3"

    PROCEDURE LOAD
        CREATE CURSOR names (cname C(40), nvalue N(19,2), dbirth D)
        INSERT INTO names VALUES('Thomas',12.5,{^1990-5-11})
        INSERT INTO names VALUES('Jerry',18.2,{^1993-1-28})
        INSERT INTO names VALUES('Andrew',9.2,{^1986-1-23})
        GO TOP
    ENDPROC

    PROCEDURE INIT
        THIS.grdNames.Column1.Header1.CAPTION = "Name"

        WITH THIS.grdNames.Column1.Text1
            .BORDERSTYLE = 0
            .MARGIN = 0
        ENDWITH

        THIS.grdNames.Column2.Header1.CAPTION = "Value"

        WITH THIS.grdNames.Column2.Text1
            .BORDERSTYLE = 0
            .MARGIN = 0
        ENDWITH

        THIS.grdNames.Column3.Header1.CAPTION = "Birthdate"

        WITH THIS.grdNames.Column3.Text1
            .BORDERSTYLE = 0
            .MARGIN = 0
        ENDWITH

    ENDPROC

ENDDEFINE

PROCEDURE ShowColumn
    WAIT WINDOW AT 4,30 "_SCREEN.ActiveForm.ActiveControl.ActiveColumn = "+TRANSFORM(_SCREEN.ActiveForm.ActiveControl.ActiveColumn) NOWAIT
ENDPROC

See Also

ActivateCell Method | ActiveRow Property | GridHitTest Method

Applies To: Grid Control


ActiveControl Property

References the active control on an object. Not available at design time; read-only at run time.

Object.ActiveControl.Property[ = Value]

Property Values

Property
The property to return or set.
Value
The current or new property value.

Remarks

This property is not available if all controls on the specified object are invisible or disabled.

If the object is active, the ActiveControl property references the control that has the focus. If the object is not active, an error occurs.

Example

The following example uses the ActiveControl property to show which control on a Form has focus. Note that Grids are containers, and they require code to determine the current ActiveControl within the Grid.

m.cTalk=SET("TALK")
SET TALK OFF

PUBLIC oTlb
oTlb = NEWOBJECT("tlbDemo")
oTlb.SHOW

PUBLIC oFrmDemo
oFrmDemo=NEWOBJECT("frmDemo")
oFrmDemo.SHOW

READ EVENTS

RELEASE oTlb
RELEASE oFrmDemo
SET TALK &cTalk

RETURN

DEFINE CLASS tlbDemo AS TOOLBAR

    HEIGHT = 31
    LEFT = 30
    TOP = 30
    WIDTH = 149
    NAME = "tlbDemo"
    CONTROLBOX = .F.

    ADD OBJECT cmdShowControl AS COMMANDBUTTON WITH ;
        TOP = 5, ;
        LEFT = 5, ;
        HEIGHT = 22, ;
        WIDTH = 100, ;
        CAPTION = "ActiveControl?", ;
        NAME = "cmdShowControl"

    ADD OBJECT sepSeparator1 AS SEPARATOR WITH ;
        TOP = 5, ;
        LEFT = 80, ;
        HEIGHT = 0, ;
        WIDTH = 0, ;
        NAME = "sepSeparator1"

    ADD OBJECT cmdExit AS COMMANDBUTTON WITH ;
        TOP = 5, ;
        LEFT = 80, ;
        HEIGHT = 22, ;
        WIDTH = 34, ;
        CAPTION = "Exit", ;
        NAME = "cmdExit"

    PROCEDURE cmdShowControl.CLICK
        DO ShowControl
    ENDPROC

    PROCEDURE cmdExit.CLICK
        CLEAR EVENTS
    ENDPROC

ENDDEFINE

DEFINE CLASS frmDemo AS FORM

    DOCREATE = .T.
    CAPTION = "Demo Form"
    NAME = "frmDemo"
    LEFT = 60
    TOP = 100

    ADD OBJECT cmdClose AS COMMANDBUTTON WITH ;
        TOP = 200, ;
        LEFT = 264, ;
        HEIGHT = 27, ;
        WIDTH = 84, ;
        CANCEL = .T., ;
        CAPTION = "Close", ;
        DEFAULT = .T., ;
        TABINDEX = 4, ;
        NAME = "cmdClose"

    ADD OBJECT grdNames AS GRID WITH ;
        COLUMNCOUNT = 2, ;
        DELETEMARK = .F., ;
        HEIGHT = 128, ;
        LEFT = 12, ;
        PANEL = 1, ;
        RECORDSOURCE = "names", ;
        SPLITBAR = .F., ;
        TABINDEX = 3, ;
        TOP = 48, ;
        WIDTH = 344, ;
        NAME = "grdNames", ;
        Column1.CONTROLSOURCE = "names.cname", ;
        Column1.WIDTH = 222, ;
        Column1.NAME = "Column1", ;
        Column2.CONTROLSOURCE = "names.nvalue", ;
        Column2.NAME = "Column2"

    ADD OBJECT txtName AS TEXTBOX WITH ;
        CONTROLSOURCE = "names.cname", ;
        HEIGHT = 24, ;
        LEFT = 56, ;
        TABINDEX = 2, ;
        TOP = 12, ;
        WIDTH = 125, ;
        NAME = "txtName"

    ADD OBJECT lblNameLabel AS LABEL WITH ;
        CAPTION = "Name:", ;
        HEIGHT = 17, ;
        LEFT = 16, ;
        TOP = 16, ;
        WIDTH = 40, ;
        TABINDEX = 1, ;
        NAME = "lblNameLabel"

    PROCEDURE LOAD
        CREATE CURSOR names (cname C(40), nvalue N(19,2))
        INSERT INTO names VALUES('Thomas',12.5)
        INSERT INTO names VALUES('Jerry',18.2)
        INSERT INTO names VALUES('Andrew',9.2)
        GO TOP
    ENDPROC

    PROCEDURE INIT
        THIS.grdNames.Column1.Header1.CAPTION = "Name"

        WITH THIS.grdNames.Column1.Text1
            .BORDERSTYLE = 0
            .MARGIN = 0
        ENDWITH

        THIS.grdNames.Column2.Header1.CAPTION = "Value"
        WITH THIS.grdNames.Column2.Text1
            .BORDERSTYLE = 0
            .MARGIN = 0
        ENDWITH

    ENDPROC

    PROCEDURE cmdClose.CLICK
        THISFORM.RELEASE
    ENDPROC

    PROCEDURE grdNames.AFTERROWCOLCHANGE
        LPARAMETERS nColIndex
        THISFORM.REFRESH
    ENDPROC

    PROCEDURE txtName.VALID
        THISFORM.grdnames.REFRESH
    ENDPROC

ENDDEFINE

PROCEDURE ShowControl
IF TYPE("_Screen.ActiveForm.ActiveControl")=="O"
    LOCAL loActiveControl
    m.loActiveControl = _SCREEN.ACTIVEFORM.ACTIVECONTROL
    IF m.loActiveControl.BASECLASS = "Grid"
        m.loActiveControl = ;
            EVALUATE("m.loActiveControl.Columns(m.loActiveControl.ActiveColumn)." + ;
            m.loActiveControl.COLUMNS(m.loActiveControl.ACTIVECOLUMN).CURRENTCONTROL)
    ENDIF
    m.cObjHierarchy=UPPER(SYS(1272,m.loActiveControl))
    WAIT WINDOW AT 4,30 "_SCREEN.ActiveForm.ActiveControl = "+m.cObjHierarchy NOWAIT
ELSE
    WAIT WINDOW AT 4,30 "There is no ActiveControl; there is no ActiveForm" NOWAIT
ENDIF
ENDPROC

See Also

ActiveForm Property

Applies To: Container Object | Form Object | Page Object | _SCREEN | ToolBar Object


ActiveForm Property

References the active Form object in a form set or the _SCREEN object. Not available at design time; read-only at run time.

Object.ActiveForm.Property [ = Setting]
-or-
Object.ActiveForm.Method

Property Values

Property
Specifies any property of the active form contained in the form set; for example, the Caption property.
Setting
The existing or new setting of the Property.
Method
Specifies any method of the active form contained in the form set; for example, the Move method.

Remarks

If the containing FormSet object is active, ActiveForm references the Form object that has the focus. If the containing FormSet object is not active, an error occurs.

Use the ActiveForm property to access the active Form object's properties and methods.

Example

This example shows how the ActiveForm property may be used within a menu to enable opening and closing a form. When running this sample, note that the Close menu item in the Window menu pad is only enabled if there is an open form. This behavior is controlled by the SKIP FOR clause in bar 1 of the Wwindow popup, which checks to see if a form is active by testing whether the Name of the form is of the character type. The Name property will be character type if there is an active form; otherwise, the property will be undefined.

SET SYSMENU TO
SET SYSMENU AUTOMATIC

DEFINE PAD _0k50sa3dr OF _MSYSMENU PROMPT "\<Window" COLOR SCHEME 3 ;
    KEY ALT+W, ""
DEFINE PAD _0k50sa3ds OF _MSYSMENU PROMPT "E\<xit" COLOR SCHEME 3 ;
    KEY ALT+X, ""
ON PAD _0k50sa3dr OF _MSYSMENU ACTIVATE POPUP Wwindow
ON SELECTION PAD _0k50sa3ds OF _MSYSMENU DO CloseDemo

DEFINE POPUP Wwindow MARGIN RELATIVE SHADOW COLOR SCHEME 4
DEFINE BAR 1 OF Wwindow PROMPT "\<Close" ;
    SKIP FOR TYPE("_Screen.ActiveForm.Name")<>"C"
DEFINE BAR 2 OF Wwindow PROMPT "\<Open"
ON SELECTION BAR 1 OF Wwindow =_SCREEN.ACTIVEFORM.RELEASE()
ON SELECTION BAR 2 OF Wwindow DO OpenForm

PUBLIC ARRAY aoForms(1)
aoForms[1] = NEWOBJECT("frmdemo")
aoForms[1].SHOW

READ EVENTS

SET SYSMENU TO DEFAULT
CLEAR ALL

    PROCEDURE OpenForm
    DIMENSION aoForms(ALEN(aoForms)+1)
    aoForms[ALEN(aoForms)] = NEWOBJECT("frmdemo")
    aoForms[ALEN(aoForms)].SHOW
    RETURN

    PROCEDURE CloseDemo
    CLEAR EVENTS
    RETURN

DEFINE CLASS frmdemo AS FORM
    CAPTION = "Demo Form"
    NAME = "frmDemo"

    ADD OBJECT cmdClose AS COMMANDBUTTON WITH ;
        TOP = 200, ;
        LEFT = 264, ;
        HEIGHT = 27, ;
        WIDTH = 84, ;
        CANCEL = .T., ;
        CAPTION = "Close", ;
        DEFAULT = .T., ;
        NAME = "cmdClose"

    PROCEDURE cmdClose.CLICK
    m.nOKButton=0
    m.nInfo=64
    =MESSAGEBOX("After this Form closes, select Exit from the menu to return to the Command Window",m.nInfo+m.nOKButton)
    THISFORM.RELEASE
ENDPROC

    PROCEDURE RELEASE
    LOCAL m.nIndex
    FOR m.nIndex = 1 TO ALEN(aoForms)
        IF VARTYPE(aoForms[m.nIndex])=="O"
            IF aoForms[m.nIndex]=THIS
                aoForms[m.nIndex] = ""
                EXIT
            ENDIF
        ENDIF
    ENDFOR
ENDPROC
ENDDEFINE

See Also

Activate Event | Deactivate Event

Applies To: Form Object | FormSet Object | _SCREEN


ActivePage Property

Returns the number of the active Page in a PageFrame object. Available at design time; read/write at run time.

PageFrame.ActivePage

Example

The following example creates a custom class called WizardExample. It uses this class to demonstrate manipulating the ActivePage property of a tabless pageframe, commonly used in some Visual FoxPro wizards.

local loform
loform = createobject('WizardExample')
loform.Show(1)
return

DEFINE CLASS WizardExample AS form
 Caption = "Wizard Example"
 Name = "Form1"

 ADD OBJECT pageframe1 AS pageframe WITH ;
  PageCount = 3, ;
  BorderWidth = 0, ;
  Top = 12, ;
  Left = 12, ;
  Width = 336, ;
  Height = 169, ;
  Tabs = .F., ;
  Name = "Pageframe1", ;
  Page1.Caption = "Page1", ;
  Page1.Name = "Page1", ;
  Page2.Caption = "Page2", ;
  Page2.Name = "Page2", ;
  Page3.Caption = "Page3", ;
  Page3.Name = "Page3"

 ADD OBJECT CmdPrev AS commandbutton WITH ;
  Top = 216, ;
  Left = 60, ;
  Height = 27, ;
  Width = 84, ;
  Caption = "Previous", ;
  Name = "CmdPrev"

 ADD OBJECT CmdNext AS commandbutton WITH ;
  Top = 216, ;
  Left = 204, ;
  Height = 27, ;
  Width = 84, ;
  Caption = "Next", ;
  Name = "CmdNext"

 PROCEDURE CmdPrev.Click
  With THISFORM.Pageframe1
   if .ActivePage > 1 then
    .ActivePage = .ActivePage - 1
   endif
  Endwith
 ENDPROC

 PROCEDURE CmdNext.Click
  With THISFORM.Pageframe1
   if .ActivePage < .PageCount then
    .ActivePage = .ActivePage + 1
   endif
  Endwith
 endproc

 PROCEDURE Init
  With THISFORM.pageframe1
   .Page1.AddObject('Label1','label')
   With .Page1.Label1
    .Caption = "Wizard Page 1"
    .Height = 17
    .Left = 11
    .Top = 20
    .Width = 97
    .Visible = .T.
   Endwith

   .Page2.AddObject('Label1','label')
   With .Page2.Label1
    .Caption = "Wizard Page 2"
    .Height = 17
    .Left = 11
    .Top = 20
    .Width = 97
    .Visible = .T.
   Endwith

   .Page3.AddObject('Label1','label')
   With .Page3.Label1
    .Caption = "Wizard Page 3"
    .Height = 17
    .Left = 11
    .Top = 20
    .Width = 97
    .Visible = .T.
   Endwith
  Endwith
 ENDPROC
ENDDEFINE

See Also

Activate Event | GotFocus Event

Applies To: PageFrame Control


ActiveProject Property

Contains an object reference to the Project object for the currently active Project Manager window. Read-only at design time and run time.

Object.ActiveProject

Remarks

The ActiveProject property contains an object reference to the Project object for the foremost Project Manager window when more than one Project Manager window is open. An error is generated if you attempt to access the ActiveProject property when a Project Manager window isn't open.

For more information about projects, see Project Manager Hooks and Application Development and Developer Productivity.

Example

The following example uses the ActiveProject property to get a count of Reports and Labels in an active project. If the MyApp project does not exist, it will be created when MODIFY PROJECT is executed.

MODIFY PROJECT myApp NOSHOW NOWAIT
nRptsLbls=0
FOR EACH oFile IN _VFP.ACTIVEPROJECT.FILES
   IF INLIST(oFile.Type, "R", "B")  && Report and Label
      nRptsLbls=nRptsLbls+1
   ENDIF
ENDFOR

See Also

File Object | Files Collection | Project Object | ProjectHook Object | Projects Collection | Server Object | Servers Collection

Applies To: Application Object | _VFP System Variable


ActiveRow Property

Specifies the row that contains the active cell in a Grid control. Not available at design time; read-only at run time.

Grid.ActiveRow

Remarks

The ActiveRow property does not return the same value as RECNO( ) in an indexed table. ActiveRow returns zero if the grid doesn't have the focus or when you access a row outside the grid display.

Example

The following example creates a table and a form with a grid. The grid's ActiveRow property is used to show a row number within the grid.

CREATE TABLE ardemo (fruit C(15))
INSERT INTO ardemo (fruit) VALUES ("Apples")
INSERT INTO ardemo (fruit) VALUES ("Oranges")
INSERT INTO ardemo (fruit) VALUES ("Grapes")
INSERT INTO ardemo (fruit) VALUES ("Bananas")
INSERT INTO ardemo (fruit) VALUES ("Pears")
INSERT INTO ardemo (fruit) VALUES ("Cherries")
LOCATE  && Moves to top of table, synonymous with GO TOP

oForm1=NEWOBJECT("form1")
oForm1.Show
READ EVENTS
RETURN

DEFINE CLASS form1 AS Form
    Caption = "Form1"
    Name = "Form1"
    ADD OBJECT Grid1 AS Grid WITH ;
        ColumnCount = 2, ;
        Height = 200, ;
        Left = 24, ;
        RecordSource = "ardemo", ;
        Top = 24, ;
        Width = 320, ;
        Name = "Grid1", ;
        Column1.ControlSource = "ardemo.fruit", ;
        Column1.Width = 75, ;
        Column1.Name = "Column1", ;
        Column2.Bound = .F., ;
        Column2.ControlSource = "This.ActiveRow", ;
        Column2.Name = "Column2"

    PROCEDURE Init
    THIS.Grid1.Column2.Header1.Caption = 'ActiveRow'
ENDPROC
    PROCEDURE Unload
    CLEAR EVENTS
ENDPROC

ENDDEFINE

See Also

ActivateCell Method | ActiveColumn Property | GridHitTest Method | RECNO( ) Function

Applies To: Grid Control


AddLineFeeds Property

Specifies that the EditBox should insert linefeed characters (CHR(10)) after carriage return characters (CHR(13)) within the text of an EditBox whenever the Value property is read or whenever the value is stored to the ControlSource. Available at design time and run time.

Object.AddLineFeeds[ = lExpr]

Parameters

lExpr
True (.T.) (Default) Linefeed characters are inserted into the EditBox text after carriage return characters when the Value property is read or stored to the ControlSource.

False (.F.) The EditBox text is not modified when the Value property is read or stored to the ControlSource.

Remarks

The EditBox, by default, ensures that line endings have both carriage return and linefeed characters by inserting linefeed characters if they are not present when the Value property is read. In addition to when user code reads the Value property, this may also occur whenever the EditBox loses focus, since Visual FoxPro automatically reads the Value contents and stores to the ControlSource at that time.

Inserting linefeed characters shifts text, but the SelStart value does not change; therefore, the SelStart property can point to the wrong location in the text buffer. Set the AddLineFeeds property to False (.F.) to ensure that no characters are inserted into the text buffer.

Reading the Text property never causes linefeed characters to be inserted, regardless of the setting of AddLineFeeds.

See Also

ControlSource Property | SelStart Property | Text Property | Value Property

Applies To: EditBox Control


Alias Property

Specifies an alias name for the appropriate object. Read/write at design time and run time.

The Alias property mimics the behavior of the ALIAS clause in the USE command.

DataEnvironment.Cursor.Alias [= cText]

-or-

CursorAdapter.Alias [= cText]

-or-

XMLTable.Alias [= cText]

-or-

XMLTable.XMLField.Alias [= cText]

Property Values

cText
Character data type. The following table describes the values for cText, depending on the object.
Object | cText
Cursor | Alias name for each table or view associated with the cursor.
CursorAdapter | Alias name for the cursor generated by the SelectCmd property.
XMLTable Alias name for the Visual FoxPro cursor.

If cText is an empty string (""), the XMLAdapter ToXML method adds the table schema but does not add any data.

XMLField Alias name for the field name in the Visual FoxPro cursor.

If cText is an empty string (""), the XMLTable ToCursor and ApplyDiffGram methods disregards the field.

Remarks

For Cursor objects, when Visual FoxPro loads the data environment, it assigns an alias name that is the same as the table or view name to each table or view associated with the cursor by default. You can change the Alias property to override the default alias name.

For CursorAdapter objects, Visual FoxPro uses Alias property to resolve the correct alias name for tables and fields that you drag and drop to the form from the data environment at design time. If you do not specify values for Alias, Visual FoxPro generates an error and, at run time, uses the default aliases for the tables and fields.

For XMLTable and XMLField objects, Visual FoxPro loads the value of the XMLName property into the corresponding Alias property for those objects by default. If the XMLField Alias property is empty, the XMLTable ToCursor method disregards XMLField objects and creates a cursor that does not include any fields specified by those XMLField objects.

If you change the Alias property, Visual FoxPro also renames the cursor created by the ToCursor method and the Alias properties for XMLTable and XMLField objects.

When executing the ToXML method, Visual FoxPro uses the XMLName property instead of the Alias property.

See Also

Properties | USE Command | ALIAS( ) Function | InitialSelectedAlias Property | ParentAlias Property

Applies To: Cursor Object | CursorAdapter Class | XMLTable Class | XMLField Class


Align Property

Specifies the alignment of an ActiveX™ control (.ocx) on a form. Available at design time and run time.

OLEContainerControl.Align[ = nAlign]

Property Values

nAlign
The settings for the Align property are:
Setting | Description
0 | Standard alignment. The ActiveX control is placed in the same position as the OLE Container control on the form.
1 | Top. The ActiveX control is placed at the top of the form.
2 | Bottom. The ActiveX control is placed at the bottom of the form.
3 | Left. The ActiveX control is placed at the left edge of the form.
4 | Right. The ActiveX control is placed at the right edge of the form.

Remarks

An ActiveX control (.ocx file) is placed in OLE Container control.

The Align property is only available for ActiveX controls that support changes to their alignment. Insertable OLE objects such as Microsoft Excel worksheets do not support the Align property.

The Align property is available only for ActiveX controls that are placed on a form.

If two or more ActiveX controls have the same Align property setting, the controls are stacked on top of each other.

See Also

OLE Container Control | ActiveX Controls Overview | Alignment Property | Adding OLE Objects to Applications

Applies To: OLE Container Control


Alignment Property

Specifies the alignment of text associated with a control. Available at design time and run time.

Control.Alignment[ = nAlign]

Property Values

nAlign
For a CheckBox or OptionButton control, the settings for the Alignment property are:
Setting | Description
0 | (Default) Left. Aligns control to the left with text on the right.
1 | (Default for Middle Eastern versions of Windows) Right. Aligns control to the right with text on the left.

For a ComboBox, EditBox, Header, Label, or Spinner control, the settings for the Alignment property are:

Setting | Description
0 | Left. Aligns text flush left. The default for combo boxes, edit boxes, headers, and labels.
1 | (Default for Middle Eastern versions of Windows) Right. Aligns text flush right. The default for spinners.
2 | Center. Aligns the text in the middle with equal spaces to the right and left.
3 | Automatic. Aligns text based on the data type of the control source.

For a TextBox control, the settings for the Alignment property are:

Setting | Description
0 | Left. Aligns the text flush left.
1 | Right. Aligns the text flush right.
2 | Center. Aligns the text in the middle with equal spaces to the right and left.
3 | (Default) Automatic. For a TextBox control not contained in a Column, aligns text based on the data type of the control source. Numeric types (numeric, double, float, currency, integer) are right-aligned; controls with other data types are left-aligned. For a TextBox control contained in a column, the Alignment setting for the column determines alignment of text in the text box.

For a column, the settings for the Alignment property are:

Setting | Description
0 | Middle Left. Aligns the text flush left and centers it vertically.
1 | Middle Right. Aligns the text flush right and centers it vertically.
2 | Middle Center. Aligns the text in the middle with equal spaces to the right and left and centers it vertically.
3 | (Default) Automatic. Aligns text based on the data type of the control source. Numeric types (numeric, double, float, currency, integer) are right-aligned; controls with other data types are left-aligned.
4 | Top Left. Aligns the text flush left at the top of the column.
5 | Top Right. Aligns the text flush right at the top of the column.
6 | Top Center. Aligns the text in the middle with equal spaces to the right and left, at the top of the column.
7 | Bottom Left. Aligns the text flush left at the bottom of the column.
8 | Bottom Right. Aligns the text flush right at the bottom of the column.
9 | Bottom Center. Aligns the text in the middle with equal spaces to the right and left, at the bottom of the column.

Remarks

For a ComboBox, the Alignment property applies only when the Style property is set to 0.

See Also

AutoSize Property | Caption Property

Applies To: CheckBox Control | Column Object | ComboBox Control | EditBox Control | Header Object | Label Control | OptionButton Control | Spinner Control | TextBox Control


AllowAddNew Property

Specifies whether new records can be added to a table from within a grid. Available at design time and run time.

Grid.AllowAddNew[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | New records can be added to a table from within a grid.
False (.F.) | (Default) New records cannot be added to a table from within a grid.

Remarks

If AllowAddNew is set to True (.T.), you can add a new record to a table in a grid by pressing the down arrow while positioned on the last record in the grid, as long as the grid is read/write. New records cannot be added from within the grid if the grid is read-only (if the RecordSourceType is a query, a table is read-only, and so on).

See Also

APPEND | Adding Records | RecordSourceType Property

Applies To: Grid Control


AllowAutoColumnFit Property

Specifies how columns automatically fit to data inside the Grid or Browse window. Setting this property enables you to automatically fit columns to data when you double-click the area between column headers, or the square immediately preceding the first column header in the upper and leftmost corner of a grid. Read/write at design time and run time.

Grid.AllowAutoColumnFit [ = nValue ]

Property Values

nValue
Numeric data type. The following table lists the values for nValue.
nValue | Setting description
0 | Enables all or individual columns to fit data automatically. (Default)
1 | Enables only individual columns to fit all data automatically. "All data" refers only to all rows in the grid or browse window, not all records in the table.
2 | Disables capability for columns to fit data automatically.

Remarks

AllowAutoColumnFit affects interaction only through the user interface.

Fitting columns automatically to data occurs in both the left and right Grid or Browse panels, but only when either one or both are visible.

You can override AllowAutoColumnFit by using the AutoFit method, which resizes all or individual columns programmatically.

When a column resizes, the Resize event for that column fires.

You can prevent the automatic resizing of a particular column by setting the Resizable property of that column to False (.F.).

Header click events are not called because you click between the column headers.

Hidden grid columns, which have their Visible property set to False (.F.) and have a Width property value of 0, are not resized.

See Also

Properties | Fitting Columns to Data Automatically | AutoFit Method | Resizable Property

Applies To: Grid Control | BROWSE...NAME Command


AllowCellSelection Property

Specifies whether one can select individual cells in a grid. You can use the AllowCellSelection property to mimic a list box. Available at design time and run time.

Grid.AllowCellSelection [= lExpr]

Property Values

lExpr
Logical data type. The following table lists the values for lExpr.
lExpr | Description
True (.T.) | Specifies that one can select contents in a grid cell (field). (Default)
False (.F.) | Specifies that one must select the entire the row.

Remarks

Selecting individual cells or the entire row does not change color of the selected row or cell.

The following behavior is displayed when AllowCellSelection is set to False (.F.):

  • The grid disregards the SelectedItemForeColor and SelectedItemBackColor properties. The row takes on a uniform color based on the HighlightBackColor and HighlightForeColor properties and other color-related properties at the column level.
    Note If you do not specify colors for the highlighting properties, a rectangular outline appears around a selected row.
  • If the HighlightStyle property is set to a value greater than 0, the default HighlightBackColor is a 50 percent lighter gradient.
  • The grid always shows the cursor specified with the MousePointer property and does not display a text insertion pointer when inside a cell. Clicking a cell selects the entire row, instead of setting focus to the individual cell.
  • Tabbing between cells is disabled, and grid behavior acts similar to a grid with a single column.
  • Hidden columns are disregarded. You can view columns that are scrolled to the left or right outside the visible grid by using the LEFT ARROW and RIGHT ARROW keys or the mouse and the horizontal scrollbar.
  • The ActiveColumn property evaluates to 0; use the RelativeColumn property to obtain the correct column in the grid.
  • The ActiveCell method merely selects the entire row.
  • All events are handled at the grid level instead of at the control level. For example, double-clicking a cell is handled by the Grid.DblClick event. However, header events and attributes are still supported. For example, you can click on a header to resort the column's contents based on the field.
  • Support for Find is disabled as well as Edit menu commands because setting AllowCellSelection makes the grid read-only. However, the AllowCellSelection property does not affect the delete mark column in a grid.
  • The AfterRowColChange and BeforeRowColChange events only work for row change. The RowColChange property always returns a value of 1 (Row Change).

The AllowCellSelection property supports all standard Visual FoxPro controls; however, ActiveX controls embedded within a column are not supported.

If the AllowCellSelection property for a grid is set to True (.T.), Visual FoxPro disregards the Grid KeyPress event and uses the event at the individual cell level.

See Also

Properties | ActiveColumn Property | AfterRowColChange Event | BeforeRowColChange Event| HighlightBackColor Property | HighlightStyle Property | RelativeColumn Property | SelectedItemForeColor Property | KeyPress Event

Applies To: Grid Control


AllowDelete Property

Specifies whether to permit delete operations against a data source. Read/write at design time and run time.

Note AllowDelete does not affect the ability to delete a row in the cursor itself.
CursorAdapter.AllowDelete [ = lValue ]

Property Values

lValue
Logical data type. The following table lists the settings for lValue.
lValue | Description
True (.T.) Permit delete operations. (Default)

When the CursorAdapter DeleteCmd property is empty (""), Visual FoxPro generates a SQL DELETE command automatically. For more information, see Data Access Management Using CursorAdapters.
False (.F.) | Does not permit delete operations.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


AllowHeaderSizing Property

Specifies whether the height of a grid's header can be changed at run time. Available at design time and run time.

Grid.AllowHeaderSizing[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | (Default) The height of the grid's header can be changed by dragging the header at run time.
False (.F.) | The height of the grid's header cannot be changed by dragging the header at run time.

See Also

AllowRowSizing Property | HEADER( ) Function | HeaderHeight Property

Applies To: Grid Control


AllowInsert Property

Specifies whether to permit insert operations against a data source. Read/write at design time and run time.

Note AllowInsert does not affect the ability to insert a row into the cursor itself.
CursorAdapter.AllowInsert [ = lValue ]

Property Values

lValue
Logical data type. The following table lists the settings for lValue.
lValue | Description
True (.T.) Permit insert operations. (Default)

When the CursorAdapter InsertCmd property is empty (""), Visual FoxPro generates a SQL INSERT command automatically. For more information, see Data Access Management Using CursorAdapters.
False (.F.) | Does not permit insert operations.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


AllowOutput Property

Specifies whether to allow default output to appear on a form. Read/write at design time and run time.

Form.AllowOutput = lExpr

Parameters

lExpr
Logical data type. The following table lists the settings for lExpr.
lExpr | Description
True (.T.) | (Default) Sends user output to the form if it is active.
False (.F.) | Redirects user output to the desktop if the form is active.

Remarks

If the AllowOutput property is programmatically changed from True (.T.) to False (.F.), at run time, Visual FoxPro automatically redirects output to the desktop.

Note Using the AllowOutput property can affect code that relies on the position and size of a window. This includes the use of WOUTPUT( ) or other commands, such as DEFINE POPUP...FROM, that implicitly base their coordinates on the output window.

Setting the AllowOutput property to False (.F.) on a form, changes the following Visual FoxPro behavior.

  • Painting of the form is redirected to the next output window or desktop. This affects commands, such as ?, ??, DIR, LIST, DISPLAY, CLEAR, and other commands that display output on a form.
  • The WOUTPUT( ) function does not return the name of the active form. It returns the name of the current output form or desktop.
  • The BROWSE command does not inherit the window size and window settings of the form.
  • The MCOL( ) and MROW( ) functions, without the use of their optional parameter, may not be relative to the form they are called on.

When a form closes with the AllowOutput property set to False (.F.), Visual FoxPro defaults to the next output form or desktop.

See Also

Properties | ? | ?? Command | BROWSE Command | CLEAR Command | DEFINE POPUP Command | DIR or DIRECTORY Command | DISPLAY Command | LIST Command | WOUTPUT( ) Function

Applies To: Form Object


AllowRowSizing Property

Specifies whether the height of records in a grid can be changed at run time. Available at design time and run time.

Grid.AllowRowSizing[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | (Default) The height of records in the grid can be changed by dragging at run time.
False (.F.) | The height of records in the grid cannot be changed by dragging at run time.

See Also

AllowHeaderSizing Property | RowHeight Property | ROW( ) Function

Applies To: Grid Control


AllowSimultaneousFetch Property

Specifies whether to permit simultaneous fetching for Open Database Connectivity (ODBC) cursors when using a shared connection. Read/write at design time and run time.

Note AllowSimultaneousFetch applies only when the CursorAdapter DataSourceType property is set to "ODBC". If the associated connection is not shared, setting AllowSimultaneousFetch has no effect.
CursorAdapter.AllowSimultaneousFetch [= lValue]

Property Values

lValue
Logical data type. The following table specifies the values for lValue.
lValue | Description
False (.F.) | When using a shared connection, similarly configured cursors that share the connection are not permitted to fetch rows simultaneously. (Default)
True (.T.) | When using a shared connection, similarly configured cursors that share the connection are permitted to fetch rows simultaneously.

Remarks

Views created in the current version of Visual FoxPro are not compatible with Visual FoxPro earlier than 8.0.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | DataSourceType Property

Applies To: CursorAdapter Class


AllowTabs Property

Specifies whether to allow tabs in an EditBox control.

EditBox.AllowTabs[ = lExpr]

Property Values

lExpr
Specifies a logical value that determines whether tabs are allowed in an EditBox control. The following table lists the settings for lExpr:
lExpr Description
True (.T.) Allow tabs in the edit box.

To exit the control, press CTRL+TAB.
False (.F.) Do not allow tabs in the edit box. (Default)

To exit and move focus to the next control in the tab order, press the TAB key.

See Also

TabIndex Property | TabStop Property | TabStyle Property

Applies To: EditBox


AllowUpdate Property

Specifies whether to permit update operations against a data source. Read/write at design time and run time.

Note AllowUpdate does not affect the ability to update a row in the cursor itself.
CursorAdapter.AllowUpdate [ = lValue ]

Property Values

lValue
Logical data type. The following table lists the settings for lValue.
lValue | Description
True (.T.) Permit update operations. (Default)

When the CursorAdapter InsertCmd property is empty (""), Visual FoxPro generates a SQL UPDATE command automatically. For more information, see Data Access Management Using CursorAdapters.
False (.F.) | Does not permit update operations.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


AlwaysOnBottom Property

Prevents other windows from being covered by a form's window. Available at design time; read/write at run time.

Object.AlwaysOnBottom[ = lExpr]

Property Values

lExpr
The settings for the AlwaysOnBottom property are:
Setting | Description
True (.T.) | The form is always on the bottom (only another window with the AlwaysOnBottom property set to True (.T.) can be under the form).
False (.F.) | (Default) The form can cover another window.

Remarks

The AlwaysOnBottom property is ignored if any of the following properties are set to the specified values:

  • AlwaysOnTop = .T.
  • Desktop = .T.
  • ShowWindow = 2

The AlwaysOnBottom property setting is ignored for _SCREEN.

See Also

AlwaysOnTop Property | Desktop Property | ShowWindow Property | ZOrder Method

Applies To: Form Object | _SCREEN


AlwaysOnTop Property

Prevents other windows from covering the form's window. Available at design time; read/write at run time.

Object.AlwaysOnTop[ = lExpr]

Property Values

lExpr
The settings for the AlwaysOnTop property are:
Setting | Description
True (.T.) | The form is always on the top (only another window with the AlwaysOnTop property set to True (.T.) can be on top of the form).
False (.F.) | (Default) The form can be covered by another window.

See Also

AlwaysOnBottom Property | ShowWindow Property | ZOrder Method |

Applies To: Form Object | _SCREEN


Application Property

Provides a reference to the Application object containing an object. Not available at design time; read-only at run time.

Object.Application.Property [ = Setting]
-or-
Object.Application.Method

Property Values

Property
Specifies any property of the Application object or the _VFP system variable; for example, the Caption property.
Setting
The existing or new setting of the Property.
Method
Specifies any method of the Application object or the _VFP system variable; for example, the DoCmd method.

Remarks

Use the Application property to access an Application object's properties and methods from an object contained by the application. The Application property can also be used with the _VFP system variable to access properties and methods for the current instance of Visual FoxPro.

See Also

CREATEOBJECT( )

Applies To: CheckBox Control | Column Object | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | Cursor Object | CursorAdapter Class | Custom Object | DataEnvironment Object | EditBox Control | Form Object | FormSet Object | Grid Control | Header Object | Hyperlink Object | Image Control | Label Contol | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | Relation Object | _SCREEN | Separator Object | Session Object | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


AutoActivate Property

Determines how an OLE Container control can be activated. Available at design time and run time.

Control.AutoActivate[ = nValue]

Property Values

nValue
The settings for the AutoActivate property are:
Setting | Description
0 | Manual. The control isn't automatically activated. You can activate a control programmatically using the DoVerb method.
1 | GotFocus. If the control contains an object, the application that provides the object is activated when the control receives the focus.
2 | (Default) DoubleClick. If the control contains an object, the application that provides the object is activated when the user double-clicks the control or presses ENTER when the control has the focus.
3 | Automatic. If the control contains an object, the application that provides the object is activated based on the object's normal method of activation (when the control receives the focus or when the user double-clicks the control).

Remarks

If an embedded object supports in-place activation, you can set AutoActivate to 1 (GotFocus) to activate an object when the control receives the focus.

Note When AutoActivate is set to 2 (Double-Click), the DblClick event does not occur.

See Also

DoVerb Method | DblClick Event

Applies To: OLE Bound Control | OLE Container Control


AutoCenter Property

Specifies whether the form object is automatically centered in the main Visual FoxPro window or on the desktop the first time it is displayed. Available at design time and run time.

Object.AutoCenter [ = lExpr]

Property Values

lExpr
Specifies whether the Form object is centered or placed according to the settings of the Top and Left properties. The settings for the AutoCenter property are:
Setting | Description
True (.T.) | The Form object is centered and the values of the Top and Left properties are set to the new position.
False (.F.) | (Default) The Form object is not centered and is placed at the coordinates specified by the Top and Left properties.

Remarks

Forms are displayed in the main window, so setting AutoCenter to true (.T.) centers the form within the main window.

Note Resetting AutoCenter to false (.F.) after it has been set to true (.T.) will not return the form to the original Top and Left position.

See Also

Desktop Property | Left Property | Top Property

Applies To: Form Object | _SCREEN


AutoCloseTables Property

Specifies whether the tables or views specified by the data environment are closed when the form set, form, or report is released. Available at design time; read-only at run time.

DataEnvironment.AutoCloseTables[ = lExpr]

Property Values

lExpr
The settings for the AutoCloseTables property are:
Setting | Description
True (.T.) | (Default) Closes the tables and views when the form set, form, or report is released.
False (.F.) | Tables and views remain open when the form set, form, or report is released.

Remarks

If AutoCloseTables is set to false (.F.) and the form set, form, or report is not running in a private data session, the tables and views associated with Cursors in the data environment remain open after the form set, form, or report is released. In all other cases, the tables and views associated with Cursors in the data environment are closed.

See Also

AutoOpenTables Property | DataSession Property | DataSessionID Property

Applies To: DataEnvironment Object


AutoIncrement Property

Specifies if the build version number of a project is automatically incremented each time a distributable .exe or in-process .dll is built.

Object.AutoIncrement[ = lExpression]

Property Values

lExpression
The settings for the AutoIncrement property are:
Setting | Description
True (.T.) | The build version number of a project is automatically incremented each time a distributable .exe or in-process .dll is built.
False (.F.) | (Default) The build version number isn't automatically incremented.

Remarks

The build version number isn't incremented if AutoIncrement is set to false (.F.) or when the project is rebuilt or a distributable .app is built.

The value of the AutoIncrement property corresponds to the Auto Increment check box in the EXE Version dialog box. The build version number can be determined or set with the VersionNumber property.

See Also

BUILD APP | BUILD DLL | BUILD EXE | BUILD PROJECT | EXE Version Dialog Box | VersionNumber Property

Applies To: Project Object


AutoOpenTables Property

Determines whether the tables or views associated with a form set, form, or report's data environment are loaded automatically. Available at design time; read-only at run time.

DataEnvironment.AutoOpenTables [= lExpr]

Parameters

lExpr
Logical data type. The following table lists the values for lExpr.
lExpr | Description
True (.T.) | The form set, form, or report's tables and views are opened automatically. (Default)
False (.F.) | The tables and views are not opened automatically.

Remarks

When AutoOpenTables is set to True (.T.), the data environment automatically calls the AutoOpen method of any CursorAdapter object contained in the data environment. The data environment opens any cursors or cursor adapters in the order that they were added to the data environment.

When AutoOpenTables is set to False (.F.), you can call the OpenTables method of the data environment to programmatically load the data environment.

See Also

BeforeOpenTables Event | OpenTables Method | OpenViews Property | AutoOpen Method | CursorAdapter Class

Applies To: DataEnvironment Object


AutoRelease Property

Determines whether a form set is released when the last form in the form set is released. Available at design time; read/write at run time.

FormSet.AutoRelease[ = lExpr]

Property Values

lExpr
The settings for the AutoRelease property are:
Setting | Description
True (.T.) | The default in the Form Designer. The form set is released when the last form in the form set is released.
False (.F.) | The default in program code. The form set is not released when the last form in the form set is released.

See Also

Release Method | ReleaseType Property | Form Designer

Applies To: FormSet Object


AutoSize Property

Specifies whether a control is automatically resized to fit its contents. Available at design time and run time.

Control.AutoSize[ = lExpr]

Property Values

lExpr
Specifies whether a control is resized to fit its contents. The settings for the AutoSize property are:
Setting | Description
True (.T.) | The control is automatically resized to fit its contents.
False (.F.) | (Default) The contents are clipped when they exceed the area of the control.

Remarks

For OLE Container controls, Autosize applies only to OLE objects that support in-place editing. The Sizable property must be set to true (.T.) to change the size of an OLE object during in-place editing.

See Also

Alignment Property | Height Property | Width Property

Applies To: CheckBox Control | CommandButton Control | CommandGroup Control | Label Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control


AutoVerbMenu Property

Specifies whether a shortcut menu containing an OLE object's verbs is displayed when the OLE object is clicked with the right mouse button. Available at run time only.

Control.AutoVerbMenu[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | (Default) The shortcut menu containing the OLE object's verbs is displayed when the OLE object is right-clicked.
False (.F.) | The shortcut menu containing the OLE object's verbs is not displayed when the OLE object is right-clicked.

Remarks

At run time, if the AutoVerbMenu and Enabled properties are set to true (.T.), right-clicking the OLE object displays the shortcut menu containing the verbs supported by the OLE object. If the AutoVerbMenu and Enabled properties are set to false (.F.) or the OLE object does not support verbs, the shortcut menu isn't displayed when you right-click the OLE object.

See Also

DoVerb Method | Adding OLE Objects to Your Applications

Applies To: Enabled Property, | OLE Bound Control, | OLE Container Control


AutoYield Property

Specifies whether an instance of Visual FoxPro processes pending Windows events between execution of each line of user program code.

ApplicationObject.AutoYield[ = lExpr]

Property Values

lExpr
Specifies whether an instance of Visual FoxPro processes Windows events between each line of user program code. lExpr can be one of the following logical values:
lExpr Description
True (.T.) (Default) The instance of Visual FoxPro processes pending Windows events between execution of each line of user program code.

If lExpr is set to true (.T.), the instance of Visual FoxPro processes pending Windows events in the same manner as earlier versions of Visual FoxPro.
False (.F.) The instance of Visual FoxPro does not process pending Windows events between each line of user program code.

All pending Windows events are placed in a queue, and the events in the queue are processed when DOEVENTS is issued or a wait state occurs. A wait state occurs when Visual FoxPro is waiting for input from the user. The WAIT command does not create a wait state.

Remarks

The AutoYield property should be set to false (.F.) when a form contains an ActiveX control. Setting AutoYield to false (.F.) prevents events for an ActiveX control from executing between lines of user program code. For example, if AutoYield is set to true (.T.), clicking an ActiveX control while user program code is executing may cause an event for the ActiveX control to execute, ignoring the user program code for the event, producing undesirable or unpredictable results.

The following occurs when the AutoYield property is set to false (.F.):

  • ActiveX controls cannot process events until a wait state occurs, so clicking an ActiveX control has no effect while user program code is executing. This is the same behavior for Visual FoxPro controls such as the Grid.
  • ON KEY LABEL commands and mouse events are ignored while user program code is executing. The ON KEY LABEL commands and mouse events are placed in a queue and processed at the next wait state.
  • Pressing Esc does not interrupt program execution. This is identical to setting ESCAPE to OFF. In this case you cannot exit infinite loops without shutting down the instance of Visual FoxPro.
  • Queries cannot be interrupted.
  • Switching to other applications is supported, but you cannot switch back to Visual FoxPro while Visual FoxPro user program code is executing.

See Also

DOEVENTS Command | WAIT Command | ON KEY LABEL Command

Applies To: Application Object | _VFP System Variable


BackColor, ForeColor Properties

Specifies the background or foreground color used to display text and graphics in an object. Read/write at design and run time.

Object.BackColor[ = nColor]
Object.ForeColor[ = nColor]

Property Values

nColor
Specifies a single color value. If nColor is a negative value, Visual FoxPro uses the integer and ignores any rollover issues. For example, -1 is the equivalent of 0xFFFFFFFF. The following table lists typical color values.
Color | RGB values | nColor
White | 255, 255, 255 | 16777215
Black | 0, 0, 0 | 0
Gray | 192, 192, 192 | 12632256
Dark gray | 128, 128, 128 | 8421504
Red | 255, 0, 0 | 255
Dark red | 128, 0, 0 | 128
Yellow | 255, 255, 0 | 65535
Dark yellow | 128, 128, 0 | 32896
Green | 0, 255, 0 | 65280
Dark green | 0, 128, 0 | 32768
Cyan | 0, 255, 255 | 16776960
Dark cyan | 0, 128, 128 | 8421376
Blue | 0, 0, 255 | 16711680
Dark blue | 0, 0, 128 | 8388608
Magenta | 255, 0 ,255 | 16711935
Dark magenta | 128, 0, 128 | 8388736

Remarks

Visual FoxPro uses a red-green-blue (RGB) color scheme for colors. The red, green, and blue components are each represented by a number between 0 and 255. Use the RGB( ) function to convert the three component colors into one composite nColor.

Note The ForeColor property does not apply to the CommandGroup, OptionGroup, or Shape controls.

The color settings, or Themes, of the operating system set the default color settings for the BackColor and ForeColor properties.

If the Themes property is True (.T.), setting the BackColor property value produces a 35% transparency overlay on top of the themed button. This produces a colorizing effect.

The Page BackColor property is disregarded if Page Themes is True (.T.). However, because a page is only a visual representation in the Class Designer, the back color appears.

Example

The following example demonstrates how the Shape control can be used to display a circle, ellipse, or square on a form, and how the BackColor property can be used to specify the color of each shape.

A form is created, and a set of option buttons and a command button are placed on the form. When you choose one of the option buttons, the corresponding shape is displayed on the form. The BackColor property is used to specify the color of each shape. The Height, Width, and Curvature properties of each shape determine the type of shape created.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

BackStyle Property | ColorScheme Property | DisabledBackColor, DisabledForeColor Properties | FillColor Property | FillStyle Property | GETCOLOR( ) Function | RGB( ) Function

Applies To: CheckBox Control | Column Object | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Form Object | Grid Control | Header Object | Label Control | OptionButton Control | OptionGroup Control | Page Object | _SCREEN | Shape Control | Spinner Control | TextBox Control | ToolBar Object


BackStyle Property

Specifies whether the background of an object is transparent or opaque. Available at design time and run time.

Object.BackStyle[ = nStyle]

Property Values

nStyle
The settings for the BackStyle property are:
Setting | Description
0 | Transparent. Anything behind the object is visible.
1 | (Default) Opaque. The object's BackColor fills the control and obscures any color or graphics behind it.

Remarks

You can use the BackStyle property to create transparent controls when you are using a background color on a Form object or when you want to place a control over a graphic. Use an opaque control when you want it to stand out on a busy background.

An object's BackColor property is ignored if the BackStyle property is set to 0 (Transparent).

For a Page object, the BackStyle property is read-only when the Tabs property is set to True (.T.) for the PageFrame containing the Page.

An object's BackStyle property is ignored if the object's Theme property is set to True (.T.).

See Also

BackColor, ForeColor Properties | DisabledBackColor, DisabledForeColor Properties

Applies To: CheckBox Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Image Control | Label Control | OptionButton Control | OptionGroup Control | Page Object | Shape Control | TextBox Control


BaseClass Property

Contains the name of the Visual FoxPro base class on which the referenced object is based. Read-only at design time and run time.

Object.BaseClass

Property Values

cBaseClass
Contains the Visual FoxPro base class on which the object is based.

Remarks

For a list of Visual FoxPro base classes, see Controls and Objects.

See Also

Class Property

Applies To: CheckBox Control | Collection Class | Column Object | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | CursorAdapter Class | Custom Object | EditBox Control | Exception Class | Form Object | FormSet Object | Grid Control | Header Object | Hyperlink Object | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | _SCREEN | Session Object | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


BatchUpdateCount Property

Specifies the number of update statements sent to the remote data source for buffered tables. When working with this property for regular cursors, use the CURSORSETPROP() and CURSORGETPROP() functions. Read/write.

Adjusting BatchUpdateCount can increase automatic updating performance dramatically.

Note Setting BatchUpdateCount for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.BatchUpdateCount [ = nValue]

Property Values

nValue
Numeric data type. The nValue parameter has a default value of 1.

Remarks

BatchUpdateCount applies for CursorAdapter objects only when the data source type for the SQL INSERT, UPDATE, and DELETE commands is one of the following:

  • "ODBC"

    Additionally, the same connection handle must be used as the data source for the SQL INSERT, UPDATE, and DELETE commands.

    Note The data source and data source type might be inherited from the DataSource and DataSourceType properties of either the CursorAdapter or DataEnvironment object.
  • "ADO"

    The same ADODB Command object must be used as the data source for the SQL INSERT, UPDATE, and DELETE commands. It is recommended that you set the InsertCmdDataSource, InsertCmdDataSourceType, UpdateCmdDataSource, UpdateCmdDataSourceType, DeleteCmdDataSource, and DeleteCmdDataSourceType properties explicitly because inheritance does not work in this scenario.

  • "XML"

    It is recommended that you set the InsertCmdDataSource, InsertCmdDataSourceType, UpdateCmdDataSource, UpdateCmdDataSourceType, DeleteCmdDataSource, and DeleteCmdDataSourceType properties explicitly because inheritance does not work in this scenario.

If BatchUpdateCount is greater than 1, Visual FoxPro updates the batch by executing the UpdateCmd property once per batch.

Note If batch updating is used, the BeforeInsert, AfterInsert, BeforeUpdate, AfterUpdate, BeforeDelete, and AfterDelete events do not fire. If an update fails for a batch, Visual FoxPro attempts to send a separate update for each row in the batch; however, the events still do not fire.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function | INSERT - SQL Command | UPDATE - SQL Command | DELETE - SQL Command | DataSource Property | DataSourceType Property | InsertCmdDataSource Property | InsertCmdDataSourceType Property | UpdateCmdDataSource Property | UpdateCmdDataSourceType Property | DeleteCmdDataSource Property | DeleteCmdDataSourceType Property | UpdateCmd Property | BeforeInsert Event | AfterInsert Event | BeforeUpdate Event | AfterUpdate Event | BeforeDelete Event | AfterDelete Event

Applies To: CursorAdapter Class


BindControls Property

Specifies when data binding occurs for data-bound controls.

Visual FoxPro usually binds the controls to the data source when the form loads. However, you can use BindControls to specify when data binding occurs for various reasons, such as to improve performance or to delay binding controls to the data source until the user performs an action, after the form loads, or until the data is needed.

Note BindControls is intended for use when initially displaying a form and for binding controls after displaying the form. Although you can set BindControls to False (.F.) and back to True (.T.), BindControls is not intended for unbinding and rebinding controls at run time.
Form.BindControls [= lValue]

Property Values

Logical data type. The following table lists the values for lValue.

lValue | Description
True (.T.) | The Control.ControlSource or Grid.RecordSource binds to data when the form loads. (Default) If Form.BindControls = .T. and Control.ControlSource or Grid.RecordSource is changed, the control is rebound. If Form.BindControls is changed from .T. to .F., current bindings are not changed.
False (.F.) | The Control.ControlSource or Grid.RecordSource does not bind to data when the form loads. If Form.BindControls = .F. and Control.ControlSource or Grid.RecordSource is changed, the control is not rebound, but the ControlSource property or Recordsource property is changed. If Form.BindControls is changed from .F. to .T., all controls in the form are rebound according to the current value of Control.ControlSource or Grid.RecordSource.

Example

Suppose a form needs to load a large number of tables or has a grid or other controls that bind to a cursor produced by a SQL statement that takes a long time to run. When the user launches the form, the form does not appear until it completely loads all the data.

By setting BindControls to False (.F.), the form appears immediately. You can then change BindControls to True (.T.) when the form is activated such as when the Form Activate event occurs and display a message such as "Please wait while loading data." The user then sees the form immediately along with a message that explains the delay in loading data instead of waiting for the form to appear.

See Also

Form Object Properties, Methods and Events

Applies To: Form Object


BorderColor Property

Specifies the border color of an object. Available at design time and run time.

Object.BorderColor[ = nColor]

Property Values

nColor
Specifies the border color value.

The following table lists typical color values:

Color | RGB values | nColor value
White | 255, 255, 255 | 16777215
Black | 0, 0, 0 | 0
Gray | 192, 192, 192 | 12632256
Dark gray | 128, 128, 128 | 8421504
Red | 255, 0, 0 | 255
Dark red | 128, 0, 0 | 128
Yellow | 255, 255, 0 | 65535
Dark yellow | 128, 128, 0 | 32896
Green | 0, 255, 0 | 65280
Dark green | 0, 128, 0 | 32768
Cyan | 0, 255, 255 | 16776960
Dark cyan | 0, 128, 128 | 8421376
Blue | 0, 0, 255 | 16711680
Dark blue | 0, 0, 128 | 8388608
Magenta | 255, 0 ,255 | 16711935
Dark magenta | 128, 0, 128 | 8388736

Remarks

BorderColor applies only to a text box or edit box when the SpecialEffect property is set to 1 - Plain.

Use the RGB( ) function to convert the three component colors into one composite nColor.

See Also

BackColor, ForeColor Properties | GetColor( ) | RGB( ) | SpecialEffect Property

Applies To: ComboBox Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Image Control | Line Control | ListBox Control | OptionGroup Control | PageFrame Control | Shape Control | TextBox Control


BorderStyle Property

Specifies the border style of an object. Available at design time and run time.

Object.BorderStyle[ = nStyle]

Property Values

nStyle
For a CommandGroup, EditBox, Image, Label, OptionGroup, or TextBox control, the settings for the BorderStyle property are:
Setting | Description
0 | None. Default for Image and Label controls.
1 | Fixed Single. Default for CommandGroup, EditBox, OptionGroup, and TextBox controls.

For a line or shape, the settings for the BorderStyle property are:

Setting | Description
0 | Transparent
1 | (Default) Solid. The outer edge of the border is the outer edge of the Shape control.
2 | Dash
3 | Dot
4 | Dash-Dot
5 | Dash-Dot-Dot
6 | Inside Solid

For a Form object, the settings for the BorderStyle property are:

Setting | Description
0 | No border
1 | Fixed Single
2 | Fixed Dialog
3 | (Default) Sizable

Remarks

If the BorderWidth property setting is greater than 1, regardless of the BorderStyle setting, a solid border is drawn. If BorderWidth is set to 1, BorderStyle produces the effects described in the tables above.

See Also

BorderColor Property | BorderWidth Property | DrawStyle Property | DrawWidth Property

Applies To: ComboBox Control | CommandGroup Control | EditBox | Form Object | Image Control | Label Control | Line Control | OptionGroup Control | _SCREEN | Shape Control | TextBox Control | Spinner Control


BorderWidth Property

Specifies the width of a control's border. Available at design time and run time.

Control.BorderWidth[ = nWidth]

Property Values

nWidth
Specifies the width, which can range from 0 to 8192.
Note If the BorderWidth setting is greater than 1, the BorderStyle property setting is ignored.

Remarks

When BorderWidth is set to 0, the control appears to have no border. The BorderWidth setting is ignored for PageFrame controls when the Tabs setting is .T. (True).

See Also

BorderStyle Property

Applies To: Container Object | Control Object | Line Control | PageFrame Control | Shape Control


Bound Property

Determines whether a control in a Column object is bound to the control source for the Column. Available at design time and run time.

Column.Bound[ = lExpr]

Property Values

lExpr
The settings for the Bound property are:
Setting | Description
True (.T.) | (Default) The control is bound to the column's control source.
False (.F.) | The control is not bound to the column's control source.

Remarks

If a column's Bound property is set to true (.T.), the column's ControlSource property setting applies to the column and any controls contained in it. If you attempt to set the contained control's ControlSource property, an error occurs. If a column's Bound property is set to false (.F.), you can set the ControlSource property of a contained control directly. If you subsequently set the ControlSource setting of the column, it overrides the ControlSource setting of the contained control.

Typically, the following controls are bound to the corresponding data types:

Column control base class | Typical column data types
CheckBox | Logical, Numeric
ComboBox | Character, Numeric
CommandButton | Character, Numeric
EditBox | Character
ListBox | Character, Numeric
OptionButton | Character, Numeric
Spinner | Currency, Numeric
TextBox | Any data type except General or Memo

Note You cannot bind a control to a column whose data type is General or Memo.

See Also

AddObject Method | ControlSource Property | CurrentControl Property | Sparse Property

Applies To: Column Object


BoundColumn Property

Determines which column of a multicolumn list box or combo box is bound to the Value property of the control. Available at design time and run time.

Control.BoundColumn[ = nCol]

Property Values

nCol
Specifies the number of the column that is bound to the Value property. The default for nCol is 1.

Remarks

Use BoundColumn when the list box or combo box has multiple columns and when you want the data in a column other than the first column to be stored in the control's Value property.

See Also

Value Property | ActiveColumn Property | Columns Property

Applies To: ComboBox Control | ListBox Control


BoundTo Property

Specifies whether the Value property of a combo box or list box is determined by the List or the ListIndex properties. Available at design time and run time.

 [Form.]Control.BoundTo[ = lExpression]

Property Values

lExpression
The settings for the BoundTo property are:
Setting | Description
.T. | The Value property is determined by the List property.
.F. (Default) The Value property is determined by data type of the variable or field specified in the ControlSource property.

If the variable or field specified in the ControlSource property setting is of character type, the Value property is determined by the List property.

If the variable or field specified in the ControlSource property setting is of numeric type, the Value property uses the index number from the ListIndex property.

This setting provides compatibility with Microsoft Visual FoxPro 3.0 and 2.x versions of FoxPro.

Remarks

In Visual FoxPro 3.0, if the ControlSource property for a combo box or list box is numeric, the ListIndex property value of the selected item is stored in the variable or field to which the control is bound. Set the BoundTo property to true (.T.) to store the value of the List property in the variable or field to which the control is bound.

See Also

ControlSource Property | ListIndex Property | Value Property

Applies To: ComboBox Control | ListBox Control


BreakOnError Property

Specifies whether Visual FoxPro permits errors to break program execution at the location where they occurred or sends them to the cursor adapter. Read/write at design time and run time.

BreakOnError applies only when the cursor adapter executes an event or an SQL INSERT, UPDATE, or DELETE command.

CursorAdapter.BreakOnError [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) Visual FoxPro does not display an error message and sends the error to the cursor adapter. (Default)

This behavior is the same as if Visual FoxPro raised an error, and the user cancelled execution. The error routine makes the last unhandled error available to the calling routine.
True (.T.) | Visual FoxPro permits the execution of the event or method to break at the location where the error occurs and displays an error message.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


BufferMode Property

Specifies whether records are updated pessimistically or optimistically. Available at design time and run time.

Object.BufferMode[ = nValue]

Property Values

nValue
The settings for the BufferMode property are:
Setting | Description
0 | (Default) None. Records are locked when editing begins and fields are written when the record pointer moves. Mimics FoxPro 2.x behavior.
1 | Pessimistic. Records are locked when editing begins and fields are written when the record pointer moves. You can use TABLEREVERT( ) to undo your changes to the current record.
2 | Optimistic. Records are not locked when edited and Visual FoxPro attempts to lock the records when they are written to disk with TABLEUPDATE( ).

Remarks

If BufferMode is set to 1 or 2, any cursor used by a Grid control is enabled for table buffering. Any other control bound to data uses row buffering.

The BufferMode property setting will override any buffering settings made to form cursors prior to the form Init method, including those made in the form Load method.

See Also

BufferModeOverride Property | TABLEREVERT( ) | TABLEUPDATE ( )

Applies To: Form Object | FormSet Object | _SCREEN


BufferModeOverride Property

Specifies whether to override the BufferMode property set at the form or form set level. Available at design time and run time.

DataEnvironment.Cursor.BufferModeOverride[ = nValue]

Property Values

nValue
The settings for the BufferModeOverride property are listed in the following table:
Setting | Description
3 | Optimistic row buffering. Allows edits to a single record and locks the record only when it is written to disk. You can use TABLEREVERT( ) to undo your changes.
5 | Optimistic table buffering. Allows edits to all records and does not lock them until the records are written to disk with TABLEUPDATE( ). You can use TABLEREVERT( ) to undo your changes.

See Also

BufferMode Property | TABLEREVERT( ) | TABLEUPDATE ( )

Applies To: Cursor Object | CursorAdapter Class


BuildDateTime Property

Contains the last build date and time for a project. Read-only.

Object.BuildDateTime

Remarks

A project is built with BUILD PROJECT or by choosing Rebuild Project in the Build Options dialog box.

BuildDateTime contains the empty DateTime if the project has not been built.

See Also

Build Options Dialog Box | BUILD PROJECT | DATETIME( ) Function

Applies To: Project Object


ButtonCount Property

Specifies the number of buttons in a CommandGroup or OptionGroup. Available at design time and run time.

Control.ButtonCount[ = nNumber]

Property Values

nNumber
Specifies the number of buttons for the control.

Remarks

Use the ButtonCount property to dynamically set the number of buttons contained in a CommandGroup or OptionGroup.

If you change the number of buttons at run time, names are automatically assigned to the new buttons. The buttons are assigned the name CommandN for a CommandGroup or OptionN for an OptionGroup where N is the number of the button added. For example, if there are four buttons in the CommandGroup and the Buttons property setting is changed to 5, the new button is named Command5.

Example

The following example creates an OptionGroup control and places the control on a form. The OptionGroup control has three buttons; depending on the option button you click, a circle, ellipse, or square appears. The ButtonCount property is used to specify the number of buttons in the OptionGroup. The Buttons and Caption properties specify the text displayed next to each option button.

The Shape control is used to create the circle, ellipse, and square. The OptionGroup control's Click event uses a DO CASE ... ENDCASE structure and the Value property to display the appropriate shape when you click an option button.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

Buttons Property | DO CASE ... ENDCASE Command | CommandButton Control

Applies To: CommandGroup Control | OptionGroup Control


Buttons Property

An array for accessing every button in a group. Not available at design time.

Control.Buttons (nIndex).Property = Value-or-
Control.Buttons (nIndex).Method

Property Values

nIndex
An integer between 1 and the number of buttons specified in the ButtonCount property for Control.
Property
A property of a CommandButton or OptionButton.
Value
The value of Property.
Method
A method of a CommandButton or OptionButton.

Remarks

You can use the Buttons property to set properties and call methods for all the buttons in the group. The Buttons property is an array that is created when the button group is created.

Example

The following example creates an OptionGroup control and places the control on a form. The OptionGroup control has three buttons; depending on the option button you click, a circle, ellipse, or square appears. The ButtonCount property specifies the number of buttons in the OptionGroup. The Buttons and Caption properties specify the text displayed next to each option button.

The Shape control is used to create the circle, ellipse, and square. The OptionGroup control's Click event uses a DO CASE ... ENDCASE structure and the Value property to display the appropriate shape when you click an option button.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

ButtonCount Property | SetAll Method | CommandButton Control

Applies To: CommandGroup Control | OptionGroup


c...Alias Properties

cBaseFontName

cBaseMonoFontName

cCovFileAlias

cDefaultWritePath

cMarExecuted

cMarkNotExecuted

cOldPath

cSavedSkippedFiles

cSavedTargetDBF

cSkippedAlias

cSourceAlias

cSourcefile

cSuspendedLog

cTargetAlias

See Also

Coverage Engine Object


Cancel Property

Specifies whether a CommandButton or OLE Container control is the Cancel button; that is, if the user presses the ESC key, the Cancel button's Click event will occur. Available at design time and run time.

Object.Cancel[ = lExpr]

Property Values

lExpr
The settings for the Cancel property are:
Setting | Description
True (.T.) | The CommandButton or OLE Container control is the Cancel button.
False (.F.) | (Default) The CommandButton or OLE Container control is not the Cancel button.

Remarks

The Cancel property applies only to an OLE Container control that contains an "Acts like a Button" ActiveX control (.ocx).

Example

The following example creates a command button and an OptionGroup control and places them on a form. The Cancel property is used to assign the command button as the Cancel button. If the ESC key is pressed, the Command button's Click event occurs and the Click event procedure executes CLEAR EVENTS to close the form and stop event processing.

The OptionGroup control has three buttons; depending on the option button you click, a circle, ellipse, or square is displayed. The Shape Control is used to create the circle, ellipse, and square. The OptionGroup control's Click event uses a DO CASE ... ENDCASE structure and the Value property to display the appropriate shape when you click an option button.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

Click Event | Default Property | CANCEL Command | Cancel Button

Applies To: CommandButton | OLE Container Control


Caption Property

Specifies the text displayed in the caption of an object. Available at design time and run time.

Object.Caption[ = cText]

Property Values

cText
Specifies text displayed with an object. The following table describes how captions display depending on the object.
Object | Caption display
Form | Caption displays in the title bar of the form. When the form minimizes, the caption displays to the right of the form icon.
PageFrame | Caption displays on the tab of each page in the page frame.
Controls | Caption displays on or next to the control. If the control displays an icon, setting the PicturePosition property determines the placement of the icon and therefore, the placement of the caption.

Remarks

When you create a new form or control, the default value of the Name property sets the default value of the Caption property. This default caption includes the name of the object class and an integer, for example, Command1, Combo1, or Form1.

Use the Name property to properly refer to an object in code. The Caption property describes only the text that appears on the screen for identifying the control. These two properties begin with the same value, but are set independently thereafter.

If you do not specify a Width property setting for a control, the control is automatically sized to contain the caption.

To automatically resize a Label control to fit its caption, set the AutoSize property to True (.T.). The maximum number of characters for the Caption property of a Label control is 256.

To assign an access key to a control, include a backslash and a less-than sign (\<) in the caption immediately preceding the character you want to designate as the access key. A user can then press ALT and the specified character to move focus to that control. If the control is a command button, check box, or option button, pressing ALT and the specified character also has the effect of clicking the control.

To add an underline to a character in a column header caption, precede the character with an ampersand (&). If you want to include the character "&" in a column header caption, use two consecutive & characters. Note that this does not cause the letter to behave as an access key, but only underlines the header caption character.

Example

This example demonstrates the use of the Caption property to change the main Visual FoxPro window caption from Microsoft Visual FoxPro to the current version number of Visual FoxPro.

_SCREEN.Caption=VERSION()

See Also

AutoSize Property | BorderStyle Property | Name Property | Style Property | Width Property

Applies To: CheckBox Control | CommandButton Control | Form Object | Header Object | Label Control | OptionButton Control | Page Object | _SCREEN | ToolBar Object


Centered Property

Specifies whether a CheckBox control is centered within the control boundaries.

CheckBox.Centered [= lExpr]

Property Values

lExpr
Logical data type. The following table lists the values of lExpr.
lExpr | Description
False (.F.) | The CheckBox control is not centered within the control boundaries. (Default)
True (.T.) | Centers the CheckBox control within the control boundaries.

Remarks

If a CheckBox control is not contained in a grid, the control is centered within its own control boundaries.

Centered works in conjunction with the Alignment property. If you supply a caption, the left and right alignment values of the Alignment property determine on which side of the check box the caption appears. If the Centered property is also set to True (.T.), both the caption and check box are centered horizontally and vertically in the grid column.

If the Sparse property of the column is set to True (.T.) (default), the Alignment property of the column determines the placement of text in all the cells in the column. However, when a particular cell gets focus, and the control appears, Visual FoxPro uses the Alignment property of the control. If you set the Sparse property of the column to False (.F.), Visual FoxPro uses the Alignment property of the control and disregards the column's Alignment property.

When the column's Alignment property is set at design time, the designer attempts to set the Alignment property on the controls in the column as well. When that control is a CheckBox, setting the column's Alignment to any of the "center" property values automatically sets the Centered property to True (.T.).

If Centered is True (.T.), the check box remains centered horizontally and vertically in the grid cell as the grid columns and rows are resized.

Example

The following example shows how you can set the Centered property to align a check box with the center of the control and its caption to the right of the check box:

Checkbox1.Centered = .T.
Checkbox1.Alignment = 1

Example 2

The following example shows how you can set the Centered property to align a check box within the center of a grid column. Setting the Sparse property of the column to False (.F.) specifies that the Alignment property of the control takes precedence over the Alignment property of the grid column:

Column1.Sparse = .F.
Column1.Checkbox1.Centered = .T.
Column1.Checkbox1.Caption = ""

See Also

Properties | Sparse Property | Alignment Property

Applies To: CheckBox Control


Century Property

Specifies whether the century portion of a date is displayed in a text box. Available at design time and run time.

Object.Century[ = nValue]

Property Values

nValue
One of the following settings:
Setting | Description
0 | Off. The century portion of the date is not displayed.
1 | (Default) On. The century portion of the date is displayed.
2 | The SET CENTURY setting determines if the century portion of the date is displayed. If SET CENTURY is ON, the century portion of the date is displayed. If SET CENTURY is OFF, the century portion of the date is not displayed.

Remarks

The Century property setting is ignored if the DateFormat property is set to Short or Long.

Note that in earlier versions of Visual FoxPro the default for the Century property is 2.

See Also

DateFormat Property, | DateMark Property, | Hours Property, | Seconds Property, | SET CENTURY, | StrictDateEntry Property

Applies To: TextBox Control


ChildAlias Property

Specifies the alias of the child table. Read-only at design time and run time.

DataEnvironment.Relation.ChildAlias[ = cText]

Property Values

cText
Specifies the alias of the child table in the relation.

Remarks

The ChildAlias property setting must be the same name as the Alias property setting for the Cursor object that represents the child table.

See Also

Alias Property | ParentAlias Property | Cursor Object | Cursor Object Properties, Methods and Events

Applies To: Relation


ChildOrder Property

Specifies the index tag for the record source of the Grid control or Relation object. Available at design time and read-only at run time.

Object.ChildOrder[ = cTagName]

Property Values

cTagName
Specifies an existing index tag name.

Remarks

If the ChildOrder property is set, the Order property of the Cursor for the child table is ignored.

Use this property to link two tables that have a one-to-many relationship. For example, a customer table containing one record per customer links to an order table containing multiple orders per customer. For this one-to-many relationship, set the ChildOrder property to the customer ID index tag field.

The ChildOrder property mimics the behavior of SET ORDER.

See Also

ControlSource Property | LinkMaster Property | SET ORDER

Applies To: Grid Control | Relation Object


ChildTable Property

Contains an object reference to a child XMLTable object. Read/write.

XMLTable.ChildTable

Property Values

Object reference. ChildTable contains an object reference to a child XMLTable object and null (.NULL.) when not populated.

Remarks

For nested tables in SQL XML, Visual FoxPro populates the ChildTable property with information about the nested tables involved in the join operation. However, XMLAdapter does not assign the ChildTable property when working with ADO.NET DataSets. For more information about how XMLAdapter treats nested tables for ADO.NET DataSet and SQL XML data sources, see XMLAdapter Class.

Example

The following example illustrates how an XMLAdapter object treats the Orders table as child table for the Customers table and the Order_details table as a child table for the Orders table.

<?xml version="1.0" encoding="utf-8"?>
<SqlXmlAdoData>
   <Schema name="Schema1" xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes">
      <ElementType name="Customers" content="eltOnly" model="closed" order="many">
         <element type="Orders" maxOccurs="*"/>
         <element type="CustomerID"/>
         <element type="CompanyName"/>
      </ElementType>
      <ElementType name="CustomerID" content="textOnly" model="closed" dt:type="string"/>
      <ElementType name="CompanyName" content="textOnly" model="closed" dt:type="string"/>
      <ElementType name="Orders" content="eltOnly" model="closed" order="many">
         <element type="Order_details" maxOccurs="*"/>
         <element type="OrderID"/>
         <element type="OrderDate"/>
         <element type="ShipName"/>
      </ElementType>
      <ElementType name="OrderID" content="textOnly" model="closed" dt:type="i4"/>
      <ElementType name="OrderDate" content="textOnly" model="closed" dt:type="dateTime"/>
      <ElementType name="ShipName" content="textOnly" model="closed" dt:type="string"/>
      <ElementType name="Order_details" content="eltOnly" model="closed" order="many">
         <element type="ProductID"/>
         <element type="UnitPrice"/>
         <element type="Quantity"/>
      </ElementType>
      <ElementType name="ProductID" content="textOnly" model="closed" dt:type="i4"/>
      <ElementType name="UnitPrice" content="textOnly" model="closed" dt:type="fixed.14.4"/>
      <ElementType name="Quantity" content="textOnly" model="closed" dt:type="i2"/>
   </Schema>
   <Customers xmlns="x-schema:#Schema1">
      <CustomerID>CACTU</CustomerID>
      <CompanyName>Cactus Comidas para llevar</CompanyName>
      <Orders>
         <OrderID>10521</OrderID>
         <OrderDate>1997-04-29T00:00:00</OrderDate>
         <ShipName>Cactus Comidas para llevar</ShipName>
         <Order_details>
            <ProductID>35</ProductID>
            <UnitPrice>18</UnitPrice>
            <Quantity>3</Quantity>
         </Order_details>
         <Order_details>
            <ProductID>41</ProductID>
            <UnitPrice>9.65</UnitPrice>
            <Quantity>10</Quantity>
         </Order_details>
         <Order_details>
            <ProductID>68</ProductID>
            <UnitPrice>12.5</UnitPrice>
            <Quantity>6</Quantity>
         </Order_details>
      </Orders>
   </Customers>
</SqlXmlAdoData>

See Also

Properties | XMLTable Object Properties, Methods, and Events

Applies To: XMLTable Class


Class Browser Properties

The following properties are associated with the Class Browser.

Note Properties marked as "Reference only" or "Internal use only" are maintained internally and used by the Class Browser. Avoid changing the value of reference-only properties; you might cause errors in the Class Browser.
lActive
Reference only. Returns the active status of the Class Browser. If the Class Browser has the focus, the value is True (.T.).
cAlias
Returns the alias of the work area within the Class Browser data session associated with the selected class in the class list. By default, the Class Browser private data session opens at least two table aliases: BROWSER and METADATA. The BROWSER alias is for Browser.dbf and is shared for all instances. The METADATA alias is for the class library (.vcx) or form (.scx) open in the Class Browser. If more than one file is open, the METADATA alias is incremented once for each open file.
cAddInMethod
Reference only. Returns the method name that called the external add-in being executed and clears when execution is complete. When an add-in is executed, this property contains the name of the method that called the add-in.
lAddInMode
Returns the status of a Class Browser add-in. If True (.T.), the add-in is called; if False (.F.), the add-in is complete.
lAddInTrace
Returns the status of the display trace mode that monitors the events of an add-in. If True (.T.), messages describing the events of an add-in are sent to the Visual FoxPro main window.
nAtPos
Internal use only. The default value is 0.
lAutoExpand
Determines whether the class list expands or collapses automatically when it is refreshed. If the value is True (.T.), the class list automatically expands or collapses the class trees in the outline. If False (.F), the class list outline does not expand or collapse. The default value is True (.T.).
cBaseClass
Reference only. Returns the name of the base class of the selected class in the class list.
cBrowserTable
Reference only. Returns the full path of the Browser.dbf registration table.
lBusyState
Reference only. Returns the status of the refresh operation for the Class Browser. If True (.T.), the refresh operation is in progress.
cClass
Reference only. Returns the name of the selected class in the class list.
nClassCount
Reference only. Returns the total number of items in the class list. The default value is 0.
cClassLibrary
Reference only. Returns the name of the class library for the selected class in the class list.
aClassList
Reference only. A two-dimensional array of values associated with a class library (.vcx) or form (.scx) file in the current class list. Each file in the list has its own alias. For example, if the class list displays two files, the aliases are METADATA1 and METADATA2.

The array contains the following formation.

aClassList position | Setting
[nIndex,1] | Name of a class
[nIndex,2] | Associated metadata record number
[nIndex,3] | Outline indentation level
[nIndex,4] | Name of the file containing the parent class
[nIndex,5] | Name of the parent class
[nIndex,6] | Name of the file containing the class
[nIndex,7] | Name of the class icon file
[nIndex,8] | The BaseClass of the class
[nIndex,9] | Specifies whether class is defined as OLE public
nClassListIndex
Reference only. Returns the position of the selected class in the Class list. The value for the first item is 0. The default value is – 1.
nClassTimeStamp
The TimeStamp value (from the .vcx/.scx TimeStamp field) for the selected class.
cClassType
Reference only. Returns the current filter on the Class list as specified in the ClassType box.
tcClassType
The initial Type filter for the Class list.
tcDefaultClass
Reference only. Returns the value or reference of the second parameter passed to BROWSER.APP. For example, if you open the Class Browser by typing the following code, this property returns "baseform."
DO (_BROWSER) WITH "wizstyle.vcx","baseform"
lDescriptions
If True (.T.), descriptions are displayed for classes and members.
lDisplayHierarchyError
Whether or not to display an error message if classes without valid ParentClasses are loaded in the Class Browser. The default is True (.T.).
nDisplayMode
Reference only. Returns the display mode specified by the display mode option group: 1 – hierarchical or 2 – alphabetical. The default value is 1.
lDragDrop
For internal use only. Whether or not a drag operation is in progress.
cDragIcon
Returns the current cursor file for the drag icon during a drag operation.
lEmptyFilter
If True (.T.), empty methods are displayed in the Members list. The default is False (.F.).
lError
Returns the status of error checking. If True (.T.), an error occurred and the Class Browser error dialog box is displayed. When the Class Browser opens, this property is set to False (.F.). If you want to check for errors, make sure this property is set to False.
lExpanded
For internal use only.
nFileCount
Reference only. Returns the number of class library (.vcx) or form (.scx) files currently open in the Class Browser. The default value is 0.
lFileMode
Reference only. Returns the type of the selected item in the class list. If True (.T.), a file is selected; if False (.F.), a class is selected.
cFileName
Reference only. Returns the full path of the file associated with the selected class in the class list.
tcFileName
Reference only. Returns the value or reference of the second parameter passed to BROWSER.APP. For example, if you open the Class Browser by typing the following code, this property returns "Wizstyle.vcx."
DO (_BROWSER) WITH "wizstyle.vcx","baseform"
aFiles
Reference only. An array of class library (.vcx), form (.scx), application (.exe), object library (.olb), and type library (.tlb) files currently opened in the Class Browser.
cFilter
Reference only. Returns the current SET FILTER setting from the open metadata table for the selected class in the class list.
lFormAddObject
For internal use only.
cGetFileExt
Determines the Class Browser's GETFILE( ) default method extensions. The default value is "VCX;SCX;PJX;EXE;OLB;TLB."
lHiddenFilter
If True (.T.), hidden members are displayed in the Members list. The default is False (.F.).
lIgnoreErrors
For internal use only.
lInitialized
Reference only. Returns the initialization state of the Class Browser. If True (.T.), the Class Browser is initialized; if False (.F.), the Class Browser is not initialized.
aInstances
Reference only. An array of instances associated with the selected class in the class list. Functionality is identical to AINSTANCE( ).
nInstances
Reference only. Returns the total number of instances associated with the selected class in the class list using AINSTANCE( ). The default value is 0.
cLastFindText
For internal use only.
nLastHeight
The initial height of a form before a Resize event occurs. The default value is (THIS.Height).
nLastRecNo
For internal use only. The initial value is 1.
cLastSetComp
The setting of SET COMPATIBLE when the Class Browser was loaded.
cLastSetESC
The setting of SET ESCAPE when the Class Browser was loaded.
cLastSetUDFParms
The setting of SET UDFPARMS when the Class Browser was loaded.
cLastValue
For internal use only.
nLastWidth
Returns the initial width of a form before a Resize event occurs. The default value is (THIS.Width).
tlListBox
If a True (.T.) value is passed to the Class Browser in this argument, classes and members are displayed in list boxes rather than in tree view controls.
lModalDialog
Determines if the class list is refreshed when the Class Browser regains focus after activating a modal dialog box. If True (.T.), the list is not refreshed; if False (.F.), the list is refreshed. The default value is True (.T.).
nMouseButton
For internal use only. Returns which mouse button was pressed.
lNoDefault
Returns the status indicating how default behavior is handled when returning from an add-in. If True (.T.), the default behavior is ignored.
lOutlineOCX
Reference only. If True (.T.), classes and members are displayed in tree view controls. You might need this information in an add-in program.
cParentClass
Reference only. Returns the name of the parent class of the selected class in the class list.
lParentClassBrowser
If True (.T.), the Edit ParentClass Method toolbar is displayed. The default is True. You can click this button to immediately view or edit the parent class method from the editor
cParentClassBrowserCaption
The caption of the ParentClass Browser toolbar. The default value is SPACE(10) + "ParentClass Browser"
cParentClassSymbol
Determines the symbol displayed beside a class to indicate that it is a subclass of a class that is not displayed in the Classes list.
nPixelOffset
Internal use only. Determines the number of pixels to cascade multiple instances of the Class Browser. The default value is 22.
cPlatform
Reference only. Returns the name of the current platform.
cProgramName
Reference only. Returns the full path of the BROWSER.APP file being executed.
lProtectedFilter
If True (.T.), protected members are displayed in the Members list. The default is False (.F.).
lReadOnly
Reference only. Returns the read-only status of the file associated with the selected class in the class list.
nRecCount
Reference only. Returns the total number of records in the open class library (.vcx) and form (.scx) files. The default value is 0.
lRefreshMode
Internal use only.
lRelease
Internal use only. Specifies that the Class Browser is automatically released.
lResizeMode
Internal use only. Returns the resize mode status of the Class Browser.
lSCXMode
Reference only. Returns the status of the file type of the selected class in the class list. If True (.T.), the file is a form (.scx); if False (.F.), the file is a class library (.vcx).
nShift
For internal use only. State of the SHIFT key when a mouse button is pressed.
oSource
Reference only. Returns the reference for an object dropped on a form from the Class Browser. After the DragDrop method is complete, oSource is set to null (.NULL.).
cStartName
Reference only. Returns the Name property of the Class Browser from when the Class Browser was loaded, but before the name is incremented. For example, the default value is ClassBrowser and, for each instance opened, the name is incremented: ClassBrowser1, ClassBrowser2.
nStrLen
For internal use only. The default value is 0.
cTimeStamp
Reference only. Returns the timestamp field value of the selected class in the class list.
lVCXSCXMode
If True (.T.), the class or file selected is a .vcx or .scx, or is in a .vcx or .scx.
tnWindowState
For internal use only. Whether the Class Browser window is minimized (1), maximized (2), or normal (0).

Initial Values of Class Browser Properties

When an instance of the Class Browser is opened, the properties are set to the default values shown in the following table.

Class Browser property | Initial setting
Caddin | ""
caddinmethod | ""
Calias | ""
Caption | "Class Browser"
Cbaseclass | ""
Cbrowsertable | ""
Cclass | ""
Cclasslibrary | ""
cclasstimestamp | ""
Cclasstype | ""
Cdragicon | ""
Cfilename | ""
Cfilter | ""
Cgetfileext | vcx;scx;pjx;exe;olb;tlb
clastgetfileext | ""
Clastsetcomp | ""
Clastsetesc | ""
clastsetudfparms | ""
Clastvalue | ""
Cparentclass | ""
cparentclasssymbol | (IIF(VERSION(3)=="00",CHR(171),"<"))
Cplatform | ""
cprogramname | ""
Cstartname | ""
DataSession | 2
FontBold | .F.
FontName | "MS Sans Serif"
FontSize | 8
Height | 360
HelpContextID | 95825501
Icon | Browser.ico
Lautoexpand | .T.
Ldescriptions | .T.
ldisplayhierarchyerror | .T.
Left | 0
lparentclassbrowser | .T.
MinHeight | (175)
MinWidth | (250)
Name | "classbrowser"
Natpos | 0
Nclasscount | 0
nclasslistindex | -1
Ndisplaymode | 1
Nfilecount | 0
Ninstances | 0
Nlastheight | (this.Height)
Nlastrecno | 1
Nlastwidth | (this.Width)
nmousebutton | 0
Npixeloffset | 22
Nreccount | 0
Nshift | 0
Nstrlen | 0
Ntimestamp | 0
oparentclassbrowser | .NULL.
Osource | .NULL.
ShowTips | .T.
Top | -1
Width | 462

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Object Members | Class Browser Properties | Class Browser Window | Customizing the Class Browser


Class Property

Returns the name of the class on which an object is based. Read-only at design time and run time.

Object.Class

Remarks

In the Class Designer, the Class property returns the actual name of the class.

See Also

AddObject Method | BaseClass Property

Applies To: CheckBox Control | Collection Class | Column | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | CursorAdapter Class | Custom Object | EditBox Control | Exception Class | Form Object | FormSet Object | Grid Control | Header Object | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | Session Object | Shape Control | _SCREEN | Spinner Control | TextBox Control | Timer Control | ToolBar Object


ClassLibrary Property

Specifies the file name of the user-defined class library that contains the object's class. Read-only at design time and run time.

Object.ClassLibrary

Remarks

Visual FoxPro base class objects are built into the product and have no ClassLibrary setting.

See Also

BaseClass Property | Class Property

Applies To: CheckBox Control | Collection Class | Column Object | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | Custom Object | CursorAdapter Class | EditBox Control | Exception Class | Form Object | FormSet Object | Grid Control | Header Object | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | _SCREEN | Session Object | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


ClipControls Property

Determines whether graphics methods in Paint events repaint the entire object or only newly exposed areas. Also determines whether the graphical operating environment creates a clipping region that excludes nongraphical controls contained by the object. Available at design time and run time.

Object.ClipControls[ = lExpr]

Property Values

lExpr
The settings for the ClipControls property are:
Setting | Description
True (.T.) | (Default) Graphics methods in Paint events repaint the entire object. A clipping region is created around nongraphical controls on a form before a Paint event.
False (.F.) | Graphics methods in Paint events repaint only newly exposed areas. A clipping region is not created around nongraphical controls.

See Also

Paint Event | DataToClip Method | _CLIPTEXT System Variable

Applies To: Form Object | _SCREEN


Closable Property

Specifies whether the form can be closed by double-clicking the window pop-up menu icon, choosing Close from the window pop-up menu, or by clicking the Close button. Available at design time and run time.

Object.Closable[ = lExpr]

Property Values

lExpr
The settings for the Closable property are:
Setting | Description
True (.T.) | (Default) The Close item is added to the window pop-up menu.
False (.F.) | The form cannot be closed by double-clicking the window pop-up menu icon, and the Close item is removed from the window pop-up menu.

Example

The following example demonstrates how the Closable property is set to False (.F.) to prevent a form from being closed using the window pop-up menu or the Close button. If the form's Closable property is set to True (.T.) and the form is closed using the window pop-up menu, CLEAR EVENTS must be issued to stop event processing and exit the program.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the window pop-up menu
                          && and Close button

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

ControlBox Property | TitleBar Property | DEFINE CLASS | QueryUnload Event | Unload Event | Release Method | Destroy Event

Applies To: Form Object | _SCREEN


CLSID Property

Contains the registered CLSID (Class Identifier) for a server in a project. Read-only at design time and run time.

Object.CLSID

Remarks

A CLSID is created in the Windows registry for a server when you build an executable file (.exe) or dynamic link library (.dll) from a project.

Example

The following example demonstrates a use of the CLSID property after creation of a COM server (.dll).

* In a program("Testclass.prg"), create a class
DEFINE CLASS myclass AS SESSION OLEPUBLIC
ENDDEFINE
...

In a project, include the .prg file in a .dll or MTDLL Build. The server object properties are then available by code access. For example, in the Command window, type the following:

MyServer = _VFP.ActiveProject.Servers("myclass")
? "Class ID is ", MyServer.CLSID      && Class ID is {620E56FE-F7F8-4E99-B767-CB08009261F0}
                                    && a GUID
? "Description is ", MyServer.Description    && testclass.myclass

See Also

CREATEOBJECTEX( ) | ProgID Property | TypeLibCLSID Property | TypeLibDesc Property | TypeLibName Property

Applies To: Server Object


CodePage Property

Contains the code page of a file in a project. Read-only at design time and run time.

Object.CodePage

Remarks

The code page is a numeric value indicating the character set used for the file. Code pages usually correspond to different platforms and languages and are used in international applications.

Example

This example counts how many project files are using code page 1252 (ANSI Windows).

nCode1252=0
MODIFY PROJECT myproject NOWAIT
FOR i = 1 TO _VFP.ActiveProject.Files.Count
   IF  _VFP.ActiveProject.Files(i).CodePage = 1252
      bCode1252=nCode1252+1
   ENDIF
ENDFOR
?nCode1252    && Show the count in the Visual FoxPro screen.

See Also

CPCONVERT( ) Function | CPCURRENT( ) Function | CPDBF( ) Function

Applies To: File Object


ColorScheme Property

Included for backward compatibility. Use the BackColor, ForeColor Properties instead.


ColorSource Property

Determines how a control's colors are set. Available at design time and run time.

Object.ColorSource[ = nSource]

Property Values

nSource
The settings for nSource are:
Setting | Description
0 Object's Color Properties. The control uses its color property settings (ForeColor, BackColor, and so on). This setting is available for the following controls and objects:

CheckBox, ComboBox, CommandButton, CommandGroup, Container, Control, EditBox, Form, Image, Label, Line, ListBox, OptionButton, OptionGroup, Page, PageFrame, Shape, Spinner, TextBox, and Toolbar.
1 Form's Color Scheme. The control uses the color scheme of the form in which it is placed. This setting is available for the following controls and objects:

CheckBox, ComboBox, CommandButton, EditBox, Label, ListBox, OptionButton, Shape, Spinner, and TextBox.
2 ColorScheme Property Scheme. The control uses the color scheme specified in its ColorScheme property. This setting is available for the following controls and objects:

CheckBox, ComboBox, CommandButton, EditBox, Label, ListBox, OptionButton, Shape, Spinner, and TextBox.
3 Default Scheme. The control uses its default color scheme. For most controls, the default color scheme is the form's color scheme; for EditBoxes and ListBoxes, the default color scheme is Scheme 2, User Menus. This setting is available for the following controls and objects:

CheckBox, ComboBox, CommandButton, EditBox, Label, ListBox, OptionButton, Shape, Spinner, and TextBox.
4 Windows Control Panel (3D Colors) (Default). The control uses the 3D color settings specified in the Windows Control Panel. This setting is available for the following controls and objects:

CheckBox, ComboBox, CommandButton, CommandGroup, Container, Control, EditBox, Form, Image, Label, Line, ListBox, OptionButton, OptionGroup, Page, PageFrame, Shape, Spinner, TextBox, and Toolbar.
5 | Windows Control Panel (Windows Colors). The control uses the color settings specified in the Windows Control Panel.This setting is available only for the Form object.

Remarks

Setting a color property (ForeColor, BackColor, SelectedForeColor, and so on) for an object overrides the ColorSource property setting. If a color property is not set for an object, the object's colors are determined by the ColorSource property setting.

See Also

ColorScheme Property

Applies To: CheckBox Control | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Form Object | Image Control | Label Control | Line Control | ListBox Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | Shape Control | Spinner Control | TextBox Control | Toolbar Object


ColumnCount Property

Specifies the number of Column objects in a Grid, ComboBox, or ListBox control. For a grid, available at design time and read/write at run time. For a combo box or list box, available at design time and run time.

Object.ColumnCount[ = nCol]

Property Values

nCol
For a Grid control, specifies the number of columns to display. The default is –1, which specifies that the Grid control should contain enough columns to accommodate all the fields in the grid's record source. The maximum number of columns is 255. If you create a specific number of columns by setting nCol to a positive value, specify the data to display in a particular column by setting that column's ControlSource property. (If ControlSource is not specified for a column, the Grid control displays the next available undisplayed field of the grid's record source.)

For a ComboBox or ListBox control, nCol specifies the number of columns the control contains. If you set ColumnCount to 0, the first column is displayed based on the RowSource property or on the items added with the AddItem method.

Remarks

For a grid, use the AddColumn method to increase the number of columns.

See Also

AddColumn Method | ColumnOrder Property | Order Property

Applies To: ComboBox Control | Grid Control | ListBox Control


ColumnLines Property

Shows or hides the lines between columns. Available at design time and run time.

Control.ColumnLines[ = lExpr]

Property Values

lExpr
Specifies whether lines separating columns are displayed. The settings for the ColumnLines property are:
Setting | Description
True (.T.) | (Default) The lines between columns are visible.
False (.F.) | The lines between columns are hidden.

See Also

ColumnWidths Property | ColumnOrder Property | Columns Property

Applies To: ComboBox Control | ListBox Control


ColumnOrder Property

Specifies the relative order of column objects in a Grid control. Available at design time and run time.

Column.ColumnOrder[ = nExpr]

Property Values

nExpr
Specifies the order of a column relative to other columns in the grid.

Remarks

If a Grid contains five columns and you want the third column displayed last, set the ColumnOrder property of the third column to 5. The ColumnOrder setting for the fourth column becomes 3, the ColumnOrder setting for the fifth column becomes 4, and so on.

Note ColumnOrder settings do not have to be sequential. There can be gaps. For example, if a Grid contains three columns, you can add a fourth and set its ColumnOrder property to 10.

See Also

Activate Event | Deactivate Event | ZOrder Method | ColumnCount Property | ColumnLines Property | ColumnWidths Property

Applies To: Column Object


Columns Property

An array for accessing individual Column objects in the Grid control by column number. Available at design time and read-only at run time.

Grid.Columns(nCol).Property [ = Setting]

Property Values

nCol
Specifies the column in agGrid whose property is referenced. The far left Column is number 1.
Property
Specifies the column's property to access.
Setting
Specifies the new property setting for all cells specified with nCol.

Remarks

Use the Columns property to access the properties of a particular Column in a Grid. For example, SpecialGrid.Column(1).BackColor = RGB(255,0,0) changes the BackColor property of all the cells in Column 1 to bright red.

See Also

Column Object | ColumnCount Property | SetAll Method

Applies To: Grid Control


ColumnWidths Property

Specifies the width of columns for a ComboBox or ListBox control. Available at design time and run time.

Control.ColumnWidths[ = "cCol1Width, cCol2Width, ... cColnWidth"]

Property Values

"cCol1Width, cCol2Width, ... cColnWidth"
Specifies the width of a column or series of columns in the ComboBox or ListBox. For example, cColumnWidths = "5, 7, 9" specifies that the first column is 5 units wide, the second column is 7 units wide, and the third column is 9 units wide, in the unit of measurement specified by the ScaleMode property of the form. Use commas to separate each width number. You can specify the number of columns with the ColumnCount property.

See Also

ColumnCount Property | ScaleMode Property | Width Property | ColumnLines Property

Applies To: ComboBox Control | ListBox Control


Comment Property

Stores information about an object. Available at design time and run time.

Object.Comment[ = cTextString]

Property Values

cTextString
Specifies a text string.

Remarks

Unlike other properties, the value of the Comment property is not used by Visual FoxPro; you can use this property to identify or describe objects.

You can use this property to assign an identification string to an object without affecting any of its other property settings. The Comment property is useful for checking the identity of a control or form that is passed as a variable to a procedure.

By default, the Comment property is set to a zero-length string ("").

Tip When you create a new instance of a form, assign a unique value to the Comment property.

See Also

Caption Property | Name Property

Applies To: CheckBox Control | Collection Class | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | CursorAdapter Class | Custom Object | EditBox Control | Exception Class | Form Object | FormSet Object | Grid Control | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | _SCREEN | Session Object | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


CompareMemo Property

Specifies whether memo fields of type Memo, General, or Picture are included in the WHERE clause when using automatic updating. When working with this property for regular cursors, use the CURSORSETPROP() and CURSORGETPROP() functions. Read/write.

Note Setting CompareMemo for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.CompareMemo [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Includes memo fields in the WHERE clause.
True (.F.) | Does not include memo fields in the WHERE clause.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


ContinuousScroll Property

Specifies if scrolling within a form is continuous, or if scrolling occurs only when a scroll box is released. Available at design time and run time.

Object.ContinuousScroll[ = lExpression]

Property Values

lExpression
The settings for lExpression are:
Setting | Description
True (.T.) | (Default) Scrolling is continuous within the form. The form scrolls continuously as the scroll boxes are moved. The Scrolled event occurs continuously as the form is scrolled.
False (.F.) | Scrolling only occurs when a scroll box is released. The form is stationary until a scroll box is released, and then the form is redrawn in its new position. The Scrolled event occurs after the form is redrawn.

Remarks

The Scrollbars property determines if a form has scroll bars.

See Also

ScrollBars Property | Scrolled Event | HScrollSmallChange Property

Applies To: Form Object


ControlBox Property

Specifies whether a pop-up menu icon appears in the upper-left corner of a form or toolbar at run time. Available at design time and run time.

Object.ControlBox[ = lExpr]

Property Values

lExpr
The settings for the ControlBox property are:
Setting | Description
True (.T.) | (Default) Displays a pop-up menu icon.
False (.F.) | Does not display a pop-up menu icon.

Remarks

Both modal and modeless forms and toolbars can include a pop-up menu icon. The menu commands available at run time depend on the settings for related properties. For example, setting MaxButton and MinButton to False (.F.) disables the Maximize and Minimize menu commands on the pop-up menu, but the Move and Close menu commands remain available.

Note Settings you specify for ControlBox, BorderStyle, MaxButton, and MinButton are not reflected in the form's appearance until run time.

See Also

BorderStyle Property | Closable Property | MaxButton Property | MinButton Property

Applies To: Form Object | _SCREEN | ToolBar Object


ControlCount Property

Specifies the number of controls in a container object. Not available at design time; read-only at run time.

Object.ControlCount

Remarks

You can use this property to cycle through all the controls on a container and perform an operation on each.

See Also

Controls Property

Applies To: Column Object | Container Object | Control Object | Form Object | Page Object | _SCREEN | ToolBar Object


Controls Property

An array for accessing the controls in a container object. Available at run time.

ContainerObject.Controls(Index).Property[ = Expr]

Property Values

Expr
Specifies a property value for a control contained in ContainerObject.

Remarks

Use the Controls property to access the properties of contained objects.

See Also

ControlCount Property

Applies To: Column Object | Container Object | Control Object | Form Object | Page Object | _SCREEN | ToolBar Object


ControlSource Property

Specifies the source of data to which an object is bound. Available at design time and run time.

Object.ControlSource[ = cName]

Property Values

cName
For controls, cName is a variable or field.

Remarks

Once the ControlSource property is set to a field or variable, the Value property always has the same data value and the same data type as the variable or field to which the ControlSource property is set.

For TextBox controls, cName is typically a field.

In a Grid control, if you do not specify a ControlSource setting for a column, the column displays the next available undisplayed field of the grid's record source.

If a Column's Bound property is set to True (.T.), the Column's ControlSource property setting applies to the column and any controls contained in it. If you attempt to set the contained control's ControlSource property, an error occurs. If a Column's Bound property is set to False (.F.), you can set the ControlSource property of a contained control directly. If you subsequently set the ControlSource setting of the Column, it overrides the ControlSource setting of the contained control.

See Also

Bound Property | Order Property | RecordSourceType Property | Value Property

Applies To: CheckBox Control | Column Object | ComboBox Control | CommandGroup Control | EditBox Control | ListBox Control | OLE Bound Control | OptionButton Control | OptionGroup Control | Spinner Control | TextBox Control


ConversionFunc Property

Specifies a comma-delimited list of field and function name pairs separated by single spaces. Read/write at design time and run time.

Note ConversionFunc applies only when using automatic updating. ConversionFunc is not evaluated at design time.

Use ConversionFunc to specify native Visual FoxPro or custom conversion functions that are applied to one or more cursor fields before sending them to the data source through an update, insert, or delete operation. The actual values sent to the data source are the values returned by the function associated with each field.

CursorAdapter.ConversionFunc [ = 'cFieldName1 cFuncName1 [, cFieldName2 cFuncName2 ]...' ]

Property Values

cFieldName
Specifies a field name.
cFuncName
Specifies a function name that accepts a field value as the first parameter. The specified function or method must accept the associated field name as the sole parameter.
Note Do not include parentheses at the end of the function or method name.

Remarks

If the local cursor contains character fields that are used as part of the WHERE clause for an automatically generated update command, the data source might require that the trailing spaces be removed to obtain a proper match at the data source. The following example illustrates how to remove such spaces:

CursorAdapter.ConversionFunc = "companyname TRIM, contactname TRIM"

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


Count Property

Contains the number of items in a collection, for example, project , file, or server objects in a project, file, or server collection. Read-only at design time and run time.

Object.Count

Property Values

Numeric

Remarks

For a projects collection, the Count property contains zero if no instances of the Project Manager exist. For a file or server collection, the Count property contains zero if no files or servers exist in the file or server collection.

You can use the Count property to access the number of items in a collection. However, you cannot manually change Count except by using the Add and Remove methods of the collection. Collection objects provide their own Add and Remove methods.

You should use Count to determine the number of items in a collection when iterating through items in the collection using FOR…ENDFOR or referencing individual items with the Item method.

Count supports the Access method. Since Count is read-only, it does not support the Assign method.

See Also

Item Method (File Object) | Add Method (File Object) | Remove Method (File Object) | Item Method (Collection Class) | Add Method (Collection Class) | Remove Method (Collection Class) | FOR … ENDFOR Command | Access and Assign Methods

Applies To: Files Collection | Projects Collection | Servers Collection | Collection Class


CurrentControl Property

Specifies which control contained in a Column object is used to display the values of the active cell. Available at design time; read/write at run time.

Column.CurrentControl[ = cName]

Property Values

cName
Specifies the name of the control that displays and accepts data for the active cell in a Column object.

Remarks

The default control is a TextBox having Text1 as the Name property. Use the AddObject method to add other controls.

If the Column's Sparse property is set to true (.T.), only the active cell in the Column uses the object specified in the CurrentControl property; the other cells display data using a TextBox. If the Sparse property is set to false (.F.), all cells in the Column use the CurrentControl property to display data.

Note You can add an unlimited number of controls to a Column object using the AddObject method. However, you can set the CurrentControl property for only one control at any given time.

See Also

AddObject Method | Bound Property | RemoveObject Method | Sparse Property

Applies To: Column Object


CurrentX, CurrentY Properties

Specifies the horizontal (X) and vertical (Y) coordinates for the next drawing method. Not available at design time; read/write at run time.

Object.CurrentX[ = nXCoord]
Object.CurrentY[ = nYCoord]

Property Values

nXCoord
Specifies the horizontal coordinate of the form, in the unit of measurement specified by the ScaleMode property of the form.
nYCoord
Specifies the vertical coordinate of the form, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

Coordinates are measured from the upper-left corner of an object. CurrentX is 0 at an object's left edge and CurrentY is 0 at its top edge. Coordinates are expressed in foxels or the current unit of measurement defined by the ScaleMode property.

When you use the following graphics methods, the CurrentX and CurrentY settings are changed as indicated.

Method | CurrentX, CurrentY set to
Box | The endpoint of the box as specified by the last two arguments.
Circle | The center of the object.
Cls | 0, 0.
Line | The endpoint of the line.
Print | The next print position.
Pset | The point drawn.

See Also

Box Method | Circle Method | Cls Method | DrawMode Property | DrawStyle Property | Left Property | Line Method | PSet Method | ScaleMode Property | SYS(1270) - Object Location | Top Property

Applies To: Form Object | _SCREEN


CursorSchema Property

Specifies the structure of the cursor associated with a CursorAdapter object. Read/write at design time and run time.

CursorSchema is essentially the portion "between the parentheses" of the SQL CREATE TABLE and CREATE CURSOR commands. You can use CursorSchema to define an XML data source. Visual FoxPro uses CursorSchema at design time to determine the structure of the cursor to place on the surface of the Data Environment Designer. Visual FoxPro uses CursorSchema at run time if specified by the CursorFill method.

Note You must make sure that CursorSchema matches and maps to the data source columns in an acceptable manner.
CursorAdapter.CursorSchema [ = cList ]

Property Values

cList
Character data type. The cList parameter specifies a character string or expression that evaluates to a valid comma-delimited list of field names and types.

For example:

CursorAdapter.CursorSchema = ;
"col1 I, col2 c(25), col3 M, col4 Y, col5 n(12,3)"

If CursorSchema is empty or set to null (.NULL.), Visual FoxPro uses the data source of the CursorAdapter object to determine the cursor structure.

Remarks

When the lUseCursorSchema parameter in the CursorFill method evaluates to True (.T.), or when you add a CursorAdapter-based cursor to the surface of the Data Environment Designer, a CursorAdapter object uses CursorSchema as a template for the cursor created by CursorFill.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CursorFill Method

Applies To: CursorAdapter Class


CursorSource Property

Specifies the name of the table or view associated with a Cursor object. Read-only at design time; read/write at run time.

DataEnvironment.Cursor.CursorSource[ = cText]

Property Values

cText
For views, specifies the name of the view in a database. For tables in a database, specifies the long table name. For free tables, specifies the full path to the free table.

See Also

Database Property | CURSORGETPROP( ) | CURSORSETPROP( ) Function

Applies To: Cursor Object


CursorStatus Property

Specifies whether the CursorAdapter object represented by the CursorAdapter Alias property is attached and how it is attached. Visual FoxPro requires CursorStatus to determine state of the current CursorAdapter object and from where the associated cursor originated. Read-only.

CursorAdapter.CursorStatus [ = nValue ]

Property Values

nValue
Numeric data type. The following table lists the possible values for nValue.
nValue | Description
0 | CursorAdapter <Alias> is not attached. (Default)
1 | CursorAdapter <Alias> is attached via the CursorFill method.
2 | CursorAdapter <Alias> is attached via the CursorAttach method.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | Alias Property | CursorFill Method | CursorAttach Method

Applies To: CursorAdapter Class


Curvature Property

Specifies the curvature of a Shape control's corners. Available at design time and run time.

Shape.Curvature[ = nCurve]

Property Values

nCurve
The settings for the Curvature property are:
Setting | Description
0 | Specifies no curvature, creating square corners.
1 through 98 | Specifies progressively rounded corners. A higher number increases the curvature.
99 | Specifies maximum curvature and creates a circle or ellipse.

Example

The following example demonstrates how the Curvature property can be used with the Shape control to display a circle, ellipse, or square on a form.

A form is created, and a set of option buttons and a command button are placed on the form. When you click one of the option buttons, the corresponding shape is displayed on the form. The Height, Width, and Curvature properties of each shape determine the type of shape (circle, ellipse, or square) created. The Curvature property is set to 99 to create the circle and ellipse.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

DEFINE CLASS Command | DO CASE ... ENDCASE Command | Shape Control Properties, Methods and Events

Applies To: Shape Control


Database Property

Specifies the path to the database that contains the table or view associated with a cursor or CursorAdapter. Read-only at design time; read/write at run time.

Note When you access a regular cursor using the CURSORSETPROP() function, the Database property is read-only at run time.
DataEnvironment.Cursor.Database [ = cPath ]

Property Values

cPath
Specifies the full path to the database (.dbc) file.

Remarks

If the cursor is based on a free table, Database contains an empty string ("").

See Also

CursorSource Property | CURSORSETPROP() Function | Database Manipulation

Applies To: Cursor Object


DataEnvironment Property

Provides a reference to the object's data environment. Read-only at design time and run time.

Object.DataEnvironment

See Also

DataEnvironment Object | DataEnvironment Object Properties, Methods and Events

Applies To: Form Object | FormSet


DataSession Property

Specifies whether an object can run in its own data session with a unique data environment. Available at design time; read-only at run time.

Object.DataSession[ = nSession]

Property Values

nSession
The settings for the DataSession property are:
Setting | Description
1 | (Default) Default data session.
2 | Private data session. Creates a new data session for each instance that is created.

See Also

DataSessionID Property | SET DATASESSION

Applies To: Form Object | FormSet Object | _SCREEN | Session Object | ToolBar Object


DataSessionID Property

Returns the data session ID that identifies the private data session for the object. Read-only at design time; read/write at run time.

If the DataSession property of the object is set to 1 (Default Data Session), returns the default data session ID.

Object.DataSessionID

Remarks

Available only if the DataSession property of the object is set to 2 (Private data session).

You can use SET DATASESSION with the DataSessionID property to change data sessions.

When you set DataSessionID, the setting affects the working data session for the object. The DataSessionID property setting does not affect objects you create by using CREATEOBJECT( ).

Changing the DataSessionID property setting increments the reference count of the data session changed to and decrements the reference count of the data session changed from. However, if you create a data session by setting the DataSession property to 2 (Private data session), changing the DataSessionID property setting does not release the initial data session. In such case, the object must be released to free the initial session.

For more information on multiple data sessions, see Programming for Shared Access.

Caution Changing the DataSessionID property setting of an object that contains data-bound controls causes the controls to lose their original data sources. In general, use DataSessionID on objects that do not contain data-bound controls.

See Also

CREATEOBJECT( ) | DataSession Property | SET DATASESSION

Applies To: Form Object | FormSet Object | _SCREEN | Session Object | ToolBar Object


DataSource Property

Specifies the data source for DataEnvironment and CursorAdapter objects to use. The DataEnvironment or CursorAdapter DataSourceType property determines the value of the corresponding DataSource property. Read/write at design time and run time.

DataEnvironment.DataSource [= DataSource]

-or-

CursorAdapter.DataSource [= DataSource]

Property Values

DataSource
Specifies a reference to an existing data source of permissible data source types. DataSource acts only as a pointer to the actual data source, which must exist at run time.

The following table lists the values for DataSource, which depend on the value of the DataSourceType property.

DataSource | DataSourceType
Reference to a valid ActiveX Data Object (ADO) RecordSet object | "ADO"
Positive integer that represents or memory variable that contains a valid Open Database Connectivity (ODBC) connection handle | "ODBC"
Disregarded. | "Native", "XML", null (.NULL.), or empty string ("")

Remarks

When the CursorAdapter DataSourceType is "Native", specifying CursorAdapter DataSource is not required because the cursor returned by the CursorAdapter SelectCmd property is the default data source. The name of the cursor returned is determined by the CursorAdapter Alias property, which is set by the CursorAdapter CursorFill method.

If the CursorAdapter InsertCmdDataSourceType, UpdateCmdDataSourceType, and DeleteCmdDataSourceType properties are empty, the CursorAdapter DataSource property overrides the CursorAdapter InsertCmdDataSource, UpdateCmdDataSource, and DeleteCmdDataSource properties.

If the CursorAdapter UseDeDataSource property is True (.T.), the DataEnvironment DataSource and DataSourceType properties override the same CursorAdapter properties.

See Also

Properties | DataEnvironment Object Properties, Methods and Events | CursorAdapter Object Properties, Methods, and Events | DEClass Property | DataSourceType Property

Applies To: CursorAdapter Class | DataEnvironment Object


DataSourceType Property

Specifies the data source type of the data source in the DataEnvironment or CursorAdapter DataSource property. The DataEnvironment or CursorAdapter DataSourceType property determines the value of the corresponding DataSource property. Read-only at design time and read/write at run time.

DataEnvironment.DataSourceType [= cDataSourceType]

-or-

CursorAdapter.DataSourceType [= cDataSourceType]

Property Values

cDataSourceType
Character data type. The cDataSourceType parameter specifies a character string describing the data source type of the data source used by the data environment or cursor adapter.

The following table lists the values for cDataSourceType.

DataSourceType | DataSource
"ADO" | Reference to a valid ActiveX Data Object (ADO) RecordSet or Command object
"ODBC" | A valid Open Database Connectivity (ODBC) connection handle
"Native", "XML", null (.NULL.), or empty string ("") | Disregarded

Remarks

You cannot use local and remote views as a "Native" source for CursorAdapter objects, but you can attach them using the CursorAttach method.

The DataEnvironment DataSourceType is not specified at design time when the data environment does not specify a data source.

See Also

Properties | DataEnvironment Object Properties, Methods and Events | CursorAdapter Object Properties, Methods, and Events | DEClass Property | DataSource Property | CursorAttach Method

Applies To: CursorAdapter Class | DataEnvironment Object


DataType Property

Specifies the Visual FoxPro data type for the field in the XML document.

For more information about Visual FoxPro and XML data type mapping, see Visual FoxPro and XML Schema Data Type Mapping.

XMLField.DataType

Property Values

Character data type (C(1)). The DataType property contains the name of a Visual FoxPro data type for the XMLField object.

See Also

Properties | XMLField Object Properties, Methods, and Events

Applies To: XMLField Class


DateFormat Property

Specifies the format for Date and DateTime values displayed in a text box. Available at design time and run time.

Object.DateFormat[ = nValue]

Property Values

nValue
One of the following settings:
Setting | Description | Format
0 | (Default) The displayed date format is determined by the setting of SET DATE. | Determined bySET DATE
1 | American | mm/dd/yy
2 | ANSI | yy.mm.dd
3 | British | dd/mm/yy
4 | Italian | dd-mm-yy
5 | French | dd/mm/yy
6 | German | dd.mm.yy
7 | Japan | yy/mm/dd
8 | Taiwan | yy/mm/dd
9 | USA | mm-dd-yy
10 | MDY | mm/dd/yy
11 | DMY | dd/mm/yy
12 | YMD | yy/mm/dd
13 | Short | Determined by the Windows Control Panel short date setting
14 | Long | Determined by the Windows Control Panel long date setting

Remarks

A Date or DateTime value displayed in a text box may be displayed in a different format when the text box does not have the focus. Certain short and long date formats that you can specify in the Windows Control Panel do not correspond to valid Visual FoxPro formats, and are displayed in a default format.

The Format property overrides the DateFormat property when the YS, YL, E, or D settings are specified for the Format property.

See Also

Century Property | DateMark Property | Hours Property | Seconds Property | SET DATE | StrictDateEntry Property

Applies To: TextBox Control


DateMark Property

Specifies the delimiter for Date and DateTime values displayed in a text box. Available at design time and run time.

Object.DateMark[ = cDateMarkCharacter]

Property Values

cDateMarkCharacter
Specifies the Date and DateTime value delimiter. If cDateMarkCharacter is the empty string, the delimiter is determined by the setting of SET MARK. If cDateMarkCharacter is a space, the delimiter for the current setting of the text box's DateFormat property is used.

In the Properties window, use the = command to specify the empty string (= "") or a space (= " ") for the DateMark property.

Remarks

The DateMark property setting is ignored if the DateFormat property is set to Short or Long.

See Also

Century Property | DateFormat Property | Hours Property | Seconds Property | SET MARK TO | StrictDateEntry Property

Applies To: TextBox Control


Debug Property

Specifies if debugging information is included with compiled source code in a project.

Object.Debug[ = lExpression]

Property Values

lExpression
The settings for the Debug property are:
Setting | Description
True (.T.) | (Default) Debugging information is included with the compiled source code.
False (.F.) | Debugging information is not included and you cannot view a program's execution in the Trace window or use MESSAGE(1) to return the source code for a line that causes an error. Setting lExpression to false (.F.) is identical to including the NODEBUG argument in the COMPILE command.

Remarks

Source code in a project includes program and format files, source code in form, label, report, and visual class libraries, and stored procedures in databases. The Debug property corresponds to the Debug info check box on the Project tab of the Project Information dialog box.

See Also

COMPILE | Project Information Dialog Box

Applies To: Project Object


DEClass Property

Specifies the name of the DataEnvironment class to use when adding a data environment to a form. Read/write at design time and read-only at run time.

At design time, DEClass makes it possible for you to specify a DataEnvironment class from the class library in the DEClassLibrary property.

Form.DEClass [= cClassName]

Property Values

cClassName
Character data type. The cClassName parameter specifies one of the following:
  • Name of a programmatic class in a program (.prg) file
  • Name of a non-visual class in a visual class library (.vcx) file

Remarks

Visual FoxPro supports DEClass and DEClassLibrary for form (.scx), visual class library (.vcx), and program (.prg) files but not for FormSet objects or in the Report Designer.

Visual FoxPro instantiates a DataEnvironment object from DEClass and its associated DEClassLibrary property under the following conditions:

  • DEClass specifies a DataEnvironment class at design time in the Properties window for the form.
  • DEClass specifies a DataEnvironment class when programmatically creating the form.

When the form is created, Visual FoxPro uses the specified DataEnvironment class to create the DataEnvironment object. If you specify a value for the DEClassLibrary property but not for DEClass, or if the DataEnvironment class is the wrong type or does not exist in the class library specified, Visual FoxPro generates the appropriate message.

You can set DEClass and DEClassLibrary using the Properties window in the Form Designer, in a Form class, or from a class definition in a .prg file. Visual FoxPro displays DEClass and DEClassLibrary in the Properties window as read-only. However, clicking the ellipsis (...) button in the Properties window displays the Open dialog box so you can select a desired .prg file or, if supported, .vcx file.

You can also use the ASELOBJ( ) function to store object references to an array to set object properties individually. However, if you set only the DEClass or the DEClassLibrary property, Visual FoxPro disregards the settings for these properties and uses the default DataEnvironment class. You must set both properties.

Note When setting the DEClass and DEClassLibrary properties using code or the ASELOBJ( ) function, you must set the DEClassLibrary property before setting the DEClass property.

When you open the Data Environment Designer by right-clicking the form, the following occurs:

  • DataEnvironment class containing Cursor objects

    If the contained cursor or cursors refer to an existing table or remote view, tables and views placed on the Data Environment Designer surface are read-only. You can drag and drop fields or tables on the Form Designer surface if the following properties are set with the specified requirements:

    • CursorSource (Required) Table name and path if a free table; table name only if a database container (DBC) table.
    • Database (Optional) Name and path of the DBC is filled in automatically if a DBC table or view.
    • Alias (Optional) Alias assigned to the table if different from the table name. Otherwise, the alias defaults to the CursorSource name.

    If the DataEnvironment class contains a Cursor object, but the cursor does not contain a valid reference to a table or view, the Data Environment Designer does not open. Visual FoxPro loads the data environment after generating the appropriate message.

    If the DataEnvironment class contains multiple Cursor objects, only those cursors containing valid table and/or view references are placed on the Data Environment Designer surface. Cursors that do not contain valid table or view references are disregarded.

    If the cursor references a DBC, but the cursor does not reference a valid table or view in the DBC, Visual FoxPro loads the data environment after displaying the appropriate message.

    If the DataEnvironment class does not contain a Cursor object, the Data Environment Designer does not open, and Visual FoxPro generates an appropriate message.

    When you drag a table (.dbf) file from a folder to a form while a non-DataEnvironment class data environment is open, Visual FoxPro automatically adds the table to the data environment. However, if the opened data environment is based on a DataEnvironment class, the data environment is read-only, and Visual FoxPro does not add the .dbf file to the data environment.

  • DataEnvironment class containing CursorAdapter objects

    If the DataEnvironment class contains a CursorAdapter object, the CursorAdapter must meet the following requirements to appear on the Data Environment Designer surface:

    • The CursorAdapter CursorSchema property is specified and set to a valid value.
    • The CursorAdapter Alias property is specified.
    Note If the prior conditions are met, cursor adapters appear on the Data Environment Designer surface as read-only. You can drag and drop tables and fields on the form. The properties, events, or methods of the data environment and any contained CursorAdapter objects are read-only.

    The Data Environment Designer does not open if any of the following conditions are true:

    • The DataEnvironment class contains a CursorAdapter object, but the cursor adapter does not contain valid data in the CursorSchema property.
    • The CursorAdapter object does not instantiate for any reason.

To modify the DataEnvironment class, you must close the Form Designer, release any classes in use, modify and recompile the DataEnvironment class in the file specified by the DEClassLibrary property, and return to the Form Designer.

When the DEClass and DEClassLibrary properties are set, running the form creates and loads the data environment from the DataEnvironment class specified. To set DEClass and DEClassLibrary at run time, you must use code.

If you attempt to convert a form to a form set at design time when the Form Designer is open, and the DEClass and DEClassLibrary properties are specified for the form, Visual FoxPro generates the appropriate message. If a form set is open in the Form Designer, and you attempt add a form that specifies the DEClass and DEClassLibrary properties to the form set at design time, Visual FoxPro generates the appropriate message and makes the DEClass and DEClassLibrary properties unavailable. If you attempt to add a form that specifies the DEClass and DEClassLibrary properties to the form set at run time, Visual FoxPro disregards DEClass and DEClassLibrary and does not load the data environment class specified.

DEClass and DEClassLibrary supports Public, Hidden, and Protected scope.

DEClass and DEClassLibrary does not support Access and Assign methods.

In a subclassed form, DEClass and DEClassLibrary are inherited as normal.

Example

The following example creates a Form class and then sets the DEClassLibrary and DEClass properties to specify an external DataEnvironment class and class library.

DEFINE CLASS form1 as Form
   DEClassLibrary="MyProgram.prg"
   DEClass="MyDE"
ENDDEFINE

See Also

Properties | Form Object Properties, Methods and Events | DEClassLibrary Property | Access and Assign Methods | Public Command | Class Member Protection and Hiding | Protection and Hiding of Class Members | Report Command Command | DataEnvironment Object

Applies To: Form Object


DEClassLibrary Property

Specifies the name of a program (.prg) or visual class library (.vcx) file that contains the DataEnvironment class specified by the DEClass property. Read/write at design time and read-only at run time.

Form.DEClassLibrary [= cClassLibraryName]

Property Values

cClassLibraryName
Character data type. The cClassLibraryName parameter specifies one of the following:
  • Name of a program (.prg) file
  • Name of a visual class library (.vcx) file

Remarks

For details, see DEClass Property.

Example

The following example creates a Form class and then sets the DEClassLibrary and DEClass properties to specify an external DataEnvironment class and class library.

DEFINE CLASS form1 as Form
   DEClassLibrary="MyProgram.prg"
   DEClass="MyDE"
ENDDEFINE

See Also

Properties | Form Object Properties, Methods and Events | Access and Assign Methods | Public Command | Class Member Protection and Hiding | Protection and Hiding of Class Members | Report Command | DataEnvironment Object

Applies To: Form Object


Default Property

Specifies which command button or OLE Container control responds to the ENTER key being pressed when there are two or more command buttons on an active form. Available at design time and run time.

Object.Default[ = lExpr]

Property Values

lExpr
The settings for the Default property are:
Setting | Description
True (.T.) | When the button's Default property is set to true (.T.) and its parent form is active, the user can execute the button's command by pressing ENTER. (If the focus is in an edit box, the user can press CTRL+ENTER.)If KEYCOMP is set to WINDOWS, the default button's command is not executed if the focus has been moved to another command button. In that case, pressing ENTER affects the button with the focus instead of the default button.
False (.F.) | (Default) The button is not the default button.

Remarks

The Default property only applies to an OLE Container control that contains an "Acts like a Button" ActiveX control (.ocx).

Only one command button or OLE Container control on a form can be the default command button. When the Default property is set to true (.T.) for one command button or OLE Container control, it is automatically set to false (.F.) for all other command buttons or OLE Container controls on the form. You cannot create a default command button or OLE Container control in a toolbar.

See Also

Enabled Property | KeyPress Event

Applies To: CommandButton | OLE Container Control


DefaultFilePath Property

Specifies the default drive and directory used by an Application object. Available at run time.

ApplicationObject.DefaultFilePath[ = cPath]

Property Values

cPath
Specifies one of the following:
  • A drive designator.
  • A drive designator with a directory name.
  • A child directory name.
  • Any of the above using MS-DOS® shorthand notation ( \ or ..).

Remarks

The DefaultFilePath property is similar to SET DEFAULT.

Visual FoxPro searches for a file in the default Visual FoxPro directory. The default directory is the one from which you start Visual FoxPro. However, you can use the DefaultFilePath property to specify a different default directory. If Visual FoxPro cannot find a file in the default directory, it then searches the Visual FoxPro path if one has been specified. Use SET PATH to specify the Visual FoxPro path.

See Also

SET DEFAULT | SET PATH

Applies To: Application Object, _VFP System Variable


DefOLELCID Property

Specifies the default OLE Locale ID for a form or the main Visual FoxPro window. Available at design time and run time.

Form.DefOLELCID[ = nValue]

Property Values

nValue
Specifies a default OLE Locale ID value for a form or the main Visual FoxPro window. This default value determines the Locale ID for OLE Bound controls and OLE Container controls when they are placed on the form or the main Visual FoxPro window.

Remarks

If the default OLE Locale ID value for a form or the main Visual FoxPro window is changed to a new value, OLE Bound controls and OLE Container controls placed on the form or the main Visual FoxPro window after the new default Locale ID value is in effect use the new value.

If DefOLELCID is set to zero for a form or the main Visual FoxPro window, SYS(3004) determines the default Locale ID for OLE Bound controls and OLE Container controls placed on the form or the main Visual FoxPro window.

See SYS(3005) for a listing of Locale IDs.

Note The DefOLELCID property only affects the language of the user interface, which OLE controls display, and not the language of the Automation commands. The Automation command language is affected only by the Global LocaleID, set with SYS(3005).

See Also

OLELCID Property | SYS(3005) - Set Locale ID

Applies To: Form | _SCREEN


DeleteCmd Property

Specifies the command to use when deleting rows. Read/write at design time and run time.

CursorAdapter.DeleteCmd [ = cCommand ]

Property Values

cCommand
Character data type. The following table lists the possible values for DeleteCmd.
cCommand | Description
Character string or expression | Specifies a valid command string for the data source in the DeleteCmdDataSource property.
Empty string ("") The CursorAdapter object generates a SQL DELETE command automatically if the AllowDelete property is set to True (.T.).

For more information about generating SQL commands automatically, see Data Access Management Using CursorAdapters.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


DeleteCmdDataSource Property

Specifies the data source used by the DeleteCmd property. Read/write at design time and run time.

Note The CursorAdapter DeleteCmdDataSourceType property determines how the DeleteCmdDataSource property is used.
CursorAdapter.DeleteCmdDataSource [ = cDataSource]

Property Values

cDataSource
Character data type. The cDataSource parameter specifies the data source used by the DeleteCmd property.

Remarks

The following table describes additional behaviors that apply to DeleteCmdDataSource depending on the value of DeleteCmdDataSourceType.

DeleteCmdDataSourceType DeleteCmdDataSource behavior
Empty ("") DeleteCmdDataSource is disregarded. Visual FoxPro uses the data source in the CursorAdapter DataSource property.

If the cursor associated with the CursorAdapter object is based on an ActiveX Data Object (ADO) RecordSet, Visual FoxPro uses the functionality of the ADO RecordSet to delete the record. To use this functionality, make sure the CursorAdapter DataSourceType property is set to "ADO".
"ADO" DeleteCmdDataSource must be set to a valid ADO Command object. The ActiveConnection property of the ADO Command object must be set to a valid and open ADO Connection object.

Visual FoxPro sets the CommandText property of the ADO Command object to the value of the CursorAdapter DeleteCmd property. Visual FoxPro parses the command for parameters, creates parameter values if found, and sets them in the Command object.

The delete operation occurs as:

CursorAdapter.DeleteCmdDataSource.Execute()

For more information about using an ADO RecordSet, automatic updating, and generating SQL commands automatically, see Data Access Management Using CursorAdapters.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


DeleteCmdDataSourceType Property

Specifies the data source type for the data source used by the DeleteCmdDataSource property. Read/write at design time and run time.

CursorAdapter.DeleteCmdDataSourceType [= cDataSourceType]

Property Values

cDataSourceType
Character data type. The cDataSourceType parameter specifies the data source type of the data source in the DeleteCmdDataSource property.

Remarks

If DeleteCmdDataSourceType is empty ("") or null (.NULL.), Visual FoxPro disregards the CursorAdapter DeleteCmdDataSource property and uses the CursorAdapter DataSource and DataSourceType properties.

To generate an XML UpdateGram, you must set the value of DeleteCmdDataSourceType to "XML".

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | UpdateGram Property

Applies To: CursorAdapter Class


DeleteMark Property

Specifies whether the delete mark column appears in a Grid control. Available at design time and run time.

Grid.DeleteMark[ = lExpr]

Property Values

lExpr
The settings for the DeleteMark property are:
Setting | Description
True (.T.) | (Default) The delete mark column appears on the Grid at the far left column.
False (.F.) | The delete mark column does not appear.

Remarks

The delete mark column enables the user to mark records for deletion. The user clicks in the delete column at the record to delete.

See Also

DELETE | Deleted Event

Applies To: Grid


Description Property

For a File object, the description for the file. For a Server object, the description of the server class. Available at design time and run time.

Object.Description[ = cExpression]

Property Values

cExpression
Specifies the description for the File or Server object.

For a File object, the default value is the empty string. You can also specify a description for a file in a project by choosing Edit Description from the Project menu.

For a Server, the default value is the name of the server class. You can also specify a description for a server in the Server tab of the Project Information dialog box. The Server object description also appears for the server in the Registry.

See Also

Name Property

Applies To: File Object | Server Object


Desktop Property

Specifies whether a form can appear anywhere on the Windows desktop or is contained in the main Visual FoxPro window. Available at design time; read-only at run time.

Object.Desktop[ = lExpr]

Property Values

lExpr
The settings for the Desktop property are:
Setting | Description
True (.T.) | The form can be anywhere on the Windows desktop.
False (.F.) | (Default) The form is contained in the main Visual FoxPro window.

Remarks

The Desktop property is ignored if the ShowWindow property is set to 2 – As Top-Level form.

You should not use the Desktop property when you create Single Document Interface (SDI) applications in which you might want to hide the Visual FoxPro desktop window (_SCREEN). Instead, use the ShowWindow property setting of 2 to create a top-level form.

See Also

AlwaysOnBottom Property | AlwaysOnTop Property | AutoCenter Property | MaxHeight Property | MaxLeft Property | MaxTop Property | MaxWidth Property | MinHeight Property | MinWidth Property | ShowWindow Property

Applies To: Form | _SCREEN


Details Property

Specifies additional details about an exception object that are related to information specified by the Message property. Read/write at run time.

Exception.Details

Property Value

Character data type. Details can be NULL unless the error has an additional parameter; in that case, this property contains the text of the error parameter.

Remarks

Identical to the value returned by SYS(2018) and the third element in the array produced by the AERROR() function.

See Also

Properties | Exception Object Properties, Methods, and Events | Message Property | AERROR( ) Function | SYS(2018) - Error Message Parameter | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


DisabledBackColor, DisabledForeColor Properties

Specifies the background and foreground colors for a disabled control. Read/write at design time and run time.

Control.DisabledBackColor[ = nColor]

-Or-

Control.DisabledBackColor = RGB(nRedValue, nGreenValue, nBlueValue)
Control.DisabledForeColor[ = nColor]

-Or-

Control.DisabledForeColor = RGB(nRedValue, nGreenValue, nBlueValue)

Property Values

nColor
Specifies a single number to represent the color.
nRedValue, nGreenValue, nBlueValue
Specifies three separate color intensities that compose the control's foreground color or background color. You must use the RGB( ) function with these values to consolidate the three color components into one number.

Remarks

The color you specify is dithered with gray.

Note In the Properties window, you can double-click any of the color properties to display the Color dialog box. You can choose or define colors from this dialog box. The red, green, and blue intensities that correspond to the color you choose become the settings for these properties after you close the Color dialog box.

The color settings, or Themes, of the operating system set the default color settings for the DisabledBackColor and DisabledForeColor properties.

If the Themes property is set to True (.T.), setting the DisabledBackColor property value produces a 35% transparency overlay on top of the themed button. This produces a colorizing effect.

See Also

BackColor, ForeColor Properties

Applies To: CheckBox | ComboBox | CommandButton | EditBox | Label | ListBox | OptionButton | Spinner | TextBox


DisabledItemBackColor, DisabledItemForeColor Properties

Specifies the background or foreground color for the disabled items in a ComboBox or ListBox control. Available at design time and run time.

Control.DisabledItemBackColor[ = nColor]

-or-

Control.DisabledItemBackColor RGB(nRedValue, nGreenValue,  nBlueValue)
Control.DisabledItemForeColor[ = nColor]

-or-

Control.DisabledItemForeColor RGB(nRedValue, nGreenValue, nBlueValue)

Property Values

nColor
Specifies a single number to represent the color.
Note In the Properties window, you can double-click any of the color properties to display the Color dialog box. You can choose or define colors from this dialog box. The red, green, and blue intensities that correspond to the color you choose become the settings for these properties after you close the Color dialog box.

For more information, see the color table in the BackColor, ForeColor Properties topic.

See Also

BackColor, ForeColor Properties | DisabledBackColor, DisabledForeColor Properties | RGB( ) | SelectedBackColor, SelectedForeColor Properties

Applies To: ComboBox | ListBox


DisabledPicture Property

Specifies the graphic to display when the control is disabled. Available at design time and run time.

Control.DisabledPicture[ = cPicture]

Property Values

cPicture
Specifies either a complete path and file name of a bitmap or the name of a general field in a database table.

Remarks

If you set the DisabledPicture property at design time and the file you specify does not exist, Visual FoxPro displays an error message, but the property remains set to the file you specified. Visual FoxPro ignores the DisabledPicture property at run time if it is set to a file that does not exist.

If you do not set the DisabledPicture property, Visual FoxPro uses the Picture property setting to determine the graphic displayed when the control is disabled.

For CommandButton controls, the Style property must be set to 0 (Standard) for the bitmap to be displayed on the control; For CheckBox and OptionButton controls, the Style property must be set to 1 (Graphical).

See Also

DownPicture Property | Enabled Property | Picture Property | Style Property

Applies To: CheckBox | CommandButton | OptionButton


DisableEncode Property

Enables or disables base64 or hexBinary encoding for Memo (Binary) or Character (Binary) fields.

Setting DisableEncode at the XMLAdapter level sets the default DisableEncode values for XMLField objects when they are created and added to the Fields collection by the following XMLAdapter methods:

  • LoadXML
  • Attach
  • AddTableSchema

Additionally, changing DisableEncode at the XMLAdapter level affects only the next set of XMLField objects created, not the existing XMLField objects in the Fields collection. Therefore, to modify the setting of DisableEncode for an existing XMLField object, change the value at the XMLField level.

Object.DisableEncode [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Disable base64 or hexBinary encoding for Memo (Binary) or Character (Binary) fields. (Default)
True (.T.) | Enable base64 or hexBinary encoding for Memo (Binary) or Character (Binary) fields.

Remarks

Visual FoxPro disregards invalid characters or incorrect length in base64 and hexBinary encoded strings.

If XMLAdapter DisableEncode is True (.T.) when the LoadXML method is executed, the XMLField MaxLength property is set to the maximum length for the encoded data. Otherwise, Visual FoxPro uses the original MaxLength value.

If XMLAdapter DisableEncode is True (.T.) when the ToXML method is executed, the xsd:maxLength value in the XML Schema Definition (XSD) schema is set to the maximum length for the decoded data. Otherwise, Visual FoxPro uses the value of the XMLField MaxLength property.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLField Object Properties, Methods, and Events | Fields Collection (XMLTable) | MaxLength Property | ToXML Method

Applies To: XMLAdapter Class | XMLField Class


DisplayCount Property

Specifies the maximum number of items displayed in the list portion of a ComboBox control.

Object.DisplayCount[ = nExpression]

Property Values

nExpression
Specifies the maximum number of items displayed in the list portion of the ComboBox control. The default value is zero; if nExpression is zero, a maximum of 7 items are displayed in the list.

Scroll arrows are not displayed in the list portion of a ComboBox control if nExpression is one.

See Also

ColumnCount Property | DisplayValue Property

Applies To: ComboBox


DisplayValue Property

Specifies the contents of the first column of the selected item in a ListBox or ComboBox control. Available at design time and run time.

Use the DisplayValue property when a combo box or list box has more than one column, and the control's BoundColumn property is set to a value greater than 1.

 [Form.]Control.DisplayValue[ = Expr]

Property Values

Expr
Specifies a character string or numeric value. The following table describes the values of Expr.
Expr | Description
Character string Specifies the value of the first column of the selected item.

For combo boxes, DisplayValue specifies the text displayed in the text box portion of the combo box when DisplayValue is a character string. However, the ComboBox InputMask and MaxLength properties can affect its display.
Numeric value | Specifies the index of the selected item.

Remarks

When a combo box or list box has only one column, the DisplayValue property and Value property of the control usually have the same setting if both contain character strings. An exception exists when both properties contain character strings, and a value is typed in the combo box, but the value does not exist in the list. In this case, the value is an empty string (""), and DisplayValue will be the value that is typed in.

See Also

BoundColumn Property | Value Property

Applies To: ComboBox | ListBox


Docked Property

Contains a logical value indicating whether a user-defined ToolBar object is docked. Read-only at design time and run time.

ToolBar.Docked[ = lExpr]

Property Values

lExpr
The settings for the Docked property are:
Setting | Description
True (.T.) | The toolbar is docked.
False (.F.) | The toolbar is not docked.

See Also

DockPosition Property

Applies To: ToolBar


DockPosition Property

Specifies the position where a user-defined ToolBar object is docked. Read-only at design time and run time.

ToolBar.DockPosition[= nPosition]

Property Values

nPosition
The values for nPosition are:
Setting | Position
–1 | Undocked
0 | Top
1 | Left
2 | Right
3 | Bottom

See Also

Docked Property

Applies To: ToolBar


DocumentFile Property

Returns the name of the file from which a linked OLE object was created. At design time, specifies the name of the linked file. Read-only at design time and run time for an existing object, but can be set for an object when creating it.

Object.DocumentFile[ = cFileName]

Property Values

cFileName
The name of the file to which the object is linked. The name includes the full path of the file.

Remarks

DocumentFile contains the empty string for embedded (not linked) objects.

You set the DocumentFile property of a linked OLE object using the Insert Object dialog box when you initially add an OLE container to a form. You can also set this property when creating an OLE object using the APPEND GENERAL command or when defining the object in code as part of a class definition.

Before specifying the contents of an OLE object using the DocumentFile property, specify the Automation server application by setting the object's OLEClass.

Example

The following example adds an OLE Container control to a form, and uses the DocumentFile and OleClass properties to specify a Microsoft Excel worksheet as the file to edit and Microsoft Excel as the Automation server.

The DocumentFile property specifies a worksheet named Book1.xls in the EXCEL directory on drive C. This example will not work properly if the file and directory specified in the DocumentFile property do not exist; it may be necessary to modify the DocumentFile property to specify an existing directory and worksheet file.

The DoVerb method is used to activate the worksheet for editing.

frmMyForm = CREATEOBJECT('form')  && Create a form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject("oleObject","oleExcelObject")  && Add OLE object

frmMyForm.cmdCommand1.Visible=.T.  && Display the "Quit" Command button

frmMyForm.oleObject.Visible=.T.  && Display the OLE control
frmMyForm.oleObject.Height = 50  && OLE control height

frmMyForm.Show  && Display the form

frmMyForm.oleObject.DoVerb(-1)  && -1 for Edit

READ EVENTS  && Start event processing

DEFINE CLASS oleExcelObject as OLEControl
   OleClass ="Excel.Sheet"  && Server name
   DocumentFile = "C:\EXCEL\BOOK1.XLS"  && This file must exist
ENDDEFINE

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

APPEND GENERAL | CREATEOBJECT( ) | OLEClass

Applies To: OLE Bound Control | OLE Container Control


DownPicture Property

Specifies the graphic displayed when the control is selected. Available at design time and run time.

Control.DownPicture[ = cPicture]

Property Values

cPicture
Specifies either a complete path and file name of a bitmap or the name of a general field in a table.

Remarks

If you set the DownPicture property at design time and the file you specify does not exist, Microsoft Visual FoxPro displays an error message, but the property remains set to the file you specified. Visual FoxPro ignores the DownPicture property at run time if it is set to a file that does not exist.

If you do not specify a setting for the DownPicture property, Visual FoxPro uses the graphic specified by the Picture property when the control is selected.

For CommandButton controls, the Style property must be set to 0 (Standard) for the bitmap to be displayed on the control; For CheckBox and OptionButton controls, the Style property must be set to 1 (Graphical).

See Also

DisabledPicture Property | Enabled Property | Picture Property | Style Property

Applies To: CheckBox | CommandButton | OptionButton


DragIcon Property

Specifies the icon displayed as the pointer during a drag-and-drop operation. Available at design time and run time.

Control.DragIcon[ = cIcon]

Property Values

cIcon
Specifies the file that contains the icon to use as the mouse pointer. Typically, you specify the icon file using the Properties window at design time. The file you specify must have the .cur extension and be saved in VGA-Mono 2-Color 32 x 32 format. If you try to use a color .cur file, an error message is generated. You can use ImageEdit, to create a two-color .cur file. If you omit cIcon, an arrow pointer inside a rectangle is used.

Remarks

DragIcon is useful for providing visual feedback during a drag operation — for instance, to indicate that the source control is over an appropriate target. DragIcon takes effect when the user initiates dragging. Typically, you set DragIcon during a MouseDown or DragOver event.

If you set the DragIcon property at design time and the file you specify does not exist, Visual FoxPro displays an error message, but the property remains set to the file you specified. Visual FoxPro ignores the DragIcon property at run time if it is set to a file that does not exist.

See Also

Drag Method | DragDrop Event | DragMode Property | MouseDown Event | MouseMove Event | MousePointer Property | MouseUp Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | Shape | Spinner | TextBox


DragMode Property

Specifies manual or automatic drag mode for a drag-and-drop operation. Available at design time and run time.

Control.DragMode[ = nMode]

Property Values

nMode
The settings for the DragMode property are:
Setting | Description
0 | (Default) Manual. Requires using the Drag method to initiate dragging of the source control.
1 | Automatic. Clicking the source control automatically initiates dragging.

Remarks

When DragMode is set to 0 (Manual), the control responds to mouse events and the Drag method must be used to begin drag operations.

When DragMode is set to 1 (Automatic), the control does not respond to mouse events, and drag operations begin automatically when the user presses and holds the primary (left) mouse button over the control.

Releasing the mouse button while the mouse pointer is over a target control or form during a drag operation generates a DragDrop event for the target object and ends the drag operation. Dragging can also trigger a DragOver event.

Note While a control is being dragged, it does not receive other user-initiated mouse or keyboard events (KeyPress, MouseDown, MouseMove, or MouseUp).

See Also

DragDrop Event | DragIcon Property | DragOver Event | KeyPress Event | MouseDown Event | MouseMove Event | MouseUp Event | OLEDragMode Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox


DrawMode Property

Determines, in conjunction with the color properties, how a shape or line is displayed on screen. Available at design time and run time.

Object.DrawMode[ = nMode]

Property Values

nMode
The settings for the DrawMode property are:
Setting | Description
1 | Blackness Pen. Shape is drawn black.
2 | NotMerge Pen. Inverse of setting 15.
3 | Mask Not Pen. Combination of the colors common to the BackColor and the inverse of the ForeColor.
4 | Not Copy Pen. Inverse of setting 13.
5 | Mask Pen Not. Combination of the colors common to both the ForeColor and the inverse of the BackColor.
6 | Invert. Inverse of the BackColor.
7 | XOR Pen. Combination of the colors in the ForeColor and in the BackColor, but not in both.
8 | Not Mask Pen. Inverse of setting 9.
9 | Mask Pen. Combination of the colors common to both the ForeColor and the BackColor.
10 | Not XOR Pen. Inverse of setting 7.
11 | NOP. No operation. Output remains unchanged. In effect, this setting turns drawing off.
12 | Merge Not Pen. Combination of the BackColor and the inverse of the ForeColor.
13 | (Default). Copy Pen. Color specified by the ForeColor property.
14 | Merge Pen Not. Combination of the ForeColor and the inverse of the BackColor.
15 | Merge Pen. Combination of the ForeColor and the BackColor.
16 | Whiteness Pen. Shape is drawn white.

Remarks

Use the DrawMode property to produce visual effects with Shape or Line controls or when drawing with graphics methods. As a new shape is drawn, Visual FoxPro compares each pixel in the pattern with the corresponding pixel in the existing background and then applies bitwise operations. For example, setting 7 uses the exclusive OR operator (XOR) to combine a drawing pattern pixel with the background pixel.

The exact effect of the DrawMode property setting depends on how the color of a line drawn at run time combines with colors already on the screen. Settings 1, 6, 7, 11, 13, and 16 yield the most predictable results.

See Also

Box Method | Circle Method | DrawWidth Property | DrawStyle Property | FillColor Property | FillStyle Property | Line Method | Pset Method

Applies To: Form | Line | _SCREEN | Shape


DrawStyle Property

Specifies the line style to use when drawing with graphics methods. Available at design time and run time.

Object.DrawStyle[ = nStyle]

Property Values

nStyle
The settings for the DrawStyle property are:
Setting | Description
0 | (Default) Solid
1 | Dash
2 | Dot
3 | Dash-Dot
4 | Dash-Dot-Dot
5 | Transparent
6 | Inside Solid
Note If DrawWidth is set to 1, DrawStyle produces the effect described in the preceding table for each setting. But if DrawWidth is set to a value greater than 1, settings 1 through 4 produce a solid line.

See Also

Circle Method | DrawMode Property | DrawWidth Property | FillColor Property | FillStyle Property | ForeColor Property | Line Method | PSet Method

Applies To: Form | _SCREEN


DrawWidth Property

Specifies the line width for output from graphics methods. Available at design time and run time.

Object.DrawWidth[ = nSize]

Property Values

nSize
Specifies the width of the line in pixels. You can set DrawWidth to a value of 1 through 32,767. The default value is 1 pixel wide.

Increase the value of this property to increase the width of the line.

See Also

Circle Method | DrawMode Property | DrawStyle Property | FillColor Property | FillStyle Property | ForeColor Property

Applies To: Form | _SCREEN


DynamicAlignment Property

Specifies the alignment of text and controls in a Column object. The alignment is re-evaluated at run time each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicAlignment[ = cAlign]

Property Values

cAlign
Specifies a character string expression that is re-evaluated at run time and results in one of the following values:
Setting | Description
0 | Middle Left. Aligns the text flush left and centered vertically.
1 | Middle Right. Aligns the text flush right and centered vertically.
2 | Middle Center. Aligns the text in the middle with equal spaces to the right and left and centered vertically.
3 | (Default) Automatic. Aligns text based on the data type of the control source. Numeric types (numeric, double, float, currency, integer) are right-aligned; controls with other data types are left-aligned.
4 | Top Left. Aligns the text flush left and at the top of the column.
5 | Top Right. Aligns the text flush right and at the top of the column.
6 | Top Center. Aligns the text in the middle with equal spaces to the right and left and at the top of the column.
7 | Bottom Left. Aligns the text flush left and at the bottom of the column.
8 | Bottom Right. Aligns the text flush right and at the bottom of the column.
9 | Bottom Center. Aligns the text in the middle with equal spaces to the right and left and at the bottom of the column.

See Also

Alignment Property

Applies To: Column


DynamicBackColor, DynamicForeColor Properties

Specifies the background and foreground colors of a Column object. The colors are re-evaluated at run time each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicBackColor[ = cExpression]Column.DynamicForeColor
[ = cExpression]

Property Values

cExpression
Specifies an expression in quotation marks that is re-evaluated at run time whenever the Grid control is refreshed. The run-time evaluation must result in a single color value.

Remarks

You can use the DynamicBackColor and DynamicForeColor properties to create special effects, such as displaying the odd-numbered rows in green and the even-numbered rows in gray.

Example

The following example uses the DynamicBackColor property and the SetAll method to specify the background colors for the records in a Grid control. If the number of a record displayed in the Grid is even, the record's DynamicBackColor is white, otherwise its DynamicBackColor is green.

A Grid control is placed on a form, and the customer table is opened and its contents displayed in the Grid. The Caption property is used to specify a different header caption (Customer ID) for the CUST_ID field. A command button is placed on the form to close the form.

CLOSE ALL  && Close tables and databases
OPEN DATABASE (HOME(2) + 'Data\testdata')

USE customer  IN 0  && Opens Customer table

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject('grdGrid1','Grid')  && Add Grid control

frmMyForm.grdGrid1.Left = 25  && Adjust Grid position

frmMyForm.grdGrid1.SetAll("DynamicBackColor", ;
   "IIF(MOD(RECNO( ), 2)=0, RGB(255,255,255) ;
   , RGB(0,255,0))", "Column")  && Alternate white and green records

frmMyForm.grdGrid1.Visible = .T.  && Grid control visible
frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.grdGrid1.Column1.Header1.Caption = 'Customer ID'

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLOSE ALL  && Close table and database
ENDDEFINE

See Also

BackColor_ForeColor Properties

Applies To: Column


DynamicCurrentControl Property

Specifies which control contained in a Column object is used to display the values of the active cell. The name of the control is re-evaluated each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicCurrentControl[ = cExpression]

Property Values

cExpression
Evaluates at run time to the name of the control that displays and accepts data for the active cell in Column.

Remarks

The default control is a TextBox having Text1 as the Name property. Use the AddObject method to add other controls.

If the Column's Sparse property is set to true (.T.), only the active cell in the Column uses the object specified in the DynamicCurrentControl property setting to display data; the other cells display data using a TextBox. If the Sparse property is set to false (.F.), all cells in the Column use the object specified in the DynamicCurrentControl property setting to display data.

See Also

AddObject Method | CurrentControl Property

Applies To: Column


DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Specifies that text displayed in a Column object has one or more of the following styles: Bold, Italic, Strikethru, or Underline. The logical expression is re-evaluated each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicFontBold[ = "lExpr"]Column.DynamicFontItalic
[ = "lExpr"]Column.DynamicFontStrikeThru
[ = "lExpr"]Column.DynamicFontUnderline[ = "lExpr"]

Property Values

"lExpr"
Evaluates to either true (.T.) or false (.F.). The settings for the dynamic font properties are:
Setting | Description
True (.T.) | Font style is bold, italic, strikethru, or underline.
False (.F.) | (Default except for DynamicFontBold) Font style is not bold, italic, strikethru, or underline.

Remarks

Use these properties to control the appearance of text based on data values at run time. For example, you can set DynamicFontUnderline to indicate names of new members in an organization.

See Also

DynamicFontSize Property | DynamicFontName Property | DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Applies To: Column


DynamicFontName Property

Specifies the name of the font used to display text in a Column object. The logical expression is re-evaluated at run time each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicFontName[ = cName]

Property Values

cName
Evaluates to the name of a font.

Remarks

At design time, a list of available fonts is displayed when you select the FontName property in the Properties window and click the down arrow to the right of the Properties Settings box.

See Also

FontName Property | DynamicFontOutline Property | DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Applies To: Column


DynamicFontOutline Property

Specifies whether the text associated with a Column object is outlined. The logical expression is re-evaluated at run time each time the Grid control is refreshed. Available at design time and run time.

Column.DynamicFontOutline[ = "lExpr"]

Property Values

"lExpr"
Evaluates to either true (.T.) or false (.F.). The settings for the DynamicFontOutline property are:
Setting | Description
True (.T.) | The text is outlined.
False (.F.) | (Default) The text is not outlined.

See Also

FontOutline Property | DynamicFontShadow Property | DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Applies To: Column


DynamicFontShadow Property

Specifies whether the text associated with a Column object is shadowed. The logical expression is re-evaluated at run time each time the Grid control is refreshed. Available at design time and run time.

Column.DynamicFontShadow[ = "lExpr"]

Property Values

"lExpr"
Evaluates to either true (.T.) or false (.F.). The settings for the DynamicFontShadow property are:
Setting | Description
True (.T.) | The text is shadowed.
False (.F.) | (Default) The text is not shadowed.

See Also

FontShadow Property | DynamicFontOutline Property | DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Applies To: Column


DynamicFontSize Property

Specifies the font size of text displayed in a Column object. The font size is re-evaluated at run time each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.FontSize[ = "nSize"]

Property Values

"nSize"
Evaluates to a font size. The default font size is 10 points.

Remarks

The maximum value for nSize is 2,048 points. There are 72 points in 1 inch.

Use this property to change the font size of a row.

See Also

DynamicAlignment Property | DynamicFontName Property | DynamicFontBold, DynamicFontItalic, DynamicFontStrikethru, DynamicFontUnderline Properties

Applies To: Column


DynamicInputMask Property

Specifies how data is entered and displayed in a Column object. Re-evaluated at run time each time the Grid control is refreshed. Available at design time; read/write at run time.

Column.DynamicInputMask[ = cInputMask]

Property Values

cInputMask
Specifies the dynamic format of text and controls in a column. cInputMask must evaluate to a character string of the following format:
[@cFunction] [cMask]

The following demonstrates a typical format for cInputMask:

Column1.DynamicInputMask = "@R$ ###,###,###.##"

For additional information about the format of cFunction and cMask, see the Format and InputMask properties.

Remarks

The DynamicInputMask property takes precedence over the Format and InputMask properties.

If the control specified by the column's CurrentControl property is a text box, spinner, or combo box, the Format and InputMask portions of the DynamicInputMask expression are passed to the Format and InputMask properties for the text box, spinner, or combo box.

See Also

Format Property | InputMask Property

Applies To: Column


EditorOptions Property

This application object property specifies the Visual FoxPro Editor options to be enabled.

_VFP.EditorOptions [= cOptionString]

Property Values

cOptionString
Specifies a character string consisting of one or more letters that represent options to enable or disable. The following table describes valid values for cOptionString:
Editor option | cOptionString | Default | Runtime
List Members | l | Off | No
Quick Info | q | Off | No
Auto List Members | L | On | No
Auto Quick Info | Q | On | No
Enable Hyperlinks (CTRL + Click to follow the link) | K | On | Yes
Enable Hyperlinks (Click to follow the link) | k | Off | Yes
DragDrop Between Words | W | Off | No
Designer Value Tips | T | On | No
Note You cannot use the uppercase and lowercase settings of the same letter together in the same cOptionString.

Designer Value Tips ("T") are information tips associated with items in lists and drop-down controls. These include the following:

  • Fields in data source lists (tables and views) in Database, View and Form (Data Environment) designers
  • Methods and events in Form and Class Designer method editor procedure drop-down controls

Remarks

By default, Visual FoxPro enables Auto IntelliSense. To disable automatic activation while maintaining IntelliSense functionality through keyboard shortcuts or menu items, use lowercase instead of uppercase as in the following example:

_VFP.EditorOptions = "lq"   && Disables Auto IntelliSense.
_VFP.EditorOptions = "LQ"    && Enables Auto IntelliSense

You can disable all IntelliSense functionality by setting EditorOptions to the empty string (""). The default settings are "LQKT".

See Also

EDITSOURCE( ) Function | IntelliSense Overview | List Members | Quick Info | Setting Editor Options

Applies To: Application Object | _VFP System Variable


Enabled Property

Specifies whether an object can respond to user-generated events. Available at design time and run time.

Object.Enabled[ = lExpr]

Property Values

lExpr
The settings for the Enabled property are:
Setting | Description
True (.T.) | (Default) An object responds to events.
False (.F.) | An object does not respond to events.

Remarks

The Enabled property allows objects to be enabled or disabled at run time. For example, you can disable objects that do not apply to the current state of the application. You can also disable a control to restrict its use — for example, an edit box can be disabled to display read-only information. If a control is disabled, it cannot be selected.

When a container object has its enabled property set to false (.F.), all of its contained controls are disabled, too. If the user clicks on any of the controls contained in a disabled Form, for example, no events are triggered.

Disabling a Timer control by setting Enabled to false (.F.) cancels the countdown specified by the Timer control's Interval property.

See Also

Click Event | DblClick Event | DragDrop Event | DragOver Event | DropDown Event | KeyPress Event | MouseDown Event | MouseMove Event | MouseUp Event | RightClick Event | Scrolled Event | Undock Event

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


EnableHyperlinks Property

Specifies whether hyperlinks are displayed and enabled within an EditBox or TextBox control. Read/write at design and run time.

Object.EnableHyperlinks [ = lExpr ]

Parameters

lExpr
Logical data type. The following table lists the values for lExpr.
lExpr | Setting
True (.T.) | Enables display and activation of URL hyperlinks within the control.
False (.F.) | Displays hyperlinks support within the control. (Default)

Remarks

Setting the global Enable Hyperlinks option in the Options dialog box affects EnableHyperlinks, which you can set at run time using _VFP.EditorOptions. If you turn off hyperlinks globally, Visual FoxPro disregards EnableHyperlinks and does not activate hyperlinks.

As within the editor, the activation of a hyperlink depends on the _VFP.EditorOptions setting (whether click or CTRL+Click goes to the link).

If a form's ShowTips property is set to True (.T.), Visual FoxPro displays a value tip such as "CTRL+Click to follow link" when you move the mouse over the hyperlink. If a value is specified for the ToolTipText property, Visual FoxPro displays the ToolTip text when your mouse moves over any non-hyperlink portion of the control.

See Also

Properties | Editor Tab, Options Dialog Box | _VFP System Variable | EditorOptions Property | ShowTips Property | ToolTipText Property

Applies To: EditBox Control | TextBox Control


Encrypted Property

Specifies if compiled source code in a project is encrypted.

Object.Encrypted[ = lExpression]

Property Values

lExpression
The settings for the Encrypted property are:
Setting | Description
True (.T.) | The compiled source code is encrypted. Setting lExpression to true (.T.) provides additional protection for your source code, and is identical to including the ENCRYPT argument in the COMPILE command.
False (.F.) | (Default) The compiled source code isn't encrypted.

Remarks

Source code in a project includes program and format files, source code in form, label, report, and visual class libraries, and stored procedures in databases. The Encrypted property corresponds to the Encrypted check box on the Project tab of the Project Information dialog box.

See Also

COMPILE | Project Information Dialog Box

Applies To: Project Object


ErrorNo Property

Specifies the error number for an Exception object. Read/write at run time.

Exception.ErrorNo

Property Value

Numeric data type

Remarks

If the exception results from a THROW command that specifies a value for the eUserExpression parameter, the value of ErrorNo is 2071.

Identical to the value returned by the ERROR() function and the first element in the array produced by the AERROR() function.

See Also

Properties | Exception Object Properties, Methods, and Events | ERROR( ) Function | AERROR( ) Function | SYS(2018) - Error Message Parameter | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


Exclude Property

Specifies if a file is excluded from an application (.app), dynamic link library (.dll), or executable file (.exe) when it is built from a project. Available at design time and run time.

Object.Exclude[ = lExpression]

Property Values

lExpression
Specifies if the file is excluded from an .app, .dll, or .exe when it is built. If lExpression is true (.T.), the file is excluded; otherwise the file is included.

The file type determines the default value for lExpression. For example, tables are automatically excluded when added to a project.

Remarks

Excluded files appear with a slashed circle before their names in the Project Manager. Excluded files are listed in the Project Manager window for your reference, but you must manually distribute them if the application needs them. You can also exclude a file by choosing Exclude in the Project menu.

See Also

Build Method

Applies To: File Object


Exclusive Property

Specifies whether a table associated with a Cursor object is opened exclusively. Available at design time; read/write at run time.

DataEnvironment.Cursor.Exclusive[ = lExpr]

Property Values

lExpr
The settings for the Exclusive property are:
Setting | Description
True (.T.) | (Default) The table associated with the Cursor is opened exclusively when the data environment is loaded.
False (.F.) | The table associated with the cursor is not opened exclusively when the data environment is loaded.

Remarks

Note When the Cursor object is accessed using CURSORSETPROP( ), the Exclusive property is read-only at run time.

When the data environment is loaded, each table associated with a Cursor can be opened exclusively (no other user in a multiuser environment can access the table) or in shared mode. Use the Exclusive property to specify how the table is accessed.

Note If you set the DataSession property to 2 (Private Data Session), the default setting of the Exclusive property for all Cursor objects in the data environment is changed to false (.F.).

For views, the View object itself is always opened in shared mode. However, the tables that define the view are affected by the Exclusive property. For local views, the Visual FoxPro tables that define the view are opened in exclusive or shared mode, depending on the setting of the Exclusive property. The Exclusive property has no effect on remote views.

The Exclusive property mimics the behavior of the USE command's EXCLUSIVE and SHARE clauses.

See Also

DataSession Property | SET EXCLUSIVE | USE

Applies To: Cursor


FetchAsNeeded Property

Specifies how records are fetched. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting FetchAsNeeded applies only to CursorAdapter objects with ODBC or ADO data sources, affects only the next opened cursor, and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.FetchAsNeeded [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Fetch records as needed.
False (.F.) | For CursorAdapter objects with ODBC and ADO data sources, the MaxRecords property determines the number of records fetched. For native and XML data sources, all records are fetched.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function | MaxRecords Property

Applies To: CursorAdapter Class


FetchMemo Property

Specifies whether memo fields are fetched with view results. When handling this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting FetchMemo for applies only to CursorAdapter objects with ODBC or ADO data sources and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.FetchMemo [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Fetch memo fields with view results.
False (.F.) | Do not fetch memo fields with view results.

Remarks

FetchMemo applies primarily for remote views and setting it does not affect local views. However, you can preset this property for local views that will be upsized.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


FetchSize Property

Specifies the number of rows progressively fetched from the remote table result set. When handling this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting FetchSize for applies only to CursorAdapter objects with ODBC or ADO data sources and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.FetchSize [= nValue]

Property Values

nValue
Numeric data type. The nValue parameter has a default value of 100 rows. If nValue is -1, Visual FoxPro retrieves the complete result set, which is limited by the value of the MaxRecords property.

Remarks

FetchSize applies primarily for remote views and setting it does not affect local views. However, you can preset this property for local views that will be upsized.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


FileClass Property

Contains the name of the form class on which a form in a project is based. Read-only at design time and run time.

Object.FileClass

Remarks

The FileClass property applies only to forms in a project, and contains the empty string for other file types.

See Also

FileClassLibrary Property | Type Property

Applies To: File Object


FileClassLibrary Property

Contains the name of the class library containing the class on which a form in a project is based. Read-only at design time and run time.

Object.FileClassLibrary

Remarks

The FileClassLibrary property applies only to forms in a project, and contains the empty string for other file types.

See Also

FileClass Property | Type Property

Applies To: File Object


FillColor Property

Specifies the color used to fill shapes drawn on an object by graphics routines. Available at design time and run time.

Object.FillColor[ = nColor ]
Object.FillColor[ = RGB(nRedValue, nGreenValue, nBlueValue) ]

Property Values

nColor
Specifies a single number to represent the color. By default, FillColor is set to 0 (Black). For more information on color settings, see the BackColor_ForeColor Properties topic.
nRedValue, nGreenValue, nBlueValue
Specifies three separate color intensities that compose the fill color; must be used with the RGB( ) function to consolidate the three color components into one number, which is what the FillColor property is.
Note In the Properties window, you can double-click any of the color properties to display the Color dialog box. You can choose or define colors from this dialog box. The red, green, and blue intensities that correspond to the color you choose become the settings for these properties after you close the Color dialog box.

Remarks

When the FillStyle property is set to its default, 1 (Transparent), the FillColor setting is ignored.

Only an enclosed shape, such as a circle, box, or ellipse can be filled.

Shape objects use the BackColor property to specify the fill color.

See Also

BackColor_ForeColor Properties | BorderColor Property | Box Method | Circle Method | FillStyle Property | ForeColor Property | GETCOLOR( ) | RGB( )

Applies To: Form | _SCREEN | Shape


FillStyle Property

Specifies the pattern used to fill shapes and figures created with the Circle and Box graphics methods. Available at design time and run time.

Object.FillStyle[ = nStyle]

Property Values

nStyle
Specifies the pattern used to fill a shape or figure. The settings for the FillStyle property are:
Setting | Description
0 | Solid.
1 | (Default) Transparent. The FillColor property is ignored.
2 | Horizontal Line.
3 | Vertical Line.
4 | Upward Diagonal. Upward diagonal lines from upper left to lower right.
5 | Downward Diagonal. Downward diagonal from lower left to upper right.
6 | Cross. Crossed vertical and horizontal lines forming squares.
7 | Diagonal Cross.

See Also

BorderStyle Property | Box Method | Circle Method | DrawMode Property | DrawStyle Property | DrawWidth Property | FillColor Property

Applies To: Form | _SCREEN | Shape


Filter Property

Excludes records that do not meet the criteria in the specified expression. Available at design time; read/write at run time.

DataEnvironment.Cursor.Filter[ = cExpr]

Property Values

cExpr
Any Visual FoxPro expression, typically an expression that operates on a set of records.

Remarks

Mimics the behavior of SET FILTER.

Note When the Cursor object is accessed using CURSORSETPROP( ), the Filter property is read-only at run time.

See Also

SET FILTER

Applies To: Cursor | CURSORSETPROP( ) Function


FirstElement Property

Specifies the first element of an array to display in a ComboBox or ListBox control. Available at design time and run time.

Control.FirstElement[ = nElement]

Property Values

nElement
Specifies which element in the array is displayed as the first element in the list.

Remarks

This property is available only when the RowSource is an array (RowSourceType = 5). Note that the FirstElement property only applies to ComboBoxes and ListBoxes with one column.

See Also

NumberOfElements Property | RowSource Property

Applies To: ComboBox | ListBox


Flags Property

Specifies desired flag settings as described by the nFlags parameter in the XMLUPDATEGRAM( ) function. Read/write at design time and run time.

Note Flags applies only when the CursorAdapter DataSourceType property is set to "XML". The CursorAdapter object passes flags specified by the Flags property when constructing an XML UpdateGram. The CursorAdapter object evaluates Flags only once per update operation.
CursorAdapter.Flags [= nFlags]

Property Values

nFlags
Integer data type. The nFlags parameter specifies nFlag settings from the XMLUPDATEGRAM( ) function and has a default value of 0.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | UpdateGram Property

Applies To: CursorAdapter Class


FontBold, FontItalic, FontStrikethru, FontUnderline Properties

Specifies whether text has one or more of the following styles: Bold, Italic, Strikethru, or Underline. Available at design time and run time.

Object.FontBold[ = lExpr]Object.FontItalic
[ = lExpr]Object.FontStrikeThru[ = lExpr]Object.FontUnderline[ = lExpr]

Property Values

lExpr
The settings for the font properties are:
Setting | Description
True (.T.) | Font style is bold, italic, strikethru, or underline.
False (.F.) | (Default except for FontBold) Font style is not bold, italic, strikethru, or underline.

Remarks

In general, change the FontName property before you set size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, and FontUnderline properties. However, when you set TrueType fonts to smaller than 8 points, you should set the point size with the FontSize property, next set the FontName property, and then set the size again with the FontSize property. Windows uses a different font for TrueType fonts that are smaller than 8 points.

Note Fonts that are available vary according to your system configuration, display devices, and printing devices. Font-related properties can be set only to values for which actual fonts exist.
Note The FontBold property does not apply to the Page object.

See Also

FontName Property | FontSize Property | SetAll Method

Applies To: CheckBox | Column | ComboBox | CommandButton | EditBox | Form | Grid | Header | Label | ListBox | OptionButton | Page | _SCREEN | Spinner | TextBox


FontCharSet Property

Specifies the character set, or language script, of the font used to display text for every object that supports fonts. Read/write at design and run time.

Object.FontCharSet [ = nFontCharSet ]

Parameters

Numerical data type. The following table lists the values for FontCharSet.

nFontCharSet | Language script
0 | Standard Windows characters (ANSI)
1 | Default
2 | Symbol
77 | Macintosh
128 | Japanese
129 | Korean
134 | Simplified Chinese
136 | Traditional Chinese
161 | Greek
162 | Turkish
163 | Vietnamese
177 | Hebrew
178 | Arabic
186 | Baltic
204 | Cyrillic
238 | Central European
255 | OEM/DOS

Remarks

When setting the FontCharSet property, you must use a numeric value, not the language script name, for example, Western.

Visual FoxPro attempts to retrieve the character set identifier for the font you specify. If Visual FoxPro cannot find the character set identifier, or if you pass an invalid FontCharSet value for a particular font set, the Windows font manager makes the appropriate substitution using the Default character set, usually ANSI or Symbol.

Fonts support only certain language scripts. To choose a language script that a font can support, select the FontCharSet property in the Properties window and click the ellipsis (…) button that appears to open the Font dialog box. You can select a language script from the Script drop-down list. You can also change the font, size, and style. Visual FoxPro updates the font properties with the changed values.

If you change the font to one for which the current FontCharSet value is not supported, Visual FoxPro resets the FontCharSet property.

If the Style property for a Label is set to 3 (Themed), the FontCharSet property is ignored. If the Themes property is set to True (.T.) for a grid, the FontCharSet property for the grid Header is ignored. To display the grid Header using the FontCharSet property, set Themes of the grid to False (.F.).

The GETFONT( ) function supports the passing or retrieving of a font script.

See Also

Properties | GETFONT( ) Function | Style Property | AFONT( ) Function

Applies To: CheckBox Control | Column Object | ComboBox Control | CommandButton Control | EditBox Control | Form Object | Grid Control | Header Object | Label Object | ListBox Control | OptionButton Control | Page Object | _SCREEN System Variable | Spinner Control | TextBox Control


FontCondense, FontExtend Properties

Available in Visual FoxPro for Macintosh only


FontName Property

Specifies the name of the font used to display text. Available at design time and run time.

Object.FontName[ = cName]

Property Values

cName
Specifies the name of the font. The default is Arial.

Remarks

The default FontSize property setting is 9 points. Available fonts vary according to your system configuration. Font-related properties can be set only to values for which fonts exist. At design time, a list of available fonts is displayed when you select the FontName property in the Properties window and click the down arrow to the right of the Property Settings box.

In general, change FontName before setting size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, and FontUnderline properties.

See Also

FontBold Property | FontItalic Property | FontStrikethru Property | FontUnderline Property | FontSize Property

Applies To: CheckBox | Column | ComboBox | CommandButton | EditBox | Form | Grid | Header | Label | ListBox | OptionButton | Page | _SCREEN | Spinner | TextBox


FontOutline Property

Included for compatibility with the Macintosh.


FontShadow Property

Included for compatibility with the Macintosh.


FontSize Property

Specifies the font size for text displayed with an object. Available at design time and run time.

Object.FontSize[ = nSize]

Property Values

nSize
Specifies the size of the font in points. The default font size is 9 points.

Remarks

The maximum value for nSize is 127 points. There are 72 points in 1 inch.

In general, you should change the FontName property before you set size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, and FontUnderline properties. However, when you set TrueType fonts to smaller than 8 points, you should set the point size with the FontSize property, next set the FontName property, and then set the size again with the FontSize property. The Windows environment uses a different font for TrueType fonts that are smaller than 8 points.

Note Available fonts vary according to your system configuration and printing devices. Font-related properties can be set only to values for which fonts exist.

See Also

FontBold Property | FontItalic Property | FontStrikethru Property | FontUnderline Property

Applies To: CheckBox | Column | ComboBox | CommandButton | EditBox | Form | Grid | Header | Label | ListBox | OptionButton | Page | _SCREEN | Spinner | TextBox


ForceCloseTag Property

Specifies whether to replace single empty element tags with a set of empty element open and close tags. You can use the ForceCloseTag if you search for open and close tags when parsing XML or if you want to increase readability.

ForceCloseTag applies when executing the XMLAdapter ToXML method, which creates XML consistent with its setting.

XMLAdapter.ForceCloseTag [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Does not replace single empty element tags with a set of empty element open and close tags. (Default)
True (.T.) | Replaces single empty element tags with a set of empty element open and close tags.

Example

The following example contains an empty element tag, <col1/>:

<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<VFPData>
   <etest>
      <col1>One</col1>
   </etest>
   <etest>
      <col1/>
   </etest>
</VFPData>

Setting ForceCloseTag to True (.T.) replaces the single empty element tag with a set of valid empty element open and close tags, <col1></col1>.

<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<VFPData>
   <etest>
      <col1>One</col1>
   </etest>
   <etest>
      <col1></col1>
   </etest>
</VFPData>

See Also

Properties | XMLAdapter Object Properties, Methods, and Events

Applies To: XMLAdapter Class


Format Property

Specifies the input and output formatting of a control's Value property. Available at design time and run time.

Control.Format[ = cFunction]

Property Values

cFunction
Specifies the character constraints for data entry and formatting for display.

The valid cFunction settings for an EditBox control are:

Setting | Description
K | Selects all the text when the control gets the focus.

The valid cFunction settings for a Spinner control are:

Setting | Description
$ Displays the currency symbol.
^ Displays numeric data using scientific notation.
K | Selects all the text when the control gets the focus.
L | Displays leading zeros (instead of spaces) in the text box.
R | Displays the format mask for the text box that is specified in the InputMask property. The mask formats data for easier entry and clearer display (for example, if the mask is 99-999, the number 12345 is displayed as 12-345), but is not stored as part of the data. Use only with character or numeric data.
Z | Displays the value as blank if it is 0, except when the control has the focus.

The valid cFunction settings for a TextBox control and Column object are:

Setting | Description
! Converts alphabetic characters to uppercase. Use with Character data only.
$ Displays the currency symbol. The ControlSource property must specify a numeric source for the text box.
^ Displays numeric data using scientific notation. The ControlSource property must specify a numeric source for the text box.
A | Allows alphabetic characters only (no spaces or punctuation marks).
D | Uses the current SET DATE format.
E | Edits Date values as British dates.
K | Selects all the text when the control gets the focus.
L | Displays leading zeros (instead of spaces) in the text box. The ControlSource property must specify a numeric source for the text box.
M | Included for backward compatibility.
R | Displays the format mask for the text box that is specified in the InputMask property. The mask formats data for easier entry and clearer display (for example, if the mask is 99-999, the number 12345 is displayed as 12-345), but is not stored as part of the data. Use only with character or numeric data.
T | Trims leading and trailing blanks from the input field.
YS | Displays Date values in a short date format determined by the Windows Control Panel short date setting.
YL | Displays Date values in a long date format determined by the Windows Control Panel long date setting.

Remarks

The Format property mimics the behavior of the FUNCTION clause for the @ ... GET and @ ... EDIT commands.

The Format property specifies a behavior for the entire input field. You can mix several Format codes, but they always affect everything in the input field. This property contrasts to the InputMask property in which each entry in the input mask corresponds to an entry in the input field.

See Also

DynamicInputMask Property | InputMask Property

Applies To: Column | ComboBox | EditBox | Spinner | TextBox


FormattedOutput Property

Generates XML as formatted output or as a single continuous string.

FormattedOutput applies when executing the XMLAdapter ToXML method, which creates XML consistent with its setting.

XMLAdapter.FormattedOutput [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Display XML as formatted output. (Default)
False (.F.) | Display XML output as a single continuous string.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | ToXML Method

Applies To: XMLAdapter Class


FormCount Property

Contains the number of forms in a form set. Not available at design time; read-only at run time.

Object.FormCount

Remarks

You can use this property to cycle through all the forms in a form set and do some action.

See Also

Forms Property

Applies To: FormSet | _SCREEN


Forms Property

An array to access individual forms in a form set. Not available at design time; read-only at run time.

Object.Forms(nIndex)

Property Values

nIndex
Uniquely identifies a form in a form set.

Remarks

Use the Forms property to change the property settings of forms in a form set without using the Name property of the forms. You can use the Forms property in conjunction with the FormCount property to step through all the forms in a form set and perform an action. For example, the following code changes the captions of all the forms in a form set:

FOR x = 1 TO THISFORMSET.FormCount
   THISFORMSET.Forms(x).Caption = THISFORMSET.Forms(x).Caption;
      + "[Read Only]"
ENDFOR

See Also

FormCount Property | Objects Collection

Applies To: FormSet | _SCREEN


FractionDigits Property

For Numeric data types, FractionDigits specifies the number of digits to the right of the decimal point.

XMLField.FractionDigits

Property Values

Numeric data type. FractionDigits specifies the number of digits to the right of the decimal point. If none exists or if FractionDigits is not applicable, the value of FractionDigits is -1.

See Also

Properties | XMLField Object Properties, Methods, and Events | Visual FoxPro and XML Schema Data Type Mapping

Applies To: XMLField Class


FullName Property

Contains the file name of an instance of Visual FoxPro and the name of the directory from which the instance of Visual FoxPro was started. Read-only at run time.

ApplicationObject.FullName

Remarks

Use the FullName property to determine the directory from which an instance of Visual FoxPro was started.

See Also

HOME( )

Applies To: Application Object | _VFP System Variable


GridLineColor Property

Specifies the color of the lines separating cells in a Grid control. Available at design time; read/write at run time.

Grid.GridLineColor[ = nColor]

-or-

Grid.GridLineColor = RGB(nRedValue, nGreenValue, nBlueValue)

Property Values

nColor
Specifies a single number to represent the color. By default, GridLineColor is set to 0 (Black).
nRedValue, nGreenValue, nBlueValue
Specifies three separate color intensities that compose the Grid's line color; must be used with the RGB( ) function to consolidate the three color components into one number, which is what the GridLineColor property is.
Note the Properties window, you can double-click any of the color properties to display the Color dialog box. You can choose or define colors from this dialog box. The red, green, and blue intensities that correspond to the color you choose become the settings for these properties after you close the Color dialog box.

See Also

GridLines Property | GridLineWidth Property

Applies To: Grid


GridLines Property

Determines whether horizontal and vertical lines are displayed in the Grid control. Available at design time; read/write at run time.

Grid.GridLines[ = nSetting]

Property Values

nSetting
The settings for the GridLines property are:
Setting | Description
0 | None. No grid lines.
1 | Horizontal. Horizontal grid lines only.
2 | Vertical. Vertical grid lines only.
3 | (Default) Both. Both horizontal and vertical grid lines.

See Also

GridLineColor Property | GridLineWidth Property

Applies To: Grid


GridLineWidth Property

Specifies the thickness, in pixels, of the lines separating cells in a Grid control. Available at design time; read/write at run time.

Grid.GridLineWidth[ = nWidth]

Property Values

nWidth
Specifies the thickness of the line separating cells in a Grid control. The default value for nWidth is 1, and the minimum and maximum values are 1 and 40 respectively.

See Also

GridLineColor Property | GridLines Property

Applies To: Grid


HalfHeightCaption Property

Specifies whether the caption of a form is half the normal height. Available at design time and run time.

Object.HalfHeightCaption[ = lExpr]

Property Values

lExpr
The settings for the HalfHeightCaption property are:
Setting | Description
True (.T.) | The form's caption is half the normal height.
False (.F.) | (Default) The form's caption is normal height.

See Also

Caption Property

Applies To: Form | _SCREEN | Height Property


HeaderClass Property

Specifies the name of the member class to use when adding new header member objects to a Column container. Read/write at design time and run time.

The HeaderClass property is used instead of MemberClass for a Column parent container. For more information about the MemberClass property, see MemberClass Property.

Note If the member class is based on a class that is stored in a program (.prg) file, make sure that the compiled program (.fxp) file is synchronized with the .prg file.
Column.HeaderClass [ = cClassName ]

Property Values

cClassName
Specifies the name of a member class in a program (.prg) file.

Remarks

You cannot edit or create a subclass of the Header class in a visual class library (.vcx). You need to use a program (.prg) file to define a Header class.

The Column class can contain only one header; therefore, no header count property is associated with the column.

At run time, changing the HeaderClassLibrary and HeaderClass properties at run time does not affect the header. You can change the header only by using the AddObject or NewObject methods, which replaces the current header with the new header.

See Also

Member Classes | MemberClass Property | HeaderClassLibrary Property | AddObject Method | NewObject Method

Applies To: Column Object


HeaderClassLibrary Property

Specifies the class library containing the member class associated with the HeaderClass property. Read/write at design time and run time.

HeaderClassLibrary is used instead of MemberClassLibrary for a Column parent container. For more information, see MemberClassLibrary Property.

Column.HeaderClassLibrary [= cClassFile]

Property Values

Character string. The cClassFile parameter specifies the program (.prg) file name containing the member class definition specified by HeaderClass.

Remarks

Visual FoxPro includes the HeaderClassLibrary program (.prg) in the project during a project build.

If you set HeaderClassLibrary at run time, you must use the full file name including its extension.

See Also

Member Classes | HeaderClass Property | MemberClassLibrary Property | MemberClassLibrary Property

Applies To: Column Object


HeaderHeight Property

Specifies the height of column headers in the Grid control. Available at design time; read/write at run time.

Header.HeaderHeight[ = nHeight]

Property Values

nHeight
The height of the header, specified in pixels.

See Also

ScaleMode Property | Height Property | HEADER( ) Function

Applies To: Grid


Height Property

Specifies the height of an object on the screen. Available at design time and run time.

Object.Height[ = nHeight]

Property Values

nHeight
Specifies the object's height measured in the unit of measurement specified by the ScaleMode property of the form.

Remarks

For forms, the Height measurement does not include the borders and title bar. Also, if the ScrollBars property is set to enable scroll bars, Height does not include space taken up by the scroll bar when it appears.

For controls, the height is measured from the outside of the control's border.

The value for this property changes as the object is sized by the user or by code.

Use the Height and Width properties for calculations based on an object's total area.

Note The Height property is read-only when it applies to a control contained in a Column object.

Example

The following example demonstrates how the Height property is used specify the height of three command buttons on a form.

The AddObject method is used to add a Line control and three command buttons to a form. The Height property specifies the vertical height of each command button.

frmMyForm = CREATEOBJECT('form')  && Create a form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

Left Property | Move Method | ScaleMode Property | Top Property | Width Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Custom | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


HelpContextID Property

Specifies a context ID for a topic in a Help file to provide context-sensitive Help for the object. Available at design time and run time.

Object.HelpContextID[ = nContextID]

Property Values

nContextID
Specifies the context ID number of a topic in a Help file. The valid range for context ID numbers is range 0 to 268,435,455.

Remarks

To create context-sensitive Help for an object in your application, you must assign the same context number to both the object and the associated Help topic when you create the Help file.

If you have created Help for your application, Visual FoxPro calls the Help file and requests the topic identified by the current context ID number. You can specify a Help file with SET HELP TO, and you can specify a key to activate the Help file with ON KEY LABEL. The Help compiler required to create graphical-style help is included with Visual FoxPro.

The current context ID number is the setting of the HelpContextID property for the object that has the focus. If a nonzero current context number is not found, the main contents screen of the Help file is displayed.

For a server object, the HelpContextID property specifies the context ID for the type library created for the server. The ServerHelpFile property specifies the Help file containing the help topic corresponding to the context ID.

See Also

ServerHelpFile Property | SET HELP | SET TOPIC

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | _SCREEN | Server Object | Shape | Spinner | TextBox | ToolBar


HideSelection Property

Specifies whether selected text appears selected when a control loses focus. Available at design time and run time.

Control.HideSelection[ = lExpr]

Property Values

lExpr
The settings for the HideSelection property are:
Setting | Description
True (.T.) | (Default) Selected text does not appear selected when the control loses the focus.
False (.F.) | Selected text appears selected when the control loses the focus.

Remarks

You can use this property to indicate the text that is selected while another form or a dialog box has the focus — for example, in a spelling-check routine.

See Also

DisabledBackColor, DisabledForeColor Properties | GotFocus Event | LostFocus Event

Applies To: ComboBox | EditBox | Spinner | TextBox


Highlight Property

Specifies whether the cell with the focus in a Grid control appears selected. Available at design time and read/write at run time.

Grid.Highlight [= lExpr ]

Property Values

lExpr
The settings for the Highlight property are:
Setting | Description
True (.T.) | The cell is marked (highlighted) as selected. (Default)
False (.F.) | The cell is not selected.

Remarks

If the HighLight property is set to true (.T.), you can use it in conjunction with a Column's SelectOnEntry property to determine if the entire cell appears selected. If you set the HighLight property to false (.F.), the SelectOnEntry property is ignored.

See Also

HighlightRow Property | SelectOnEntry Property | HighlightForeColor Property | HighlightBackColor Property | HighlightStyle Property

Applies To: Grid Control


HighlightBackColor Property

Specifies the background color of a Grid row when it is selected. A grid's HighlightBackColor property applies only when the grid's HighlightStyle property is set to a value greater than 0. Read/write at design and run time.

Grid.HighlightBackColor [= nColor ]

Parameters

nColor
Numeric data type. HighlightBackColor specifies an integer representing a single color value. Visual FoxPro derives the default color setting from the Windows operating system color setting for Selected Items. For more information about valid color values, see BackColor, ForeColor Properties.

Remarks

If HighlightStyle contains a value greater than 0, Visual FoxPro defaults to displaying HighlightBackColor as a 50% lighter gradient fill. If you override the HighlightBackColor setting, Visual FoxPro does not apply any gradient effect.

For more information, see HighlightForeColor Property.

See Also

Properties | HighlightStyle Property | AllowCellSelection Property | HighlightBackColor Property | ResetToDefault Method | DynamicBackColor, DynamicForeColor Properties | Highlight Property | HighlightRow Property | HighlightStyle Property

Applies To: Grid Control | BROWSE Command


HighlightForeColor Property

Specifies the foreground or highlight color of the text in a Grid row when it is selected. A grid's HighlightForeColor property applies only when the grid's HighlightStyle property is set to a value greater than 0. Read/write at design and run time.

Grid.HighlightForeColor [= nColor ]

Parameters

nColor
Numeric data type. HighlightForeColor specifies an integer representing a single color value. Visual FoxPro derives the default color setting from the Windows operating system font color setting for Selected Items. For information about valid color values, see BackColor, ForeColor Properties.

Remarks

In Windows XP, you can find the Selected Items font color setting in the Advanced Appearance dialog box. To open the Advanced Appearance dialog box, right-click the Windows desktop, click Properties. In the Display Properties dialog box, click the Appearance tab, then Advanced, and select Selected Items from the Item list. The operating system font color is specified in the Color box to the right of the Font box.

In Windows 2000, you can set the font color for Selected Items information on the Appearance tab.

Note Changing the font color for Selected Items changes the setting for all applications.

You can select a color by typing the RGB value in the Properties window property settings box or display the Color dialog box by double-clicking the property in the Properties window properties list. The RGB value for the color you select in the Color dialog box becomes the setting after you close the Color dialog box.

After setting HighlightStyle to a value greater than 0, highlighting remains in effect until HighlightStyle is set to 0. If HighlightStyle is set to a value of 2, only the highlight colors persist. Selected items display only when a grid has focus.

Highlighting affects all cells in a row except the currently selected one, unless the grid's AllowCellSelection property is set to False (.F.), and overrides color property settings such as BackColor and DynamicBackColor settings for any column in the grid.

The following example shows how you can interchange the Windows Selected Items and Selected Items font colors for HighlightForeColor and HighlightBackColor:

tmpColor1 = THIS.GrdCustomer.HighlightBackcolor
tmpColor2 = THIS.GrdCustomer. HighlightForecolor
THIS.GrdCustomer.HighlightBackcolor= tmpColor2
THIS.GrdCustomer.HighlightForecolor=tmpColor1

See Also

Properties | HighlightStyle Property | AllowCellSelection Property | HighlightBackColor Property | ResetToDefault Method | DynamicBackColor, DynamicForeColor Properties | Highlight Property | HighlightRow Property | HighlightStyle Property

Applies To: Grid Control | BROWSE Command


HighlightRow Property

Specifies whether the current row and cell in a Grid control is highlighted. Available at design time and read/write at run time.

Grid.HighlightRow [= lExpr]

Property Values

lExpr
The settings for the HighlightRow property are:
Setting | Description
True (.T.) | Current row and cell are highlighted. (Default)
False (.F.) | Current row and cell are not highlighted.

See Also

Highlight Property | HighlightForeColor Property | HighlightBackColor Property | HighlightStyle Property

Applies To: Grid Control


HighlightRowLineWidth Property

Specifies the thickness of the border around the selected Grid row.

Grid.HighlightRowLineWidth [= nValue]

Parameters

nValue
Specifies the horizontal line thickness of the border in pixels. The minimum value is 0, the maximum value is 7, and the default value is 1. The vertical line thickness is not displayed at design time, but is a run time visual effect.

Remarks

This property is effective only when the HighlightRow property is set to True (.T.).

See Also

HighlightRow Property

Applies To: Grid


HighlightStyle Property

Specifies whether the selected row in a Grid remains highlighted when changing the focus to another control in the form. Read/write at design and run time.

HighlightStyle works with the HighlightForeColor and HighlightBackColor properties in determining whether the selected row is highlighted, and whether it remains highlighted when you press the TAB key to move around in the grid, or when you click outside the grid to move focus to another control.

Grid.HighlightStyle [ = nValue ]

Parameters

nValue
Numerical data type. The following table describes the settings for nValue.
nValue
0 | No color highlighting for grid row (Default)
1 | Enable highlighting for current row.
2 | Enable highlighting for current row and persist when grid is not the current active control.

Remarks

If HighlightStyle contains a value greater than 0, the default color of HighlightBackColor appears as a 50% lighter gradient fill.

If HighlightStyle is set to a value of 2, only the highlight colors persist. Selected items display only when a grid has focus.

If a column's Sparse property is set to False (.F.), the column will not be highlighted, when the grid's HighlightStyle property is set to 1 or 2.

See Also

Properties | HighlightForeColor Property | Highlight Property | HighlightBackColor Property | HighlightRow Property

Applies To: Grid Control


HomeDir Property

Specifies the home directory for a project.

Object.HomeDir[ = cDirectory]

Property Values

cDirectory
Specifies the home directory for the project. The default value is the directory in which the project file (.pjx) is located.

Remarks

The home directory for a project is the relative path for all the files in the project. The HomeDir property corresponds to the directory in the Home text box on the Project tab of the Project Information dialog box.

See Also

CURDIR( ) | Project Information Dialog Box

Applies To: Project Object


HostName Property

Returns or sets the user-readable host name of your Visual FoxPro application. Available at design time; read/write at run time.

Control.HostName [ = cName]

Property Values

cName
Returns or sets a string expression specifying the host name.

Remarks

When editing an object, the HostName property setting can be displayed in the object's window title. However, some applications that provide objects do not display the HostName.

See Also

DocumentFile Property

Applies To: OLE Bound Control | OLE Container Control


Hours Property

Specifies whether the hours portion of a DateTime value is displayed in 12- or 24-hour time format. Available at design time and run time.

Object.Hours[ = nValue]

Property Values

nValue
One of the following settings:
Setting | Description
0 | (Default) The SET HOURS setting determines whether the hours portion of a DateTime value is displayed in 12- or 24-hour time format. If SET HOURS is 12, the hours portion of a DateTime value is displayed in 12-hour time format. If SET HOURS is 24, the hours portion of a DateTime value is displayed in 24-hour time format.
12 | The hour portion of the DateTime value is displayed in a 12-hour time format.
24 | The hour portion of the DateTime value is displayed in a 24-hour time format.

Remarks

The Hours property setting is ignored if the DateFormat property is set to Short or Long.

See Also

Century Property | DateFormat Property | DateMark Property | Seconds Property | SET HOURS | StrictDateEntry Property

Applies To: TextBox


HScrollSmallChange Property

Specifies the increment a form scrolls in the horizontal direction when you click on a horizontal scroll arrow. Available at design time and run time.

Object.HScrollSmallChange[ = nExpression]

Property Values

nExpression
Specifies the increment for horizontal scrolling. The unit of measure is determined by the Scalemode property setting. The default increment is 10 pixels when the Scalemode property is set to 3 - Pixels.

See Also

ScaleMode Property | ScrollBars Property | VScrollSmallChange Property

Applies To: Form


hWnd Property

Returns a handle to Forms and user-defined Toolbar objects.

Object.hWnd

Remarks

The Microsoft Windows operating environment identifies each form in an application by assigning it a handle, or hWnd. The hWnd property is used with Windows API calls. Many Windows operating environment functions require the hWnd of the active window as an argument.

Because the value of this property can change while a program is running, you cannot rely on its value (e.g., when stored in a variable).

hWnd is available in user-defined Forms and Toolbar objects and is read-only at both run and design-time.

See Also

Form Object | Toolbar Object | _WhToHwnd( ) API Library Routine


Icon Property

For forms, specifies the icon displayed for a form at run time when the form is minimized. Available at design time and run time.

For a project object, specifies the icon displayed for a distributed .exe application.

Object.Icon[ = cFileName]

Property Values

cFileName
For a form, specifies the file name and path of the icon to display when the form is minimized. For a distributed .exe application, specifies the file name and path of the icon displayed for the application.

Remarks

For forms, use the Icon property to specify a custom icon for any form that the user can minimize at run time. For example, you can assign a unique icon to a form to indicate the form's function. Enter the file name of the icon in the Properties window at design time. The file name you enter must have the .ico extension and icon format. If you do not specify a custom icon, the Visual FoxPro default icon for forms is used.

You can use the Microsoft Visual FoxPro Icon Library in HOME( )+"graphics\icons" as a source for icons.

Note If you set the Icon property at design time and the file you specify does not exist, Visual FoxPro displays an error message, but the property remains set to the file you specified. Visual FoxPro ignores the Icon property at run time if it is set to a file that does not exist.

For a project object, use the Icon property to specify the icon displayed for a distributed .exe application. You cannot specify an icon for a distributed Visual FoxPro .app application.

See Also

Caption Property | Picture Property

Applies To: Form | Project Object | _SCREEN


IMEMode Property

Specifies the Input Method Editor (IME) window setting for an individual control. Available at design time and run time.

Object.IMEMode[ = nExpression]

Property Values

nExpression
One of the following settings:
nExpression | IME window action
0 | (Default) No Control. The operating system determines if the IME window is opened when the control has the focus. If the IME window is closed when the control has the focus, the IME window can be opened by pressing the key combination that activates the IME window.
1 | Open IME. The IME window is opened when the control has the focus.
2 | Close IME. The IME window is closed when the control has the focus. The IME window can be opened by pressing the key combination that activates the IME window.

Remarks

This property is ignored unless you are running an East Asia version of a supported version of Microsoft Windows.

See Also

Entering International Data | IMESTATUS( ) | SET BROWSEIME

Applies To: ComboBox | EditBox | TextBox


Increment Property

Specifies how much the value in the Spinner control increases or decreases when you click the up or down arrow. Available at design time and run time.

Spinner.Increment[ = nIncrement]

Property Values

nIncrement
Specifies the number to add to the Spinner when the up button is clicked and the number to subtract from the Spinner when the down button is clicked. The default is 1.00.

See Also

RangeLow Event | IncrementalSearch Property

Applies To: Spinner


IncrementalSearch Property

Specifies whether a control supports an incremental search for keyboard steering. Available at design time and run time.

Control.IncrementalSearch[ = lExpr]

Property Values

lExpr
The settings for the IncrementalSearch property are:
Setting | Description
True (.T.) | (Default) Supports incremental search.
False (.F.) | Does not support incremental search.

Remarks

An example of an incremental search is if you are searching for the word "ELASTIC," you can type E-L-A, and so on. As you type, Visual FoxPro incrementally searches for the combination of letters you have typed to match the word you are looking for. Otherwise, it finds the first word that starts with an E, then the first word that starts with an L, and so on.

Note that the setting of the _INCSEEK System Variable system variable determines how long to wait for the next letter to be typed. You may need to adjust the value of _INCSEEK to make incremental searching work properly.

A combo box with the Style property set to 0 (Dropdown Combo) will only show incremental searching in the text box if the drop-down list is shown. With the Style property set to 2 (Dropdown List), incremental searching will show in the text box, regardless of whether the drop-down list is shown.

See Also

ComboBox | _INCSEEK System Variable | ListBox

Applies To: ComboBox | ListBox


InitialSelectedAlias Property

Specifies an alias associated with a Cursor object as the current alias when the data environment is loaded. Available at design time; read-only at run time.

DataEnvironment.InitialSelectedAlias[ = cText]

Property Values

cText
Specifies an alias name associated with a Cursor object.

Remarks

Mimics the behavior of SELECT.

See Also

Alias Property | SELECT

Applies To: DataEnvironment


InputMask Property

Specifies how data is entered and displayed in a control. Available at design time and run time.

Control.InputMask[ = cMask]

Property Values

cMask
The settings for the InputMask property are:
Setting | Description
! Converts lowercase letters to uppercase letters.
# Digits, blanks, and signs.
$ The current currency symbol (specified with SET CURRENCY) in a fixed position.
$$ Floating currency symbol that is always adjacent to the digits in the spinner or text box.
, Current Digit grouping symbol setting of the Windows Regional Options Control panel.
. Current SET POINT character (Default = period (.)).
9 | Digits and signs, such as a minus ( – ) sign can be entered.
A | Alphabetic characters only.
L | Logical data only.
N | Letters and digits only.
X | Any character can be entered.
Y | Y, y, N, and n for the logical values true (.T.) and false (.F.), respectively.

Remarks

This property is in contrast to the Format property in which a behavior for the entire input field is specified. You can mix several Format codes, but they always affect everything in the input field.

See Also

DynamicInputMask Property | Format Property

Applies To: Column | ComboBox | Spinner | TextBox


InsertCmd Property

Specifies the command to use for inserting new rows. Read/write at design time and run time.

CursorAdapter.InsertCmd [ = cCommand ]

Property Values

cCommand
Character data type. The following table lists the possible values for cCommand.
cCommand | Description
Character string or expression | Specifies a valid command string for the data source in the InsertCmdDataSource property.
Empty string ("") The CursorAdapter object generates a SQL INSERT command automatically if the AllowInsert property is set to True (.T.).

For more information about generating SQL commands automatically, see Data Access Management Using CursorAdapters.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


InsertCmdDataSource Property

Specifies the data source to use for the InsertCmd property. Read/write at design time and run time.

Note The CursorAdapter InsertCmdDataSource property determines how the InsertCmdDataSource property is used.
CursorAdapter.InsertCmdDataSource [= cDataSource]

Property Values

cDataSource
Character data type. The cDataSource parameter specifies the data source used by the InsertCmd property.

Remarks

The following table describes behaviors that apply to InsertCmdDataSource depending on the value of InsertCmdDataSourceType.

InsertCmdDataSourceType | InsertCmdDataSource behavior
Empty ("") InsertCmdDataSource is disregarded. Visual FoxPro uses the data source in the CursorAdapter DataSource property.

However, if the cursor associated with the CursorAdapter object is based on an ActiveX Data Object (ADO) RecordSet, Visual FoxPro uses the functionality of the ADO RecordSet to insert the record. To use this functionality, make sure the CursorAdapter DataSourceType property is set to "ADO".
"ADO" InsertCmdDataSource must be set to a valid ADO Command object. The ActiveConnection property of the ADO Command object must be set to a valid and open ADO Connection object.

Visual FoxPro sets the CommandText property of the ADO Command object to the value of the CursorAdapter InsertCmd property. Visual FoxPro parses the command for parameters, creates parameter values if found, and sets them in the Command object.

The insert operation occurs as:

CursorAdapter.InsertCmdDataSource.Execute()

For more information about using an ADO RecordSet, automatic updating, and generating SQL commands automatically, see Data Access Management Using CursorAdapters.
"XML" | Visual FoxPro disregards the CursorAdapter DataSource property.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


InsertCmdDataSourceType Property

Specifies the data source type of the data source in the InsertCmdDataSource property. Read/write at design time and run time.

CursorAdapter.InsertCmdDataSourceType [= cDataSourceType]

Property Values

cDataSourceType
Character data type. The cDataSourceType parameter specifies the data source type of the data source in the InsertCmdDataSource property.

Remarks

If InsertCmdDataSourceType is empty ("") or null (.NULL.), Visual FoxPro disregards the CursorAdapter InsertCmdDataSource property and uses the CursorAdapter DataSource and DataSourceType properties.

To generate an XML UpdateGram, you must set the value of InsertCmdDataSourceType to "XML".

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | UpdateGram Property

Applies To: CursorAdapter Class


Instancing Property

Specifies how a server in a project can be instantiated. Available at design time and run time.

Object.Instancing[ = nExpression]

Property Values

nExpression
Specifies how the server can be instantiated. The following table lists the values for nExpression with a description of each.
Settings | FoxPro.h constant | Description
0 | SERVERINSTANCE_NOTCREATABLE | Makes it possible for you to create instances of the class only inside Visual FoxPro.
1 SERVERINSTANCE_SINGLEUSE (Default) Makes it possible for you to create an instance of the class both inside Visual FoxPro and outside of Visual FoxPro using Automation.

Each request for an instance of the class by an automation client outside of the project causes a separate copy of the automation server to start.
2 SERVERINSTANCE_MULTIUSE Makes it possible for you to create an instance of the class both inside Visual FoxPro and outside of Visual FoxPro using Automation.

Each request for an instance of the class by an automation client outside of the project causes an already running copy of the automation server to be provided as the source for the new instance.

See Also

GETOBJECT( ) Function | ServerClass Property | ServerClassLibrary Property

Applies To: Server Object


IntegralHeight Property

Specifies that the height of an EditBox or ListBox control is automatically adjusted so the last item in the control is properly displayed. Specifies that the height of a TextBox control is adjusted to accommodate one line of text. Available at design time; read-only at run time.

Object.IntegralHeight[ = lExpr]

Property Values

lExpr
One of the following:
lExpr | Description
True (.T.) | The height an EditBox or ListBox control is adjusted as necessary so the last item in the control is properly displayed. The height of a TextBox is adjusted to accommodate one line of text.
False (.F.) | (Default) The height of an EditBox or ListBox isn't adjusted, allowing the last item in the control to be improperly displayed. The height of a TextBox isn't adjusted to accommodate one line of text.

Remarks

The last line of text in an EditBox or ListBox control might be partially displayed if the control isn't the proper height. For example, the height of the control may be such that only the top half of the last item is displayed in the control. Set IntergralHeight to true (.T.) to automatically adjust the height of the control so the last item in the control is always properly displayed.

For a TextBox, set IntergralHeight to true (.T.) to ensure that the control automatically adjusts its height when its FontSize property is changed.

When the IntegralHeight property is set to true (.T.), the value of the Height property might not match the actual height of the control.

See Also

Height Property

Applies To: EditBox | ListBox | TextBox


Interval Property

Specifies the number of milliseconds between calls to a Timer control's Timer event. Available at design time and run time.

Timer.Interval[ = nTime]

Property Values

nTime
Specifies the number of milliseconds between Timer events. The default value is 0, which prevents the Timer event from firing.

Remarks

For more information about the Interval property, see "Initializing a Timer Control" in Performing Specific Actions at Given Intervals .

See Also

Reset Method | Timer Event

Applies To: Timer


IsAttribute Property

Specifies whether the field is represented as an Attribute in the associated XML document.

XMLField.IsAttribute [= lValue]

Property Values

Logical data type. The following table lists values for lValue.

lValue | Description
False (.F.) | The field is in Element form, not Attribute form, in the associated XML document. (Default)
True (.T.) | The field is represented as an Attribute in the associated XML document.

See Also

Properties | XMLField Object Properties, Methods, and Events

Applies To: XMLField Class


IsBase64 Property

Specifies whether the field in the XML document is encoded as base64 or hexBinary.

XMLField.IsBase64 [= lValue]

Property Values

Logical data type. The following table lists values for lValue.

lValue | Description
False (.F.) | The field is encoded as hexBinary. (Default)
True (.T.) | The field is encoded as base64.

Remarks

IsBase64 applies only when the IsBinary property is True (.T.).

See Also

Properties | XMLField Object Properties, Methods, and Events | IsBinary Property

Applies To: XMLField Class


IsBinary Property

Specifies whether the field is Binary in the XML Schema.

XMLField.IsBinary [= lValue]

Property Values

Logical data type. The following table lists values for lValue.

lValue | Description
False (.F.) | The field is not Binary but String in the XML Schema. (Default)
True (.T.) | The field is specified as Binary in the XML Schema.

Remarks

For the IsBase64 property to apply, IsBinary must be True (.T.).

See Also

Properties | XMLField Object Properties, Methods, and Events

Applies To: XMLField Class


IsDiffGram Property

Indicates whether the XMLAdapter object is associated with a .NET DiffGram. Read/write.

Note Setting the IsDiffGram property does not actually alter the associated XML document.
XMLAdapter.IsDiffGram [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | The XMLAdapter object is not a .NET DiffGram. (Default)
True (.T.) | The XMLAdapter object is a .NET DiffGram.

Remarks

XMLAdapter detects whether imported XML is a DiffGram and sets IsDiffGram. When creating and generating XML from tables and executing the XMLAdapter ToXML method, Visual FoxPro checks IsDiffGram and creates XML consistent with its setting.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | ToCursor Method | ToXML Method

Applies To: XMLAdapter Class


IsLoaded Property

Indicates whether the XMLAdapter object is associated with an XML document. Read-only.

XMLAdapter.IsLoaded [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | XMLAdapter is not associated with an XML document. (Default)
True (.T.) | XMLAdapter is associated with an XML document.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events

Applies To: XMLAdapter Class


IsNull Property

Specifies whether the field in the XML document supports null values.

XMLField.IsNull [= lValue]

Property Values

Logical data type. The following table lists values for lValue.

lValue | Description
False (.F.) | The field does not support null values. (Default)
True (.T.) | The field supports null values.

See Also

Properties | XMLField Object Properties, Methods, and Events

Applies To: XMLField Class


ItemBackColor, ItemForeColor Properties

Specifies the background or foreground color used to display the text of items in a ComboBox or ListBox control. Available at design time and run time.

Control.ItemBackColor [= nColor ]
-or-
Control.ItemBackColor = RGB( nRedValue, nGreenValue, nBlueValue )
Control.ItemForeColor [ = nColor ]
-or-
Control.ItemForColor = RGB( nRedValue, nGreenValue, nBlueValue )

Property Values

nColor
Specifies an integer that represents the color of the text. For more information, see the color table in the BackColor_ForeColor Properties topic.

Remarks

To choose or define colors, double-click any of the color properties in the Properties window to display the Color dialog box. The red, green, and blue color values corresponding to the color you choose become the settings for these properties after you close the Color dialog box.

See Also

BackColor, ForeColor Properties

Applies To: ComboBox Control | ListBoxControl


ItemData Property

Uses an index to reference a one-dimensional array that contains the same number of items as a ComboBox or ListBox control's List property setting. Not available at design time; read/write at run time.

Control.ItemData(nIndex)[ = nData]

Property Values

nIndex
Specifies the index of the item to store or retrieve. The nIndex corresponds to the display order of the items in the list.
nData
The number to store or retrieve from the ItemData list.

Remarks

Use the ItemData property to associate a specific number with each item in a combo box or list box. You can then use these numbers in code to identify the items in the list. For example, you can use an identification number to identify each employee name in a list box. When you fill the list box, also fill the corresponding elements in the ItemData array with the employee numbers.

Note When you insert an item into a list with the AddItem method, an item is automatically allocated in the ItemData array as well. However, the value is not initialized; it retains the value that was in that position before you added the item to the list. When you use the ItemData property, be sure to set each element's value when adding new items to a list.

See Also

AddItem Method | ItemIDToIndex Method | List Property | ListItemID Property | NewItemID Property | RemoveItem Method | Selected Property | TopItemID Property

Applies To: ComboBox | ListBox


ItemIDData Property

Uses a unique identification number to reference a one-dimensional array that contains the same number of items as a ComboBox or ListBox control's List property setting. Not available at design time; read/write at run time.

Control.ItemIDData(nItemID)[ = nData]

Property Values

nItemID
Specifies the item ID, a unique identification number.
nData
The number to store or retrieve from the ItemIDData list.

Remarks

Use the ItemIDData property to associate a specific number with each item in a combo box or list box. You can then use these numbers in code to identify the items. For example, you can use an identification number to identify each employee name in a list box. When you fill the list box, also fill the corresponding elements in the ItemIDData array with the employee numbers.

Note When you insert an item into a list with the AddItem method, an item is automatically allocated in the ItemIDData array as well. However, the value is not initialized; it retains the value that was in that position before you added the item to the list. When you use the ItemIDData property, be sure to set each element's value when adding new items to a list. This is the same array that is accessed by the ItemData Property.

See Also

IndexToItemID Method | List Property | ListItemID Property | NewItemID Property | RemoveItem Method | Selected Property | TopItemID Property

Applies To: ComboBox | ListBox


ItemTips Property

Specifies whether item tips are displayed for items in a combo box or list box. Available at design time; read/write at run time.

Control.ItemTips[= lExpression]

Property Values

lExpression
The settings for the ItemTip property are:
Setting | Description
True (.T.) | Item tips are displayed for items in a combo box or list box.
False (.F.) | (Default) Item tips are not displayed for items in a combo box or list box.

Remarks

An item tip is a small window that displays an entire combo box or list box item when the mouse pointer is positioned over the item. Set this property to true (.T.) whenever items in a ComboBox or ListBox control are longer than the width of the control.

See Also

ItemData Property

Applies To: ComboBox | ListBox


IXMLDOMElement Property

Contains an object reference to an IXMLDOMElement object after the successful execution of the XMLAdapter LoadXML or Attach method. XMLAdapter methods work within the scope of this IXMLDOMElement object.

For more information about IXMLDOMElement objects, see the Microsoft XML Core Services (MSXML) 4.0 SDK on the MSDN Library Web site at http://msdn.microsoft.com/library/.

XMLAdapter.IXMLDOMElement

Property Values

Object reference. IXMLDOMElement contains an object reference to an IXMLDOMElement object. When not populated, IXMLDOMElement contains null (.NULL.).

Remarks

The XMLAdapter LoadXML method points IXMLDOMElement to the root element of the document.

If you pass an XMLDOMElement object as the first parameter of the XMLAdapter Attach method, Attach assigns the element to the IXMLDOMElement property.

If you pass an IXMLDOMDocument object as the first parameter of the XMLAdapter Attach method, Attach assigns its root element to the IXMLDOMElement property.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | LoadXML Method | Attach Method

Applies To: XMLAdapter Class


KeyboardHighValue, KeyboardLowValue Properties

Specifies the highest or lowest value that can be entered into a Spinner control text box using the keyboard. Available at design time and run time.

Spinner.KeyboardHighValue[ = nHigh]Spinner.KeyboardLowValue[ = nLow]

Property Values

nHigh
Specifies the highest value that can be entered. The default value for nHigh is 2,147,483,647.
nLow
Specifies the lowest value that can be entered. The default value for nLow is – 2,147,483,647.

See Also

SpinnerHighValue, SpinnerLowValue Properties | KEYBOARD Command

Applies To: Spinner


Keyfield Property

Specifies whether the field is a key field.

Keyfield applies only when executing the XMLTable ApplyDiffgram method. You can set this property when desired; Visual FoxPro does not set this property.

XMLField.Keyfield [= lValue]

Property Values

Logical data type. The following table lists the values for lValue.

lValue | Description
False (.F.) | The field is not a key field. (Default)
True (.T.) | The field is a key field.

See Also

Properties | XMLField Object Properties, Methods, and Events | ApplyDiffgram Method

Applies To: XMLField Class


KeyFieldList Property

Specifies a comma-delimited list of primary fields for the cursor or CursorAdapter object. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting KeyFieldList for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.KeyFieldList [= cList]

Property Values

cList
Character data type. The cList parameter specifies a comma-delimited list of primary fields for the cursor or CursorAdapter object and does not have a default value.
Note You must include a list of field names when using automatic updating for updates to work.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


KeyPreview Property

Specifies whether a form's KeyPress event intercepts the KeyPress events of a control. Available at design time and run time.

Object.KeyPreview[ = lExpr]

Property Values

lExpr
The settings for the KeyPreview property are:
Setting | Description
True (.T.) | The form receives KeyPress events first and then the active control receives KeyPress events.
False (.F.) | (Default) The active control receives Keypress events; the form doesn't.

Remarks

The KeyPreview property is used to allow the form to handle KeyPress events before the active control processes them.

You can use this property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, you can process the keystrokes at the form level rather than writing code for each control that can receive keystroke events.

If a form has no visible and enabled controls, it automatically receives all keyboard events.

See Also

Enabled Property | KeyPress Event | Visible Property

Applies To: Form | Page | _SCREEN | ToolBar


KeySort Property

Specifies how Visual FoxPro enumerates through items in a collection when you use the FOR EACH command. Available at design time and run time.

Collection.KeySort [ = nValue ]

Property Values

nValue
The following table lists values for nValue.
nValue | Description
0 | Index ascending (default)
1 | Index descending
2 | Key ascending
3 | Key descending

Remarks

The KeySort property applies only to FOR EACH enumerations.

The KeySort property does not affect how the Add method for collection objects adds items to a collection. Add always adds items by index at the end unless you specify an eBeforeItem or eAfterItem parameter.

You can have a collection in which none of the items have keys. In this case, the last two values you can specify for nValue, 2 and 3, do not apply. If you specify a value of 3, Visual FoxPro uses the value of 1.

Within a collection's FOR EACH loop, changing the KeySort property does not affect the sequencing of items. However, you can nest collection enumerations to change the sequencing. In the following example, the outer FOR EACH loop is sorted using KeySort with a value of 1, and the inner loop is sorted using KeySort with a value of 2:

oCollection.KeySort = 1
FOR EACH oItem IN oCollection
     oCollection.KeySort = 2
     FOR EACH oItem2 IN oCollection
     ENDFOR
ENDFOR

Example

You can set a value for KeySort as shown in the following example:

* Sorts a collection in ascending index order
oCollection.KeySort = 1

See Also

Collection Object Properties, Methods, and Events | Add Method (Collection Class) | FOR EACH ... ENDFOR Command

Applies To: Collection Class


LanguageOptions Property

This application object property provides ability to control general Visual FoxPro language settings. This includes the ability to check for improperly declared memory variables.

_VFP.LanguageOptions [= eValue]

Parameters

eValue

Bit Value | Description
1 | Strict type declaration is required for memory variables.

Remarks

When LanguageOptions is set to 1, you must declare all memory variables and arrays as LOCAL or PUBLIC prior to using them. An attempt to use an undeclared variable or array will generate output to the DEBUG OUTPUT window. No error is generated. You can log this output to a file as in the following code:

   SET DEBUGOUT TO MyErrorFile

The output from undeclared variables in LanguageOptions is comma-delimited in the following format:

LangOptionsErr, DateTime, cLineNo, cProcedure|cMethod, cFileName, cVarName

Item | Description
LangOptionsErr | Specifies the name of the output type for searches and filters
DateTime | Specifies the time stamp when run (= DATETIME( ))
cLineNo | Specifies the line number where error occurred (=LINENO( ))
cProcedure|cMethod | Specifies the name of the procedure or method in which the error occurred ( = PROGRAM( ))
cFileName | Specifies the name of the file in which the error occurred. (=SYS(16( ))
cVarName | Specifies the name of the undeclared variable

Declaring variables PRIVATE does not create a variable (unlike declaring variables PUBLIC or LOCAL), so the following code generates a log entry:

   PRIVATE myvar
   myvar = 1

Commands that create variables on the fly, such as SCATTER ... NAME, REPORT... NAME and others, will generate log entries, because these variables are created as PRIVATE.

Example

The following code shows the debug output resulting from entering an undeclared variable, RR.

example:
vfp.LanguageOptions=1
RR=4

LangOptionsErr,01/23/01 03:02:41 PM,11,TTT,C:\VFP\TEST\TTT.FXP,RR

Strict typing in Visual FoxPro is enforced only at run time, so you must run code to detect errors. Strict typing affects both development and run-time versions of Visual FoxPro.

Note Use of private variables such as those declared with the PRIVATE command or those created using the NAME clause of certain commands will generate errors. If you are distributing code that might be affected by developers potentially setting this property to 1, you should protect your code by resetting this property to 0 when needed.

See Also

PUBLIC | PRIVATE | LOCAL | Setting Properties at Run Time | Variable Declaration

Applies To: Application Object | _VFP System Variable


LastModified Property

Contains the date and time of the last modification made to a file in a project. Read-only at design time and run time.

Object.LastModified

Remarks

The LastModified property contains a DateTime value indicating when the file was last modified.

See Also

FDATE( ) Function | FTIME( ) Function

Applies To: File Object


Left Property

Specifies the distance between the left edge of a control or form and its container object. Available at design time and run time.

Object.Left[ = nDist]

Property Values

nDist
Specifies the distance between the left edge of an object or form and the left edge of its container object.

The default container for a form is the main Visual FoxPro window.

Remarks

The Left property specifies how far from the object's zero position the object is located. For example, if a form is contained within the Visual FoxPro main window, the zero position is immediately to the right of the main window's left border. If a toolbar is docked to the left of the main window, the zero position is immediately to the right of the toolbar.

Use Left, Top, Height, and Width properties for operations based on an object's external dimensions, such as moving or resizing. Use the ScaleMode property to change the unit of measurement.

Note The Left property is read-only when it applies to a control contained in a Column object.

Example

The following example demonstrates how the Left property is used to position controls on a form. The AddObject method is used to add a Line control and three command buttons to a form, and the Left property specifies the horizontal placement of each control on the form.

frmMyForm = CREATEOBJECT('Form')  && Create a form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

Height Property | Move Method | ScaleMode Property | Top Property | Width Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Custom | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


LeftColumn Property

Contains the number of the left-most column being displayed by a Grid control. Read-only at design time and run time.

Grid.LeftColumn

Remarks

Use the LeftColumn property to determine which columns are not visible to the user. For example, if LeftColumn = 3, columns 1 and 2 are not visible.

See Also

ActiveColumn Property | ActiveRow Property | ColumnOrder Property | RelativeColumn Property | RelativeRow Property

Applies To: Grid


LineContents Property

Specifies the contents of the line that produced an exception object. Read/write at run time.

Exception.LineContents

Property Value

Character data type

Remarks

Identical to the value returned by the statement:

MESSAGE(1)

See Also

Properties | Exception Object Properties, Methods, and Events | MESSAGE( ) Function | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


LineNo Property

Specifies the line number of the statement that produced an exception object. Read/write at run time.

Exception.LineNoProperty

Property Value

Numeric data type

Remarks

Identical to the value returned by the LINENO() function.

See Also

Properties | Exception Object Properties, Methods, and Events | LineNo Property | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


LineSlant Property

Specifies which way a line slants, from upper left to lower right or lower left to upper right. Available at design time and run time.

Line.LineSlant[ = cSlant]

Property Values

cSlant
The settings for the LineSlant property are:
Setting Description
\ (Default) Line slants from upper left to lower right.
/ Line slants from lower left to upper right.

Example

The following example demonstrates how to use the LineSlant property to specify the direction in which a Line control slants.

A Line control is added to a form. Three command buttons are added to the form, making it possible for you to change the direction in which the line slants or to close the form.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

DrawMode Property | DrawStyle Property

Applies To: Line


LinkMaster Property

Specifies the parent table linked to the child table displayed in a Grid control. Available at design time; read/write at run time.

Grid.LinkMaster[ = cName]

Property Values

cName
Specifies the alias of the parent table that drives the display of the child table in a Grid control.

Remarks

Use the LinkMaster property to set up a one-to-many relationship between the parent, or primary, table of the Form, and the table referenced by the Grid's RecordSource property.

See Also

ChildOrder Property | RelationalExpr Property

Applies To: Grid


List Property

A character string array used to access the items in a ComboBox or ListBox control. Not available at design time; read/write at run time.

Control.List(nRow [, nCol]])[ = cChar]

Property Values

nRow
Specifies the row of the item to be retrieved using the display order. For example, nRow = 3 specifies the third row shown in the list.
nCol
Specifies the column of the item to be retrieved using the display order. For example, nCol = 2 specifies the second column shown in the list. If nCol is not specified, the List property retrieves the first column by default. Specify nCol only for ComboBox and ListBox controls that have more than one column.
cChar
Specifies a value to add to a combo box or list box.

Remarks

The List property works in conjunction with the ListCount property; enumerating a list from 1 to ListCount returns all items in the list.

You cannot use array functions with the List property. However, if you set the RowSourceType property to 5 (Array) and set the RowSource property to the array of values to be contained in the list, you can use array functions on the array specified in the RowSource property.

Note When RowSourceType is set to 0 or 1, add items to a combo box or list box using the AddItem method. To remove items, use the RemoveItem method. To keep items in alphabetic order, set the control's Sorted property to true (.T.) before adding items to the list.

Example

In the following example, ListCount is used to cycle through all the of the items specified by the List property of the combo box or list box.

The following example creates a list box. The source of the items that appear in the list box items is an array; the array is specified with the RowSourceType and RowSource properties.

The MultiSelect property for the list box is set to true (.T.), making it possible for you to make multiple selections from the list box. The ListCount property is used within a FOR ... ENDFOR loop to display the item or items you choose in the list box. The Selected property is used to determine the items you chose, and the List property is used to return the items.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
ENDFOR

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

* Add "Quit" command button and list box control
frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')
frmMyForm.AddObject('lstListBox1','lstMyListBox')

* && Specifies an array containing listbox items
frmMyForm.lstListBox1.RowSourceType = 5
frmMyForm.lstListBox1.RowSource = 'gaMyListArray'

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

AddItem Method | IndexToItemID Method | ItemIDToIndex Method | ListCount Property | ListItem Property | ListItemID Property | RowSource | RowSourceType | Sorted Property

Applies To: ComboBox | ListBox


ListCount Property

Contains the number of items in the list portion of a ComboBox or ListBox control. Not available at design time; read-only at run time.

Control.ListCount

Example

The following example creates a list box. The source of the items that appear in the list box items is an array; the array is specified with the RowSourceType and RowSource properties.

ListCount is used to cycle through all of the items specified by the List property of the ComboBox or ListBox.

The MultiSelect property for the list box is set to true (.T.), allowing you to make multiple selections from the list box. The ListCount property is used within a FOR ... ENDFOR loop to display the item or items you choose in the list box. The Selected and List properties are used to determine the items you chose.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
ENDFOR

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" Command button
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add list box control

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Array containing listbox items

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

AddItem Method | List Property | ListItemID Property | RemoveItem Method

Applies To: ComboBox | ListBox


ListIndex Property

Specifies the index number of the selected item in a ComboBox or ListBox control. Not available at design time; read/write at run time.

Control.ListIndex[ = nIndex]

Property Values

nIndex
The settings for the ListIndex property are:
Setting | Description
0 | (Default) Indicates no items selected. For a combo box, this means that the user has entered a value not in the list.
1 ... ListCount | The index of the selected item.

Remarks

The following displays the string of the selected item.

? List(MyList.ListIndex)

You can return the same value by using the control's Value property.

Setting the MultiSelect property of a ListBox to .T. allows more than one item to be selected. In this case, the ListIndex will contain the index of the item that currently has the selection border.

See Also

AddItem Method | AddListItem Method | IndexToItemID Method | ItemIDToIndex Method | List Property | ListItem Property | RemoveItem Method | Value Property

Applies To: ComboBox | ListBox


ListItem Property

A character string array used to access the items in a ComboBox or ListBox control by item ID. Not available at design time; read/write at run time.

Control.ListItem(nRow [, nCol])[ = cChar]

Property Values

nRow
Specifies the row from which to retrieve the item. You can use the control.listitemID property.
nCol
Specifies, optionally, the column from which to derive the value. If you specify only listitemID column one provides the value.
nChar
Represents a value, optionally, to be assigned to the specified Control.listitem.

Remarks

Use the List property to retrieve items in the order they are displayed; use the ListItem property to retrieve items according to their item ID.

Note To add items to a combo box or list box, use the AddItem or AddListItem method. To remove items, use the RemovetItem method or the RemoveListItem method. To keep items in alphabetic order, set the control's Sorted property to True (.T.) before adding items to the list.

The ListItem property is also set when the Selected property on a Listbox control is set.

See Also

AddItem Method | AddListItem Method | IndexToItemID Method | ItemIDToIndex Method | ListCount Property | List Property | ListItemID Property | Selected Property

Applies To: ComboBox | ListBox


ListItemID Property

Specifies the unique ID number for the selected item in a ComboBox or ListBox control. Not available at design time; read/write at run time.

Control.ListItemID[ = nItemID]

Property Values

nItemID
The settings and interpretations for the ListItemID property are:
Setting | Description
– 1 | Indicates no items selected. For a combo box, it means that the user has entered a value not in the list.
1 (or any number greater than 1) | The item ID of the selected item.

Remarks

If an item is removed from a list using the RemoveListItem method, all remaining items retain their unique identification numbers. When an item is added to a list using the AddItem method, and the Sorted property is set to false (.F.), nItemID is assigned the lowest number available. When an item is added to a list using the AddListItem method, and the Sorted property is set to false (.F.), you can assign any number to nItemID.

The ListItemID property is also set when the SelectedID property on a Listbox control is set.

See Also

AddItem Method | AddListItem Method | IndexToItemID Method | ItemIDToIndex Method | ListCount Property | List Property | ListItem Property | RemoveItem Method | RemoveListItem Method | SelectedID Property

Applies To: ComboBox | ListBox


LoadXML Method

Loads XML from a file or string into a Document Object Model (DOM) document and attaches it to the XMLAdapter object.

LoadXML also sets the XMLAdapter IXMLDOMElement property. In addition, if the XML schema is analyzed, Visual FoxPro repopulates the Tables collection with a new set of XMLTable objects and sets the XMLAdapter XMLName, XMLNamespace, XMLPrefix, IsDiffgram, and SOM properties to appropriate values.

XMLAdapter.LoadXML( cXMLDocument [, lFile [, lValidateOnParse ]] )

Parameters

cXMLDocument
Specifies an XML file name, XML string, or expression that evaluates to a valid XML file name or string.
lFile
Specifies whether cXMLDocument is a file name. The default value of lFile is False (.F.).
lValidateOnParse
Specifies whether the XML should be validated upon parsing. The default value of lValidateOnParse is True (.T.).

For more information about how DOM performs validation, see the Microsoft XML Core Services (MSXML) 4.0 SDK on the MSDN Library Web site at http://msdn.microsoft.com/library/.

Remarks

The following property settings affect how LoadXML method is executed:

  • DisableEncode
  • MapN19_4ToCurrency
  • NoCpTrans
  • PreserveWhiteSpace
  • WrapCharInCDATA
  • WrapMemoInCDATA
  • XMLSchemaLocation

See Also

Methods | XMLAdapter Object Properties, Methods, and Events | IXMLDOMElement Property | Tables Collection (XMLAdapter) | XMLName Property | XMLNamespace Property | XMLPrefix Property | IsDiffgram Property | SOM Property | LoadXML Method

Applies To: XMLAdapter Class


LockColumns Property

Specifies the number of columns to lock in the right panel of a grid, beginning at the left edge. Read/write at design and run time.

After LockColumns is set, the ability to move columns is disabled. Locked columns remain in the Grid or Browse window when tabbing to the right.

Grid.LockColumns [ = nValue ]

Parameters

nValue
Numeric data type. Specifies a number of columns to lock in the right panel of a grid. The default value is 0. If nValue is greater than 0, setting nValue to 0 removes the current number of columns locked.

Remarks

A grid always contains two panels; however, only the right panel is visible when in default mode. You can activate the left panel by setting the SplitBar property to True (.T.) and dragging the split bar in the user interface to expose the left panel, or by setting a value for the Partition property.

A column separator line, which appears 1 pixel wider than the line separating the other columns, indicates the area where the locked columns end and the normal columns begin.

LockColumns applies only to the right grid panel, which is displayed by default. To lock columns in the left grid panel, when exposed via the Partition or SplitBar properties, use the LockColumnsLeft property.

The Column SetFocus method does not work if a column is locked and not visible in the grid window, for example, scrolled off to the left side.

When any of the locked columns scroll out of the Grid window to the left, they remain out of view and do not become visible again until locking is removed. For example, suppose a grid contains five columns, and the data source has ten columns. When you scroll two columns to the right, the first and second columns scroll out of the grid to the left.

Suppose you set LockColumns with the following code:

Grid.LockColumns = 3

The first, second, and third columns are now locked. The third column appears as the first visible column in the locked grid, even though the first and second columns still exist and remain out of view. You cannot scroll to the left to view all of the locked columns. This functionality is useful if you want to lock the columns in the middle of the grid and do not want to display the preceding or following columns.

Example

The following example demonstrates how to use LockColumns with BROWSE...NAME:

CLOSE DATABASES
OPEN DATABASE testdata && Open testdata database in \Samples\Data.
USE Customer
BROWSE NAME Customer
Customer.LockColumns = 2 && Locks first two columns in right pane.

See Also

Properties | SplitBar Property | Partition Property | LockColumnsLeft Property | SetFocus Method | Locking Columns

Applies To: Grid Control | BROWSE...NAME Command


LockColumnsLeft Property

Specifies the number of columns to lock in the left panel of a grid, beginning at the left edge. Read/write at design and run time.

Locked columns remain in the Grid or Browse window when tabbing to the right. LockColumnsLeft applies only to the left grid panel, which is not displayed by default. After LockColumns is set, the ability to move columns is disabled.

Grid.LockColumnsLeft [ = nValue ]

Parameters

nValue
Numeric data type. Specifies a number of columns to lock in the left panel of a grid. The default value is 0. If nValue is greater than 0, setting nValue to 0 removes the current number of columns locked.

Remarks

A column separator line, which appears 1 pixel wider than the line separating the other columns, indicates the area where the locked columns end and the normal columns begin.

To lock columns in the right panel of the grid, use the LockColumns property.

Example

The following example demonstrates how to use LockColumnsLeft with BROWSE...NAME:

CLOSE DATABASES
OPEN DATABASE testdata && Open testdata database in \Samples\Data.
USE Customer
BROWSE NAME Customer
Customer.LockColumnsLeft = 2 && Locks first two columns in left pane.

See Also

Properties | LockColumns Property | Locking Columns

Applies To: Grid Control | BROWSE...NAME Command


LockScreen Property

Determines whether a form batches all changes to property settings for its contained objects. Available at design time and run time.

Object.LockScreen[ = lExpr]

Property Values

lExpr
The settings for the LockScreen property are:
Setting | Description
True (.T.) | The form's contained objects reflect changes in property settings only when LockScreen is reset to false (.F.) rather than as soon as the changes are made.
False (.F.) | (Default) The form's contained objects reflect changes in property settings as soon as the changes are made.

Remarks

Set LockScreen to true (.T.) to reduce annoying screen refreshes when presentation properties such as BackColor, FontName, and so on are changed during run time.

The LockScreen property does not prevent changes to the form from being reflected immediately. For example, even if LockScreen is set to true, the form is moved if you call its Move method.

Note If you set LockScreen to false (.F.), the form's contained controls are repainted immediately.

See Also

Paint Event

Applies To: Form | _SCREEN | ToolBar


MacDesktop Property

Included for backward compatibility. Specifies whether a form is placed in the main Visual FoxPro window.

Object.MacDesktop[ = nValue]

Property Values

nValue
The settings for the MacDesktop property are:
Setting | Description
0 | (Default) Automatic. The form is contained in the Visual FoxPro main window according to the setting established with the SET MACDESKTOP command. If SET MACDESKTOP is set to ON, the form exists at the level of the Macintosh desktop; if set to OFF, the form is contained within the Visual FoxPro main window.
1 | Macintosh Desktop. The form exists at the level of the Macintosh desktop, and can be moved and resized independently of the main Visual FoxPro window.
2 | Visual FoxPro Desktop. The form is contained in the Visual FoxPro main window and cannot be moved outside it.

Remarks

Setting the MacDesktop property enables you to override for individual forms the setting established with the SET MACDESKTOP command. SET MACDESKTOP affects user-defined windows (forms) and system windows such as the Browse, View, and Form Designer windows. By default, user-defined windows behave according to the SET MACDESKTOP setting.

The MacDesktop property enables you to control whether your applications resemble Macintosh applications or Windows applications.

See Also

SET KEYCOMP

Applies To: Form


MainFile Property

Contains the name and path of the file set as the main program in a project. Read-only.

Object.MainFile

Remarks

MainFile contains the empty string if a main program has not been set for a project. A program or form can be set as the main program in a project by right-clicking the program or form and choosing Set Main from the shortcut menu. You can also use the SetMain method to programmatically specify a main program for a project.

See Also

SetMain Method

Applies To: Project Object


MapN19_4ToCurrency Property

Specifies whether to map the XML type xsd:decimal to the Visual FoxPro Currency data type when the XML facets totalDigits and fractionDigits are 19 and 4 respectively. You can set the MapN19_4ToCurrency property to preserve precision. Read/write.

MapN_4ToCurrency applies only when executing the LoadXML and Attach methods, which retrieve XML consistent with its setting.

XMLAdapter.MapN19_4ToCurrency [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Does not map xsd:decimal to Currency. (Default)
True (.T.) | Map xsd:decimal to Currency. The XML facets totalDigits and fractionDigits must be 19 and 4 respectively.

Remarks

By default, Visual FoxPro maps xsd:decimal to Numeric. However, you can retain currency type precision by mapping xsd:decimal to Currency instead of Numeric. For example, SQL Server currency fields are represented in XML as decimal 19,4 with 19 total digits and 4 digits following the decimal point.

For more information about Visual FoxPro and XSD data type mapping, see Visual FoxPro and XML Schema Data Type Mapping.

Example

The following example shows how the XML schema type simpleType, as defined, is mapped to Currency in Visual FoxPro:

<xsd:simpleType>
   <xsd:restriction base="xsd:decimal">
   <xsd:totalDigits value="19"/>
   <xsd:fractionDigits value="4"/>
   </xsd:restriction>
   </xsd:simpleType>

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | Currency Data Type | Numeric Data Type | LoadXML Method | Attach Method

Applies To: XMLAdapter Class


Margin Property

Specifies the margin width created in the text portion of the control. Available at design time and run time.

Control.Margin[ = nValue]

Property Values

nValue
Specifies the margin created in the text portion of the control.

Remarks

Use the Margin property to specify the position of text on the control. The Margin property creates a margin in the interior portion of the control; it doesn't affect the size of the control.

See Also

Alignment Property

Applies To: ComboBox | EditBox | Spinner | TextBox


MaxButton Property

Specifies whether a form has a Maximize button. Available at design time and run time.

Object.MaxButton[ = lExpr]

Property Values

lExpr
The settings for the MaxButton property are:
Setting | Description
True (.T.) | (Default) The form has a Maximize button.
False (.F.) | The form doesn't have a Maximize button.

Remarks

A Maximize button enables a user to enlarge a form to full-screen size.

A Maximize button automatically becomes a Restore button when a window is maximized. Minimizing, or restoring, a window automatically changes the Restore button back to a Maximize button.

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the form's appearance until run time.

Maximizing a form at run time triggers the Resize event.

Note The WindowState property reflects the current state of the window. If you set the WindowState property to 2 (Maximized), the form is maximized independently of whatever settings are in effect for the MaxButton and BorderStyle properties.

See Also

BorderStyle Property | ControlBox Property | MinButton Property | Resize Event | TitleBar Property | WindowState Property

Applies To: Form | _SCREEN


MaxHeight Property

Determines the maximum height to which a form can be sized. Available at design time and run time.

Object.MaxHeight[ = nHeight]

Property Values

nHeight
The maximum height, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

When the user sizes a form by choosing either the Size command from the Control menu or by dragging the borders of the form, the form doesn't exceed the height specified in the MaxHeight property setting.

The default setting for the MaxHeight property is – 1; no maximum height is specified.

See Also

ScaleMode Property

Applies To: Form | _SCREEN


MaxLeft Property

Specifies the distance a maximized form is from the left edge of the main Visual FoxPro window. Available at design time and run time.

Object.MaxLeft[ = nMaxLeft]

Property Values

nMaxLeft
Specifies the distance from the left edge of the main Visual FoxPro window to the left edge of the maximized form, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

Use the MaxLeft property to ensure that a maximized form does not get moved too far to the left in the main Visual FoxPro window at run time.

See Also

MaxTop Property | MaxWidth Property | MinHeight Property | Scalemode Property

Applies To: Form | _SCREEN


MaxLength Property

Specifies the maximum length in characters that can be entered in an EditBox, TextBox, or ComboBox control. For these controls, use MaxLength to limit the amount of text a user can enter in an edit box, text box, or combo box.

For XMLField objects, MaxLength specifies the total length of the Character or Numeric field in a cursor when using the XMLTable ToCursor method or in an XML schema when using the XMLAdapter ToXML method.

Available at design time and run time.

Control.MaxLength [= nMaxLength]

-or-

XMLField.MaxLength [= nMaxLength]

Property Values

nMaxLength
Specifies the maximum number of characters that can be entered in an edit box, text box, or combo box.

When nMaxLength is set to 0, there is no limit to the number of characters that can be entered into an edit box. For text and combo boxes, the size of the text or combo box and its data type determines the number of characters that can be entered.

For XMLField objects, MaxLength for Memo fields is 2147483647. For Numeric, Float, and Double fields, MaxLength is the same as XML facet totalDigits+1.

Remarks

For text or combo boxes, MaxLength applies only when set to a value greater than 0, and the control does not use the InputMask property. For combo boxes, MaxLength is significant only when Style is set to 0 and applies only to the text box portion of the combo box. The Value property of the text box must be of Character type; however, the Value property of a combo box can be other types, such as Numeric.

If the ControlSource property of a control is bound to a field, Visual FoxPro truncates any characters entered that exceed the length of the field.

See Also

Properties | ToCursor Method | ToXML Method | InputMask Property | Value Property | Style Property | ControlSource Property | SelLength Property

Applies To: ComboBox | EditBox | TextBox | XMLField Class


MaxRecords Property

Specifies the maximum number of rows to fetch when result sets are returned. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting MaxRecords for applies only to CursorAdapter objects with ODBC or ADO data sources and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.MaxRecords [= nValue]

Property Values

nValue
Numeric data type. The nValue parameter has a default value of -1, which specifies that all rows be returned. Setting nValue to 0 specifies that the view is executed, but no results are fetched.

Remarks

MaxRecords applies primarily for remote views and setting it does not affect local views. However, you can preset this property for local views that will be upsized.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


MaxTop Property

Specifies the distance a maximized form is from the top edge of the main Visual FoxPro window. Available at design time and run time.

Object.MaxTop[ = nMaxTop]

Property Values

nMaxTop
Specifies the distance from the top edge of the main Visual FoxPro window to the top edge of the maximized form, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

This property is ignored in Visual FoxPro for the Macintosh.

Use the MaxTop property to ensure that a maximized form doesn't get moved too close to the top of the main Visual FoxPro window at run time.

See Also

MaxLeft Property | MaxWidth Property | MinHeight Property | MinWidth Property | Scalemode Property

Applies To: Form | _SCREEN


MaxWidth Property

Specifies the maximum width a form can be resized to. Available at design time and run time.

Object.MaxWidth[ = nMaxWidth]

Property Values

nMaxWidth
Specifies the maximum width a form can be resized to, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

When the user sizes a form by choosing either the Size command from the Control menu or dragging the borders of the form, the form doesn't exceed the width specified in the MaxWidth property setting.

The default for the MaxWidth property setting is –1; no maximum width is specified.

See Also

MaxHeight Property | MinHeight Property | MinWidth Property | ScaleMode Property

Applies To: Form | _SCREEN


MDIForm Property

Specifies if the form is multiple-document interface (MDI) compliant.

Object.MDIForm[ = 1Expr]

Property Values

IExpr
The settings for the MDIForm property are:
Setting | Description
True (.T) | The form will be combined with a parent form when maximized.
False (.F) | (Default) The form is always in a separate window.

Remarks

Set a form's MDIForm property to .T. (true) if you want the child form to be combined with the parent when maximized, or to .F. (false) if the child window should be retained as a separate window when maximized.


MemberClass Property

Specifies the name of the member class to use when adding new members to a container. Read/write at design time and run time.

For a Column parent container and its header members, use the HeaderClass property instead of MemberClass.

Note If the member class is based on a class that is stored in a program (.prg) file, make sure that the compiled program (.fxp) file is synchronized with the .prg file.
Object.MemberClass [ = cClassName ]

Property Values

cClassName
Specifies the name of a member class in a program (.prg) or visual class library (.vcx) file.

Remarks

Visual FoxPro creates a member object using MemberClass under the following conditions:

  • MemberClass is specified for a container class definition at design time. When Visual FoxPro creates the container, it instantiates members using MemberClass.
  • The member object's Count property, such as the PageCount, ButtonCount, or ColumnCount properties, is increased at run time. If the member object's Count property is programmatically or interactively increased, Visual FoxPro adds new instances using MemberClass.
    Note The ColumnCount property is unique in that you can specify its value as -1 or 0. All other Count properties must be greater than or equal to zero.

Both MemberClass and MemberClassLibrary support the Access and Assign methods and Public, Hidden and Protected scope.

A container can hold objects of different member classes with the same base class. For example, suppose you have a PageFrame object and two member classes, myPage1 and myPage2, defined as Page classes. You can specify myPage1 for the PageFrame MemberClass property at design time and change PageFrame MemberClass to myPage2 at run time, followed by an increase in the PageFrame PageCount property.

The MemberClass and MemberClassLibrary properties have the following additional behaviors at design time and run time:

  • Behavior at design time

    When setting the MemberClass and MemberClassLibrary properties at design time, you are prompted to destroy existing member classes, including property settings; new, added, or modified method code; and added objects.

    When you create a subclass from a container that specifies the MemberClass property, the subclass inherits the proper MemberClass and MemberClassLibrary properties, which you can modify.

    Visual FoxPro displays the MemberClass and MemberClassLibrary properties in the Properties window as read-only. However, you can set these properties in the Properties window by clicking the ellipsis (...) button to display the Open dialog box, browsing for, and selecting the member class and class library you want to use.

    Note If you want to specify a member class for the container, you must set, not only one, but both MemberClass and MemberClassLibrary properties.

    If you are setting the member object's Count property in a program (.prg) file at design time, you must specify the member object's Count property after setting the MemberClass and MemberClassLibrary properties because of certain dependencies. For example:

    DEFINE CLASS myPageFrame AS PageFrame
   MemberClassLibrary = 'MyPages.prg'
   MemberClass = 'myPage'
   PageCount = 3
ENDDEFINE

    When using the ASELOBJ( ) function to set the MemberClass and MemberClassLibrary properties individually, the following behavior occurs:

    • If you specify only the MemberClass or MemberClassLibrary property using the ASELOBJ() function, Visual FoxPro does not generate an error but disregards the property specified and uses the base class when adding a new member object.
    • If the member object's Count property is 0 (or -1 for Grid objects), Visual FoxPro does not perform error checking when setting MemberClass and MemberClassLibrary, which you can set in any order.
    • If the member object's Count property is greater than 0, Visual FoxPro performs error checking when MemberClass is set. Therefore, in this situation, you need to set MemberClassLibrary before setting MemberClass.
      Note If either property is invalid, Visual FoxPro generates the appropriate message if the class or class library is invalid and sets the member object's Count property back to 0.

      If both MemberClass and MemberClassLibrary are valid, Visual FoxPro recreates all existing member classes based on the new member class, and all previous member object data is lost.

      Caution Visual FoxPro does not prompt you to destroy existing member classes, including property settings; new, added, or modified method code; and added objects when setting MemberClass and MemberClassLibrary in code.

      As when setting the member object's Count property in a program (.prg) file at design time, you must specify the member object's Count property after setting the MemberClass and MemberClassLibrary properties.

      You can change MemberClassLibrary to another class library that has the same MemberClass. If you increase the member object's Count property, Visual FoxPro adds a new member class using the new MemberClassLibrary. Though the designer displays member classes from different class libraries, only the most recent MemberClassLibrary persists when saving the class. Therefore, when you instantiate or open the class again, all member objects are created from the most recent MemberClassLibrary.

  • Behavior at run time

    Changing MemberClass and MemberClassLibrary affects only newly created member objects, not existing member objects in the container. You can also use the AddObject and NewObject methods, which function as usual, to specify a different class.

    Note You should specify both MemberClass and MemberClassLibrary properties at run time. If you specify only MemberClass or MemberClassLibrary at run time, Visual FoxPro does not generate an error; however, it uses the base class when adding a new member and disregards the property specified.

    To reliably determine the member class used to instantiate a particular member object, use the Class and ClassLibrary properties of the member object instead of MemberClass and MemberClassLibrary because the latter properties can change at run time.

    Note A container can have member objects derived from different member classes.

    Visual FoxPro does not support the capability to specify a class in a class library bound inside a compiled Visual FoxPro application (.app).

Example

The following example creates a form, adds a PageFrame container to the form, defines the PageFrame container as "myPageFrame", sets the MemberClassLibrary and MemberClass properties for "myPageFrame", defines a Page member object as "myPage", and adds code for a command button and events.

PUBLIC x
x = CREATEOBJECT("form")
x.ADDOBJECT("pf1","myPageFrame")
x.pf1.Visible = .T.
x.Show()

DEFINE CLASS myPageFrame AS PageFrame
   MemberClassLibrary = 'myPages.PRG'
   MemberClass = 'myPage'
   PageCount = 2
   TabOrientation = 1
ENDDEFINE

DEFINE CLASS myPage AS Page
   ADD OBJECT cmd1 AS commandbutton WITH ;
      Caption = "Hello", FontBold = .T.
   PROCEDURE Init
      THIS.Caption = "Funpage"+TRANSFORM(THIS.Parent.PageCount)
   ENDPROC
   PROCEDURE cmd1.Click
      MESSAGEBOX(this.Caption)
      THIS.Parent.Parent.PageCount = THIS.Parent.Parent.PageCount+1
   ENDPROC
ENDDEFINE

See Also

Member Classes | MemberClassLibrary Property | HeaderClass Property | HeaderClassLibrary Property | ASELOBJ( ) Function

Applies To: PageFrame Control | CommandGroup Control | OptionGroup Control | Grid Control


MemberClassLibrary Property

Specifies the name of the class library containing the member class in the MemberClass property. Read/write at design time and run time.

For a Column parent container and its header members, use the HeaderClassLibrary property instead of MemberClassLibrary.

Object.MemberClassLibrary [ = cClassFile ]

Property Values

Character string. The cClassFile parameter specifies the file name containing the member class in MemberClass.

Remarks

Visual FoxPro includes the MemberClassLibrary visual class library (.vcx) or program (.prg) in the project during a project build.

If you set MemberClassLibrary at run time, you must use the full file name including the file extension.

If you specify MemberClassLibrary without specifying MemberClass, Visual FoxPro does not generate an error; however, it uses the base class when adding a new member and disregards the property specified.

For additional information about the MemberClassLibary and MemberClass properties, see MemberClass Property.

See Also

Member Classes | MemberClass Property | HeaderClassLibrary Property

Applies To: PageFrame Control | CommandGroup Control | OptionGroup Control | Grid Control


MemoWindow Property

Included for backward compatibility. Use an EditBox control instead.


Message Property

Specifies the actual error message for an exception object. Read/write at run time.

Exception.MessageProperty

Property Value

Character data type

Remarks

Identical to the value returned by the MESSAGE() function and the second element in the array produced by the AERROR() function.

See Also

Properties | Exception Object Properties, Methods, and Events | MESSAGE( ) Function | AERROR( ) Function | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


MinButton Property

Specifies whether a form has a Minimize button. Available at design time and run time.

Object.MinButton[ = lExpr]

Property Values

lExpr
The settings for the MinButton property are:
Setting | Description
True (.T.) | (Default) The form has a Minimize button.
False (.F.) | The form does not have a Minimize button.

Remarks

A Minimize button enables users to minimize a Form window to an icon.

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the Form's appearance until run time.

In Microsoft Windows version 3.0 or later, an MDI child form is displayed with a Minimize button regardless of the setting of MinButton. However, if MinButton is set to false (.F.), 'it is disabled, and the corresponding Minimize command is not on the form's Control-box menu.

Minimizing a form to an icon at run time generates a Resize event. The WindowState property reflects the current state of the window. If you set the WindowState property to 1 (Minimized), the Form is minimized independently of whatever settings are in effect for the MinButton and BorderStyle properties.

See Also

BorderStyle Property | ControlBox Property | MaxButton Property | TitleBar Property | WindowState Property

Applies To: Form | _SCREEN


MinHeight Property

Specifies the minimum height that a form can be resized to. Available at design time and run time.

Object.MinHeight[ = nHeight]

Property Values

nHeight
The minimum height that the form can be resized to, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

When the user sizes a form by choosing either the Size command from the Control menu or by dragging the borders of the form, the form does not become any shorter than the height specified in the MinHeight property setting.

The default setting for the MinHeight property setting is –1; no minimum height is specified.

See Also

MaxHeight Property | MaxWidth Property | MinWidth Property | ScaleMode Property

Applies To: Form | _SCREEN


MinWidth Property

Specifies the minimum width that a form can be resized to. Available at design time and run time.

Object.MinWidth[ = nWidth]

Property Values

nWidth
The minimum width that the form can be resized to, in the unit of measurement specified by the ScaleMode property of the Form.

Remarks

When the user sizes a Form by choosing either the Size command from the Control menu or by dragging the borders of the form, the Form cannot be made any narrower than the width specified in the MinWidth property setting.

The default setting for the MinWidth property is – 1; no minimum width is specified.

See Also

MaxHeight Property | MaxWidth Property | MinHeight Property | ScaleMode Property

Applies To: Form | _SCREEN


MouseIcon Property

Specifies the mouse pointer icon displayed when the mouse pointer is positioned over an object. Available at design time and run time.

Object.MouseIcon[ = cFileName]

Property Values

cFileName
Specifies the file that is displayed when the mouse pointer is positioned over the object. You can specify a mouse icon (.ico) file, a mouse cursor (.cur) file, or an animated mouse cursor (.ani) file.

Remarks

To display the mouse icon, set the MousePointer property to 99 (Custom).

See Also

MousePointer Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | _SCREEN | Shape | Spinner | TextBox | ToolBar


MousePointer Property

Specifies the shape of the mouse pointer when you move the mouse over a particular part of an object at run time. You can use the MousePointer property to indicate changes in functionality as the mouse pointer passes over controls on a form or dialog box. Available at design time and run time.

Object.MousePointer [= nType]

Property Values

nType
Specifies a value representing the shape of the mouse pointer.
Note When you set the MousePointer property using the Properties window, the drop-down list displays the setting names used in Visual FoxPro for Windows.

The following table lists the values for nType.

nType | Description
0 | Shape determined by the object (Default)
1 | Arrow
2 | Cross (cross-hair pointer)
3 | I-beam
4 | Icon (small white square within a black square)
5 | Size (four-pointed arrow pointing north, south, east, west)
6 | Size NE SW (double arrow pointing northeast and southwest)
7 | Size NS (double arrow pointing north and south)
8 | Size NW SE (double arrow pointing northwest and southeast)
9 | Size WE (double arrow pointing west and east)
10 | Up arrow
11 | Hourglass or wristwatch
12 | No Drop
13 | Hide pointer
14 | Arrow. Not a valid property value for grids and returns the error "Expression evaluated to an illegal value."
15 | Hand
99 | Custom. Uses pointer specified in object's MouseIcon property.

Remarks

To indicate that the user should wait for a process to finish, set the MousePointer property to 11 (Hourglass or Wristwatch).

When MousePointer is set to 15 (Hand), an arrow appears instead of a hand when running Visual FoxPro applications on Windows NT 4.0 operating systems.

See Also

MouseMove Event | MouseIcon Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | _SCREEN | Shape | Spinner | TextBox | ToolBar


Movable Property

Specifies whether an object can be moved at run time by the user. Available at design time; read-only at run time.

Object.Movable[ = lExpr]

Property Values

lExpr
The settings for the Movable property are:
Setting | Description
True (.T.) | (Default) The object can be moved. For forms in Visual FoxPro for Windows, the Move command is added to the Control menu.
False (.F.) | The object cannot be moved. For grid columns, you cannot move the column by direct manipulation. However, the column can be moved if you change the column's ColumnOrder property or move another column on top of it.

See Also

Sizable Property

Applies To: Column | Form | _SCREEN | ToolBar


MoverBars Property

Specifies whether mover bars are displayed on a ListBox control. Available at design time; read/write at run time.

ListBox.MoverBars[ = lExpr]

Property Values

lExpr
The settings for the MoverBars property are:
Setting | Description
True (.T.) Display mover bars.

Users can interactively reorganize the contents of the control.
False (.F.) | Does not display mover bars. (Default)

Remarks

You can select and move an item by pressing CTRL+UP ARROW, CTRL+DOWN ARROW, using the mouse, or programmatically by calling the MoveItem method. The OnMoveItem event occurs when an item moves up or down in a list box.

The MoverBars property is available only if the RowSourceType property is set to 0 (None) or 1 (Value).

See Also

RowSourceType Property | ScrollBars Property | OnMoveItem Event | MoveItem Method

Applies To: ListBox


MultiSelect Property

Specifies whether a user can make multiple selections in a ListBox control and how the multiple selections can be made. Available at design time; read/write at run time.

ListBox.MultiSelect[ = nChoice]

Property Values

nChoice
The settings for the MultiSelect property are:
Setting | Description
0 | (Default) Multiple selection isn't allowed.
1 | Multiple selection is allowed. To select multiple items in a ListBox control, hold the CTRL key down while clicking the items.

Remarks

Set MultiSelect to true (.T.) to enable a user to select multiple items in a list. You can use the Selected property to determine which items are selected.

Example

The following example creates a ListBox. The MultiSelect property for the list box is set to true (.T.), allowing you to make multiple selections from the list box. The source of the items that appear in the list box items is an array; the array is specified with the RowSourceType and RowSource properties.

The ListCount property is used within a FOR ... ENDFOR loop to display the item or items you choose in the list box. The Selected property is used to determine the items you chose, and the List property is used to return the items.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
ENDFOR

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" Command button
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add ListBox control

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Array containing listbox items

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

AddItem Method | Clear Method | List Property | ListCount Property | NewItemID Property | RemoveItem Method | Selected Property | TopItemID Property

Applies To: ListBox


Name Property

Specifies the name used to reference an object in code. Available at design time; read/write at run time.

Object.Name[ = cName]

Property Values

cName
Specifies the name used to reference the object in code.

Remarks

The default name for new objects is the type of object plus a unique integer. For example, the first new Form object is Form1, and the third text box you create on a Form is Text3.

Note If the object is the first object in the object hierarchy (that is, the outermost container object), use the object variable to reference the object instead of the Name property.

For a Project object, the Name property contains the name and path to the project, and is read-only at design time and run time.

For a File object, the Name property contains the name and path to the file, and is read-only at design time and run time.

See Also

Caption Property | NewIndex Property | NewItemID Property | ServerName Property | TypeLibName Property

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | File Object | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Project Object | ProjectHook Object | Relation | _SCREEN | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


NewIndex Property

Specifies the index of the item most recently added to a ComboBox or ListBox control. Not available at design time; read-only at run time.

Control.NewIndex

Remarks

The NewIndex property is especially useful when adding items to a sorted list.

See Also

Caption Property | NewItemID Property | Name Property

Applies To: ComboBox | ListBox


NewItemID Property

Specifies the item ID of the item most recently added to a ComboBox or ListBox control. Not available at design time; read-only at run time.

 [Form.]Control.NewItemID

Remarks

For more information about the differences between using an item ID or an index, see AddItem Method or AddListItem Method.

See Also

AddItem Method | AddListItem Method | Clear Method | ItemData Property | List Property | ListCount Property | MultiSelect Property | NewIndex Property | RemoveItem Method | Selected Property | TopItemID Property

Applies To: ComboBox | ListBox


NoCpTrans Property

Specifies whether character and memo field types are created as Character (Binary) or Memo (Binary) data types. Read/write.

For more information about Visual FoxPro and XSD data type mapping, see Visual FoxPro and XML Schema Data Type Mapping.

Setting NoCpTrans at the XMLAdapter level sets the default NoCpTrans values for XMLField objects they are created and added to the Fields collection by the following XMLAdapter methods:

  • LoadXML
  • Attach
  • AddTableSchema

Additionally, changing NoCpTrans at the XMLAdapter level affects only the next set of XMLField objects created, not the existing XMLField objects in the Fields collection. Therefore, to modify the setting of NoCpTrans for an existing XMLField object, change the value at the XMLField level.

XMLAdapter.NoCpTrans [= lValue]

-or-

XMLField.NoCpTrans [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Create field as normal Character or Memo field. (Default)
True (.T.) | Create field as Character (NoCpTrans) or Memo (NoCpTrans) field.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLField Object Properties, Methods, and Events | Visual FoxPro Data and Field Types | XMLAdapter Class | Fields Collection (XMLTable)

Applies To: XMLAdapter Class | XMLField Class


NoDataOnLoad Property

Causes the view associated with a Cursor to activate without downloading data. Available at design time; read/write at run time.

DataEnvironment.Cursor.NoDataOnLoad[ = lExpr]

Property Values

lExpr
The settings for the NoDataOnLoad property are:
Setting | Description
True (.T.) | The view associated with the Cursor is opened without downloading data.
False (.F.) | (Default) The view associated with the Cursor is opened with data.

Remarks

Note When the Cursor object is accessed using CURSORSETPROP( ), the NoDataOnLoad property is read-only at run time.

Use the NoDataOnLoad property to ensure that the FormSet or Form associated with the view loads quickly (it can be time-consuming to download data from a backend server). You can use REQUERY( ) in conjunction with NoDataOnLoad to download data into the active view once the Form is loaded.

The NoDataOnLoad property mimics the behavior of the NODATA clause of USE.

See Also

REQUERY( ) | USE

Applies To: Cursor


NullDisplay Property

Specifies the text that is displayed to indicate null values. Available at design time and run time.

Object.NullDisplay[ = cNullText]

Property Values

cNullText
Specifies the text that is displayed for null values. .NULL. is the default value.

Remarks

This property changes the null display for individual objects only. To change null display for all objects, use SET NULLDISPLAY.

See Also

CREATE TABLE - SQL | SET NULLDISPLAY

Applies To: ComboBox | EditBox | ListBox | Spinner | TextBox


NumberOfElements Property

Specifies how many items in an array are used to fill the list portion of a ComboBox or ListBox control. Available at design time and run time.

 [Form.]Control.NumberOfElements[ = nTotal]

Property Values

nTotal
Specifies the number of elements that a list can contain.

Remarks

Available only when the ListSourceType property is set to 5 (Array) and the ColumnCount property is set to 1.

NumberOfElements is useful to limit the number of elements in an array that are displayed in a list. The number of elements used for the list begins with the FirstElement property setting and includes the number of elements specified in the NumberOfElements property setting.

See Also

DisplayCount Property | FirstElement Property

Applies To: ComboBox | ListBox


Object Property

Provides access to the Automation server properties and methods for an OLE object. Not available at design time. Depending on the Automation server, the properties for the OLE object may be read-only or read/write at run time.

OLEObject.Object[.Property] [= eValue]
-or-
OLEObject.Object[.Method]

Property Values

Property
Specifies a property the Automation server supports for the OLE object.
eValue
Specifies a value for a property the Automation server supports for the OLE object.
Method
Specifies a method the Automation server supports for the OLE object

Remarks

For information about the properties and methods supported by the Automation server, see the documentation for the OLE enabled application that created the object. For example, if the OLE object is a Microsoft Excel worksheet, see the Excel documentation for the properties and methods supported by Excel (an OLE enabled application).

See Also

CREATEOBJECT( ) | GETOBJECT( )

Applies To: OLE Bound Control | OLE Container Control


OLEClass Property

Returns the named class ID of an OLE object. Read-only at design time and run time for an existing object, but can be set for an object when creating it.

Control.OLEClass[ = cName]

Property Values

cName
The named class ID of the object. This is the registered name of the application that was used to create the object or will be invoked if the object is activated.

Remarks

You set OLEClass property of an OLE container object using the Insert Object dialog box when you initially add an OLE container to a form, or in code when creating an OLE object as part of a class definition. This property is also set when you create OLE objects using the APPEND GENERAL command.

The OLEClass property of an object specifies the application that is used to create or edit the OLE object. To specify the actual contents of the object, set its DocumentFile property.

Example

The following example adds an OLE Container control to a form, and uses the OLEClass and DocumentFile properties to specify Microsoft Excel as the Automation server and an Excel worksheet as the file to edit.

Define class myForm as form
 add object oleXLSheet1 as oleXLSheet
EndDefine

Define class oleXLSheet as OLECONTROL
 oleclass = "Excel.Sheet"
 documentfile="C:\msoffice\Excel\mysheet.xls"
 oletypeallowed = 1  && Embedded
EndDefine

See Also

APPEND GENERAL | CREATEOBJECT( ) | DocumentFile Property

Applies To: OLE Bound Control | OLE Container Control


OLEDragMode Property

Specifies how a drag operation is initiated. Available at design time and run time.

Object.OLEDragMode[= nValue]

Property Values

nValue
Specifies how the control or object handles OLE drag operations. The following table lists the settings for nValue.
Setting Description
0 Manual (Default).

Visual FoxPro does not initiate the OLE drag operation when you attempt to drag data. You must call the OLEDrag method to begin the drag operation.

Setting OLEDragMode to 0 provides backward compatibility (no OLE drag support) for existing applications if you do not include additional drag operation coding.
1 Automatic

Visual FoxPro allows automatically initiates a drag operation when you attempt to drag data.

Remarks

OLEDragMode is a drag source property. If the DragMode property for a control or object is set to 1 – Automatic, the control or object cannot act as an OLE drag source. This provides backward compatibility for previous drag-and-drop support in earlier versions of Visual FoxPro.

Note that OLEDragMode property is read-only for the Grid control.

See Also

DragMode Property | OLE Drag-and-Drop Overview | OLEDrag Method | OLEStartDrag Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OLEDragPicture Property

Specifies the picture displayed under the mouse pointer during an OLE drag-and-drop operation. Available at design time and run time.

Object.OLEDragPicture[= cFileName]

Parameters

cFileName
Specifies the file name and path of the graphic to display when an OLE drag-and-drop operation occurs. The graphics file you specify can be of type .bmp, .dib, .jpg, .gif, .ani, .cur, or .ico.

The graphics file is typically a translucent or outline representation of the object being dragged. To create a translucent representation of the object, use a black-and-white checkerboard mask file (.msk).

Remarks

OLEDragPicture is a drag source property. The picture is displayed when the mouse pointer is positioned over the form containing the drag source.

See Also

OLE Drag-and-Drop Overview

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OLEDropEffects Property

Specifies the type of drop operations an OLE drop target supports. Available at design time and run time.

Object.OLEDropEffects[= nDropEffect]

Property Values

nDropEffect
Specifies the type of drop operations an OLE drop target supports. The following table lists the values for nDropEffect with a description of each.
nDropEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drop target does not accept the data as a drop target.
1 | DROPEFFECT_COPY | Data can be copied to the drop target.
2 | DROPEFFECT_MOVE | Data can be moved to the drop target.
4 | DROPEFFECT_LINK | Data can be linked to the drop target.

A drop can support multiple drop operations by adding multiple values together for nDropEffect. For example, if nDropEffect is 3, the drop target supports both copy and move drop operations (3 = 1 (copy) + 2 (move)).

Remarks

OLEDropEffects is a drop target property, and should be set in the OLEDragOver event.

See Also

OLE Drag-and-Drop Overview | OLEDragOver Event | OLEDropHasData Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLEDropHasData Property

Specifies how a drop operation is managed. Available at run time and read-only at design time.

Object.OLEDropHasData[= nDropEffect]

Property Values

nDropEffect
Specifies how the drop operation is managed. The following table lists the values for nDropEffect with a description of each.
nDropEffect | Foxpro.h constant | Description
–1 DROPHASDATA_VFPDETERMINE Default. Visual FoxPro automatically determines if the DataObject contains data in a format that can be dropped on the drop target.

If the DataObject contains data in a proper format for the drop target, the data is dropped on the drop target. Visual FoxPro handles the mouse pointer and notification of the drag source.

If the data isn't in the proper format for the drop target, Visual FoxPro displays the No Drop mouse pointer, the drop operation is canceled, and the drag source is notified that the drop operation was canceled.
0 | DROPHASDATA_NOTUSEFUL | The DataObject does not contain data in a format that can be dropped on the drop target, and the No Drop mouse pointer is displayed.
1 | DROPHASDATA_USEFUL | The DataObject contains data in a format that can be dropped on the drop target.

Remarks

OLEDropHasData is a drop target property and should be set in the OLEDragOver event. Use GetFormat in the OLEDragOver event to determine if the DataObject contains data in the proper format for the drop target. If the data is in the proper format for the drop target, set OLEDropHasData to 1.

See Also

OLE Drag-and-Drop Overview | OLEDragOver Event | OLEDropEffects Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLEDropMode Property

Specifies how a drop target manages OLE drop operations. Available at design time and run time.

Object.OLEDropMode[= nValue]

Property Values

nValue
Specifies how the control or object handles OLE drop operations. The following table lists the settings for nValue.
nValue Foxpro.h constant Description
0 DROP_DISABLED Disabled (Default).

Data cannot be dropped onto the control or object, and no drop target events occur. The No Drop mouse pointer is displayed when the mouse pointer is positioned over the control or object.

Setting OLEDropMode to 0 provides backward compatibility (no OLE drop support) for existing applications.
1 DROP_ENABLED Enabled.

Visual FoxPro allows the dropping of data onto the control or object, and drop target events occur.
2 DROP_PASSTOCONTAINER Pass to Container.

The control or object behaves as if it is disabled for OLE drop operations, and the data is dropped on the container for the control or object.

The container's OLEDropMode property must be set to 1 or 2 to accept the data. The No Drop mouse pointer is displayed if the container's OLEDropMode property is set to 0.

Remarks

OLEDropMode is a drop target property. If the DropMode property for a control or object is set to 0 – Disabled, the control or object cannot act as an OLE drop source. This provides backward compatibility for previous drag-and-drop support in earlier versions of Visual FoxPro.

If the Enabled property of a control or object is set to false (.F.), you cannot drop data on the control or object. For drop operations, the No Drop mouse pointer is displayed when the Enabled property of a control or object is set to false (.F.).

See Also

Enabled Property | OLE Drag-and-Drop Overview

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLEDropTextInsertion Property

Specifies if you can drop text in the middle of a word in the text box portion of a control.

Object.OLEDropTextInsertion[= lExpression]

Parameters

lExpression
The settings for the OLEDropTextInsertion property are:
Setting | Description
0 | (Default) Text can be dropped into a word.
1 | Text can only be dropped before or after a word.

Remarks

The OLEDropMode property of a control must be set to 1 – Enabled to drop text in the text box portion of the control.

See Also

OLE Drag-and-Drop Overview | OLEDropMode Property

Applies To: ComboBox | EditBox | Spinner | TextBox


OLELCID Property

Contains a numeric value indicating the Locale ID for an OLE Bound control or an OLE Container control. Read-only at design time and run time.

Control.OLELCID

Remarks

The Locale ID value is determined by the value of the DefOLELCID property for the form or the main Visual FoxPro window when an OLE Bound control or an OLE Container control is placed on the form or the main Visual FoxPro window.

If the form or the main Visual FoxPro window's DefOLELCID property is zero when the OLE Bound control or OLE Container control is placed on the form or the main Visual FoxPro window, the control uses the current Visual FoxPro Locale ID (LCID). Use SYS(3004) to determine the current Visual FoxPro Locale ID. Use the DefOLELCID property to specify a Locale ID for a form.

See SYS(3005) for a listing of Locale IDs.

Note The OLELCID property only affects the language of the user interface, which OLE controls display, and not the language of the Automation commands. The Automation command language is affected only by the Global LocaleID, set with SYS(3005).

See Also

DefOLELCID Property | SYS(3005) - Set Locale ID

Applies To: OLE Bound Control | OLE Container Control


OLERequestPendingTimeout Property

Specifies how long after an Automation request is made before a busy message is displayed. Read/write at run time.

ApplicationObject.OLERequestPendingTimeout[ = nMilliseconds]

Property Values

nMilliseconds
Specifies the number of milliseconds that must elapse before a busy message is displayed when an Automation request is pending. The busy message is displayed when a mouse or keyboard event occurs. The default value for nMilliseconds is 5,000 milliseconds.

If nMilliseconds is 0, a busy message isn't displayed when an Automation request is pending and a mouse or keyboard event occurs.

See Also

OLEServerBusyRaiseError Property | OLEServerBusyTimeout Property

Applies To: Application Object | _VFP System Variable


OLEServerBusyRaiseError Property

Specifies whether an error message is displayed when an Automation request is rejected. Read/write at run time.

ApplicationObject.OLEServerBusyRaiseError[ = lExpression]

Property Values

lExpression
One of the following settings:
Setting | Description
.T. (True) | An error doesn't occur and a busy message is not displayed when the number of milliseconds specified by the OLEServerBusyTimeout property have elapsed.
.F. (False) | (Default) An error occurs and a busy message is displayed when the number of milliseconds specified by the OLEServerBusyTimeout property have elapsed.

See Also

OLERequestPendingTimeout Property | OLEServerBusyTimeout Property

Applies To: Application Object | _VFP System Variable


OLEServerBusyTimeout Property

Specifies how long an Automation request is retried while a server is busy. Read/write at run time.

ApplicationObject.OLEServerBusyTimeout[ = nMilliseconds]

Property Values

nMilliseconds
Specifies the number of milliseconds for which an Automation request is retried before a server busy message is displayed.

See Also

OLERequestPendingTimeout Property | OLEServerBusyRaiseError Property

Applies To: Application Object | _VFP System Variable


OLETypeAllowed Property

Returns the type of OLE object (embedded or linked) contained in a control. Read-only at design time and run time.

Control.OLETypeAllowed[ = nValue]

Property Values

nValue
Returns a value that indicates the type of OLE object (embedded or linked) contained in a control. Possible values are 0 (Linked), 1 (Embedded), –1 (an OLE Bound control that does not contain an OLE object), and –2 (ActiveX control (.ocx)).

Remarks

OLETypeAllowed is only useful when you specify a setting for the DocumentFile property.

Note You can set the OLETypeAllowed property in code to create a linked OLE object using the DEFINE CLASS command.

See Also

DEFINE CLASS | DocumentFile Property

Applies To: OLE Bound Control | OLE Container Control


OneToMany Property

When moving through records in the parent table, specifies whether the record pointer remains on the same parent record until the record pointer of the child table moves through all related records. Available at design time; read-only at run time.

Object.DataEnvironment.Relation.OneToMany[ = lExpr]

Property Values

lExpr
The settings for the OneToMany property are:
Setting | Description
True (.T.) | The record pointer remains on the same parent record until the record pointer of the child table moves through all related records.
False (.F.) | (Default) The parent table's record pointer moves to the specified record and the child table's record pointer moves to the first related record.

Remarks

The OneToMany property can be used to specify the record pointer movement in a simple parent-child table relationship. To specify the record pointer movement in a more complex relationship (for example, a grandparent-parent-child relationship), use SET SKIP in the Init method for the Form or report.

When OneToMany is set to true (.T.), it mimics the behavior of SET SKIP.

See Also

SET SKIP

Applies To: Relation


OpenViews Property

Determines the type of views associated with a form set, form, or report's data environment that are opened automatically. Available at design time; read-only at run time.

DataEnvironment.OpenViews[ = nExpression]

Property Values

nExpression
The settings for the OpenViews property are:
Setting | Description
0 | (Default) Local and Remote. Both local and remote views for the data environment for the form set, form, or report are opened automatically.
1 | Local only. Only local views for the data environment for the form set, form, or report are opened automatically.
2 | Remote only. Only remote views for the data environment of the form set, form, or report are opened automatically.
3 | None. No views are opened for the data environment of the form set, form, or report.

Remarks

The OpenViews property applies when the AutoOpenTables property is set to true (.T.) or the OpenTables method is executed.

See Also

AutoOpenTables Property | OpenTables Method

Applies To: DataEnvironment


OpenWindow Property

Included for backward compatibility. Use an EditBox control instead.


Order Property

Specifies the controlling index tag for a Cursor object. Available at design time and run time.

DataEnvironment.Cursor.Order[ = cTagName]

Property Values

cTagName
Specifies an existing index tag for a table.

Remarks

If the ChildOrder property of a relation object is set, the Order property is ignored.

Use the Order property to specify the order in which records are displayed or accessed. Setting the Order property changes the index order and moves the record pointer to the first record in the cursor.

See Also

ChildOrder Property | INDEX | SET ORDER

Applies To: Cursor


PageCount Property

Specifies the number of pages contained in a page frame. Available at design time and run time.

PageFrame.PageCount[ = nPages]

Property Values

nPages
Specifies the number of pages contained in a page frame.

Remarks

The minimum value for the PageCount property setting is 0, and the maximum value is 99.

Caution If you decrease the PageCount property setting (for example, if you change the setting from 3 to 2), all pages that exceed the new setting and the objects they contain are lost.

See Also

ButtonCount Property | ControlCount Property | FormCount Property | Page Object

Applies To: PageFrame Control


PageHeight Property

Specifies the height of a page. Read-only at design time and run time.

PageFrame.PageHeight[ = nHeight]

Parameters

nHeight
Specifies the height of the page in the unit of measurement specified by the ScaleMode property of the form.

See Also

PageWidth Property | Page Object | ScaleMode Property

Applies To: PageFrame


PageOrder Property

Specifies the relative order of pages in a page frame. Available at design time and run time.

Page.PageOrder[ = nOrder]

Parameters

nOrder
Specifies the relative order of a page in a page frame.

Remarks

If a page frame contains five pages and you want the third page displayed last, set the PageOrder property of the third page to 5. The PageOrder setting for the fourth page becomes 3, the PageOrder setting for the fifth page becomes 4, and so on.

Note PageOrder settings don't have to be sequential. Also, the PageOrder must be less than or equal to the number of pages in a page frame.

See Also

Activate Event | Deactivate Event | PageFrame Control | ZOrder Method

Applies To: Page


Pages Property

An array used to access individual pages in a page frame. Available at run time only.

PageFrame.Pages(Index).Property[ = Expr]

Parameters

Index
Represents the index of the page you want to access.
Expr
Specifies a property value for the page contained in a page frame.

See Also

Buttons Property | Page Object | PageCount Property

Applies To: PageFrame


PageWidth Property

Specifies the width of the page. Available at design time; read-only at run time.

PageFrame.PageWidth[ = nWidth]

Property Values

nWidth
Specifies the width of the page in the unit of measurement specified by the ScaleMode property of the form.

Remarks

The PageWidth property setting is the same as the Width property setting unless the page frame contains more than one page and the pages are stacked.

See Also

PageHeight Property | Page Object | ScaleMode Property

Applies To: PageFrame


Panel Property

Specifies the active panel in a Grid control. Available at design time; read/write at run time. Available only if the Partition property is set to a value greater than 0.

Grid.Panel[ = nSide]

Property Values

nSide
The settings for the Panel property are:
Setting | Description
0 | Left panel is active.
1 | (Default) Right panel is active.

See Also

PanelLink Property | Partition Property

Applies To: Grid


PanelLink Property

Specifies whether the left and right panels of a Grid control are linked when the grid is split. Available at design time; read/write at run time. Available only if the Partition property is set to a value greater than 0.

Grid.PanelLink[ = lExpr]

Property Values

lExpr
The settings for the PanelLink property are:
Setting | Description
True (.T.) | (Default) The left and right panels of the grid are linked when the grid is split.
False (.F.) | The left and right panels of the grid are not linked when the grid is split.

If PanelLink is set to true (.T.), both panels of the grid are affected when the following properties are set: HeaderHeight, DeleteMark, GridLineColor, GridLines, GridLineWidth, Highlight, RecordMark, RowHeight, and ScrollBars.

If PanelLink is set to false (.F.), the Panel property setting determines which panel the following properties are set on: HeaderHeight, DeleteMark, GridLineColor, GridLines, GridLineWidth, HighLight, RecordMark, RowHeight, and ScrollBars.

See Also

DeleteMark Property | GridLineColor Property | GridLines Property | GridLineWidth Property | HeaderHeight Property | Highlight Property | Panel Property | Partition Property | RecordMark Property | RowHeight Property | ScrollBars Property

Applies To: Grid


ParentAlias Property

Specifies the alias name of the parent table. Read-only at design time and at run time.

DataEnvironment.Relation.ParentAlias[ = cAliasName]

Property Values

cAliasName
Specifies the alias name of the parent table in the relation.

Remarks

The ParentAlias property setting must be the same name as the Alias property setting for the Cursor object that represents the parent table.

See Also

Alias Property | ChildAlias Property

Applies To: Relation


ParentClass Property

Returns the name of the class on which the object's class is based. Read-only at design time and run time.

Object.ParentClass

Remarks

In the Class Designer, the ParentClass property contains the name of the class on which the subclass's class is based.

See Also

Parent Property

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | CursorAdapter Class | Custom | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | _SCREEN | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


ParentTable Property

Contains an object reference to a parent XMLTable object that exists and contains the XMLTable object. Read-only.

XMLTable.ParentTable

Property Values

Object reference. ParentTable contains one of the following:

  • An object reference to the parent XMLTable object when it contains the XMLTable object
  • Null (.NULL.) under the following conditions:
    • You create the XMLTable object by itself, neither contained by an XMLAdapter object nor as the child of another XMLTable object.
    • When the XMLTable object is contained by an XMLAdapter object. The XMLAdapter property contains an object reference to the XMLAdapter object containing the XMLTable object.

See Also

Properties | XMLTable Object Properties, Methods, and Events | XMLAdapter Class

Applies To: XMLTable Class


Partition Property

Specifies whether a Grid control is split into two panels and specifies where the split is relative to the left edge of the grid. Available at design time; read/write at run time.

Grid.Partition[ = nSplit]

Property Values

nSplit
Specifies the position where the grid splits into two panels. If nSplit is 0, the grid isn't split.

Remarks

Note that the SplitBar property takes precedence over the Partition property.

See Also

Panel Property | PanelLink Property | SplitBar Property

Applies To: Grid


PasswordChar Property

Determines whether the characters entered by a user or placeholder characters are displayed in a TextBox control; determines the character used as a placeholder. Available at design time and run time.

TextBox.PasswordChar[ = cCharString]

Property Values

cCharString
Specifies the characters displayed in a text box.

Remarks

Use this property to create a password field in a dialog box. Although you can use any character, most applications use the asterisk (*), ANSI character 42.

This property does not affect the Value property setting; it contains exactly what the user types or what was set from code. Set PasswordChar to an empty string ("") to display the actual text. The default setting is an empty string.

You can assign any string to this property, but only the first character is significant; all others are ignored.

See Also

Format Property | InputMask Property | Value Property

Applies To: TextBox Control


Picture Property

Specifies an image to display on a control. Available at design time and run time.

Control.Picture [ = cFileName ]

Parameters

cFileName
Character data type. The cFileName parameter specifies the name of a graphics file.

Visual FoxPro supports all graphics file formats handled by Graphics Device Interface+ (GDI+). For details about valid graphics file formats, see Graphics Support in Visual FoxPro.

Remarks

Images display centered on the control.

For CommandButton and OptionButton controls, the specified image is used whether a button is available, selected, or unavailable. You can specify a different image for each button state by setting the DownPicture and DisabledPicture properties.

To display the image for CommandButton, CheckBox, and OptionButton controls, you need to set the following Style property values for the corresponding control.

Control | Style property setting
CommandButton | 0 (Standard)
CheckBox, OptionButton | 1 (Graphical)

For Header objects, if the header does not contain a caption, the image appears in the center of the header. If the header contains a caption, the Header Alignment property determines how the image aligns with caption text. If Header Alignment is set to left or center, the image appears to the right of the caption. If Alignment is set to right, the image appears to the left of the caption.

For Toolbars, the recommended image dimensions are 16 x 15 pixels (width x height).

For ComboBox and ListBox controls, you can use the Picture property as single-value property or as an array. If you use Picture as a single-value property, all items in the control show the same image. If you use Picture as an array, which stores an image for each item in the list, each item can have a different image. For example:

oCombobox.AddItem("Home")
oCombobox.AddItem("Community")
oCombobox.AddItem("Web Services")
oCombobox.Picture[1] = 'home.bmp'
oCombobox.Picture[2] = 'community.bmp'
oCombobox.Picture[3] = 'websvc.bmp'
Note If you set the Picture property at design time, and the file you specify does not exist, Visual FoxPro displays the appropriate message, but the property remains set to the file you specified. Visual FoxPro disregards the Picture property at run time if it is set to a file that does not exist.

Visual FoxPro supports animated .gif files for the Picture property only on an Image control.

See Also

DisabledPicture Property | DownPicture Property | Style Property | Adding Pictures to Items in a List

Applies To: CheckBox Control | CommandButton Control | ComboBox Control | Container Object | Control Object | Custom Object | Form Object | Header Object | Image Control | ListBox Control | OptionButton Control | Page Object | _SCREEN System Variable |


PicturePosition Property

Specifies the location of a picture relative to its caption. Read/write at run time.

Object.PicturePosition [ = nValue ]

Parameters

nValue
Specifies alignment for a picture. The following table lists the settings for nValue.
nValue | Setting
0 | The picture appears to the left of the caption. The picture aligns with the top of the caption.
1 | The picture appears to the left of the caption. The picture is centered relative to the caption.
2 | The picture appears to the left of the caption. The picture aligns with the bottom of the caption.
3 | The picture appears to the right of the caption. The picture aligns with top of the caption.
4 | The picture appears to the right of the caption. The picture is centered relative to the caption.
5 | The picture appears to the right of the caption. The picture aligns with the bottom of the caption.
6 | The picture appears above the caption. The picture aligns with the left edge of the caption.
7 | The picture appears above the caption. The picture is centered above the caption.
8 | The picture appears above the caption. The picture aligns with the right edge of the caption.
9 | The picture appears below the caption. The picture aligns with the left edge of the caption.
10 | The picture appears below the caption. The picture is centered below the caption.
11 | The picture appears below the caption. The picture aligns with the right edge of the caption.
12 | The picture appears in the center of the control. The caption is centered horizontally and vertically with top of the picture.
13 | The picture appears in the center of the control. The caption is centered below the picture but stays relative to the bottom of the button when resized. (Default)

Remarks

The picture and caption, as a unit, are centered on the control. If no caption exists, the picture is located relative to the center of the control.

The PicturePosition property is supported on OptionButton and CheckBox controls when their Style properties are set to a value of 1 (Graphical). When Style is set to a value other than 1, Visual FoxPro disregards PicturePosition in addition to Picture.

Visual FoxPro disregards PicturePosition if the Picture property does not specify a picture. For CommandButton controls, Visual FoxPro disregards PicturePosition if Style is set to 1 (Invisible).

Wordwrapping and the AutoSize property are supported with PicturePosition.

The SpecialEffect and VisualEffect properties affect the outer border but do not affect PicturePosition.

As with current behavior, the size of the image is fixed. If you want to stretch, resize, or crop the image, you must use an Image control.

Versions earlier than Visual FoxPro 8.0 use a positioning algorithm that differs slightly from the standard 0 – 12 settings. The image always remains centered; however, the text remains relative to the bottom of the image.

When PicturePosition is set to a value of 7, similar behavior occurs. However, as the button size is reduced, the text is cropped instead of shifted towards the top of of the button. Setting PicturePosition to a value of 13 corresponds with behavior in versions prior to Visual FoxPro 8.0.

Animated .gif files are not supported.

The PicturePosition property applies to the Picture, DownPicture, and DisabledPicture properties.

See Also

Properties | Picture Property | Style Property | AutoSize Property | SpecialEffect Property | VisualEffect Property | Image Control | DownPicture Property | DisabledPicture Property

Applies To: CommandButton Control | OptionButton Control | CheckBox Control


PictureSelectionDisplay Property

Specifies how an image appears in the text box portion of a ComboBox control.

Note You can specify an image by setting the Picture property of the control to an image file name.
Combobox.PictureSelectionDisplay = nExpr

Parameters

nExpr
Numeric data type. The following table lists the values of nExpr.
nExpr | Description
0 (None) | Does not display the image in the text box of the combo box. (Default)
1 (Clip) | The image is clipped to the same height of the text box of a combo box. The width of the image remains the same.
2 (Isometric) | The image resizes to fit the height of the text box of a combo box while maintaining its original proportions.
3 (Stretch) | The image resizes to fit the height of the text box of a combo box but does not maintain its original proportions. The width of the image remains the same.

Remarks

If the combo box Style property is set to 0 (Drop-down ComboBox), images display in the text box of the combo box with the following behavior:

  • When the list portion of the combo box is not visible, and you are typing text directly into the combo box, the default image, if specified, appears until the text matches an item in the list. If no match exists, the default image appears even when the control loses focus.
  • The Margin property of the combo box specifies text spacing, plus padding, from the left and top borders of the text box. When an image appears in the text box, the Margin property specifies the spacing between the image borders and the left and top borders of the text box. The horizontal spacing between the right border of the image and the text is always four pixels, regardless of the setting of the Margin property of the combo box. The text cursor appears two pixels from the right border of the image. You can insert additional space by providing an image containing white space.
    Note Even if Margin is set to 0, a three-pixel space from the left border and top borders exists to provide space for the text cursor. Specifying a value for Margin adds pixels to this padding. However, if an image appears, Margin affects only the margin between the top border of the text box and the text. The left margin of the text always appears four pixels from the image to maintain alignment of items inside the list.

If the combo box Style property is set to 2 (Drop-down List), images display in the text box of the combo box with two pixels of horizontal spacing between the right border of the image and the text.

See Also

Properties | Margin Property | Picture Property

Applies To: ComboBox Control


Prepared Property

Specifies whether to prepare SQL statements for subsequent REQUERY( ) function calls. You can use REQUERY( ) to retrieve data again for an SQL view. When handling this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting Prepared for applies only to CursorAdapter objects overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.

For more information, see REQUERY( ) Function and SQLPREPARE( ) Function.

CursorAdapter.Prepared [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Prepare SQL statements for subsequent REQUERY( ) function calls. (Default)
False (.F.) | Do not prepare SQL statements for subsequent REQUERY() function calls.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


PreserveWhiteSpace Property

Preserves or removes white space from XML output. Read/write.

PreserveWhiteSpace applies only when executing the XMLAdapter LoadXML and ToXML methods, which respectively retrieve and create XML consistent with these settings.

XMLAdapter.PreserveWhiteSpace [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Removes white space. (Default)
True (.T.) | Preserves white space.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | LoadXML Method | ToXML Method

Applies To: XMLAdapter Class


Procedure Property

Specifies the name of the procedure or method where an exception occurs. Read/write at run time.

Exception.Procedure

Property Value

Character data type

Remarks

Identical to the value returned by the PROGRAM() function.

See Also

Properties | Exception Object Properties, Methods, and Events | PROGRAM( ) Function | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


PROCESSID Property

Returns the unique identifier of the current process.

_VFP.ProcessID

Remarks

You can use this property to evaluate resource usage during debugging.

See Also

Application Object

Applies To: Application Object | _VFP


ProgID Property

Contains the registered PROGID (Programmatic Identifier) for a server in a project. Read-only at design time and run time.

Object.ProgID

Remarks

A PROGID is created in the Windows registry for a server when you build an executable file (.exe) or dynamic link library (.dll) from a project.

See Also

CLSID Property | CREATEOBJECTEX( ) | TypeLibCLSID Property | TypeLibDesc Property | TypeLibName Property

Applies To: Server Object


ProjectHook Property

An object reference to the ProjectHook object instantiated for a project.

Object.ProjectHook[ = oProjectHookClass]

Property Values

oProjectHookClass
Specifies a class based on the Visual FoxPro ProjectHook base class. By default, contains an object reference to the default ProjectHook class specified in the Project tab of the Project Information dialog box.

Remarks

The ProjectHook property contains the null value if it has not been assigned a class based on the ProjectHook base class or the project doesn't have a default ProjectHook class (specified in the Project tab of the Project Information dialog box). Assigning the null value to ProjectHook property releases the ProjectHook object, but doesn't affect the default ProjectHook class for the project.

For more information about projects, see Project Manager Hooks.

See Also

ProjectHook Object | ProjectHookClass Property | ProjectHookLibrary Property

Applies To: Project Object


ProjectHookClass Property

The default ProjectHook class for a project.

Object.ProjectHookClass[ = cClassName]

Property Values

cClassName
Specifies the default ProjectHook class for a project. Before you can specify a ProjectHook class for a project, specify the .vcx visual class library containing the ProjectHook class with the ProjectHookLibrary property.

To delete the default ProjectHook class for a project, set the ProjectHookClass or ProjectHookLibrary property to the empty string.

Remarks

You can also specify the default ProjectHook class for a project in the Project tab of the Project Information dialog box.

Changing the ProjectHookClass property doesn't instantiate the new ProjectHook object. The change takes effect the next time the project is opened. To change the current ProjectHook object, use the ProjectHook property.

For more information about projects, see Project Manager Hooks.

See Also

ProjectHook Object | ProjectHook Property | ProjectHookLibrary Property

Applies To: Project Object


ProjectHookLibrary Property

The .vcx visual class library containing the default ProjectHook class for a project.

Object.ProjectHookLibrary[ = cLibraryName]

Property Values

cLibraryName
Specifies a .vcx visual class library that contains a class based on the ProjectHook base class. After you specify the .vcx visual class library with this property, use the ProjectHookClass property to specify the default class for the project.

To delete the default ProjectHook class for a project, set the ProjectHookLibrary or ProjectHookClass property to the empty string.

Remarks

You can also specify the default ProjectHook class for a project in the Project tab of the Project Information dialog box.

Changing the ProjectHookLibrary property doesn't instantiate the new ProjectHook object. The change takes effect the next time the project is opened. To change the current ProjectHook object, use the ProjectHook property.

For more information about projects, see Project Manager Hooks.

See Also

ProjectHook Object | ProjectHook Property | ProjectHookClass Property

Applies To: Project Object


ReadBackColor, ReadForeColor Properties

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadCycle Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadLock Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadMouse Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadObject Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.

ReadSave Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadOnly Property

Specifies whether the user can edit a control, specifies whether a table or view associated with a Cursor object allows updates, or contains a value the indicates if a file in a project can be edited. Available at design time; read/write at run time.

 [Form.]Control.ReadOnly[ = lExpr]
DataEnvironment.Cursor.ReadOnly[ = lExpr]
Project.Files.Item(nItem).ReadOnly

Property Values

lExpr
The settings for the ReadOnly property are:
Setting | Description
True (.T.) | The user cannot edit the control.The table or view associated with the Cursor object cannot be modified.
False (.F.) | (Default) The user can edit the control.The table or view associated with the Cursor object can be modified.

Remarks

Note When the Cursor is accessed using CURSORSETPROP( ), the ReadOnly property is read-only at run time.

The ReadOnly property differs from the Enabled property because when ReadOnly is set to true (.T.), the user can still move to the control.

For Cursors, ReadOnly mimics the NOUPDATE clause of USE.

For combo box controls, the ReadOnly property cannot be set to true (.T.) when the Style property is set to 2 – Drop-down List.

For a file in a project, the ReadOnly property contains a logical value that indicates if the file can be edited. If ReadOnly is true (.T.), the file can be edited; otherwise the file cannot be edited. Read-only at design time and run time.

See Also

Enabled Property | USE

Applies To: CheckBox | Column | ComboBox | Cursor | EditBox | File Object | Grid | Spinner | TextBox


ReadTimeout Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


RecordMark Property

Specifies whether the record selector column is displayed in a Grid control. Available at design time; read/write at run time.

Grid.RecordMark[ = lExpr]

Property Values

lExpr
The settings for the RecordMark property are:
Setting | Description
True (.T.) | (Default) The record selector column is displayed in a Grid.
False (.F.) | The record selector column is not displayed in a Grid.

See Also

ScrollBars Property | Controlling Record Selection with Joins

Applies To: Grid


RecordSource Property

Specifies the source of data to which the Grid control is bound. Available at design time; read/write at run time.

Grid.RecordSource[ = cName]

Property Values

cName
cName is typically the alias name of a cursor or the name of a table. The RecordSource property specifies the main cursor that the grid is bound to.

Remarks

If you specify a record source for a grid, you can specify the contents of individual columns in the grid by setting their ControlSource property. If you do not set the ControlSource property for a column in the grid, the column displays the next available undisplayed field of the grid's record source.

See Also

ControlSource property | Order Property | RecordMark Property | RecordSourceType Property

Applies To: Grid


RecordSourceType Property

Specifies how the data source that populates the Grid control is opened. Available at design time and read/write at run time.

Grid.RecordSourceType[ = nType]

Property Values

nType
The settings for the RecordSourceType property are:
Setting | Description
0 | Table. Automatically opens the table specified in the RecordSource property setting.
1 | (Default) Alias. Treats the record source as specified.
2 | Prompt. The user is prompted for the record source at run time. If a database is open, the user can choose one of the tables it contains as a record source.
3 | Query (.qpr). The RecordSource property setting specifies a .qpr file.
4 | SQL Statement. The SQL statement is specified in the RecordSource property.

See Also

RecordSource Property | Setting the Data Environment

Applies To: Grid


RelationalExpr Property

Specifies the expression based on fields in the parent table that relates to an index in the child table joining the two tables. For the Grid control, available at design time; read/write at run time. For the Relation object, available at design time; read-only at run time.

Object.RelationalExpr[ = cExpr]

Property Values

cExpr
Specifies any Visual FoxPro expression, typically one that matches the child table's current index as specified by the ChildOrder property.

See Also

ChildOrder Property | LinkMaster Property | SET RELATION

Applies To: Grid | Relation


RelativeColumn Property

Specifies the active column in the visible portion of a Grid control. Not available at design time and read-only at run time.

Grid.RelativeColumn[ = nColumn]

Property Values

nColumn
Specifies the active column in a Grid control.

Remarks

Use the RelativeColumn property to determine the relative position of the active column in a grid. For example, if you scroll through a grid so that the first column is no longer visible, but the active column is the first visible column in the grid, RelativeColumn is set to 1. To determine the absolute position of the active column in a grid, use the ActiveColumn property.

See Also

ActiveColumn Property | ActiveRow Property | RelativeRow Property

Applies To: Grid


RelativeRow Property

Contains the active row in the visible portion of a Grid control. Not available at design time and read-only at run time.

Grid.RelativeRow

Property Values

nRow
Numeric data type. RelativeRow contains the number of the active row in a Grid control.

Remarks

You can use RelativeRow to determine the relative position of the active row in a grid. For example, if you scroll through a grid so that the first row is no longer visible, but the active row is the first visible row in the grid, RelativeRow is set to 1.

To determine the absolute position of the active row in a grid, use the ActiveRow property.

See Also

Properties | ActiveColumn Property | ActiveRow Property | RelativeColumn Property

Applies To: Grid


ReleaseType Property

Returns an integer that determines how a Form object is released. Not available at design time; read-only at run time.

Object.ReleaseType

Property Values

The settings for the ReleaseType property are:

Setting | Description
0 | Variable released.
1 | Close menu command or close box.
2 | Exit Visual FoxPro.

Remarks

The ReleaseType property is set prior to the QueryUnload event being called.

See Also

QueryUnload Event | Unload Event

Applies To: Form Object | _SCREEN System Variable


ReleaseXML Method

Releases the attached IXMLDOMElement object.

XMLAdapter.ReleaseXML( [lDisposeSchema] )

Parameters

lDisposeSchema
Determines whether schema information is cleaned by ReleaseXML. The following table lists the values for lDisposeSchema.
lDisposeSchema | Description
True (.T.) Clean Tables collection and sets the following XMLAdapter properties:
  • XMLName, XMLNamespace, and XMLPrefix to an empty string ("")
  • IsDiffGram to False (.F.)
  • SOM to null (.NULL.)
  • XMLConstraints to null (.NULL.)

(Default)
False (.F.) | Schema information remains and XMLAdapter XMLName, XMLNamespace, XMLPrefix, IsDiffGram, XMLConstraints, and SOM remain unchanged.

See Also

Methods | XMLAdapter Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | XMLName Property | XMLNamespace Property | XMLPrefix Property | IsDiffGram Property | SOM Property | XMLConstraints Property

Applies To: XMLAdapter Class


Resizable Property

Specifies whether a Column object can be sized at run time by the user. Available at design time; read/write at run time.

Column.Resizable[ = lExpr]

Property Values

lExpr
The settings for the Resizable property are:
Setting | Description
True (.T.) | The Column object is sizable.
False (.F.) | (Default) The Column object cannot be sized by the user.

See Also

Width Property | Resize Object | Resize Event

Applies To: Column


RespectCursorCP Property

Specifies whether to take the code page of the cursor into consideration.

Note The UTF8Encoded property works in conjunction with the setting of RespectCursorCP when UTF8Encoded is True (.T.).

RespectCursorCP applies only when executing the XMLAdapter ToXML method, which creates XML consistent with its setting.

For more information about how code pages map to XML encoding attributes, see CURSORTOXML( ) Function.

XMLAdapter.RespectCursorCP [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Create XML with default Windows-1252 encoding. (Default)
True (.T.) | Set encoding to the code page of the cursor.

Remarks

For example, the following table describes how RespectCursorCP and UTF8Encoded interact with each other.

RespectCursorCP | UTF8Encoded | Conversion performed
False | False | Windows-1252 (Default)
True | False | Set output encoding attribute to the code page of the cursor.
False | True | Set output encoding attribute to UTF-8. No character translation occurs.
True | True | Set output encoding attribute to UTF-8. Translate character data to UTF-8.
True | False | Set output encoding attribute to the code page of the cursor.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | UTF8Encoded Property | ToXML Method

Applies To: XMLAdapter Class


RightToLeft Property

Ignored unless you are running a Middle Eastern version of Microsoft Windows. Specifies the reading order of text in controls and the display of streaming output on forms. Available at design time; read/write at run time.

Object.RightToLeft[ = lExpression]

Property Values

lExpression
The settings for the RightToLeft property are:
Setting | Description
True (.T.) | (Default) Text is entered and displayed in controls in a right to left reading order. Streaming output (for example, text displayed with ? or ??) is displayed on forms in a right-to-left reading order.
False (.F.) | Text is entered and displayed in controls in a left-to-right reading order. Streaming output is displayed on forms in a left-to-right reading order.

Remarks

Use the Alignment property to specify the orientation of text in check boxes and option buttons.

See Also

Alignment Property

Applies To: CheckBox | ComboBox | CommandButton | EditBox | Form | Grid | Label | ListBox | OptionButton | PageFrame | _SCREEN | Spinner | TextBox


RotateFlip Property

Specifies a rotation or inversion (flip) for an image. Read/write at design and run time.

Image.RotateFlip [ = nValue ]

Parameters

nValue
Numeric data type. The following table lists the values for nValue.
nValue | Setting | Description
0 | RotateNoneFlipNone | Specifies no rotation or flipping.
1 | Rotate90FlipNone | Specifies a 90-degree rotation without flipping.
2 | Rotate180FlipNone | Specifies a 180-degree rotation without flipping.
3 | Rotate270FlipNone | Specifies a 270-degree rotation without flipping.
4 | RotateNoneFlipX | Specifies no rotation and a horizontal flip.
5 | Rotate90FlipX | Specifies a 90-degree rotation followed by a horizontal flip.
6 | Rotate180FlipX | Specifies a 180-degree rotation followed by a horizontal flip.
7 | Rotate270FlipX | Specifies a 270-degree rotation followed by a horizontal flip.

Remarks

Animated .gif images are not supported.

Because an image can have an .msk file, the .msk file must be formatted properly.

Note Visual FoxPro stores a single image in memory internally. If you use that image multiple times, Visual FoxPro renders it the same way regardless of RotateFlip. If you want to display the same image multiple times in various rotations, rename each copy of the image that you use. If you issue the CLEAR...RESOURCES command, Visual FoxPro reloads the image into memory and loses any prior GDI+ settings.

See Also

Properties | Graphics Support in Visual FoxPro | CLEAR Commands | PicturePosition Property | Picture Property

Applies To: Image Control


RowColChange Property

Contains a value that identifies the type of cell movement made in a grid. Readonly at design and run-time.

Grid.RowColChange

Remarks

The value of RowColChange is 0 at opening and after refresh of a grid. You can query this property in AfterRowColChange and BeforeRowColChange events to determine the type of change that triggered the event, according to the following table.

Value | Description
0 (default) | No change.
1 | Row change
2 | Column change
3 | Row and column change

See Also

Grid Control | AfterRowColChange Event | BeforeRowColChange Event

Applies To: Grid


RowHeight Property

Specifies the height of the rows in a Grid control. Available at design time; read/write at run time.

Grid.RowHeight[ = nHeight]

Property Values

nHeight
Specifies the height of all the rows in a Grid control.

Remarks

If RowHeight is set to –1 (Auto), it automatically resizes the rows to fit the current FontSize property setting.

See Also

FontSize Property | RowColChange Property | RowSource Property

Applies To: Grid


RowSource Property

Specifies the source of the values in a ComboBox or ListBox control. Available at design time and run time.

Control.RowSource[ = cName]

Property Values

cName
Specifies the source of the values.

Remarks

The source of the values can be a comma-delimited list of values, a table, a SQL statement that creates a cursor or a table, a query, an array, a comma-delimited list of fields (which may be prefaced by a period and the table alias), a file skeleton (such as *.dbf or *.txt), a table's field names, or a menu. Use the RowSourceType property to set the type of row source.

You can use RowSource to specify multiple columns for a ComboBox or ListBox control at design time. To specify multiple columns, set RowSourceType to 1 (Value) and specify the RowSource values (separated by a comma) as follows:

Col1Row1,Col2Row1,Col1Row2,Col2Row2,,Col2Row3

To specify an alias for the table containing the columns, use the following syntax:

Alias.Col1Row1,Col2Row1,Col1Row2,Col2Row2,,Col2Row3

The values you specify fill the control, by row, up to the number of columns that are specified by the ColumnCount property. The preceding example assumes that ColumnCount is set to 2. As shown in the preceding example, there will be no value in column 1, row 3 because there are two successive commas with no value entered between them preceding column 2, row 3.

Example

The following example creates a list box. The source of the items that appear in the list box items is an array; the name of the array is specified with the RowSource property. The RowSourceType property is set to 5 (array) to specify that an array is the source for the items in the list box.

The MultiSelect property for the list box is set to true (.T.), allowing you to make multiple selections from the list box. The item or items you choose in the list box are displayed by using the ListCount, Selected and List properties to determine the number of items in the list box and the items you chose.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
NEXT

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" Command button
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add ListBox control

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Array containing listbox items

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

ColumnCount Property | RecordSource Property | RowSourceType Property

Applies To: ComboBox | ListBox


RowSourceType Property

Specifies the type of source for the values in a control. Available at design time and run time.

Control.RowSourceType[ = nSource]

Property Values

nSource
The settings for the RowSourceType property are:
Setting | Description
0 | (Default) None. When the default value is used, fill the list at run time using the AddItem or AddListItem method.
1 | Value. Populated by a comma-delimited list.
2 | Alias. Use the ColumnCount property to select fields in the table.
3 | SQL Statement. A SQL SELECT command that creates a cursor or a table.
4 | Query (.qpr). Specify a file name with a .qpr extension.
5 | Array. Set the columns property to display multiple dimensions.
6 | Fields. A comma delimited list of fields. The fields may be prefaced by the table alias and a period.
7 | Files. List is populated from the current directory. Specify file skeleton (such as *.dbf or *.txt) or mask in the RowSource property.
8 Structure. Fields from the table specified in RowSource.

Note that when RowSourceType is set to 8, if the RowSource property is empty the currently selected table is used as the source of the values in a ComboBox or ListBox control. Otherwise, the RowSource property specifies the alias of the table, the name of the table, or the name of the database used as the source of the values in a ComboBox or ListBox control.
9 | Pop-up. Included for backward compatibility.

For more information about using each of the RowSourceType settings, see Application of List Boxes and Drop-Down List Boxes .

Example

The following example creates a list box. The source of the items that appear in the list box items is an array; the name of the array is specified with the RowSource property. The RowSourceType property is set to 5 (array) to specify that an array is the source for the items in the list box.

The MultiSelect property for the list box is set to true (.T.), allowing you to make multiple selections from the list box. The item or items you choose in the list box are displayed by using the ListCount, Selected and List properties to determine the number of items in the list box and the items you chose.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
NEXT

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .f.  && Disable the Control menu box

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" Command button
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add ListBox control

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Array containing listbox items

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.lstListBox1.Visible =.T.  && "List Box visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item
      ENDIF
   ENDFOR

ENDDEFINE

See Also

RowSource Property

Applies To: ComboBox | ListBox


ScaleMode Property

Specifies the unit of measurement for the coordinates of an object when using graphics methods or when positioning controls. Available at design time and run time.

Object.ScaleMode = nMode

Property Values

nMode
The settings for the ScaleMode property are:
Setting | Description
0 | Foxels (A Visual FoxPro term. Equivalent to the maximum height and average width of a character in the current font.)
3 | Pixels (default; smallest unit of monitor or printer resolution)

See Also

DrawMode Property | DrawStyle Property

Applies To: Form | _SCREEN | ToolBar


SCCProvider Property

The name of the source code control provider for a project. Read-only.

Object.SCCProvider

Remarks

You can specify a source code control provider for new projects in the Projects tab of the Options dialog box. The SCCProvider property contains the empty string if a project isn't under source control.

See Also

Source Control Software in Visual FoxPro | SCCStatus Property | Projects tab | Options dialog box

Applies To: Project Object


SCCStatus Property

Contains a numeric value indicating the source control status of a file in a project. Read-only at design time and run time.

Object.SCCStatus

Remarks

The following table lists the values the SCCStatus property can contain:

Value | FoxPro.h constant | Description
0 | SCCFILE_NOTCONTROLLED | File is not source controlled.
1 | SCCFILE_NOTCHECKEDOUT | File is in source control but is not checked out.
2 | SCCFILE_CHECKEDOUTCU | File is checked out to the current user.
3 | SCCFILE_CHECKEDOUTOU | File is checked out to someone other than the current user.
4 | SCCFILE_MERGECONFLICT | File has a merge conflict.
5 | SCCFILE_MERGE | File has been merged without conflict.
6 | SCCFILE_CHECKEDOUTMU | File is checked out to multiple users.

See Also

SCCProvider Property | Source Control Software in Visual FoxPro | Putting Projects Under Source Control

Applies To: File Object


ScrollBars Property

Specifies the type of scroll bars an edit box, form, or grid has. Read/write at design time; read-only at run time.

 [Form.]Control.ScrollBars[= nType]

Property Values

nType
For an edit box, the settings are:
Setting | Description
0 | None
2 | (Default) Vertical

For a form, the ScrollBars property settings are:

Setting | Description
0 | (Default) None
1 | Horizontal
2 | Vertical
3 | Both vertical and horizontal

For a grid, the ScrollBars property settings are:

Setting | Description
0 | None
1 | Horizontal
2 | Vertical
3 | (Default) Both vertical and horizontal

Remarks

If enabled, the scroll bars are displayed automatically when the form, grid, or edit box contains more information than can be displayed in the space provided. The Scrollbars property setting is evaluated for a form when the form is instantiated.

If you want to control scrollbar size at run time, specify a non-zero value for nType.

Note Values of nType greater than 0, require more memory in order to accommodate the possible use of the SAVEAS( ) function. To save memory specify nType =0.

The Scrollbars property is ignored for _SCREEN.

See Also

ContinuousScroll Property | DoScroll Method | Scrolled Event

Applies To: EditBox | Form | Grid


Seconds Property

Specifies whether the seconds portion of a DateTime value is displayed in a text box. Available at design time and run time.

Object.Seconds[ = nValue]

Property Values

nValue
One of the following settings:
Setting | Description
0 | Off. The seconds portion of the DateTime value is not displayed.
1 | On. The seconds portion of the DateTime value is displayed.
2 | (Default) The SET SECONDS setting determines if the seconds portion of the DateTime value is displayed. If SET SECONDS is ON, the seconds portion of the DateTime value is displayed. If SET SECONDS is OFF, the seconds portion of the DateTime value is not displayed.

Remarks

The Seconds property setting is ignored if the DateFormat property is set to Short or Long.

See Also

Century Property | DateFormat Property | DateMark Property | Hours Property | SET SECONDS | StrictDateEntry Property

Applies To: TextBox


SelectCmd Property

Specifies the command for retrieving data from the data source in the CursorAdapter DataSourceType property. Read/write at design time and run time.

CursorAdapter.SelectCmd [ = cCommand ]

Property Values

cCommand
Specifies a character string or expression that evaluates to a valid command string.

For XML data sources, cCommand should be one of the following:

  • An expression that evaluates to a valid XML source for the XMLTOCURSOR( ) function. XMLTOCURSOR( ) retrieves the data.
  • An expression that evaluates to an XMLTable object. The XMLTable ToCursor method retrieves the data.

Remarks

If the CursorAdapter UseDeDataSource property is True (.T.), and the cursor adapter is a member of the data environment, the DataEnvironment DataSource and DataSourceType properties override the relevant CursorAdapter properties.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | XMLTOCURSOR( ) Function | XMLTable Class | ToCursor Method

Applies To: CursorAdapter Class


Selected Property

Specifies whether an item is selected in a ComboBox or ListBox control. Not available at design time and read/write at run time.

[Form.]Control.Selected(nIndex) [= lExpr ]

Property Values

nIndex
Numeric data type. Selected specifies the index of an item in a ComboBox or ListBox.
lExpr
Logical data type. The following table lists the settings for the Selected property.
Setting | Description
True (.T.) | Item is selected.
False (.F.) | Item is not selected. (Default)

Remarks

Setting the Selected property on a ListBox control also sets the ListItem property and fires the ProgrammaticChange event.

The Selected property is particularly useful where users can make multiple selections. You can quickly check which items in a list are selected. You can also use this property to select or clear items in a list from within a program. To check whether the third item in a list box is selected, use the following code:

IF MyList.Selected(3)
  WAIT WINDOW "It's selected!"
ELSE
  WAIT WINDOW "It's not!"
ENDIF

Example

The following example creates a list box. An array serves as the source of the items that appear in the list box items, and the name of the array is specified using the RowSource property. The RowSourceType property is set to 5 (array) to specify that an array is the source for the items in the list box.

The MultiSelect property for the list box is set to True (.T.), making it possible for you to make multiple selections from the list box. The item or items you choose in the list box are displayed by using the ListCount, Selected, and List properties to determine the number of items in the list box and the items you chose.

CLEAR

DIMENSION gaMyListArray(10)
FOR gnCount = 1 to 10  && Fill the array with letters
   STORE REPLICATE(CHR(gnCount+64),6) TO gaMyListArray(gnCount)
NEXT

frmMyForm = CREATEOBJECT('Form')  && Create a form.
frmMyForm.Closable = .f.  && Disable window context menu.

frmMyForm.Move(150,10)  && Move the form.

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add "Quit" command button.
frmMyForm.AddObject('lstListBox1','lstMyListBox')  && Add ListBox control.

frmMyForm.lstListBox1.RowSourceType = 5  && Specifies an array.
frmMyForm.lstListBox1.RowSource = 'gaMyListArray' && Specifies array source containing list box items.

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" command button visible.
frmMyForm.lstListBox1.Visible =.T.  && List box visible.

frmMyForm.SHOW  && Display form.
READ EVENTS  && Start event processing.

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create command button.
   Caption = '\<Quit'  && Assign caption on the command button.
   Cancel = .T.  && Assign default Cancel command button (Esc).
   Left = 125  && Command button column.
   Top = 210  && Command button row.
   Height = 25  && Command button height.

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing and close form.
      CLEAR  && Clear main Visual FoxPro window.
ENDDEFINE

DEFINE CLASS lstMyListBox AS ListBox  && Create ListBox control.
   Left = 10  && List Box column
   Top = 10  && List Box row
   MultiSelect = .T.  && Allow selecting more than 1 item.

PROCEDURE Click
   ACTIVATE SCREEN
   CLEAR
   ? "Selected items:"
   ? "---------------"
   FOR nCnt = 1 TO ThisForm.lstListBox1.ListCount
      IF ThisForm.lstListBox1.Selected(nCnt)  && Is item selected?
         ? SPACE(5) + ThisForm.lstListBox1.List(nCnt) && Show item.
      ENDIF
   ENDFOR

ENDDEFINE

See Also

AddItem Method | Clear Method | ItemBackColor, ItemForeColor Properties | | List Property | ListCount Property | ListItemID Property | MultiSelect Property | NewItemID Property | RemoveItem Method | RemoveListItem Method | SelectedID Property | SelectedItemBackColor Property | SelectedItemForeColor Property | TopItemID Property

Applies To: ComboBox Control | ListBox Control


SelectedBackColor, SelectedForeColor Properties

Specifies the background or foreground color for the selected text. Available at design time and run time.

Control.SelectedBackColor[ = nColor]

-Or-

Control.SelectedBackColor = RGB(nRedValue, nGreenValue, nBlueValue)
Control.SelectedForeColor[ = nColor]

-Or-

Control.SelectedForeColor = RGB(nRedValue, nGreenValue, nBlueValue)

Property Values

nColor
Specifies a single number to represent the color.
Note In the Properties window, you can double-click any of the color properties to display the Color dialog box. You can choose or define colors from this dialog box. The red, green, and blue intensities that correspond to the color you choose become the settings for these properties after you close the Color dialog box.

See Also

BackColor, ForeColor Properties | RGB( ) | SelectedItemBackColor Property | SelectedItemForeColor Property

Applies To: ComboBox | EditBox | Spinner | TextBox


SelectedID Property

Specifies whether an item is selected in a combo box or list box. Not available at design time; read/write at run time.

Control.SelectedID(nItemID)[= lExpr]

Property Values

nItemID
Specifies the item ID of an item in a combo box or ListBox.
lExpr
The settings for the SelectedID property are:
Setting | Description
True (.T.) | The item is selected.
False (.F.) | (Default) The item isn't selected.

Remarks

Setting the SelectedID property on a Listbox control also sets the ListItemID property, and fires the Programmatic Change event.

The SelectedID property is particularly useful where users can make multiple selections. You can quickly check which items in a list are selected. You can also use this property to select or deselect items in a list using code. To check whether the third item in a ListBox is selected, issue the following:

IF MyList.SelectedID(3)
  WAIT WINDOW "It's selected!"
ELSE
  WAIT WINDOW "It's not!"
ENDIF

See Also

AddItem Method | Clear Method | List Property | ListCount Property | ListItemID Property | MultiSelect Property | NewItemID Property | RemoveItem Method | RemoveListItem Method | Selected Property | TopItemID Property

Applies To: ComboBox | ListBox


SelectedItemBackColor Property

Specifies the background color for a selected item in a ComboBox or ListBox or cell (TextBox only) in a Grid control. SelectedItemBackColor is related to the HighlightForeColor and HighlightBackColor properties in that you need to control the color of the selected cell in a Grid row. Read/write at design and run time.

Control.SelectedItemBackColor [= nColor ]

-or-

Control.SelectedItemBackColor = RGB( nRedValue, nGreenValue, nBlueValue )

Parameters

nColor
Numeric data type. SelectedItemBackColor specifies an integer representing a single color value. Visual FoxPro derives the default color setting from the Windows operating system color setting for Selected Items. For information about valid color values, see BackColor, ForeColor Properties.

Remarks

You can find the Selected Items color setting in the Advanced Appearance dialog box, which you can open by going to the Start Menu, opening the Control Panel, selecting Display, clicking the Appearance tab, clicking Advanced, and selecting Selected Items from the Item drop-down list.

You can also define colors by entering the RGB value for the property in the Properties window or choose colors by double-clicking the property in the Properties window to display the Color dialog box. The red, green, and blue color values corresponding to the color you choose become the settings for these properties after you close the Color dialog box.

At the Grid control level, SelectedItemBackColor and SelectedItemForeColor apply only to TextBox controls. Though a Grid column can contain many different types of objects, only the default TextBox control is supported. You must set SelectedItemBackColor and SelectedItemForeColor individually at the control level for other controls. The priority of the Grid SelectedItemBack and SelectedItemForeColor settings over the behavior of a specific TextBox control in the column is determined as follows:

  • When Grid HighlightStyle is set to 0, Grid SelectedItemBackColor and SelectedItemForeColor are disregarded, and the properties of the text box take precedence. If Grid HighlightStyle is set to a value of 2, only the highlight colors persist, and selected items display only when a grid has focus.
  • When Grid HighlightStyle is set to a value greater than 0, the following behavior applies:
    • The TextBox control properties control the actual colors of the selected text box.
    • When Grid SelectedItemBackColor and SelectedItemForeColor are explicitly set, the corresponding properties for all TextBox controls the grid are set. This occurs at design time and run time.
    • The grid's property settings take precedence over conflicting text box property settings. If you want the TextBox SelectedItemBackColor and SelectedItemForeColor to override the corresponding grid properties, set the individual text box properties after setting the grid properties.
      Tip You can create routine that performs this process, which provides flexibility should the grid properties change at run time.
    • When setting the TextBox BackColor and ForeColor properties to control how the text box displays when clicked for editing, the Grid SelectedItemBackColor and SelectedItemForeColor properties behave as if the entire cell was selected.

You can reset the colors of a grid and its text boxes to their class default settings by calling the ResetToDefault method for the Grid and TextBox SelectedItemForeColor and SelectedItemBackColor properties.

Note This differs from how Visual FoxPro handles other grid color settings. For example, when you call ResetToDefault on a grid's BackColor property, the underlying columns and text boxes are set to the grid's default BackColor property and not the default BackColor properties of the columns and text boxes.

See Also

Properties | HighlightStyle Property | SelectedItemForeColor Property | TextBox Control | ResetToDefault Method | Selected Property | ItemBackColor, ItemForeColor Properties | RGB( ) Function

Applies To: ComboBox Control | ListBox Control | Grid Control


SelectedItemForeColor Property

Specifies the foreground color of the text of a selected item in a ComboBox or ListBox or cell (TextBox only) in a Grid control. SelectedItemForeColor is related to the HighlightForeColor and HighlightBackColor properties in that you need to control the color of the selected cell in a grid row. Read/write at design and run time.

Control.SelectedItemForeColor [= nColor ]

-or-

Control.SelectedItemForeColor = RGB( nRedValue, nGreenValue, nBlueValue )

Parameters

nColor
Numeric data type. SelectedItemForeColor specifies an integer representing a color value. Visual FoxPro derives the default color setting from the Windows operating system font color setting for Selected Items. For information about valid color values, see BackColor, ForeColor Properties.

Remarks

For more information about the Grid SelectedItemForeColor and GridSelectedItemBackColor properties, see SelectedItemBackColor Property.

See Also

Properties | HighlightStyle Property | TextBox Control | ResetToDefault Method | Selected Property | ItemBackColor, ItemForeColor Properties | RGB( ) Function

Applies To: ComboBox Control | ListBox Control | Grid Control


SelectOnEntry Property

Specifies whether text in a column cell, edit box, or text box selected when the user moves to it. Available at design time and run time.

Object.SelectOnEntry[ = lExpr]

Property Values

The settings for the SelectOnEntry property are:

Setting | Description
True (.T.) | (Default for columns) The text is selected.
False (.F.) | (Default for edit and text boxes) The text isn't selected

Remarks

If the Highlight property is set to true (.T.), you can use it in conjunction with the SelectOnEntry property to determine if the entire text appears selected. If you set the Highlight property to false (.F.), the SelectOnEntry property is ignored.

See Also

Highlight Property | HighlightRow Property

Applies To: Column | EditBox Control | TextBox Control


SelLength Property

Returns the number of characters the user selects in a text-entry area of a control, or specifies the number of characters to select. Not available at design time; read/write at run time.

 [Form.]Control.SelLength[= nLength]

Property Values

nLength
Specifies the number of characters selected. Selected text appears highlighted. The valid range of settings is 0 to the total number of characters in the control. Setting SelLength to less than 0 causes a run-time error.

Remarks

Use this property with the SelStart and SelText properties for tasks such as:

  • Setting the insertion point within a string of characters.
  • Establishing an insertion range that limits where the insertion point can go.
  • Selecting a specific group of characters (substrings) in a control.
  • Clearing text.

When working with these properties, be aware of the following behaviors:

  • Setting SelLength to less than 0 causes a run-time error.
  • Setting SelStart to greater than the text length sets the property to the existing text length. Changing SelStart changes the selection to an insertion point and sets SelLength to 0.
  • Setting SelText to a new value sets SelLength to 0 and replaces the selected text with the new string.

See Also

SelStart Property | SelText Property

Applies To: ComboBox | EditBox | Spinner | TextBox


SelStart Property

Returns the starting point of a text selection made by the user in a text-entry area of a control, or indicates the position of the insertion point if no text is selected. Also, specifies the starting point of a text selection in a text-entry area of a control. Not available at design time; read/write at run time.

 [Form.]Control.SelStart[= nStart]

Property Values

nStart
Specifies the starting point of text selected or indicates the position of the insertion point if no text is selected. Selected text appears shaded. The valid range of settings is 0 to the total number of characters in the edit area of the control.

Remarks

Use this property with the SelLength and SelText properties for tasks such as:

  • Setting the insertion point within a string of characters.
  • Establishing an insertion range that limits where the insertion point can go.
  • Selecting a specific group of characters (substrings) in a control.
  • Clearing text.

When working with these properties, be aware of the following behaviors:

  • Setting SelLength to less than 0 causes a run-time error.
  • Setting SelStart to greater than the text length sets the property to the existing text length. Changing SelStart changes the selection to an insertion point and sets SelLength to 0.
  • Setting SelText to a new value sets SelLength to 0 and replaces the selected text with the new string.

See Also

SelLength Property | SelText Property

Applies To: ComboBox | EditBox | Spinner | TextBox


SelText Property

Returns the text that the user selected in a text-entry area of a control, or returns an empty string ("") if no characters are selected. Specifies the string containing the selected text. Not available at design time; read/write at run time.

 [Form.]Control.SelText[= cString]

Property Values

cString
Specifies the string containing the selected text or consists of an empty string if no characters are selected. Selected text appears shaded.

Remarks

Use this property with the SelLength and SelStart properties for tasks such as:

  • Setting the insertion point within a string of characters.
  • Establishing an insertion range that limits where the insertion point can go.
  • Selecting a specific group of characters (substrings) in a control.
  • Clearing text.

When working with these properties, be aware of the following behaviors:

  • Setting SelLength to less than 0 causes a run-time error.
  • Setting SelStart to greater than the text length sets the property to the existing text length. Changing SelStart changes the selection to an insertion point and sets SelLength to 0.
  • Setting SelText to a new value sets SelLength to 0 and replaces the selected text with the new string.

See Also

SelLength Property | SelStart Property | Applies To: ComboBox | EditBox | Spinner | TextBox


SendUpdates Property

Specifies whether to send an SQL update query to update tables. When handling this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting SendUpdates for applies only to CursorAdapter objects with ODBC or ADO data sources and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.SendUpdates [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
True (.T.) | Send an SQL update query to update tables when a view is used to make the update. (Default)
False (.F.) | Do not send an SQL update query to update tables.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


ServerClass Property

Contains the name of a server class in a project. Read-only at design time and run time.

Object.ServerClass

Remarks

The names of server classes in a project are also displayed in the Server tab of the Project Information dialog box.

Automation servers are created in Visual FoxPro by adding classes defined as OLEPUBLIC to a project, and then building an executable file (.exe) or dynamic link library (.dll) from the project. You can have as many OLEPUBLIC classes as you want in the project and they can be defined in program files (.prg) or class libraries (.vcx).

For information about creating custom Automation servers, see Creating Automation Servers.

See Also

CREATE CLASS | DEFINE CLASS | ServerClassLibrary Property

Applies To: Server Object


ServerClassLibrary Property

Contains the name of the class library or program containing a server class. Read-only at design time and run time.

Object.ServerClassLibrary

Remarks

The name of the class library or program containing the server class is also displayed in the Server tab of the Project Information dialog box.

Automation servers are created in Visual FoxPro by adding classes defined as OLEPUBLIC to a project, and then building an executable file (.exe) or dynamic link library (.dll) from the project. You can have as many OLEPUBLIC classes as you want in the project and they can be defined in program files (.prg) or class libraries (.vcx).

For information about creating custom Automation servers, see Creating Automation Servers.

See Also

CREATE CLASS | DEFINE CLASS | ServerClass Property

Applies To: Server Object


ServerHelpFile Property

The help file for the type library created for server classes in a project.

Object.ServerHelpFile[ = cHelpFileName]

Property Values

cHelpFileName
Specifies the name of the help file for the type library. By default, cHelpFileName contains the empty string.

Remarks

The help file for a type library is typically used to provide information about properties or methods in server classes when the type library is viewed in a class or object browser. Visual FoxPro includes the Object Browser, which makes it possible for you to view type library information.

A type library is created when you build a .dll or .exe that contains server classes. Visual FoxPro binds the type library with the .dll if you build the .dll on a machine running Windows NT 4.0 or later. If you build the .dll on a machine running Windows 98, Visual FoxPro does not bind the library with the .dll.

If you use the ServerHelpFile property to specify a help file for the type library, you can provide help for the properties or methods in the server classes from within a class or object browser.

See Also

HelpContextID Property | Server Object | Servers Collection | ServerProject Property

Applies To: Project Object


ServerName Property

Contains the full path and file name for an Automation server. Read-only at run time.

ApplicationObject.ServerName

Remarks

The ServerName property makes it possible for you to determine the directory from which an in-process .dll or an out-of-process .exe Automation server was started, facilitating referencing of other files in distributed applications. You can also use ServerName to determine the directory from which a Visual FoxPro .EXE application was started.

The ServerName property for a development version of Visual FoxPro started in an interactive session contains the same value as the FullName property.

See Also

FullName Property | StartMode Property

Applies To: Application Object | _VFP


ServerProject Property

The name of the project containing server classes.

Object.ServerProject[ = cName]

Property Values

cName
Specifies the name of the project containing server classes. The default value is the name of the project containing the server classes, or, identically, the value of the Name property for the project.

Remarks

The ServerProject name you specify is the first section of the ProgID (Programmatic Identifier) that uniquely identifies the server. For example, if you set the ServerProject property to "MyApplication" and the server has an OLEPublic class named "Server1," you access the Server1 class with the syntax "MyApplication.Server1."

This property corresponds to the Project name item on the Server tab of the Project Information dialog box.

See Also

Name Property | Server Object | Servers Collection | ServerHelpFile Property

Applies To: Project Object


ShowInTaskbar Property

Specifies whether the top-level form object appears in the Windows taskbar at runtime. This setting is read-only at runtime.

Form.ShowInTaskbar = lExpr

Parameters

lExpr
Defaults to true (.T.), enabled. False (.F.) disables this property

Remarks

The ShowInTaskbar setting is ignored unless the ShowWindow Property value = 2

See Also

ShowWindow Property | Form Object


ShowTips Property

Determines whether ToolTips are shown for the controls on the specified Form object or the specified ToolBar object. Available at design time and run time.

Object.ShowTips = lExpr

Property Values

lExpr
Determines whether ToolTips are shown for the specified control. The settings for the ShowTips property are:
Setting | Description
True (.T.) | (Default for the ToolBar object) ToolTips are displayed when a user places the mouse on a control.
False (.F.) | (Default for the Form object) ToolTips are not displayed when a user places the mouse on a control.

Remarks

You can specify the text that appears in each ToolTip using the ToolTipText property.

See Also

ToolTipText Property

Applies To: Form | _SCREEN | ToolBar


ShowWindow Property

Specifies whether a form or toolbar is a top-level form or a child form. Available at design time; read-only at run time.

Form.ShowWindow[ = nExpr]

Property Values

nExpr
The settings for the ShowWindow property are:
Setting | Description
0 | In Screen (Default). The form is a child form that is placed in the main Visual FoxPro window.
1 In Top-Level Form. The form is a child form of the active top-level form, which can be the main Visual FoxPro window or another top-level form. Use this setting if you want the child form to be placed inside the active top-level form.

If nExpr is set to 1 when the top-level form is the main Visual FoxPro window, Visual FoxPro automatically resets nExpr to 0.
2 | As Top-Level Form. The form is a top-level form in which child forms can be placed. Note that a top-level form is always modeless, regardless of the WindowType property setting.

Remarks

A child form is a form contained within another form. Child forms cannot be moved outside the bounds of their parent form; when minimized, they appear at the bottom of their parent form. If a parent form is minimized, the child forms are also minimized.

A top-level form is an independent, modeless form without a parent form, and is used to create an SDI (single document interface) application or to serve as the parent for other child forms. Top-level forms work at the same level as other Windows applications, and can appear in front of or behind them. Top-level forms appear on the Windows taskbar.

The Desktop property determines the behavior of a child form. If the Desktop property is set to true (.T.) the child form is not constrained to the borders of its parent form and can be moved anywhere on the Windows desktop. The child form does not appear in the Windows taskbar.

See Also

ACTIVATE WINDOW | AlwaysOnBottom Property | AlwaysOnTop Property | Desktop Property

Applies To: Form | ToolBar


Sizable Property

Specifies whether an object can be sized. Available at design time; read/write at run time.

Object.Sizable = lExpr

Property Values

lExpr
The settings for the Sizable property are as follows:
Setting | Description
True (.T.) | (Default) You can size the object.
False (.F.) | You cannot size the object.

Remarks

For bound and unbound OLE controls, Sizable affects the OLE object that the control contains. If Sizable is set to true (.T.) and you activate the OLE object, you can size it larger or smaller than the OLE control. If the AutoSize property is set to true (.T.), the OLE control automatically resizes to fit the new size of the OLE object when you deactivate it.

Note To make a Form sizable, set the BorderStyle property to 3.

See Also

AutoSize Property | BorderStyle Property

Applies To: OLE Bound Control | OLE Container Control | ToolBar


SizeBox Property

Included for backwards compatibility with the Macintosh. Specifies whether a form has a size box. Available at design time; read/write at run time.

Object.SizeBox = lExpr

Property Values

lExpr
The settings for the SizeBox property are as follows:
Setting | Description
True (.T.) | A size box appears in the lower-right corner of the form if the form's BorderStyle property is set to 3 (the default).
False (.F.) | (Default) No size box appears in the form.

Remarks

The SizeBox provides a way for users to resize a form using the mouse. The size box can appear in a form only if the form's BorderStyle property is set to 3 (Sizable Border), which is the default for new forms.

See Also

BorderStyle Property | ZoomBox Property

Applies To: Form


SOM Property

Contains an object reference to the XML Schema Object Model (SOM) document (ISchema) after the successful execution of the XMLAdapter LoadXML or Attach method.

XMLAdapter.SOM

Property Values

Object reference. SOM contains an object reference to a SOM document or a null value (.NULL.) when not populated.

Remarks

The SOM provides a navigable set of classes that directly reflect the W3C XML Schema Definition (XSD) language specification. These classes make it possible for you to traverse the elements of an XML Schema document and obtain information about properties and declarations and the relationships between them.

For more information about XML SOM ISchema, see the SOM Reference in Microsoft XML Core Services 4.0 reference on the MSDN Library Web site at http://msdn.microsoft.com/library/.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | LoadXML Method | Attach Method

Applies To: XMLAdapter Class


Sorted Property

Specifies whether the items in the list portion of a ComboBox or ListBox control are automatically sorted alphabetically. Available at design time and run time.

 [Form.]Control.Sorted[= lExpr]

Property Values

lExpr
The settings for the Sorted property are as follows:
Setting | Description
True (.T.) | List items are sorted alphabetically (case-sensitive). Visual FoxPro handles almost all necessary string processing to maintain alphabetic order, including changing the index numbers for items as required when items are added or removed from the list.
False (.F.) | (Default) List items are not sorted alphabetically.

Remarks

The Sorted property is only available if the RowSourceType property is set to 0 (None) or 1 (Value).

Note that once the items are sort alphabetically, setting the Sorted property to false (.F.) doesn't restore the items to their original order. To restore the original order, set the control's RowSource property to itself, as in the following example:

MyForm.MyCombo1.Rowsource = MyForm.MyCombo1.Rowsource

See Also

AddItem Method | List Property | ListCount Property | ListItemID Property | RemoveItem Method | RowSource Property | RowSourceType Property

Applies To: ComboBox | ListBox


Sparse Property

Specifies whether the CurrentControl property affects all cells or only the active cell in a Column object. Available at design time; read/write at run time.

Column.Sparse [= lExpr]

Property Values

lExpr
The settings for the Sparse property are as follows:
Setting | Description
True (.T.) | (Default) Only the Column's active cell uses the CurrentControl property setting to accept and display data. The other cells use the TextBox control if the current control for the cells is not the container object or a command button. The other cells remain empty if the current control for the cells is the container object or a command button.
False (.F.) | All cells in the Column object use the CurrentControl property setting to display data; the active cell accepts data.

See Also

Bound Property | CurrentControl Property | DynamicCurrentControl Property

Applies To: Column


SpecialEffect Property

Specifies different format options for a control. Available at design time and run time.

 [Form.]Control.SpecialEffect = nExpr

Property Values

nExpr
For a PageFrame control, Container object, or Control object, the settings for the SpecialEffect property are as follows:
Setting | Description
0 | Raised. The control appears to be raised from the form.
1 | Sunken. The control appears to be set into the form.
2 | Flat.
Note For a PageFrame control, SpecialEffect is available only if the Tabs Property is set to false (.F.). Also, the BorderColor property for a PageFrame applies only when nExpr is set to 2 (Flat).

For all other controls, the settings for the SpecialEffect property are as follows:

Setting | Description
0 | (Default for all controls and objects except the Container object.) 3D. Border of control is raised to simulate a 3-dimensional look.
1 | Plain. Control appears without a 3-dimensional border.
2 | Hot tracking. Provides mouseover effect for specific controls.
Note If the Height property is set to a value too small, the 3D setting has no effect. Hot tracking is supported on the following controls: ListBox, ComboBox, Spinner, TextBox, EditBox, CommandButton, CheckBox, OptionButton. Hot tracking for CheckBox or OptionButton controls is only supported if Style = 2 (graphical). Hot tracking is supported for CommandButtons only when Style <> 1 (invisible). The following table describes hot tracking support.
Control | Default | Mouseover effect
Listbox | Plain | 3D
ComboBox | Plain | 3D
Spinner | Plain | 3D
TextBox | Plain | 3D
EditBox | Plain | 3D
CommandButton | Plain in normal position | 3D
CheckBox | Plain | None
OptionButton | Plain in normal position | 3D

See Also

BackColor, ForeColor Properties | SelectedBackColor, SelectedForeColor Properties

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | ListBox | OptionButton | OptionGroup | PageFrame | Shape | Spinner | TextBox


SpinnerHighValue, SpinnerLowValue Properties

Specifies the highest or lowest value that can be entered into a Spinner control by clicking the up and down arrows. Available at design time and run time.

Spinner.SpinnerHighValue[ = nHigh]
Spinner.SpinnerLowValue[ = nLow]

Property Values

nHigh
Specifies the highest value that can be entered into a spinner with the up arrow.
nLow
Specifies the lowest value that can be entered into a spinner with the down arrow.

See Also

KeyboardHighValue, KeyboardLowValue Properties

Applies To: Spinner


SplitBar Property

Specifies whether the split bar is displayed in a Grid control. Available at design time; read-only at run time.

Grid.SplitBar[ = lExpr]

Property Values

lExpr
One of the following:
lExpr | Description
True (.T.) | (Default) The split bar is displayed in a Grid control, allowing you to split the Grid into two separate panes. To synchronize the two halves of the grid, add "This.Refresh" to the Grid AfterRowColChange event.
False (.F.) | The split bar isn't displayed in a Grid control, preventing you from splitting the Grid into separate panes.

Remarks

Note that the SplitBar property takes precedence over the Partition property.

See Also

GridLines Property | Partition Property

Applies To: Grid Control


StackLevel Property

Specifies the stack level for the program in which the exception occurs. Read/write at run time.

Exception.StackLevel

Property Value

Numeric data type

See Also

Properties | Exception Object Properties, Methods, and Events | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


StartMode Property

Contains a numeric value that indicates how an instance of Visual FoxPro was started. Read-only at run time.

ApplicationObject.StartMode

Remarks

The following table lists the numeric values the StartMode property can contain and how the instance of Visual FoxPro was started.

Value | Description
0 | A development version of Visual FoxPro was started in an interactive session.
1 Visual FoxPro was started as an application object. For example, the following command creates an instance of Visual FoxPro as an application object:
oMyObject = CREATEOBJECT('VisualFoxPro.Application')
2 | Visual FoxPro was started as an out-of-process .exe automation server.
3 | Visual FoxPro was started as an in-process .dll automation server.
4 | Visual FoxPro was started as a distributable .app or .exe file.
5 | Visual FoxPro was started as an in-process .dll automation server for multithreaded use.

For additional information about using Visual FoxPro to create custom automation servers, see Adding OLE.

See Also

CREATEOBJECT( ) | ServerName Property | SYS(2335) – Unattended Server Mode

Applies To: Application Object | _VFP System Variable


StatusBar Property

Specifies the text displayed in the status bar of an instance of Visual FoxPro. Read/write at run time.

ApplicationObject.StatusBar[ = cMessageText]

Property Values

cMessageText
Specifies the text displayed in the status bar.

See Also

SET MESSAGE Command

Applies To: Application Object | _VFP System Variable


StatusBarText Property

Specifies the text that is displayed in the status bar when a control gains focus or when the mouse pointer moves over the control. Read/write at design time and run time.

 [Form.]Control.StatusBarText [= cExpr]

Property Values

cExpr
Character data type. StatusBarText specifies the text that describes the control.

Remarks

Text appears in the status bar only when either the graphical status bar or status section is visible.

Text appears in the status bar for controls that gain focus only when the control gains focus, regardless of how the ShowTips property of the form is set. Text appears in the status bar for controls that never gain focus only when the mouse moves over the control, and the ShowTips property for the form is set to True (.T.). The following controls never gain focus:

  • CommandGroup
  • OptionGroup
  • Container
  • Line
  • Label
  • Image
  • Shape

If the graphical status bar is not visible because SET STATUS BAR is set to OFF, but the status section is visible because SET STATUS is set to ON, the text in the status bar displays in the center of the status section at the bottom of the screen.

See Also

Caption Property

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container | Control | EditBox | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OptionButton | OptionGroup | PageFrame | Shape | Spinner | TextBox


Stretch Property

Specifies how an image is sized to fit inside a control. Available at design time and run time.

 [Form.]Control.Stretch[= nType]

Property Values

nType
The settings for the Stretch property are as follows:
Setting | Description
0 | (Default) Clip. The image is clipped to fit the control.
1 | Isometric. The image resizes to fit the control while maintaining its original proportions.
2 | Stretch. The image resizes to fit the control, but does not maintain its original proportions.

Remarks

You must set the Picture Property of the object before setting Stretch, or the Stretch setting will be ignored.

Example

CREATE FORM xxx nowait
oform=_vfp.ActiveForm
oform.ADDOBJECT("image1","image")
this1=oform.image1
this1.picture= HOME()+"\graphics\bitmaps\assorted\beanie.bmp"
this1.stretch=0
this1.height = 50
this1.width = 50

See Also

Autosize Property | Sizable Property

Applies To: Image | OLE Bound Control | OLE Container Control


StrictDateEntry Property

Specifies whether date and DateTime values must be entered in a specific, strict format in a text box. Available at design time and run time.

Object.StrictDateEntry[ = nValue]

Property Values

nValue
One of the following settings:
Setting Description
0 Loose. Dates and DateTime values can be entered in a loosely formatted manner. The order in which the days, months, and years are entered is determined by the DateFormat property or SET DATE.

Spaces, backslashes, periods, hyphens, and the current date delimiter (specified with the DateMark property or SET MARK ) can be used to delimit date values. If the year is omitted from a date, the current year is used for the date.

A caret (^) can be included as the first character in a date to specify year-month-day date ordering, overriding the order specified by the DateFormat property or SET DATE.

A comma or a space can be used to delimit the date from the time in a DateTime value. When entering just an hour in a DateTime value, the colon can be omitted if the year is included in the date or a comma is used to separate the date from the time.

If an invalid date or DateTime value is entered, an error message is not displayed and the text box value is set to an empty date or DateTime value. You can test for an invalid date in the Valid event.
1 (Default) Strict. Provides compatibility with previous versions of Visual FoxPro.

Dates in date and DateTime values must be entered in a strict 99/99/99 format when CENTURY is set to OFF, or a 99/99/9999 format when CENTURY is set to ON. 99 represents days, months, and years, and 9999 represents years including the century. The order in which the days, months, and years are entered is determined by the DateFormat property or SET DATE.

Remarks

The following table lists valid date and DateTime values you can enter in a text box when StrictDateEntry is set to 0 (Loose).

Date or DateTime value | Description
12 31 | December 31st of the current year.
12 31 98 14 | December 31st of 1998, 2 P.M.
12 31, 14 | December 31st of the current year, 2 P.M.
12 - 31 - 98, 2p | December 31st of 1998, 2 P.M. Note the extra spaces between the hyphen delimiters.
^98-12-31, 2p | December 31st of 1998, 2 P.M. Caret (^) specifies year-month-day date ordering, overriding the order specified by the DateFormat property or SET DATE.
^/12/31 | December 31st of the current year. Caret (^) specifies year-month-day date ordering, overriding the order specified by the DateFormat property or SET DATE.

See Also

Century Property | DateFormat Property | DateMark Property | Hours Property | Seconds Property | SET CENTURY | SET DATE | SET MARK TO | SET STRICTDATE

Applies To: TextBox


Style Property

Specifies certain styles for a control. Read/write at design and run time.

[Form.]Control.Style[= nType]

Property Values

nType
For ComboBox controls, the following table lists the settings for the Style.
nType Description
0 Drop-down combo box, including a list and an edit box.

The user can select from the list or type characters in the edit box.
2 Drop-down list.

The user must select from the list.

Follow these guidelines in deciding which setting to choose:

  • Set Style to 0 (drop-down combo box) to provide a list of choices and allow the user to type a selection in the edit box. Style 0 saves space on a form because the list closes when the user makes a selection.
  • Set Style to 2 (drop-down list) to display a fixed list of choices that the user can select an item from. The list closes when the user selects an item.

For CheckBox and OptionButton controls, the following table lists the settings for the Style property.

nType | Description
0 | Standard
1 Graphical.

The button appears like a command button and can contain both graphics and text. When the button contains both, the position of the text and graphic is determined by the PicturePosition property.

For CommandButton controls, the following table lists the settings for the Style property.

nType | Description
0 | Standard
1 | Invisible

For TextBox controls, the following table lists the settings for the Style property.

nType | Description
0 | Normal (Default)
1 | Included for backward compatibility with the FoxPro version 2.x @ ... SAY command. The text box is read-only and cannot receive focus.

For Toolbar separator objects, the following table lists the settings for the Style property.

nType | Description
0 Normal (Default).

No vertical line rule.
1 | Specifies a vertical line as the separator object in toolbars and is visible at run time only.

For Label and Shape controls, and Container and Control objects, the following table lists the settings for the Style property.

nType | Description
0 | Normal (Default)
3 | Themed

Setting nType to 3 produces the following effects:

  • On a Label control, Style controls the color of the text. If Themes is enabled for a label, Visual FoxPro disregards the Enabled and FontCharSet properties.
  • On a Shape control, Container or Control object, Style controls the color and style of the border. If Themes is turned on for a Shape control, Visual FoxPro disregards the Curvature property.

If an operating system does not support Windows XP Themes, or if Themes is turned off, Visual FoxPro uses the settings for other properties such as SpecialEffect.

See Also

Click Event | DblClick Event | Curvature Property | SpecialEffect Property | Enabled Property | FontCharSet Property

Applies To: CheckBox Control | ComboBox Control | CommandButton Control | OptionButton Control | Separator Object | TextBox Control | ToolBar Object | Label Control | Shape Control | Container Object | Control Object


SYS(1269) - Property Information

Returns a logical value that indicates whether a property setting has changed from its default setting or whether the property is read-only.

SYS(1269, oObjectName, cProperty, nPropertyAttribute)

Return Values

Logical

Parameters

oObjectName
Specifies the object for which the property setting information is returned.
cProperty
Specifies the property for which SYS(1269) returns information.
nPropertyAttribute
Specifies the property attribute.

If nPropertyAttribute is 0, SYS(1269) returns true (.T.) if the property setting has changed from its default setting. SYS(1269) returns false (.F.) if the property setting has not been changed from its default value.

If nPropertyAttribute is 1, SYS(1269) returns true (.T.) if the property setting is read-only. SYS(1269) returns false (.F.) if the property setting is read/write.

Remarks

Use SYS(1269) to determine whether a property setting has been changed from its default value or is read-only before attempting to set the property programmatically.

See Also

CREATE FORM | GETPEM( ) | PEMSTATUS( ) | SYS(1270) - Object Location | SYS(1271) - Object's .SCX File | SYS(1272) - Object Hierarchy


TabIndex Property

Specifies the tab order of controls on a page and the tab order of forms in a form set. Available at design time and run time.

 [Object.]Control.TabIndex[ = nOrder]

Property Values

nOrder
Specifies the tab order for the control.

Remarks

For controls on a form, a tab order is assigned based on the order in which the controls are added. Each new control is placed last in the tab order.

For a form in a form set, a tab order is assigned based on the order in which the form was added. The form with nOrder set to 1 is the first form that is active in the form set. When a user tabs from the last control on a form, the first control on the next form in the tab order gets the focus. If a form is not included in a form set, the TabIndex property is ignored.

You can make changes at design time using the Properties window or at run time using code. However, if you change the TabIndex setting of one control or form, be sure to change the TabIndex setting for all controls on the pages or forms in the form set. If you do not designate a tab order for all controls or forms, Microsoft Visual FoxPro assigns the tab order for the remaining controls and forms based on the order in which they are added and changed at run time, which can produce unintended results.

To ignore the tab order of a control or a form, set the TabStop property to false (.F.).

See Also

TabStop Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Label | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Spinner | TextBox


Tables Property

Specifies a comma-delimited list of table names, which must have the table names in the exact order you want them to appear in the SQL UPDATE, INSERT, and DELETE commands. When working with this property for regular cursors, use the CURSORSETPROP() and CURSORGETPROP() functions. Read/write.

Note You must include this list of table names when using automatic updating for updates to work.
Setting Tables for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.Tables [= cList]

Property Values

cList
Character data type. The cList parameter specifies a comma-delimited list of table names that displays the table names in the exact order you want them to appear in the SQL UPDATE, INSERT, and DELETE commands. No default setting exists.

Remarks

Tables should not refer to a cursor that was attached to a CursorAdapter object by CursorAttach.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


TabOrientation Property

Specifies where the tabs display on a PageFrame control. Read/write at design and run time.

PageFrame.TabOrientation [ = nValue ]

Parameters

nValue
Numeric data type. The following table lists the possible values for nValue.
nValue | Setting
0 | Top (default)
1 | Bottom
2 | Left
3 | Right

Remarks

You can usually specify hotkeys in Page captions by including the "\<" characters. Though Visual FoxPro functionally supports hotkeys when TabOrientation is set to left or right positions, the hotkeys do not visually display.

See Also

Properties | Themes Property

Applies To: PageFrame Control


Tabs Property

Specifies whether a page frame has tabs. Available at design time and run time.

PageFrame.Tabs[ = lExpr]

Property Values

lExpr
The settings for the Tabs property are as follows:
Setting | Description
True (.T.) | (Default) The page frame has tabs.
False (.F.) | The page frame does not have tabs.

Remarks

Specify the text on the tabs by setting the Caption property of the page. The width of the tab is increased if the Caption width is greater than the default width of the tab. Shorter captions have no effect on tab width.

See Also

Caption Property | AllowTabs Property | TabStop Property

Applies To: PageFrame


TabStop Property

Specifies whether a user can use the TAB key to move the focus to an object. Available at design time and run time.

 [Object.]Control.TabStop[ = lExpr]

Property Values

lExpr
Specifies whether an object is included in the tab order. The settings for the TabStop property are as follows:
Setting | Description
True (.T.) | (Default) The control or form is included in the tab order, as determined by the TabIndex property.
False (.F.) | The object is ignored in the tab order. For a control, when a user presses the TAB key, the focus skips a control that has its TabStop property set to false (.F.). For a form, when a user presses the TABkey on the last control on a form and the next form in the tab order has its TabStop property set to false (.F.), the focus moves to the first control on the same form. The focus does not move to the next form in the tab order.

Remarks

If TabStop property is set to false (.F.) for a control or form, the control or form is skipped when the TAB key is used to move through the tab order, but it can still receive the focus when the mouse is used.

Note The TabStop property is read-only when it applies to a control contained in a Column object.

See Also

TabIndex Property

Applies To: CheckBox | ComboBox | CommandButton | Container Object | Control Object | EditBox | Form | Grid | ListBox | OLE Bound Control | OLE Container Control | OptionButton | Page | PageFrame | _SCREEN | Spinner | TextBox


TabStretch Property

Specifies the behavior if the tabs do not fit on the page frame. Available at design time and run time. TabStretch is available only if Tabs is set to true (.T.).

PageFrame.TabStretch[ = nSetting]

Property Values

nSetting
The settings for the TabStretch property are as follows
Setting | Description
0 | Stack. A second row of tabs is created.
1 | (Default) Clip. The tabs are clipped as necessary.

See Also

Tabs Property | TabStyle Property

Applies To: PageFrame


TabStyle Property

Specifies whether the Page tabs in a page frame are justified or non-justified. Available at design time and run time.

PageFrame.TabStyle[ = nStyle]

Property Values

nStyle
One of the following:
nStyle Description
0 (Default) Justified. The width of each page tab is adjusted to accommodate its caption. If necessary, the width of each page tab is increased so the page tabs span the entire width of the PageFrame.

This setting is ignored if the TabStretch property is set to 1, Single Row.
1 Non-justified. The width of each page tab is not adjusted to accommodate its caption. The width of each page tab is not adjusted so that the page tabs span the entire width of the PageFrame.

This setting is ignored if the TabStretch property is set to 1, Single Row.

See Also

TabStretch Property | AllowTabs Property

Applies To: PageFrame


Tag Property

Stores any extra data needed for your program. Available at design time and run time.

Object.Tag[ = Expr]

Property Values

Expr
Specifies any string.

Remarks

By default, the Tag property is set to an empty string (""). You can use this property to assign any string to an object without affecting it in any way. Unlike other properties, the value of the Tag property is not used by Visual FoxPro.

See Also

Comment Property

Applies To: CheckBox | Collection Class | ComboBox | CommandButton | CommandGroup | CursorAdapter Class | EditBox | Exception Class | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | ProjectHook Object | _SCREEN | Session Object | Shape | Spinner | TextBox | Timer


TerminateRead Property

Included for backward compatibility with the READ command.


Text Property

Contains the unformatted text entered in the textbox portion of a control. Not available at design time; read-only at run time.

Object.Text

Remarks

Unlike the Value property, the value contained in the Text property is unformatted and is identical to the text entered in the control by the user.

The unformatted text contained in a control's Text property can differ from the control's Value property for the following reasons:

  • The Value property may not be of Character type; it may contain a Date or Numeric value.
  • For an edit box, the Value property may add line feeds to the text entered in the edit box, providing compatibility with previous versions. For this reason, using the Text property is the preferred method for selecting text with the SelStart and SelLength properties.
  • If the Format property for the control uses the R setting, input mask characters are removed from the Value property.

If the Style property for a combo box control is set to 2 (Drop-down List), the Text property contains the empty string because the ComboBox does not have a text box.

See Also

Format Property | SelStart Property | SelLength Property | Style Property | Value Property

Applies To: ComboBox | EditBox | Spinner | TextBox


Themes Property

Specifies whether Windows XP Themes are enabled or disabled for a control. For forms and toolbars, Themes controls whether child objects are themed. Read/write at design and run time.

Note The Themes property for visual classes can affect your existing user interface when using Microsoft Windows XP. You can turn this support off by setting the Themes property at the control, form, or _SCREEN system variable level.
Object.Themes [ = lExpr ]

Parameters

lExpr
Logical data type. The following table lists the settings for lExpr.
lExpr
True (.T.) | Enabled (Default)
False (.F.) | Disabled

Remarks

Controls defined using @...GET or @...SAY and similar @... commands are not compatible with Windows XP Themes. Therefore, when running programs written with FoxPro 2.x on Windows XP or later, you should set the _SCREEN Themes property to False (.F.); otherwise, the controls on the forms disappear.

When Themes is enabled, Visual FoxPro overrides the SpecialEffect property and uses the default theme except when SpecialEffect is set to a value of 2 (hot tracking). In this scenario, Visual FoxPro preserves hot tracking, which displays special effects when you move the mouse over the CommandButton, graphical OptionButton and CheckBox controls.

For CheckBox controls, Themes supports three-state check boxes.

For Form and ToolBar objects, Themes enables themes for the entire form. To enable themes for a control, you need to set Themes to True (.T.) for both the form and control. For other container controls such as PageFrame, Themes does not control how child objects display themes; it controls only visual aspects such as borders or tabs.

Note When Themes are enabled, you should avoid using the CLEAR COMMAND for forms because it might cause paint issues with themed controls, such as command buttons, that have mouse hovering effects.

For OptionGroup, CommandGroup, and Image controls, Themes determines whether borders are themed.

Controls such as PageFrame tabs and Grid headers are dynamically drawn by the operating system Themes manager when you move your mouse over them. Therefore, do not position other controls on top of these controls.

For a Grid control, Themes affects the visual appearance of column headers. If themes are enabled for a grid, the BackColor and ForeColor properties of the header are disregarded because they inherit the attributes of the theme. However, the BackColor and ForeColor properties of a Column object display independently from the setting of a grid's Themes property.

For PageFrame controls, Themes determines whether tabs are themed. You might need to make minor modifications to forms that contain PageFrame objects. The Themes property provides a gradient effect on Page objects, so a label, option button, or similar control with text does not appear correctly if the BackStyle property of the control is set to Opaque. You can remedy this situation by setting BackStyle to Transparent.

If your operating system does not support themes, or if Themes is turned off, Visual FoxPro uses the settings controlled by SpecialEffect and other properties.

You can use set _SCREEN Themes property to False (.F.) to disable Themes entirely in Visual FoxPro.

Note When you set _SCREEN Themes property, you do not actually alter the current state of Themes set at the operating system level. You should use SYS(2700) - Enables Windows XP Themes to check the current state of Themes.

For more specific details about Windows XP Themes, see the following resources:

  • "Using Windows XP Visual Styles" at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwxp/html/xptheming.asp
  • "Visual Styles" at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/CommCtls/Userex/themes.asp
  • "Microsoft Windows XP: What's in It for Developers?" at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwxp/html/winxpintro.asp

See Also

Properties | SpecialEffect Property | _SCREEN System Variable | Style Property | SYS(2700) - Enables Windows XP Themes

Applies To: CheckBox Control, ComboBox Control | CommandButton Control | CommandGroup Control | Form Object | Grid Control | Image Control | ListBox Control | OptionButton Control | OptionGroup Control | PageFrame Control | Spinner Control | TextBox Control | ToolBar Object


ThreadID Property

Returns the Win32 ID of the thread on which the object was called.

_VFP.ThreadID

Remarks

You can use this property especially during debugging. For instance, you can use it to compare the threadID of a received call with the threadID of the object receiving the call.

See Also

Application Object

Applies To: Application Object | _VFP


TitleBar Property

Specifies if a title bar appears at the top of a form.

Object.TitleBar[ = nExpression]

Property Values

nExpression
The settings for the TitleBar property are as follows:
Setting | Description
0 | The title bar is not displayed.
1 | (Default) The title bar is displayed.

Remarks

If the TitleBar property is set to 0, a title bar is not displayed and the window pop-up menu and the Minimize, Maximize, and Close buttons are not available.

See Also

Closable Property | MaxButton Property | MinButton Property | WhatsThisButton Property

Applies To: Form


ToCursor Method

Creates a cursor specified by XMLTable with the fields described by the XMLTable Fields collection and loads it with data from the referenced XML document.

ToCursor is supported only for XMLTable objects in the XMLAdapter Tables collection.

XMLTable.ToCursor( [ lAppend [, cAlias [, Reserved ]]] )

Parameters

lAppend
Specifies whether to append data or records to an existing cursor specified by the cAlias parameter. The following table lists the values for lAppend.
lAppend | Description
False (.F.) | Does not add fields to an existing cursor. (Default)
True. (.T.) | Adds fields to an existing cursor.
cAlias
Specifies the alias for the target cursor. The value of cAlias defaults to the XMLTable Alias property, including when cAlias is an empty string ("").
Reserved
Reserved for future use. The default value is 0.

Remarks

If the XMLField Alias property is empty, the XMLTable ToCursor method disregards XMLField objects and creates a cursor that does not include any fields specified by those XMLField objects.

When you use ToCursor in append mode, Visual FoxPro adds an empty row if no XMLField object name matches any cursor column.

When mapping binary fields to Character data types, Visual FoxPro fills any remaining white space with 0x00 characters (CHR(0) or zeros) after decoding.

See Also

Methods | XMLTable Object Properties, Methods, and Events | Fields Collection (XMLTable) | XMLName Property | Fields Collection (XMLTable) | Alias Property | ToCursor Method | XMLField Class

Applies To: XMLTable Class


ToolTipText Property

Specifies the text that appears as a ToolTip for a control. You can set the ToolTipText property only if the ShowTips property of the form or toolbar that contains the control is set to True (.T.). Read/write at design and run time.

Control.ToolTipText [= cExpr]

Property Values

cExpr
Specifies the text to use for the ToolTip. The maximum number of characters you can specify for cExpr is 4,095.

Remarks

Visual FoxPro supports wordwrapping for ToolTips.

When you specify the ToolTipText property for contained controls like a Column, Header, or OptionButton, the ToolTipText property of the innermost object takes precedence if the mouse cursor moves over both objects that specify a ToolTip.

For all contained controls except the Grid control, if the contained object does not specify the ToolTipText property, but the container does, Visual FoxPro does not display a ToolTip when the mouse moves over the contained control.

If the objects contained in a Grid control do not specify the ToolTipText property, but the container does, Visual FoxPro displays the ToolTip for the container. For example, if the mouse moves over a column Header object, and the Header does not specify the ToolTipText property, Visual FoxPro displays the ToolTip of the column.

Visual FoxPro displays controls inside a column, for example, a TextBox control, that specify the ToolTipText property only when the control has focus. If the control does not specify a ToolTip when it has focus, the ToolTip of the column is displayed.

Examples

Example 1

The following code sections illustrate how to display ToolTips for contained controls other than a grid. The following example shows how the ToolTips for the CommandButton control and the CommandGroup control display when each control has focus, for example, when you move the mouse pointer over the command button or command group.

CommandGroup1.ToolTipText = "Hi, I'm a CommandGroup."
CommandGroup1.Command1.ToolTipText = "Hi, I'm Command 1."
CommandGroup1.Command2.ToolTipText = "Hi, I'm Command 2."

In the following code section, the ToolTip for Command2 does not display when the control has focus because the ToolTip for the control is not specified.

CommandGroup1.ToolTipText = "Hi, I'm a CommandGroup."
CommandGroup1.Command1.ToolTipText = "Hi, I'm Command 1."

Example 2

The following code sections illustrate how to display ToolTips for controls contained in a grid. The following example shows how the ToolTip for the TextBox control displays when the control has focus, for example, when you move the mouse pointer over the text box.

Grid1.ToolTipText = "Hi, I'm a Grid."
Grid1.Column1.ToolTipText = "Hi, I'm a Column."
Grid1.Column1.Header1.ToolTipText = "Hi, I'm a Header."
Grid1.Column1.Text1.ToolTipText = "Hi! I'm the Textbox!"

In the following code section, the ToolTip for the TextBox control does not display when the control has focus because the ToolTip for the text box is not specified.

Grid1.ToolTipText = "Hi, I'm a Grid."
Grid1.Column1.ToolTipText = "Hi, I'm a Column."
Grid1.Column1.Header1.ToolTipText = "Hi, I'm a Header."

In the following code section, the ToolTip for the column appears when the Header control has focus because the ToolTip for the header is not specified.

Grid1.ToolTipText = "Hi, I'm a Grid."
Grid1.Column1.ToolTipText = "Hi, I'm a Column."

In the following code section, the ToolTip for the grid appears when the Column or Header control has focus because the ToolTip for the column or header is not specified.

Grid1.ToolTipText = "Hi, I'm a Grid."

See Also

ShowTips Property

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container | Control | EditBox | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OptionButton | OptionGroup | PageFrame | Shape | Spinner | TextBox


Top Property

Specifies the distance between the top edge of a control or form and its container object. Available at design time and run time.

Object.Top[ = nValue]

Property Values

nValue
Specifies the distance between the top edge of an object or form and the top edge of its container object.

The default container for a form is the main Visual FoxPro window.

Remarks

The Top property specifies how far from the object's zero position the object is located. For example, if a form is contained within the Visual FoxPro main window, the zero position is immediately below the system menu, or if a toolbar is docked to the top of the main window, immediately below the toolbar.

Use the Left and Top and the Height and Width properties for operations based on an object's external dimensions, such as moving or resizing.

Note The Top property is read-only when it applies to a control contained in a Column object.

The unit of measurement used by the Top property is determined by the control's ScaleMode property setting.

Example

The following example demonstrates how the Top property is used to position controls on a form. The AddObject method is used to add a Line control and three command buttons to a form. The Top property specifies the vertical placement of each control on the form.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

Left Property | Height Property | Move Method | ScaleMode Property | Width Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Custom | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


TopIndex Property

Specifies the item that appears in the top-most position in a list.

Control.TopIndex[ = nIndex]

Property Values

nIndex
Specifies the index of the item that appears in the top-most position in a list.

Remarks

The index of an item reflects its position in the list, which is relative to other items in the list and can change.

Combo box controls are read-only all the time and list box controls are read-only at design time and read/write at run time.

See Also

AddItem Method | Clear Method | List Property | ListCount Property | MultiSelect Property | NewItemID Property | RemoveItem Method | Selected Property | TopItemID Property

Applies To: ComboBox | ListBox


TopItemID Property

Specifies the item ID of the item that appears in the top-most position in a list.

Control.TopIItemID[ = nItemID]

Property Values

nItemID
Specifies the item ID of the item that appears in the top-most position in a list.

Remarks

The default setting for the TopItemID property is 1, or the first item in the list.

Combo box controls are read-only all the time and list box controls are read-only at design time and read/write at run time.

See Also

AddItem Method | Clear Method | List Property | ListCount Property | MultiSelect Property | NewItemID Property | RemoveItem Method | Selected Property | TopIndex Property

Applies To: ComboBox | ListBox


ToXML Method

Generates XML to a file or memory variable.

XMLAdapter.ToXML( cXMLDocument [, cSchemaLocation [, lFile [, lIncludeBefore [, lChangesOnly ]]]] )

Parameters

cXMLDocument
Specifies the file or memory variable name for the XML document.
cSchemaLocation
Specifies the location for a reference to external schema. The default value of cSchemaLocation is empty (""). If cSchemaLocation is empty and external schema has been generated, the value of XMLAdapter XMLSchemaLocation is used as the external schema reference.
lFile
Specifies whether cXMLDocument is a file. The default value of lFile is False (.F.).
lIncludeBefore
Specifies whether to include the diffgr:before section in the DiffGram. The diffgr:before section contains the original version of a row. The default value of lIncludeBefore is False (.F.).

If lIncludeBefore is True (.T.), Visual FoxPro filters deleted records, regardless of the current filter setting, such as SET FILTER TO NOT DELETED( ) and SET DELETED ON or OFF. All deleted records in the table buffer are inserted in the diffgr:before section but have no matching row in the DiffGram DataInstance block.

Although you might want to hide deleted rows by using a filter, the DiffGram indicates which rows were deleted so that the data source can be correctly updated.

Visual FoxPro disregards lIncludeBefore if the XMLAdapter IsDiffGram property is False (.F.).

lChangesOnly
Specifies whether the XML should contain changes only.

Visual FoxPro disregards lChangesOnly if the XMLAdapter IsDiffGram property is False (.F.) or if lIncludeBefore is False (.F.).

Remarks

If the XMLTable Alias property is empty, no XML elements are generated for that XMLTable object, however, the table is included in the schema if one is generated.

For character fields, Visual FoxPro fills any remaining space in the field with white space (0x20). When ToXML maps character fields to binary fields and performs encoding, ToXML encodes the trailing white space regardless of the value for the XMLAdapter PreserveWhiteSpace property.

The following XMLAdapter property settings affect how ToXML is executed:

  • ForceCloseTag
  • FormattedOutput
  • PreserveWhiteSpace
  • RespectCursorCP
  • UTF8Encoded
  • XMLSchemaLocation

XML Encoding When the XMLAdapter RespectCursorCP property is True (.T.), XMLAdapter UTF8Encoded is False (.F.), and two or more table aliases are referenced in the Tables collection, those tables should use the same code page. Otherwise, Visual FoxPro reports an error.

Numeric Overflow Conditions An XMLAdapter object does not load XML containing Visual FoxPro-type numeric overflow conditions, for example, *****.**, in the place of a Numeric or Integer value. The Microsoft XML Core Services (MSXML) parser causes an error similar to the following:

Error 2110 (XML Error): XML Error: XML Parse error: The value of '***' is invalid according to its data type.
The element: 'myfield' has an invalid value according to its data type.
Line 7, Position 17.
   <myfield>***</myfield>

See Also

Methods | XMLAdapter Object Properties, Methods, and Events | IsDiffGram Property | Alias Property | XMLTable Class | Tables Collection (XMLAdapter)

Applies To: XMLAdapter Class


Type Property

Contain a character indicating the file type of a file in a project. Available at design time and run time.

Object.Type

Remarks

The following table list the values the Type property can contain and the corresponding file types.

Value | FoxPro.H Constant | File Type and Extension
d | FILETYPE_DATABASE | Database, .dbc
D | FILETYPE_FREETABLE | Free table, .dbf
Q | FILETYPE_QUERY | Query, .qpr
K | FILETYPE_FORM | Form, .scx
R | FILETYPE_REPORT | Report, .frx
B | FILETYPE_LABEL | Label, .lbx
V | FILETYPE_CLASSLIB | Visual class Library, .vcx
P | FILETYPE_PROGRAM | Program, .prg
L | FILETYPE_APILIB | Visual FoxPro dynamic link library, .fll
Z | FILETYPE_APPLICATION | Application, .app
M | FILETYPE_MENU | Menu, .mnx
T | FILETYPE_TEXT | Text file, varies
x | FILETYPE_OTHER | Other, varies

These values are stored in the Type field of the project's .pjx file.

See Also

FileClass Property | FileClassLibrary Property

Applies To: File Object


TypeLibCLSID Property

The registry CLSID (Class Identifier) for a type library created for server classes in a project. Read-only.

Object.TypeLibCLSID

Remarks

A type library is created and registered when you build a .dll or .exe from a project that contains server classes. Type libraries have a .tlb extension, and are placed in the same directory as the .dll or .exe that is built.

See Also

CLSID Property | ProgID Property | TypeLibDesc Property | TypeLibName Property

Applies To: Project Object


TypeLibDesc Property

The description for a type library created for server classes in a project.

Object.TypeLibDesc[ = cTypeLibraryDescription]

Property Values

cTypeLibraryDescription
Specifies the description for a type library created for server classes in a project. By default, contains the name of the project containing the server classes appended with "Type Library."

Remarks

A type library is created and registered when you build a .dll or .exe from a project that contains server classes. Type libraries have a .tlb extension, and are placed in the same directory as the .dll or .exe that is built.

This property corresponds to the Typelib description item on the Server tab of the Project Information dialog box.

See Also

CLSID Property | ProgID Property | TypeLibCLSID Property | TypeLibName Property

Applies To: Project Object


TypeLibName Property

The name of the type library created for server classes in a project. Read-only.

Object.TypeLibName

Remarks

A type library is created and registered when you build a .dll or .exe from a project that contains server classes. Type libraries have a .tlb extension, and are placed in the same directory as the .dll or .exe that is built.

See Also

CLSID Property | Name Property | ProgID Property | TypeLibCLSID Property | TypeLibDesc Property

Applies To: Project Object


Unicode Property

Specifies how the XMLAdapter LoadXML, Attach, AddTableSchema, and ToXML methods and the XMLTable ToCursor, ChangesToCursor, and ApplyDiffGram methods handle character strings.

XMLField Unicode specifies whether to place a Unicode string into the field.

Note If XMLField IsBinary property is True (.T.), and XMLField Unicode is True (.T.), Visual FoxPro generates the appropriate message.

Read/write at design time and run time.

Object.Unicode [= lValue]

Parameters

lValue
Specifies a logical value that determines the how strings are handled depending on the method being executed or are stored.

The following table describes the values and behaviors of Unicode depending on the method being called or object.

Method or Object lValue
XMLAdapter LoadXML and Attach methods True (.T.): Doubles length of a given string and assigns result to the XMLField MaxLength property.

False (.F.): Assigns length of a given string to the XMLField MaxLength property.

When LoadXML and Attach is called, XMLField Unicode is set to the value of XMLAdapter Unicode for Character and Memo fields.

XMLAdapter AddTableSchema method True (.T.): Assigns value of XMLAdapter Unicode (True, or .T.) to XMLField Unicode.

False (.F.): Assigns value of XMLAdapter Unicode (False, or .F.) to XMLField Unicode.
XMLAdapter ToXML method True (.T.): Divides length of a given character field by 2 and assigns the result to xsd:maxLength.

False (.F.): Assigns length of a given character field to xsd:maxLength.

When using XMLAdapter ToXML, the content of the field is converted from Unicode to the code page of the XML, and the embedded null symbol (CHR(0)+CHR(0)) is considered a string terminator. For Unicode strings stored in Character fields, if the string length is shorter than the field size, the null terminator is required. To terminate the string, use CHR(0)+CHR(0).
XMLTable ToCursor, ChangesToCursor, and ApplyDiffgram methods True (.T.): Creates field with NOCPTRANS flag regardless of XMLField NoCpTrans property and stores a Unicode string in the field. For more information, see SET NOCPTRANS Command.
Note If the XMLField MaxLength property is an odd number, Visual FoxPro generates the appropriate message.

False (.F.): Creates the field as a regular Character or Memo field.
XMLField object True (.T.): Stores a Unicode string in the field.

False (.F.): Stores a non-Unicode string in the field.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLField Object Properties, Methods, and Events | LoadXML Method | Attach Method | ToCursor Method | ChangesToCursor Method | ApplyDiffGram Method | AddTableSchema Method

Applies To: XMLAdapter Class | XMLField Class


UpdatableFieldList Property

Specifies a comma-delimited list of fields in the view and includes fields from the cursor. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note You must include a list of field names for updates to work when using automatic updating.
Setting UpdatableFieldList for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.UpdatableFieldList [= cList]

Property Values

cList
Character data type. The cList parameter specifies a comma-delimited list of fields in the view and includes fields from the cursor.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


UpdateCmd Property

Specifies the command to use when updating tables. Read/write at design time and run time.

CursorAdapter.UpdateCmd [ = cCommand ]

Property Values

cCommand
Character data type. The following table lists the possible values for cCommand.
cCommand | Description
Character string or expression | Specifies a valid command string for the data source in the UpdateCmdDataSource property.
Empty string ("") | The CursorAdapter object generates a SQL UPDATE command automatically if the CursorAdapter AllowUpdate property is set to True (.T.).

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


UpdateCmdDataSource Property

Specifies the data source used by the UpdateCmd property. Read/write at design time and run time.

CursorAdapter.UpdateCmdDataSource [= cDataSource]

Property Values

cDataSource
Character data type. The cDataSource parameter specifies the data source used by the UpdateCmd property.

Remarks

The following table describes behaviors that apply to UpdateCmdDataSource depending on the value of UpdateCmdDataSourceType.

UpdateCmdDataSourceType UpdateCmdDataSource behavior
Empty ("") UpdateCmdDataSource is disregarded. Visual FoxPro uses the data source in the CursorAdapter DataSource property.

However, if the cursor associated with the CursorAdapter object is based on an ActiveX Data Object (ADO) RecordSet, Visual FoxPro uses the functionality of the ADO RecordSet to update a record. To use this functionality, make sure the CursorAdapter DataSourceType property is set to "ADO".
"ADO" UpdateCmdDataSource must be set to a valid ADO Command object. The ActiveConnection property of the ADO Command object must be set to a valid and open ADO Connection object.

Visual FoxPro sets the CommandText property of the ADO Command object to the value of the CursorAdapter UpdateCmd property. Visual FoxPro parses the command for parameters, creates parameter values if found, and sets them in the Command object.

The update operation occurs as:

CursorAdapter.UpdateCmdDataSource.Execute()

For more information about using an ADO RecordSet, automatic updating, and generating SQL commands automatically, see Data Access Management Using CursorAdapters.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


UpdateCmdDataSourceType Property

Specifies the data source type for the data source used by the UpdateCmdDataSource property. Read/write at design time and run time.

CursorAdapter.UpdateCmdDataSourceType [= cDataSourceType]

Property Values

cDataSourceType
Character data type. The cDataSourceType parameter specifies the data source type of the data source in the UpdateCmdDataSource property.

Remarks

If UpdateCmdDataSourceType is empty ("") or null (.NULL.), Visual FoxPro uses the data source in the CursorAdapter DataSource property.

To generate an XML UpdateGram, you must explicitly set the value of UpdateCmdDataSourceType to "XML".

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | UpdateGram Property

Applies To: CursorAdapter Class


UpdateGram Property

Contains the XML UpdateGram generated only under the following conditions:

  • Visual FoxPro executes insert, update, or delete commands.
  • UpdateCmdDataSourceType, InsertCmdDataSourceType, and DeleteCmdDataSourceType properties are set to "XML".

Read–only at design time and run time.

CursorAdapter.UpdateGram

Property Values

Character data type. UpdateGram contains an XML UpdateGram.

Remarks

Even though a CursorAdapter object can generate the XML UpdateGram, you must implement the actual update operation using the appropriate protocols, such as SQL XML through HTTP, SQL XML OLEDB, or XML Web service to .NET.

For more information about automatic updating and XML, see Data Access Management Using CursorAdapters.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


UpdateGramSchemaLocation Property

Specifies the mapping schema name and location passed to the XMLUPDATEGRAM( ) function. Read/write at design time and run time.

Note UpdateGramSchemaLocation applies only when CursorAdapter DataSourceType is "XML". When specified, UpdateGramSchemaLocation is passed to the SchemaLocation parameter in XMLUPDATEGRAM( ). Visual FoxPro does not support creating mapping schemas; therefore, you must supply one.
CursorAdapter.UpdateGramSchemaLocation [= cName]

Property Values

cName
Character data type. The cName parameter specifies a mapping schema name and location, and the default value is an empty string ("").

See Also

Properties | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


UpdateNameList Property

Specifies a comma-delimited list consisting of pairs of local and full remote field names. Each pair of names consists of a local field name followed by the full remote field name. The full remote field name appears as <remote table name>, <remote field name>, where <remote table name> matches the name from the Tables property. Read/write.

Note Setting UpdateNameList for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
You must set UpdateNameList, which you can also use to specify valid Visual FoxPro names for fields in the cursor that have invalid Visual FoxPro field names.

When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions.

CursorAdapter.UpdateNameList [= cList]

Property Values

cList
Character data type. The cList parameter specifies a comma-delimited list consisting of pairs of local and full remote field names.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function | Tables Property

Applies To: CursorAdapter Class


UpdateType Property

Specifies what to do with old data when performing updates. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting UpdateType for a CursorAdapter object overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.UpdateType [= nValue]

Property Values

nValue
Numeric data type. The following table lists the values for nValue.
nValue | Description
1 | Update old data with new data. (Default)
2 | Delete old data and insert new data.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


UseDeDataSource Property

Determines whether to use the data source of the data environment container as the data source for the CursorAdapter object. The data source of the associated data environment is specified by the DataEnvironment DataSource property. Read/write at design time and run time.

Note UseDeDataSource applies only when the cursor adapter exists in the data environment.
CursorAdapter.UseDeDataSource [ = lValue ]

Property Values

lValue
Logical data type. The following table lists the settings for lValue.
lValue | Description
True (.T.) Use the data source of the associated data environment as the cursor adapter data source.

Setting UseDeDataSource to True (.T.) is not appropriate if the data environment contains multiple CursorAdapter objects using ActiveX Data Object (ADO) data sources. Multiple cursor adapters cannot share a single ADO RecordSet. You should set each cursor adapter's DataSource and DataSourceType properties individually.

If the cursor adapter is a member of the data environment, the DataEnvironment DataSource and DataSourceType properties override the relevant CursorAdapter properties.
False (.F.) | Do not use the data source of the associated data environment as the cursor adapter data source.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | DataEnvironment Object Properties, Methods, and Events

Applies To: CursorAdapter Class


UseMemoSize Property

Specifies the minimum size in bytes for returning result columns in memo fields. For example, if the width of a column result exceeds the value of UseMemoSize, the column result is stored in a memo field. Read/write.

Note Setting UseMemoSize applies only for CursorAdapter objects with ODBC or ADO data sources and overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.

When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions.

CursorAdapter.UseMemoSize [= nValue]

Property Values

nValue
Numeric data type. The nValue parameter has a default value of 255 bytes and can vary from 1 byte to 255 bytes.

Remarks

This property applies primarily for remote views and setting it does not affect local views. However, you can preset this property for local views that will be upsized.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function

Applies To: CursorAdapter Class


UserValue Property

Specifies the value passed by the THROW statement used to generate an exception. You can use this value as an object reference. Read/write at run time.

Exception.UserValue

Property Value

Variant data type

See Also

Properties | Exception Object Properties, Methods, and Events | TRY...CATCH...FINALLY Command | Structured Error Handling

Applies To: Exception Class


UTF8Encoded Property

Specifies whether to set encoding to Unicode Transformation Format-8 (UTF-8). UTF8Encoded works in conjunction with the RespectCursorCP property.

UTF8Encoded applies only when executing the XMLAdapter ToXML method, which creates XML consistent with its setting.

XMLAdapter.UTF8Encoded [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Does not set encoding to UTF-8. (Default)
True (.T.) | Sets encoding to UTF-8.

Remarks

The default encoding for XML is UTF-8, whereas for Visual FoxPro, the default encoding is Windows-1252. When you want to output data to XML, you can preserve UTF-8 encoding by setting encoding to UTF-8 and instructing Visual FoxPro to translate double-byte characters to the proper UTF-8 encoding sequence.

If you have a group of characters representing Korean or Chinese text, you can convert those characters to double-byte character sets (DBCS) to view them in Visual FoxPro. You can then reconvert them to UTF-8 when transmitting them across the Web as XML so that other systems can correctly display the data.

For example, the following table describes how RespectCursorCP and UTF8Encoded interact with each other.

RespectCursorCP | UTF8Encoded | Conversion performed
False | False | Windows-1252 (Default)
True | False | Set output encoding attribute to the code page of the cursor.
False | True | Set output encoding attribute to UTF-8. No character translation occurs.
True | True | Set output encoding attribute to UTF-8. Translate character data to UTF-8.
True | False | Set output encoding attribute to the code page of the cursor.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | RespectCursorCP Property | ToXML Method

Applies To: XMLAdapter Class


Value Property

Specifies the current state of a control. Available at design time and run time.

[Form.]Control.Value[ = nSetting]

Property Values

nSetting
For a CheckBox control, the settings for the Value property are:
Setting | Description
0 | (Default) Unchecked.
1 | Checked.
2 | Mixed-value. This setting is only available in code.

For CommandGroup, ComboBox, EditBox, ListBox, OptionGroup, and Spinner controls, the setting for the Value property is the character string or numeric value that is currently selected.

For an OptionButton control, the settings for the Value property are:

Setting | Description
0 | (Default) Indicates the button isn't selected.
1 | Indicates the button is selected.

For a TextBox control, the setting for the Value property is the character string or numeric, date, datetime, currency, or logical value that is currently selected. The default setting is a character string.

Remarks

For the Grid control, the Value property is available only when the Grid control has the focus.

The Value method does not support the Assign method.

The Value property of a CommandGroup or OptionGroup control can be used to determine which button in the group caused an event. It is set to an integer that indicates which button in the group caused the event.

The Value property changes behavior when a control source is set for a control. When a control source is set, the Value property setting of a control is the data type of the variable or field referenced by the ControlSource property. If the data type is not valid for the given control, Visual FoxPro generates an error.

The following is a list of valid data types:

Control | Data Types allowed
CheckBox | Integer, Logical, Numeric
ComboBox | Character, Integer, Numeric
CommandGroup | Character, Integer, Numeric
EditBox | Character, Memo
Grid | Character, Numeric
ListBox | Character, Integer, Numeric
OptionButton | Integer, Logical, Numeric
OptionGroup | Character, Integer, Numeric
Spinner | Currency, Integer, Numeric
TextBox | Any data type

See Also

Bound Property | ListIndex Property

Applies To: CheckBox | ComboBox | CommandGroup | EditBox | Grid | ListBox | OptionButton | OptionGroup | Spinner | TextBox


Version Property

Returns the version number of an instance of Visual FoxPro as a character string. Read-only at run time.

ApplicationObject.Version

See Also

VERSION( )

Applies To: Application Object | _VFP System Variable


VersionComments Property

The comments for a project.

Object.VersionComments[ = cComments]

Property Values

cComments
Specifies the comments for a project. The default value is the empty string.

Remarks

The VersionComments property corresponds to the value of the Comments item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionCompany Property | VersionCopyright Property | VersionDescription Property | VersionLanguage Property | VersionNumber Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionCompany Property

The company name information for a project.

Object.VersionCompany[ = cCompanyName]

Property Values

cCompanyName
Specifies the company name information for a project. The default value is the empty string.

Remarks

The VersionCompany property corresponds to the value of the Company Name item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCopyright Property | VersionDescription Property | VersionLanguage Property | VersionNumber Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionCopyright Property

The copyright information for a project.

Object.VersionCopyright[ = cCopyRight]

Property Values

cCopyRight
Specifies the copyright information for a project. The default value is the empty string.

Remarks

The VersionCopyRight property corresponds to the value of the Legal Copyright item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionDescription Property | VersionLanguage Property | VersionNumber Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionDescription Property

The description for a project.

Object.VersionDescription[ = cDescription]

Property Values

cDescription
Specifies the description for a project. The default value is the empty string.

Remarks

The VersionDescription property corresponds to the value of the File Description item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionCopyright Property | VersionLanguage Property | VersionNumber Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionLanguage Property

The language information for a project.

Object.VersionLanguage[ = nLanguage]

Property Values

nLanguage
Specifies the language ID for a project. FOXPRO.H contains a listing of the values for the primary and sub-language IDs that can be combined to create a valid language ID. For example, the following code sets the VersionLanguage to United States English (0x09 specifies English, 0x0400 specifies United States English) for the current project:
Application.ActiveProject.VersionLanguage = 0x09 + 0x0400

Remarks

The VersionLanguage property corresponds to the value of the Language ID item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionCopyright Property | VersionDescription Property | VersionNumber Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionNumber Property

The build number for a project.

Object.VersionNumber[ = cBuildNumber]

Property Values

cBuildNumber
Specifies a build number for a project. The standard format for a project build number is "MMMM.mmmm.bbbb" where MMMM is the major build number, mmmm is the minor build number, and bbbb is the build number. Separate each component of a project build number with a period (.). Each build number can be zero to four digits (numbers). Do not use letters in the build number. You can specify ".." for cBuildNumber to reset both the minor build number and the build number to zero.

If the AutoIncrement property is set to true (.T.) and you build an executable (.exe) or dynamic link library (.dll) from the project, the build number has leading zeros removed from last portion (".bbbb") of the build number.

The default value is the empty string.

Remarks

The VersionNumber property corresponds to the values of Version Number items in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionCopyright Property | VersionDescription Property | VersionLanguage Property | VersionProduct Property | VersionTrademarks Property

Applies To: Project Object


VersionProduct Property

The product name information for a project.

Object.VersionProduct[ = cProductName]

Property Values

cProductName
Specifies the product name information for a project. The default value is the empty string.

Remarks

The VersionProduct property corresponds to the value of the Product Name item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionCopyright Property | VersionDescription Property | VersionLanguage Property | VersionNumber Property | VersionTrademarks Property

Applies To: Project Object


VersionTrademarks Property

The trademarks information for a project.

Object.VersionTrademarks[ = cTradeMarks]

Property Values

cTradeMarks
Specifies the trademarks information for a project. The default value is the empty string.

Remarks

The VersionTrademarks property corresponds to the value of the Legal Trademarks item in the EXE Version dialog box.

See Also

AGETFILEVERSION( ) | VersionComments Property | VersionCompany Property | VersionCopyright Property | VersionDescription Property | VersionLanguage Property | VersionNumber Property | VersionProduct Property

Applies To: Project Object


VFPXMLProgID Property

References a COM component you can use to override the internal functionality of the CURSORTOXML( ), XMLTOCURSOR( ), and XMLUPDATEGRAM( ) functions.

You can create the COM component in Visual FoxPro, Visual C/C++, Visual Basic or any developer tool that creates COM components with the ability to implement interfaces.

_VFP.VFPXMLProgID [=cValue]

Property Value

cValue
Specifies the ProgID of the COM component class whose functions override the functionality of the listed Visual FoxPro XML functions. Setting cValue to the default empty string ("") value resets use to the internal implementations of these functions.

Remarks

The class you use must implement the IVFPXML interface from the Visual FoxPro type library. To provide methods to overwrite, open the Object Browser from the Tools menu. From the Microsoft Visual FoxPro 8.0 Type Library, drag the IVFPXML interface to a program (.prg) file.

Example

The following example creates a classes that replace the CURSORTOXML( ), XMLTOCURSOR( ), and XMLUPDATEGRAM( ) functions. Create a project for these classes and add custom XML function handler code to the three methods.

DEFINE CLASS MyXMLClass AS session OLEPUBLIC
   IMPLEMENTS IVFPXML8 IN "VisualFoxPro.Application.8"

   * Replaces CURSORTOXML( ).
   PROCEDURE IVFPXML8_CursorToXML(bstrAlias AS STRING, ;
      nOutputFormat AS Number, nFlags AS Number, ;
      nRecords AS Number, bstrOutputFile AS STRING, ;
      bstrSchema AS STRING, bstrSchemaLocation AS STRING, ;
      bstrNameSpace AS STRING, pVFP AS VARIANT) AS VARIANT ;
      HELPSTRING "Converts from a Cursor to XML"
      * Add user code here.
   ENDPROC

   * Replaces XMLTOCURSOR( ).
   PROCEDURE IVFPXML8_XMLToCursor(pvarXMLSource AS VARIANT, ;
      bstrCursorName AS STRING, nFlags AS Number, pVFP AS VARIANT) ;
      AS Number HELPSTRING "Converts from XML to a Cursor"
      * Add user code here.
   ENDPROC

   * Replaces XMLUPDATEGRAM( ).
   PROCEDURE IVFPXML8_XMLUpdateGram8( nFlags AS Number, ;
      bstrCursorList AS STRING, pVFP AS VARIANT , ;
      bstrSchemaLocation AS STRING ) AS VARIANT;
      HELPSTRING "Generates an XML UpdateGram"
      * Add user code here.
   ENDPROC

   * Included for backward compatibility with previous
   * versions of this interface.
   PROCEDURE IVFPXML8_XMLUpdateGram(nFlags AS Number, ;
      bstrCursorList AS STRING, pVFP AS VARIANT) AS VARIANT;
      HELPSTRING "Generates an XML UpdateGram"
      * Add user code here.
   ENDPROC

ENDDEFINE

When you are finished, build the project into a dynamic-link library (.dll) or executable (.exe) file. Set the VFPXMLProgID property to the correct ProgID for your class. For example, if your project name is MyXMLProj, you would set VFPXMLProgID using the following line of code:

_VFP.VFPXMLProgID = "MyXMLProj.MyXMLClass"

With _VFP VFPXMLProgID set to a specific ProgID, calls to CURSORTOXML( ), XMLTOCURSOR( ), or XMLUPDATEGRAM( ) are redirected to the corresponding method in the class specified by that ProgID. A reference to _VFP is also passed to the method, providing a way to access and manipulate data cursors and memory variables. For more information, see _VFP System Variable Properties, Methods, and Events.

Prior to Visual FoxPro 8.0, XMLUPDATEGRAM( ) did not have the cSchemaLocation parameter; therefore, the interface was different. Visual Foxpro supports both interfaces and looks for the current interface first. If unsuccessful, Visual FoxPro then looks for the earlier interface.

The following is a sample class definition for the earlier interface without the cSchemaLocation parameter:

DEFINE CLASS MyXMLClass AS session OLEPUBLIC
   IMPLEMENTS IVFPXML IN "VisualFoxPro.Application.8"

   * Replaces CURSORTOXML( ).
   PROCEDURE IVFPXML_CursorToXML(bstrAlias AS STRING, ;
      nOutputFormat AS Number, nFlags AS Number, ;
      nRecords AS Number, bstrOutputFile AS STRING, ;
      bstrSchema AS STRING, bstrSchemaLocation AS STRING, ;
      bstrNameSpace AS STRING, pVFP AS VARIANT) AS VARIANT ;
      HELPSTRING "Converts from a Cursor to XML"
      * Add user code here.
   ENDPROC

   * Replaces XMLTOCURSOR( ).
   PROCEDURE IVFPXML_XMLToCursor(pvarXMLSource AS VARIANT, ;
      bstrCursorName AS STRING, nFlags AS Number, pVFP AS VARIANT) ;
      AS Number HELPSTRING "Converts from XML to a Cursor"
      * Add user code here.
   ENDPROC

   * Replaces XMLUPDATEGRAM( ).
   PROCEDURE IVFPXML_XMLUpdateGram(nFlags AS Number, ;
      bstrCursorList AS STRING, pVFP AS VARIANT) AS VARIANT;
      HELPSTRING "Generates an XML UpdateGram"
      * Add user code here.
   ENDPROC

ENDDEFINE

See Also

_VFP System Variable | Viewing Type Library Information | XML Functions | CURSORTOXML( ) Function | XMLTOCURSOR( ) | XMLUPDATEGRAM( )


View Property

Specifies the type of view for a Grid control. Available at design time; read/write at run time.

Grid.View[ = nType]

Property Values

nType
If the panes are not split (the Partition property is set to 0), the settings for the View property are:
Setting | Description
0 | Browse
1 | Change

If the panes are split, the settings for the View property are:

Setting | Description
0 | Browse (left pane), Browse (right pane)
1 | Browse (left pane), Change (right pane)
2 | Change (left pane), Browse (right pane)
3 | Change (left pane), Change (right pane)

See Also

Panel Property | PanelLink Property | Partition Property

Applies To: Grid


ViewPortHeight Property

Contains the viewport height for a form. Read-only at design time and run time.

Object.ViewPortHeight

Remarks

The viewport is the rectangular area of a form displayed in the form's container. The form container controls the size of the viewport. If you change the size of a form's container, the viewport also changes size.

The unit of measurement for the viewport height is determined by the form's ScaleMode property setting – pixels (the default) or foxels.

See Also

ScaleMode Property | SetViewPort Method | ViewPortLeft Property | ViewPortTop Property | ViewPortWidth Property

Applies To: Form Object


ViewPortLeft Property

Contains the left coordinate of the form that is visible in the viewport. Read-only at design time and run time.

Object.ViewPortLeft

Remarks

The viewport is the rectangular area of a form displayed in the form's container. The form container controls the size of the viewport. If you change the size of a form's container, the viewport also changes size.

The unit of measurement for the left coordinate of the form is determined by the form's ScaleMode property setting – pixels (the default) or foxels.

See Also

ScaleMode Property | SetViewPort Method | ViewPortHeight Property | ViewPortTop Property | ViewPortWidth Property

Applies To: Form Object


ViewPortTop Property

Contains the top coordinate of the form that is visible in the viewport. Read-only at design time and run time.

Object.ViewPortTop

Remarks

The viewport is the rectangular area of a form displayed in the form's container. The form container controls the size of the viewport. If you change the size of a form's container, the viewport also changes size.

The unit of measurement for the top coordinate of the form is determined by the form's ScaleMode property setting – pixels (the default) or foxels.

See Also

ScaleMode Property | SetViewPort Method | ViewPortHeight Property | ViewPortLeft Property | ViewPortWidth Property

Applies To: Form Object


ViewPortWidth Property

Contains the viewport width for a form. Read-only at design time and run time.

Object.ViewPortWidth

Remarks

The viewport is the rectangular area of a form displayed in the form's container. The form container controls the size of the viewport. If you change the size of a form's container, the viewport also changes size.

The unit of measurement for the viewport width is determined by the form's ScaleMode property setting – pixels (the default) or foxels.

See Also

ScaleMode Property | SetViewPort Method | ViewPortHeight Property | ViewPortLeft Property | ViewPortTop Property

Applies To: Form Object


Visible Property

Specifies whether an object is visible or hidden. Available at design time and run time.

Object.Visible[ = lExpr]

Property Values

lExpr
The settings for the Visible property are:
Setting | Description
True (.T.) | The default in the Form Designer. The object is visible.
False (.F.) | The default in program code. The object is hidden.

Remarks

Setting the Visible property for the _SCREEN system variable in versions of Visual FoxPro for Windows prior to version 5 has no effect.

Even if the object is hidden, it can still be accessed in code.

To hide an object at startup, set the Visible property to false (.F.) at design time. If you set the Visible property in code, you can hide an object and display it at run time in response to a particular event.

When a form's Visible property is set to false (.F.), the form is hidden and the last-active form set, form, or other object becomes active. When a form's Visible property is set to true (.T.), the form becomes visible. Setting a form's Visible property to true (.T.) does not affect the form's Order property setting. The form does not become active when Visible is set to true (.T.). Use the Show method to activate a form and make it visible in the same step.

Note If the Visible property of a form is set to false (.F.), the form isn't displayed, even if the form set's Visible property is set to true (.T.). However, if the form set's Visible property is set to false (.F.), all forms contained in the form set are invisible.

Example

The following example demonstrates how the Visible property is used to display controls after they have been added to a form with the AddObject method.

The AddObject method is used to add a Line control and three command buttons to the form. The Visible property is set to true (.T.) for the Line control and the command buttons, displaying them on the form. The Visible property is also used to hide the Line control before its slant direction is changed, and to display the Line control after its slant direction is changed.

frmMyForm = CREATEOBJECT('Form')  && Create a form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

Show Method | ZOrder Method

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | FormSet | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | Project Object | _SCREEN | Shape | Spinner | TextBox | ToolBar


VisualEffect Property

Makes it possible for you to apply SpecialEffect behaviors programmatically to Visual FoxPro command buttons. Available only at run time.

CommandButton.VisualEffect[ = nValue]

Property Values

nValue
Specifies the format setting of a control according to the following table:
Setting | Description
0 | None. Existing visual effect is unchanged.
1 | Raised. Gives raised visual effect similar to mouse hover with SpecialEffect=2 (Hot Tracking).
2 | Depressed. Gives sunken visual effect similar to having the mouse held down on the command button.

Remarks

Because the Raised setting of VisualEffect (1) conflicts with the 3D SpecialEffect setting, the VisualEffect value of 1 is ignored if SpecialEffect = 0.

See Also

SpecialEffect Property | OLEDropEffects Property | Create Coolbar Control Effects

Applies To: Command Button


VScrollSmallChange Property

Specifies the increment a form scrolls vertically when you click on a scroll arrow. Available at design time and run time.

Object.VScrollSmallChange[ = nExpression]

Property Values

nExpression
Specifies the increment for vertical scrolling. The unit of measure is determined by the Scalemode property setting. The default increment is 10 pixels when the Scalemode property is set to 3 - Pixels.

See Also

HScrollSmallChange Property | ScaleMode Property | ScrollBars Property

Applies To: Form


WhatsThisButton Property

Specifies whether the What's This button appears in a form's title bar. Read-only at run time.

Form.WhatsThisButton[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | Turns display of the What's This button on.
False (.F.) | (Default) Turns display of the What's This button off.

Remarks

The What's This button is not displayed in the form's title bar if the WhatsThisButton property is set to true (.T.) and any of the following are true:

  • The form's WhatsThisHelp property is set to false (.F).
  • The form's BorderStyle property is set to 0 (None).
  • The form's MinButton property is set to true (.T.).
  • The form's MaxButton property is set to true (.T.).

See Also

BorderStyle Property | MaxButton Property | MinButton Property | ShowWhatsThis Method | TitleBar Property | WhatsThisMode Method | WhatsThisHelp Property | WhatsThisHelpID Property

Applies To: Form


WhatsThisHelp Property

Specifies whether context-sensitive Help uses What's This help or the Windows help file specified with SET HELP.

Form.WhatsThisHelp[ = lExpr]

Property Values

lExpr
One of the following:
Setting | Description
True (.T.) | The form uses one of the three What's This Help techniques to open the Windows help file specified with SET HELP and display the topic specified with the WhatsThisHelpID property.
False (.F.) | (Default) The form uses the F1 key to open the Windows help file specified with SET HELP. The Help topic specified with the HelpContextID property is displayed.

Remarks

The three What's This Help techniques are as follows:

  1. A What's This button is displayed in the form title bar. When this button is clicked, the mouse pointer changes to an arrow with a question mark. The Help topic displayed when a control is clicked is specified with the WhatsThisHelpID property for the control.
  2. The WhatsThisMode method is invoked, changing the mouse pointer changes to an arrow with a question mark. The Help topic displayed when a control is clicked is specified with the WhatsThisHelpID property for the control.
  3. The ShowWhatsThis method is invoked for a control. The Help topic displayed is specified with the control's WhatsThisHelpID property.

If Help is set to an HTML Help file (for example, Foxhelp.chm), the Help topic is displayed in the HTML Help viewer. If Help is set to a Windows Help file (for example, Foxhelp.hlp), the Help topic is displayed in a small popup window next to the control.

See Also

HelpContextID Property | SET HELP | ShowWhatsThis Method | WhatsThisButton Property | WhatsThisMode Method | WhatsThisHelpID Property

Applies To: Form


WhatsThisHelpID Property

Specifies a Help topic context ID to provide What's This Help for an object. Available at design time and run time.

Object.WhatsThisHelpID[ = nContextID]

Property Values

nContextID
Specifies the context ID number of a topic in a Help file. nContextID may be negative, zero, or positive. The following table lists the values for nContextID and what is displayed when the object is clicked with the question mark mouse pointer:
nContextID | Description
Negative | (Default, –1) Displays the What's This Help popup with the message "No Help topic is associated with this item."
Zero | Visual FoxPro searches upward through the object's hierarchy for the first object with a positive WhatsThisHelpID property value. If an object with a positive WhatsThisHelpID property value is found, the What's This Help topic is displayed. If an object with a positive WhatsThisHelpID property value is not found, no What's This Help topic is displayed.
Positive | Displays the What's This Help topic corresponding to the context ID specified with nContextID. If no Help topic has the context ID specified with nContextID, the What's This Help popup with the message "No Help topic is associated with this item" is displayed.

See Also

HelpContextID Property | SET HELP | ShowWhatsThis Method | WhatsThisButton Property | WhatsThisHelp Property | WhatsThisMode Method

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Shape | Spinner | TextBox | Timer | ToolBar


WhereType Property

Specifies the fields that the WHERE clause consists of when used for updating tables. When working with this property for regular cursors, use the CURSORSETPROP( ) and CURSORGETPROP( ) functions. Read/write.

Note Setting WhereType for CursorAdapter objects overrides the property setting of a cursor when attached to a CursorAdapter object. That is, changing the settings on the cursor using CURSORSETPROP() has no effect.
CursorAdapter.WhereType [= nValue]

Property Values

nValue
Numeric data type. The following table lists the values for nValue.
nValue | Description
1 or DB_KEY (from FOXPRO.H) | Includes only the primary fields specified by the KeyFieldList property.
2 or DB_KEYANDUPDATABLE (from FOXPRO.H) | Includes the primary fields specified by the KeyFieldList property and any updatable fields.
3 or DB_KEYANDMODIFIED (from FOXPRO.H) | Includes the primary fields specified by the KeyFieldList property and other modified fields.
4 or DB_KEYANDTIMESTAMP (from FOXPRO.H) | Includes the primary fields specified by the KeyFieldList property and a comparison of time stamps.

Remarks

For forced update and delete operations, CursorAdapter uses the value of 1 for the CursorAdapter WhereType property regardless of the actual setting. Otherwise, CursorAdapter respects user settings for WhereType.

See Also

Properties | CursorAdapter Object Properties, Methods, and Events | CURSORGETPROP( ) Function | CURSORSETPROP( ) Function | KeyFieldList Property

Applies To: CursorAdapter Class


Width Property

Specifies the width of an object. Available at design time and run time.

 [Object.]Width[ = nWidth]

Property Values

nWidth
Specifies the width of an object.

Remarks

Use the Height, Width, Left, and Top properties for operations or calculations based on an object's total area, such as sizing or moving the object.

For forms and controls, the values for this property changes as the object is sized by the user or in code. Maximum settings of this property for all objects are system-dependent.

For forms, the Width property specifies the external width of the form, excluding the borders. If the ScrollBars property is set to enable scroll bars, Width does not include space taken up by the scroll bar when it appears.

For controls, the Width property is measured from the center of the control's border so that controls with different border widths align correctly.

Note The Width property is read-only when it applies to a control contained in a Column object.

The Width property is determined in the unit of measurement specified by the ScaleMode property setting.

See Also

Height Property | Left Property | Move Method | ScaleMode Property | Top Property

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Custom | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


WindowList Property

Included for backward compatibility with READ. Use the Form Designer instead of READ.


WindowState Property

Specifies whether a form window is displayed as a maximized, minimized, or normal window at run time. Available at design time and run time.

 [Object.]WindowState[ = nState]

Property Values

nState
The settings for the WindowState property are as follows:
Setting | Description
0 | Normal
1 | Minimized (minimized to an icon). If the main Visual FoxPro window is minimized when you exit Visual FoxPro, the main Visual FoxPro window will not display before exiting. If your application displays a dialog before exiting, be sure to set _SCREEN.WindowState to 0 before displaying the dialog.
2 | Maximized (enlarged to fill the screen)

See Also

Height Property | Left Property | Top Property | Width Property

Applies To: Form | _SCREEN


WindowType Property

Specifies how a form set or form behaves when it is shown or run with DO FORM. Available at design time and run time.

Object.WindowType[ = nType]

Property Values

nType
For a form set, the settings for the WindowType property are as follows:
Setting | Description
0 | Modeless.
1 | Modal. No other forms can become active and the menu can be active. All forms in the form set are active.
2 | Read. The form set behaves as if it were activated by the READ command. Execution stops on the Show method or DO FORM command. When the Form is deactivated, execution continues. (Included for backward compatibility, and available only for Forms converted from previous versions of FoxPro.)
3 | Read Modal. The form set behaves as if it were activated by a READ command's MODAL clause. Program execution stops at the Show method or the DO FORM command. Any forms specified in the WindowList property are available, but other forms and the menu are not available. (Included for backward compatibility, and available only for forms converted from previous versions of FoxPro.)

For a form, the settings for the WindowType property are as follows:

Setting | Description
0 | Modeless.
1 | Modal. No other forms can become active and the menu is inactive. All forms in the form set are active.

Remarks

You cannot change the WindowType setting once the window has been displayed.

The Show method takes a parameter that can override the WindowType setting.

Note The WindowType setting of a form set overrides the individual WindowType settings of the forms it contains. For example, if the WindowType property for a form set is set to 0, all the forms contained in it are modeless, regardless of their individual WindowType property settings.

See Also

DO FORM | READ | READ EVENTS | Show Method | WindowList Property

Applies To: Form | FormSet | _SCREEN


WordWrap Property

Specifies whether a Label control expands vertically or horizontally to fit the text specified with its Caption property when the control is resized. Available at design time and run time.

 [Form.]Label.WordWrap[ = lExpr]

-or-

Specifies whether the text in a grid column header wraps at the column boundary. Available at design time and run time.

 Grid.Column.Header.WordWrap[ = lExpr]

Property Values

lExpr
The settings for the WordWrap property in labels are as follows:
Setting | Description
True (.T.) | The text wraps and the label expands or contracts vertically to fit the text and the size of the font. The horizontal size does not change.
False (.F.) | (Default) The text does not wrap and the label expands or contracts horizontally to fit the length of the text and vertically to fit the size of the font and the number of lines. The vertical size does not change.

The settings for the WordWrap property in grid column headers are as follows:

Setting | Description
True (.T.) | The text wraps but the grid column header does not expand to fit the text and the size of the font. To change the height of the header, use the Grid.HeaderHeight Property.
False (.F.) | (Default) The text does not wrap.
Note Text alignment in grid header is determined by the value of the Header Alignment property. Text is justified and centered for values of 2 - Middle Center, 6 - Top Center, and 9 - Bottom Center.

Remarks

Use this property to determine how a label displays its contents. For example, a graph that changes dynamically might have a label containing text that also changes. To maintain a constant horizontal size for the label and allow for increasing or decreasing text, you would set the WordWrap property to true (.T.).

If you want a label to expand only horizontally, set WordWrap to false (.F.). If you do not want the label to change size, set AutoSize to false (.F.).

See Also

AutoSize Property | Caption Property

Applies To: Header | Label


WrapCharInCDATA Property

Specifies whether to wrap character fields in CDATA sections.

WrapCharInCDATA applies only when executing the following methods:

  • LoadXML
  • Attach
  • AddTableSchema
XMLAdapter.WrapCharInCDATA [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Does not wrap character fields in CDATA sections. (Default)
True (.T.) | Wraps character fields in CDATA sections.

Remarks

The XMLAdapter LoadXML, Attach, and AddTableSchema methods use WrapCharInCDATA to set the XMLField WrapInCDATA property for Character fields.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLField Class | WrapCharInCDATA Property | WrapInCDATA Property

Applies To: XMLAdapter Class


WrapInCDATA Property

Specifies whether the field is wrapped in CDATA sections.

WrapInCDATA applies only to Character, Character (Binary), Memo, or Memo (Binary) fields and when executing the XMLAdapter ToXML method, which creates XML consistent with its setting.

XMLField.WrapInCDATA [= lValue]

Property Values

Logical data type. The value of WrapInCDATA defaults to the value of XMLAdapter WrapMemoInCDATA or WrapCharInCDATA properties as appropriate. The following table lists values for lValue.

lValue | Description
True (.T.) | The field is wrapped in CDATA sections.
False (.F.) | The field is not wrapped in CDATA sections.

See Also

Properties | XMLField Object Properties, Methods, and Events | Visual FoxPro Data and Field Types | ToXML Method | WrapMemoInCDATA Property | WrapCharInCDATA Property

Applies To: XMLField Class


WrapMemoInCDATA Property

Specifies whether to wrap Memo fields in CDATA sections.

WrapMemoInCDATA applies only when executing the following XMLAdapter methods:

  • LoadXML
  • Attach
  • AddTableSchema
XMLAdapter.WrapMemoInCDATA [= lValue]

Property Values

lValue
Logical data type. The following table lists the values for lValue.
lValue | Description
False (.F.) | Does not wrap Memo fields in CDATA sections. (Default)
True (.T.) | Wraps Memo fields in CDATA sections.

Remarks

The XMLAdapter LoadXML, Attach, and AddTableSchema methods use WrapMemoInCDATA to set the XMLField WrapInCDATA property for Memo fields.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLField Class | WrapMemoInCDATA Property | WrapInCDATA Property

Applies To: XMLAdapter Class


XMLAdapter Property

Contains an object reference to an XMLAdapter object only when that XMLAdapter Tables collection contains the XMLTable object.

XMLTable.XMLAdapter

Property Values

Object reference. XMLAdapter contains one of the following:

  • An object reference to an XMLAdapter object whose Tables collection contains the XMLTable object
  • Null (.NULL.) under the following conditions:
    • You create the XMLTable object by itself, neither contained by an XMLAdapter object nor as the child of another XMLTable object.
    • When the XMLTable object is contained by another XMLTable object. The ParentTable property contains an object reference to the parent XMLTable object.

See Also

Properties | XMLTable Object Properties, Methods, and Events | XMLAdapter Class | Tables Collection (XMLAdapter) | ParentTable Property

Applies To: XMLTable Class


XMLConstraints Property

Contains an object reference to the ISchemaItemCollection object after the successful execution of the XMLAdapter LoadXML or Attach method.

If the LoadXML and Attach methods analyze the XML schema, they set XMLConstraints to the appropriate value, although Visual FoxPro neither analyzes nor enforces any constraints declared in the XMLConstraints collection.

Object.XMLConstraints

Property Values

Object reference. XMLConstraints contains an object reference to the ISchemaItemCollection object or a null value (.NULL.) when not populated.

Remarks

XML schema can contain constraints, which are associated with the schema. XMLConstraints provides you with access to constraints defined within the DataSet element.

Visual FoxPro does not include any functionality in XMLAdapter that uses these constraints, but it provides access so that you can obtain constraints information and use them in your application if needed.

In the following XML example, note the location of the Primary Key constraint:

<?xml version="1.0" encoding="Windows-1252"?>
<DataSet xmlns="http://tempuri.org/">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true">
   <xs:complexType>
      <xs:choice maxOccurs="unbounded">
         <xs:element name="Tbl2">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="source"/>
                  <xs:element name="num" type="xs:int"/>
                  <xs:element name="xdtime" type="xs:dateTime"/>
                  <xs:element name="xlog" type="xs:boolean"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
      </xs:choice>
   </xs:complexType>
   <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//Tbl2"/>
      <xs:field xpath="source"/>
   </xs:unique>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
   <Tbl2 diffgr:id="Tbl21" msdata:rowOrder="0">
      <source>Buckner             </source>
      <num>9</num>
      <xdtime>2002-04-03T00:00:00.0000000-08:00</xdtime>
      <xlog>true</xlog>
   </Tbl2>
</NewDataSet>
   </diffgr:diffgram>
</DataSet>

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLTable Object Properties, Methods, and Events | LoadXML Method | Attach Method

Applies To: XMLAdapter Class | XMLTable Class


XMLName Property

Contains the following for the specified objects:

XMLAdapter: XMLName contains the name of the element that specifies where to look for table elements. Read/write.

For more information about how the XMLAdapter LoadXML and Attach methods set this property, see the Remarks section.

XMLTable: XMLName contains the element name for that table in the XML document. Read-only when associated with an XMLAdapter object.

XMLField: XMLName contains the element or attribute name for that field in the XML document. Read-only when attached to an XMLTable object.

Object.XMLName

Property Values

Character data type. XMLName contains a Unicode character string or is empty ("") when not populated.

Note Before assigning a string value to XMLName, you must convert the value to Unicode. You can use the STRCONV( ) function to perform this requirement.

Remarks

The XMLAdapter LoadXML and Attach methods set the XMLAdapter XMLName property as follows:

  • ADO.NET DataSet element name for ADO.NET DataSet
  • "data" for ADO Recordset XML
  • Empty string ("") for Microsoft XML Data Reduced Schema (XDR) as used by Microsoft SQL-XML

If XMLAdapter XMLName is empty, XMLTable ToCursor looks for table elements within element referenced by the XMLAdapter IXMLDOMElement property.

The XMLAdapter ToXML method uses the XMLAdapter XMLName as the DataSet element name. If XMLName is empty, ToXML uses the string, "VFPDataSet".

The XMLTable ChangesToCursor and ApplyDiffgram methods require that XMLAdapter XMLName be set to a nonempty value and that the XML document is in DiffGram format.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLTable Object Properties, Methods, and Events | XMLField Object Properties, Methods, and Events | LoadXML Method | Attach Method | STRCONV( ) Function | ToCursor Method | IXMLDOMElement Property | ToXML Method | XMLName Property | ChangesToCursor Method | ApplyDiffgram Method

Applies To: XMLAdapter Class | XMLTable Class | XMLField Class


XMLNamespace Property

Contains the following for the specified objects:

XMLAdapter: XMLNamespace contains the XML Namespace to which XMLAdapter XMLName belongs, if any. Read/write.

XMLTable: XMLNamespace contains the XML Namespace to which XMLTable XMLName belongs. If empty, the XMLAdapter Namespace property is used instead. Read/write.

Note Only the XMLTable ToCursor, ChangesToCursor, and ApplyDiffgram methods use the XMLTable XMLNameSpace. The XMLField XMLName should belong to the same namespace as XMLTable XMLName.
Object.XMLNamespace

Property Values

Character data type. XMLNamespace contains a Unicode character string or is empty ("") when not populated.

Note Before assigning a string value to XMLNamespace, you must convert the value to Unicode. You can use the STRCONV( ) function to perform this requirement.

Remarks

Note Visual FoxPro disregards the XMLTable XMLNamespace property when executing XMLAdapter ToXML method. Instead, it inserts the XMLTable XMLName and XMLField XMLName into the XMLAdapter XMLNamespace.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLTable Object Properties, Methods, and Events | XMLName Property | ToXML Method | ToCursor Method | ChangesToCursor Method | ApplyDiffgram Method | STRCONV( ) Function

Applies To: XMLAdapter Class | XMLTable Class


XMLPrefix Property

Contains the prefix used to reference the XMLNamespace property for the corresponding object.

Visual FoxPro disregards XMLPrefix unless XMLNamespace for the corresponding object is set to a nonempty value. The XMLAdapter ToXML method disregards XMLTable XMLPrefix.

Object.Prefix

Property Values

Character data type. XMLPrefix contains a Unicode character string or is empty ("") when not populated.

Note Before assigning a string value to XMLPrefix, you must convert the value to Unicode. You can use the STRCONV( ) function to perform this requirement.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | XMLTable Object Properties, Methods, and Events | XMLNamespace Property | ToXML Method | STRCONV( ) Function

Applies To: XMLAdapter Class | XMLTable Class


XMLSchemaLocation Property

Specifies schema information.

XMLSchemaLocation applies only when executing the following XMLAdapter methods:

  • LoadXML
  • Attach
  • ToXML
XMLAdapter.XMLSchemaLocation [= cValue]

Property Values

Character data type. The following table lists the values for cValue.

cValue | Description
"1" | LoadXML processes inline or external schema, if referenced in the XML document. ToXML generates inline schema. (Default)
"schema location" | LoadXML processes inline or external schema, if referenced and accessible in the XML document. Otherwise, Visual FoxPro attempts to load schema from the specified "schema location". ToXML generates external schema in the specified location.
"" (Empty) LoadXML does not:
  • Process any schema during loading.
  • Change the Tables collection.
  • Set the IsDiffGram property.

ToXML does not generate any schema.

See Also

Properties | XMLAdapter Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | IsDiffGram Property

Applies To: XMLAdapter Class


XMLTable Property

Contains an object reference to an associated XMLTable object.

XMLField.XMLTable

Property Values

Object reference. XMLTable contains an object reference to an associated XMLTable object.

See Also

Properties | XMLField Object Properties, Methods, and Events | XMLTable Class

Applies To: XMLField Class


XMLType Property

Contains an object reference to the Microsoft XML Core Services (MSXML) 4.0 lSchemaType object, which contains restrictions, patterns, and so on for the field.

For more information about lSchemaType objects, see the MSXML 4.0 SDK on the MSDN Library Web site at http://msdn.microsoft.com/library/.

XMLField.XMLType

Property Values

Object reference. XMLType contains an object reference to the MSXML 4.0 lSchemaType object.

See Also

Properties | XMLField Object Properties, Methods, and Events

Applies To: XMLField Class


XSDfractionDigits Property

Contains the XML Schema Definition (XSD) fractionDigits value, which appears to the right of the decimal point.

Note XSDfractionDigits is disregarded unless XMLField XSDtype has a nonempty value.

The following XMLAdapter methods populate the XSDfractionDigits property as appropriate:

  • LoadXML
  • Attach
  • AddTableSchema
XMLField.XSDfractionDigits

Property Values

Character data type. XSDfractionDigits specifies the XSD fraction digits.

Remarks

When generating XML using the XMLAdapter ToXML method, you can set this property to specify the fractionDigits restriction in the XSD schema. You might need this behavior when the fractionDigits value required for the schema differs from what Visual FoxPro would otherwise calculate. Visual FoxPro does not perform validation in this situation; therefore, you need to make sure the data conforms to the restrictions imposed by fractionDigits.

See Also

Properties | XMLField Object Properties, Methods, and Events | XSDtype Property | XMLAdapter Class | ToXML Method

Applies To: XMLField Class


XSDmaxLength Property

Contains the XML Schema Definition (XSD) maxLength value.

Note XSDmaxLength is disregarded unless XMLField XSDtype is a nonempty value.

The following XMLAdapter methods populate the XSDmaxLength property as appropriate:

  • LoadXML
  • Attach
  • AddTableSchema
XMLField.XSDmaxLength

Property Values

Character data type. XSDmaxLength specifies the XSD maximum number of units of length.

Remarks

When generating XML using the XMLAdapter ToXML method, you can set this property to specify the maxLength restriction in the XSD schema. You might need this behavior when the maxLength value required for the schema differs from what Visual FoxPro would otherwise calculate. Visual FoxPro does not perform validation in this situation; therefore, you need to make sure the data conforms to the restrictions imposed by maxLength.

See Also

Properties | XMLField Object Properties, Methods, and Events | XSDtype Property | XMLAdapter Class | ToXML Method

Applies To: XMLField Class


XSDtotalDigits Property

Contains the XML Schema Definition (XSD) totalDigits value, which determines numeric precision.

Note XSDtotalDigits is disregarded unless XMLField XSDtype is a nonempty value.

The following XMLAdapter methods populate the XSDtotalDigits property as appropriate:

  • LoadXML
  • Attach
  • AddTableSchema
XMLField.XSDtotalDigits

Property Values

Character data type. XSDtotalDigits specifies the XSD total number of digits.

Remarks

When generating XML using the XMLAdapter ToXML method, you can set this property to specify the totalDigits restriction in the XSD schema. You might need this behavior when the totalDigits value required for the schema differs from what Visual FoxPro would otherwise calculate. Visual FoxPro does not perform validation in this situation; therefore, you need to make sure the data conforms to the restrictions imposed by totalDigits.

See Also

Properties | XMLField Object Properties, Methods, and Events | XSDtype Property | XMLAdapter Class | ToXML Method

Applies To: XMLField Class


XSDtype Property

Contains the XML Schema Definition (XSD) data type of the attribute or the restriction base.

The following XMLAdapter methods populate the XSDtype property as appropriate:

  • LoadXML
  • Attach
  • AddTableSchema

For example, the xsd:int or xs:int XSD Schema data types from the XML Schema are stored as "int", without its prefix, in XSDtype.

XMLField.XSDtype

Property Values

Character data type. XSDtype specifies the XSD data type of the attribute or the restriction base. If XSDtype is empty, the following XMLField properties are disregarded:

  • XSDmaxLength
  • XSDfractionDigits
  • XSDtotalDigits

Remarks

When generating XML using the XMLAdapter ToXML method, you can set this property to specify the XSD data type in the XSD schema. You might need this behavior when Visual FoxPro does not support the data type value required for the schema. Visual FoxPro does not validate data in this situation; therefore, you need to make sure the data conforms to the limits imposed of the specified XSD data type.

See Also

Properties | XMLField Object Properties, Methods, and Events | XMLAdapter Class | ToXML Method

Applies To: XMLField Class


ZoomBox Property

Included for backward compatibility with the Macintosh. Specifies whether a form has a zoom box. Available at design time; read/write at run time.

Object.ZoomBox = lExpr

Property Values

lExpr
The settings for the ZoomBox property are as follows:
Setting | Description
True (.T.) | A zoom box appears in the upper-right corner of the form.
False (.F.) | (Default) No zoom box appears in the form.

See Also

BorderStyle Property | SizeBox Property

Applies To: Form


Methods

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

ActivateCell Method

Add Method (Collection Class)

Add Method (File Object)

AddColumn Method

AddItem Method

AddListItem Method

AddObject Method

AddProperty Method

AddTableSchema Method

AddToSCC Method

ApplyDiffGram Method

Attach Method

AutoFit Method

AutoOpen Method

B

Box Method

Build Method

C

ChangesToCursor Method

CheckIn Method

CheckOut Method

Circle Method

CleanUp Method

Clear Method

ClearData Method

CloneObject Method

Close Method

CloseTables Method

Cls Method

CursorAttach Method

CursorDetach Method

CursorFill Method

CursorRefresh Method

D

DataToClip Method

DeleteColumn Method

Dock Method

DoScroll Method

DoVerb Method

Drag Method

Draw Method

E

Eval Method

F

G

GetData Method

GetFormat Method

GetKey Method

GetLatestVersion Method

H

Help Method

Hide Method

I

IndexToItemID Method

Item Method (File Object)

ItemIDToIndex Method

J

K

L

LoadXML Method

Line Method

M

Modify Method

Move Method

MoveItem Method

N

O

OLEDrag Method

P

Point Method

Print Method

PSet Method

Q

Quit Method

R

ReadExpression Method

ReadMethod Method

Refresh Method

Release Method

ReleaseXML Method

Remove Method

RemoveFromSCC Method

RemoveItem Method

RemoveListItem Method

RemoveObject Method

Requery Method

RequestData Method

Reset Method

ResetToDefault Method

Run Method

S

SaveAs Method

SaveAsClass Method

SetAll Method

SetData Method

SetFocus Method

SetFormat Method

SetMain Method

SetVar Method

SetViewPort Method

Show Method

ShowWhatsThis Method

T

TextHeight Method

TextWidth Method

ToCursor Method

ToXML Method

U

UndoCheckOut Method

V

W

WhatsThisMode Method

WriteExpression Method

WriteMethod Method

X

Y

Z

ZOrder Method


ActivateCell Method

Activates a cell in a Grid control.

Grid.ActivateCell(nRow, nCol)

Parameters

nRow, nCol
Specifies the row and the column that contain the active cell.

See Also

ActiveColumn Property | ActiveRow Property | GridHitTest Method

Applies To: Grid Control


Add Method (Collection Class)

Use to add a member to a collection.

The member object can have any valid type that can be assigned to a memory variable. This includes simple data types, such as strings, numbers, dates, logical, or more complex types such as Visual FoxPro and Component Object Model (COM) objects.

Collection.Add( eItem [, cKey [, [eBeforeItem |, eAfterItem ]]] )

Parameters

eItem
Specifies an expression of any type that represents a member to add to the collection. Usually, this is an object, but it could be a number, string, or member that has a valid type.
cKey
Specifies an optional, unique, alphanumeric (character type) expression that represents a key string, instead of a positional index, that can be used to access a member of the collection.

For collections using keys, cKey is a case-sensitive parameter and cannot be empty or have a null value (.NULL.).

Either all items added to the collection must have the cKey parameter specified for them or not specified because of performance reasons. The first item added determines the behavior for the collection. You can test for the presence of keys in a collection by using the following code:

GetKey(1)

If the key already exists for a member in the collection, an error occurs. However, because cKey is case-sensitive, no duplication error occurs if the same keys with different case are added. A key includes any trailing spaces present in cKey.

[, [ eBeforeItem |, eAfterItem ]]
Specifies an optional expression that represents a position where a new member is to be inserted before or after another item in the collection.

You can specify a eBeforeItem or an eAfterItem expression but not both, which generates the appropriate message. This expression can be one of two types:

  • Numeric. The eBeforeItem and eAfterItem expression must have a value from 1 to the value of the Count property for the collection.
  • String. The eBeforeItem and eAfterItem expression must correspond to the cKey that was specified for the referenced item when it was added to the collection.

Inserting a new item into a collection before or after an existing one requires that the collection must be a keyed collection. When you specify a cKey value with an eBeforeItem or eAfterItem parameter, the new item is added before or after the index value of the specified key. In this case, the value of Collection KeySort has no effect. For example, suppose cKey for a new item is "ZZZ", and for an existing item, cKey is "XXX", and its index value is 15. The new item would receive an index value of 15, and the existing item would receive a new index value of 16.

To insert a new item before an existing item, include the key of the item you want to insert the new item before as shown in the following example:

loItems.Add("Roses", "flower1", "flower2")

To insert a new item after an existing item, include the key of the item you want to insert the new item after. In addition, you must pass an empty third parameter for eBeforeItem as shown in the following example:

loItems.Add("Orchids", "flower3",, "flower2")

If eBeforeItem and eAfterItem do not refer to an existing member of the collection, an error occurs. Visual FoxPro adds an item to the end of a collection when eBeforeItem or eAfterItem are not specified.

Remarks

When adding objects to collections, Visual FoxPro increases the reference count for that object. According to usual Visual FoxPro object behavior, you can release an object only when its reference count is 0. Therefore, you should make sure that the reference to the object in the collection is released when releasing the object; otherwise, the Visual FoxPro does not remove the object entirely from memory.

You are not limited to the number of items you can add to a collection. However, the size of a collection can affect the performance of operations such as accessing, searching, and enumerating items in the collection. For example, creating a large collection based on records from a very large table (.dbf) is not recommended because you cannot use query optimization and other features associated with the Visual FoxPro native data engine.

You can have a collection of collections because collections are objects. However, avoid creating circular references, such as attempting to add an outer collection to an inner collection.

Adding arrays as items to a collection instantiated from the base class has limited use because there is no easy way to reference all the elements in the array. Consider the following example:

DIMENSION x[3]
x[1] = 1
x[2] = 22
x[3] = 333
y = CREATEOBJECT("collection")
y.Add(@x)
z = y.item(1)   && Returns just the first element
? z[2]         && Error

Therefore, you should create a subclass with special handling for this scenario.

You can pass a value of NULL as an item type and use TYPE( ) and VARTYPE( ) functions to query the type of the item in the collection.

You can add items of mixed type. However, Visual FoxPro does not enforce type safety, so you should provide it for the class if needed. If an incorrect type is passed for a specific parameter, an error occurs.

Include the NODEFAULT command in the Add method for collection objects to prevent adding a particular item to the collection.

Example

The following example illustrates the following tasks:

  • Adds four items to a collection using the cKey parameter.
  • Adds a second item with a key that precedes the first item using the eBeforeItem parameter.
  • Adds a fourth item with a key that follows the first added item using the eAfterItem parameter.
  • Iterates through all the items displaying to the screen.
CLEAR
LOCAL loItems, lcFlower
loItems = NEWOBJECT("Collection")
loItems.Add("Daffodils", "flower2")

* Add "Roses" with "flower1" key before "flower2".
loItems.Add("Roses", "flower1", "flower2")
loItems.Add("Daisies", "flower4")

* Add "Orchids" with "flower4" key after "flower2".
loItems.Add("Orchids","flower3",,"flower2")
FOR EACH lcFlower IN loItems
   ? lcFlower
ENDFOR

The following example generates an error. You cannot specify both an eBeforeItem and an eAfterItem.

* Generates an error. Cannot specify both eBeforeItem and eAfterItem.
loItems.Add("Violets","flower5","flower2","flower1")

See Also

Collection Object Properties, Methods, and Events | Collection Class | KeySort Property | TYPE( ) Function | VARTYPE( ) Function | NODEFAULT Command


Add Method (File Object)

Adds a file to a project.

Object.Add(cFileName)

Return Values

Object

Parameters

cFileName
Specifies the name of the file to add to the project. An error is generated if the file you specify does not exist. The Project Manager window, if open, is refreshed after the file has been added.

Remarks

The Add method is a method for the files collection. When a file is added to a project with the Add method, a File object is created for the file, and the File object is added to the Files collection.

An object reference to the newly added file is returned if the file is successfully added to the project. The null value is returned if the file can't be added to the project.

The QueryAddFile event occurs just before a file is added to a project. If NODEFAULT is specified in the QueryAddFile event, the file isn't added to the project.

Include NODEFAULT in the QueryAddFile event to prevent a file from being added to the project.

Example

The following example programmatically creates a Project and then builds an executable (EXE) from that Project. It uses the Add method to add program code to the project.

SET SAFETY OFF
LOCAL lcCode
TEXT TO lcCode NOSHOW
CLEAR
PUBLIC loForm

SET TALK OFF
SET DELETED ON
SET EXCLUSIVE OFF
SET CENTURY ON

ON SHUTDOWN clear events
loForm = CREATEOBJECT('Test1')
loForm.Show(0)
READ EVENTS
ON SHUTDOWN
RETURN

DEFINE CLASS Test1 as Form
 Top = 0
 Left = 0
 Width = 240
 Height = 150
 Caption = 'Add Method sample'
 ShowWindow = 2

 ADD OBJECT cmdClose as CommandButton WITH ;
  Caption = '\<Close', ;
  Top = 80, ;
  Left = 80, ;
  Height = 24, ;
  Width = 80

 ADD OBJECT lblTitle as Label WITH ;
  Top = 30, ;
  Left = 40, ;
  Height = 34, ;
  Width = 160, ;
  Caption = 'This sample was made programmatically.';
  WordWrap = .t.

 PROCEDURE Init
  SET TALK off
  ThisForm.AutoCenter = .t.
 ENDPROC
 PROCEDURE Unload
  CLEAR EVENTS
 ENDPROC
 PROCEDURE cmdClose.Click
  ThisForm.Release()
 ENDPROC
ENDDEFINE
ENDTEXT

STRTOFILE(lcCode, 'addsample.prg')
CREATE PROJECT 'AddSample' NOSHOW NOWAIT SAVE
LOCAL loPJX
loPJX = _VFP.ActiveProject
WITH loPJX
 .Files.Add('addsample.prg')
 .SetMain('addsample.prg')
 .Build('addsample.exe',3,.t.,.t.,.f.)
 .Close()
ENDWITH
RUN /n addsample.exe

See Also

File Object | QueryAddFile Event | NODEFAULT Command

Applies To: Files Collection


AddColumn Method

Adds a Column object to a Grid control.

Grid.AddColumn(nIndex)

Parameters

nIndex
Specifies a number representing the position in the grid where the new Column is added.

Remarks

When AddColumn( ) is called, existing columns are moved to the right, and their ColumnOrder properties are incremented accordingly. The grid's ColumnCount property is also increased.

The grid's Controls property array is enlarged by one element, and a reference to the new column is placed in the new element. The new column is assigned a unique name.

For example, to add a new column and then assign a new name to that column, you could do the following.

THISFORM.Grid1.AddColumn(1)   && Insert column at left.
THISFORM.Grid1.Columns(THISFORM.Grid1.ColumnCount).Name = "NewColumn"
THISFORM.Grid1.NewColumn.ControlSource = "Customer.CustID"

See Also

AddObject Method | ColumnCount Property | DeleteColumn Method

Applies To: Grid Control


AddItem Method

Adds a new item to a ComboBox or ListBox control, optionally making it possible for you to specify the item's index.

Control.AddItem(cItem [, nIndex] [, nColumn])

Parameters

cItem
Specifies the string expression to add to the control.
nIndex
Specifies the position where the item is placed in the control. If you supply a valid value for the optional nIndex, cItem is placed at that position within the control. If you specify an nIndex that already exists, the item is inserted at that position and all items below that item are moved down one position in the list portion of the ComboBox or ListBox control.

If you omit nIndex and the Sorted property is set to True (.T.), cItem is added in alphabetic sort order. If you omit nIndex and the Sorted property is set to False (.F.), cItem is added to the end of the list portion of the ComboBox or ListBox control.

nColumn
Specifies the column of the control to which the new item is added. The default is 1.

Remarks

Use the AddItem method or AddListItem method when the RowSourceType property is set to 0 (None).

Each item added to a ComboBox or ListBox has two identification numbers assigned to it:

  • nItemID, an integer corresponding to the unique ID of the item in the control: the first item corresponds to nItemID = 1 unless another nItemID is specified.
  • nIndex, an integer corresponding to the order in which items are displayed by the control: the first item in the control corresponds to nIndex = 1.

The AddItem method always inserts a new row into a multicolumn ComboBox or ListBox. After a row has been inserted, columns in that row should be populated using the .List(.NewIndex, nColumn) syntax.

The backslash ("\") is treated as a special character when used in the expression for an item. The following rules apply for this character:

  • You can disable an item in a list box or combo box by adding a single backslash to the beginning of the expression.
  • Any multiple of two backslashes used in the expression is displayed as a single backslash. For example, one or two backslashes used together will display as one, and three or four backslashes together will display as two. The following example code contains a list box item containing a Universal Naming Convention (UNC) path. The code displays in the list box as \\MyServer\MyMachine\MyFolder.
    MyForm.List1.AddItem("\\\\MyServer\\MyMachine\\MyFolder")
  • If the expression begins with multiple backslashes, the item is not disabled. If you want to disable an item that begins with multiple backslashes, add a backslash and a close bracket (]) to the beginning of the item. For example, the following disables the UNC path item in the list box.
    MyForm.List1.AddItem("\]\\\MyServer\\MyMachine\\MyFolder")
  • To include a separator line, use a backslash followed by a hyphen as the item to add to the list box. For example, the following code adds a separator line to a list box.
    MyForm.List1.AddItem("\-")

Example

This example demonstrates using the AddItem and AddListItem methods to add values to the ListItem array. Both proper and improper ways of populating a combo box are shown for clarity.

PUBLIC ofrmListExamples
ofrmListExamples=NEWOBJECT("frmListExamples")
ofrmListExamples.Show
RETURN

DEFINE CLASS frmListExamples AS form

 DataSession = 2
 Top = 0
 Left = 0
 Height = 262
 Width = 325
 Caption = "List and ListItem Array Example"
 Name = "frmListExamples"

 ADD OBJECT shape1 AS shape WITH ;
  Top = 43, ;
  Left = 32, ;
  Height = 76, ;
  Width = 261, ;
  SpecialEffect = 0, ;
  Name = "Shape1"

 ADD OBJECT cbolistbad AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Height = 22, ;
  Left = 111, ;
  Sorted = .T., ;
  Style = 2, ;
  TabIndex = 1, ;
  Top = 53, ;
  Width = 147, ;
  Name = "cboListBad"

 ADD OBJECT cbolistitem AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Left = 34, ;
  Sorted = .T., ;
  Style = 2, ;
  TabIndex = 3, ;
  Top = 154, ;
  Name = "cboListItem"

 ADD OBJECT label1 AS label WITH ;
  FontBold = .T., ;
  Caption = "Using the List Array:", ;
  Height = 17, ;
  Left = 34, ;
  Top = 24, ;
  Width = 176, ;
  TabIndex = 7, ;
  Name = "Label1"

 ADD OBJECT label2 AS label WITH ;
  FontBold = .T., ;
  Caption = "Using the ListItem Array:", ;
  Height = 17, ;
  Left = 34, ;
  Top = 135, ;
  Width = 173, ;
  TabIndex = 8, ;
  Name = "Label2"

 ADD OBJECT cbolistgood AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Height = 22, ;
  Left = 111, ;
  Sorted = .T., ;
  style = 2, ;
  TabIndex = 2, ;
  Top = 86, ;
  Width = 147, ;
  Name = "cboListGood"

 ADD OBJECT label3 AS label WITH ;
  Alignment = 1, ;
  Caption = "Wrong!", ;
  Height = 17, ;
  Left = 51, ;
  Top = 56, ;
  Width = 47, ;
  TabIndex = 9, ;
  Name = "Label3"

 ADD OBJECT label4 AS label WITH ;
  Alignment = 1, ;
  Caption = "Right!", ;
  Height = 17, ;
  Left = 58, ;
  Top = 89, ;
  Width = 40, ;
  TabIndex = 10, ;
  Name = "Label4"

 PROCEDURE cbolistbad.Init
  WITH This
   .AddItem( 'Cleveland' )
   .AddItem( 'Ohio', .NewIndex, 2 )
   .AddItem( '44122', .NewIndex, 3 )
   .AddItem( 'Caversham' )
   .AddItem( 'England', .NewIndex, 2 )
   .AddItem( 'RG4 8BX', .NewIndex, 3 )
   .AddItem( 'Buffalo' )
   .AddItem( 'New York', .NewIndex, 2 )
   .AddItem( '14228', .NewIndex, 3 )
   .AddItem( 'Milwaukee' )
   .AddItem( 'Wisconsin', .NewIndex, 2 )
   .AddItem( '43225', .NewIndex, 3 )
   .AddItem( 'International Falls')
   .AddItem( 'Minnesota', .NewIndex, 2 )
   .AddItem( '42666', .NewIndex, 3 )
  ENDWITH
 ENDPROC

PROCEDURE cbolistgood.Init
  WITH This
   .AddItem( 'Cleveland' )
   .List[.NewIndex, 2] = 'Ohio'
   .List[.NewIndex, 3] = '44122'
   .AddItem( 'Caversham' )
   .List[.NewIndex, 2] = 'England'
   .List[.NewIndex, 3] = 'RG4 8BX'
   .AddItem( 'Buffalo' )
   .List[.NewIndex, 2] = 'New York'
   .List[.NewIndex, 3] = '14228'
   .AddItem( 'Milwaukee' )
   .List[.NewIndex, 2] = 'Wisconsin'
   .List[.NewIndex, 3] = '43225'
   .AddItem( 'International Falls' )
   .List[.NewIndex, 2] = 'Minnesota'
   .List[.NewIndex, 3] = '42666'
  ENDWITH
 ENDPROC

 PROCEDURE cbolistitem.Init
  WITH This
   .AddListitem( 'Cleveland' )
   .AddListItem( 'Ohio', .NewItemID, 2 )
   .AddListItem( '44122', .NewItemID, 3 )
   .AddListItem( 'Caversham' )
   .AddListItem( 'England', .NewItemID, 2 )
   .AddListItem( 'RG4 8BX', .NewItemID, 3 )
   .AddListItem( 'Buffalo' )
   .AddListItem( 'New York', .NewItemID, 2 )
   .AddListItem( '14228', .NewItemID, 3 )
   .AddListItem( 'Milwaukee' )
   .AddListItem( 'Wisconsin', .NewItemID, 2 )
   .AddListItem( '43225', .NewItemID, 3 )
   .AddListItem( 'International Falls')
   .AddListItem( 'Minnesota', .NewItemID, 2 )
   .AddListItem( '42666', .NewItemID, 3 )
  ENDWITH
 ENDPROC
ENDDEFINE

See Also

AddListItem Method | Clear Method | List Property | ListIndex Property | ListItemID Property | RowSourceType Property | RemoveItem Method | Sorted Property


AddListItem Method

Adds a new item to a ComboBox or ListBox control, optionally making it possible for you to specify the item's item ID.

Control.AddListItem(cItem [, nItemID] [, nColumn])

Parameters

cItem
Specifies the item to add to the control.
nItemID
Specifies an integer representing the unique ID of the item in the control. The maximum value you can specify for nItemID is 32,767.

If you omit nItemID and the Sorted property is set to True (.T.), cItem is added in alphabetic sort order. If you omit nItemID and the Sorted property is set to False (.F.), cItem is added to the end of the list of the ComboBox or ListBox.

nColumn
Specifies the column of the control to add the new item to. The default is 1.

Remarks

Use the AddItem method or AddListItem method when the RowSourceType property is set to 0 (None).

Each item added to a ComboBox or ListBox has two identification numbers assigned to it:

  • nItemID, an integer corresponding to the unique ID of the item in the control: the first item corresponds to nItemID = 1 unless another nItemID is specified.
  • nIndex, an integer corresponding to the order in which items are displayed by the control: the first item in the control corresponds to nIndex = 1.

The backslash ("\") is treated as a special character when used in the expression for an item. The following rules apply for this character:

  • You can disable an item in a list box or combo box by adding a single backslash to the beginning of the expression.
  • Any multiple of two backslashes used in the expression is displayed as a single backslash. For example, one or two backslashes used together will display as one, three or four backslashes together will display as two. The following example code contains a list box item containing a Universal Naming Convention (UNC) path. The code displays in the list box as \\MyServer\MyMachine\MyFolder.
    MyForm.List1.AddItem("\\\\MyServer\\MyMachine\\MyFolder")
  • If the expression begins with multiple backslashes, the item is not disabled. If you want to disable an item that begins with multiple backslashes, add a backslash and a close bracket (]) to the beginning of the item. For example, the following disables the UNC path item in the list box:
    MyForm.List1.AddItem("\]\\\MyServer\\MyMachine\\MyFolder")
  • To include a separator line, use a backslash followed by a hyphen as the item to add to the list box. For example, the following code adds a separator line to a list box.
    MyForm.List1.AddItem("\-")

Example

This example demonstrates using the AddItem and AddListItem methods to add values to the ListItem array. Both proper and improper ways of populating a combo box are shown for clarity.

PUBLIC ofrmListExamples
ofrmListExamples=NEWOBJECT("frmListExamples")
ofrmListExamples.Show
RETURN

DEFINE CLASS frmListExamples AS form

 DataSession = 2
 Top = 0
 Left = 0
 Height = 262
 Width = 325
 Caption = "List and ListItem Array Example"
 Name = "frmListExamples"

 ADD OBJECT shape1 AS shape WITH ;
  Top = 43, ;
  Left = 32, ;
  Height = 76, ;
  Width = 261, ;
  SpecialEffect = 0, ;
  Name = "Shape1"

 ADD OBJECT cbolistbad AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Height = 22, ;
  Left = 111, ;
  Sorted = .T., ;
  Style = 2, ;
  TabIndex = 1, ;
  Top = 53, ;
  Width = 147, ;
  Name = "cboListBad"

 ADD OBJECT cbolistitem AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Left = 34, ;
  Sorted = .T., ;
  Style = 2, ;
  TabIndex = 3, ;
  Top = 154, ;
  Name = "cboListItem"

 ADD OBJECT label1 AS label WITH ;
  FontBold = .T., ;
  Caption = "Using the List Array:", ;
  Height = 17, ;
  Left = 34, ;
  Top = 24, ;
  Width = 176, ;
  TabIndex = 7, ;
  Name = "Label1"

 ADD OBJECT label2 AS label WITH ;
  FontBold = .T., ;
  Caption = "Using the ListItem Array:", ;
  Height = 17, ;
  Left = 34, ;
  Top = 135, ;
  Width = 173, ;
  TabIndex = 8, ;
  Name = "Label2"

 ADD OBJECT cbolistgood AS combobox WITH ;
  ColumnCount = 3, ;
  ColumnWidths = "100,100,50", ;
  Height = 22, ;
  Left = 111, ;
  Sorted = .T., ;
  style = 2, ;
  TabIndex = 2, ;
  Top = 86, ;
  Width = 147, ;
  Name = "cboListGood"

 ADD OBJECT label3 AS label WITH ;
  Alignment = 1, ;
  Caption = "Wrong!", ;
  Height = 17, ;
  Left = 51, ;
  Top = 56, ;
  Width = 47, ;
  TabIndex = 9, ;
  Name = "Label3"

 ADD OBJECT label4 AS label WITH ;
  Alignment = 1, ;
  Caption = "Right!", ;
  Height = 17, ;
  Left = 58, ;
  Top = 89, ;
  Width = 40, ;
  TabIndex = 10, ;
  Name = "Label4"

 PROCEDURE cbolistbad.Init
  WITH This
   .AddItem( 'Cleveland' )
   .AddItem( 'Ohio', .NewIndex, 2 )
   .AddItem( '44122', .NewIndex, 3 )
   .AddItem( 'Caversham' )
   .AddItem( 'England', .NewIndex, 2 )
   .AddItem( 'RG4 8BX', .NewIndex, 3 )
   .AddItem( 'Buffalo' )
   .AddItem( 'New York', .NewIndex, 2 )
   .AddItem( '14228', .NewIndex, 3 )
   .AddItem( 'Milwaukee' )
   .AddItem( 'Wisconsin', .NewIndex, 2 )
   .AddItem( '43225', .NewIndex, 3 )
   .AddItem( 'International Falls')
   .AddItem( 'Minnesota', .NewIndex, 2 )
   .AddItem( '42666', .NewIndex, 3 )
  ENDWITH
 ENDPROC

 PROCEDURE cbolistitem.Init
  WITH This
   .AddListitem( 'Cleveland' )
   .AddListItem( 'Ohio', .NewItemID, 2 )
   .AddListItem( '44122', .NewItemID, 3 )
   .AddListItem( 'Caversham' )
   .AddListItem( 'England', .NewItemID, 2 )
   .AddListItem( 'RG4 8BX', .NewItemID, 3 )
   .AddListItem( 'Buffalo' )
   .AddListItem( 'New York', .NewItemID, 2 )
   .AddListItem( '14228', .NewItemID, 3 )
   .AddListItem( 'Milwaukee' )
   .AddListItem( 'Wisconsin', .NewItemID, 2 )
   .AddListItem( '43225', .NewItemID, 3 )
   .AddListItem( 'International Falls')
   .AddListItem( 'Minnesota', .NewItemID, 2 )
   .AddListItem( '42666', .NewItemID, 3 )
  ENDWITH
 ENDPROC

 PROCEDURE cbolistgood.Init
  WITH This
   .AddItem( 'Cleveland' )
   .List[.NewIndex, 2] = 'Ohio'
   .List[.NewIndex, 3] = '44122'
   .AddItem( 'Caversham' )
   .List[.NewIndex, 2] = 'England'
   .List[.NewIndex, 3] = 'RG4 8BX'
   .AddItem( 'Buffalo' )
   .List[.NewIndex, 2] = 'New York'
   .List[.NewIndex, 3] = '14228'
   .AddItem( 'Milwaukee' )
   .List[.NewIndex, 2] = 'Wisconsin'
   .List[.NewIndex, 3] = '43225'
   .AddItem( 'International Falls' )
   .List[.NewIndex, 2] = 'Minnesota'
   .List[.NewIndex, 3] = '42666'
  ENDWITH
 ENDPROC
ENDDEFINE

See Also

AddItem Method | Clear Method | ListIndex Property | ListItemID Property | RowSourceType Property | RemoveItem Method | Sorted Property

Applies To: ComboBox Control | ListBox Control


AddObject Method

Adds an object to a Container object at run time.

Object.AddObject(cName, cClass [, cOLEClass] [, aInit1, aInit2 ...])

Parameters

cName
Specifies the name used to reference the new object.
cClass
Specifies the class of the object to add.
cOLEClass
Specifies the OLE class of the object to add.
Note If you plan to distribute run-time applications which add ActiveX Controls requiring License key information (for example, Microsoft Treeview and Listview controls), you should not use the AddObject(.....cOLEClass) method. Instead, create and save a subclass of your ActiveX Control to a VCX class library. Then, at run time you can use the AddObject (or NewObject) method to add this OleControl class containing your control.
aInit1, aInit2
Specify parameters passed to the Init event of the new object.

Remarks

Calling the AddObject method triggers the Init event of the object being added. When a form is added to a form set, the Load event occurs before the Init event.

Note When you use AddObject to add an object to a container, the object's Visible property is set to False (.F.) so you can set the properties of the object without any awkward visual effects as the object's appearance changes.

If you use the AddObject( ) method to add an ActiveX Control to a form dynamically, your distributed application can fail if that control requires certain licensing registry keys that are not available on the target machine. Many vendors of ActiveX controls require such registry keys for manipulation of these controls at design time as with the AddObject( ) method. Avoid this licensing requirement by first subclassing the ActiveX Control in a class library file (.vcx) and then using AddObject( ) to add an instance of the subclass dynamically at run time. You should always check with the vendor of any ActiveX control you plan to distribute with your custom application since there may be other dependent files that you need to include.

Example

The following example demonstrates how the AddObject method can be used to add objects or controls to a form. AddObject is used to add a Line control and three command buttons to the form.

The Visible property is set to True (.T.) for the Line control and the command buttons. By default, objects and controls are not visible when they are added to a form.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('shpLine','Line')  && Add a Line control to the form
frmMyForm.AddObject('cmdCmndBtn1','cmdMyCmndBtn1')  && Up Cmnd button
frmMyForm.AddObject('cmdCmndBtn2','cmdMyCmndBtn2')  && Down Cmnd button
frmMyForm.AddObject('cmdCmndBtn3','cmdMyCmndBtn3')  && Quit Cmnd button

frmMyForm.shpLine.Visible = .T.  && Make Line control visible
frmMyForm.shpLine.Top = 20  && Specify Line control row
frmMyForm.shpLine.Left = 125  && Specify Line control column

frmMyForm.cmdCmndBtn1.Visible =.T.  && Up Command button visible
frmMyForm.cmdCmndBtn2.Visible =.T.  && Down" Command button visible
frmMyForm.cmdCmndBtn3.Visible =.T.  && Quit Command button visible

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmndBtn1 AS COMMANDBUTTON  && Create Command button
   Caption = 'Slant \<Up'  && Caption on the Command button
   Left = 50  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='/'  && Slant up
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn2 AS CommandButton  && Create Command button
   Caption = 'Slant \<Down'  && Caption on the Command button
   Left = 200  && Command button column
   Top = 100  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      ThisForm.shpLine.Visible = .F.  && Hide the Line control
      ThisForm.shpLine.LineSlant ='\'  && Slant down
      ThisForm.shpLine.Visible = .T.  && Show the Line control
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn3 AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 150  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

See Also

Init Event | Load Event | NewObject Method | RemoveObject Method | Visible Property

Applies To: Column Object | CommandGroup Control | Container Object | Custom Object | DataEnvironment Object | Form Object | FormSet Object | Grid Control | OptionGroup Control | Page Object | PageFrame Control | _SCREEN | ToolBar Object


AddProperty Method

Adds a new property to an object.

Object.AddProperty(cPropertyName [, eNewValue])

Return Values

Logical

Parameters

cPropertyName
Specifies the name of the new property to add to the object.
eNewValue
Specifies the value to which the new property is set. If eNewValue is omitted, the value of the new property is unchanged if the property already exists or is set to False (.F.) for a new property.

Remarks

The AddProperty( ) method makes it possible for you to add a property to an object at run time. The new property is added as a PUBLIC property.

You can also create property arrays for an object. Every element in the property array is initialized to eNewValue if it is included; otherwise every property array element contains False (.F.). The following code demonstrates how you can create a property array for an object:

oMyForm = CREATEOBJECT('Form')
oMyForm.AddProperty('MyArray(2)', 1)  && Add an array as a property
oMyForm.MyArray(2) = 'Two'
CLEAR
? oMyForm.MyArray(1)  && Displays 1
? oMyForm.MyArray(2)  && Displays Two

If a property with the name you specify does not exist, the property is created and a logical True (.T.) is returned.

If a property already exists with the name you specify, then AddProperty( ) returns the following:

  • True (.T.) if the new property is an array property and the existing property is also an array property. The size of the array is redimensioned to that of the new array. If a value is specified with eNewValue, all the elements in the array are set to its value. If eNewValue is omitted, all the array elements are set to False (.F.).
  • True (.T.) if the new property is not an array property and the existing property is an array property. The property remains an array property. If a value is specified with eNewValue, all the elements in the array are set to its value. If eNewValue is omitted, the array elements remain unchanged.
  • True (.T.) if the new property is not an array property and the existing property is not an array property or is not a read-only Visual FoxPro native property. If a value is specified with eNewValue, the existing property is set to its value. If eNewValue is omitted, the existing property value remains unchanged.
  • False (.F.) if the new property is an array property and the existing property is not an array property. The existing property remains unchanged.
  • A "Property <PropertyName> is read-only" error is generated if the existing property is a read-only Visual FoxPro native property such as the BaseClass property.
  • An "Incorrect property name" error is generated if the property name is not valid (the property name contains a space or other illegal characters).

The AddProperty( ) method only works with some native Visual FoxPro objects. You can use the ADDPROPERTY( ) function to add a property to any object that Visual FoxPro works with, such as COM objects or those created with the SCATTER...NAME property. For more information, see ADDPROPERTY( ) function.

See Also

DEFINE CLASS | NewObject Method | SaveAs Method | SaveAsClass Method

Applies To: CheckBox Control | Collection Class | Column Object | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | Cursor Object | CursorAdapter Class | Custom | DataEnvironment Object | EditBox Control | Exception Class | Form Object | FormSet Object | Grid Control | Header Object | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | ProjectHook Object | Relation Object | _SCREEN | Separator Object | Session Object | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


AddTableSchema Method

Adds a new XMLTable object to the XMLAdapter Tables collection and the necessary XMLField objects to the XMLTable Fields collection based on the specified table alias.

The following parameters must be converted to Unicode before passing as parameters to AddTableSchema:

  • cXMLName
  • cXMLNamespace
  • cXMLPrefix

You can use the STRCONV( ) function to perform this requirement.

XMLAdapter.AddTableSchema( cAlias [, lElementBased [, cXMLName
   [, cXMLNamespace [, cXMLPrefix [, lWrapMemoInCDATA [, lWrapCharacterInCDATA ]]]]]] )

Parameters

cAlias
Specifies the alias of the Visual FoxPro table or cursor to use as a schema template.
lElementBased
Specifies the style of XML. The default value of lElementBased is True (.T.).
cXMLName
Specifies the name to use for the table in the XML and must be converted to Unicode before passing as a parameter. The default value for the cXMLName parameter is the value of the cAlias parameter. Conversion to Unicode is performed automatically.
cXMLNamespace
Specifies the XML Namespace to use, which must be converted to Unicode before passing as a parameter. The default value is an empty ("") string.
cXMLPrefix
Specifies the XML Prefix to use, which must be converted to Unicode before passing as a parameter. The default value is an empty ("") string.
lWrapMemoInCDATA
Specifies whether to wrap Memo fields in CDATA sections. The default value is specified by the WrapMemoInCDATA property for the XMLAdapter object.
lWrapCharacterInCDATA
Specifies whether to wrap Character fields in CDATA sections. The default value is specified by the WrapCharInCDATA property for the XMLAdapter object.

Remarks

The following property settings affect how the AddTableSchema method is executed:

  • DisableEncode
  • NoCpTrans
  • WrapCharInCDATA
  • WrapMemoInCDATA

See Also

Methods | XMLAdapter Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | XMLField Class | Fields Collection (XMLTable) | STRCONV( ) Function | Memo Field Type | Character Data Type

Applies To: XMLAdapter Class


AddToSCC Method

Adds a file in a project to source code control.

Object.AddToSCC( )

Remarks

True (.T.) is returned if the file is successfully added to source code control. False (.F.) is returned if the file could not be added to source code control or the project is not under source code control.

See Also

CheckIn Method | CheckOut Method | GetLatestVersion Method | RemoveFromSCC Method | UndoCheckOut Method

Applies To: File Object


ApplyDiffgram Method

Applies a DiffGram to local Visual FoxPro tables.

ApplyDiffgram is supported only for XMLTable objects in the XMLAdapter Tables collection. ApplyDiffgram disregards XMLField objects when the XMLField Alias property is empty.

XMLTable.ApplyDiffgram( [ cAlias [, oCursorAdapter [, lPreserveChanges [, Reserved ]]]] )

Parameters

cAlias
Specifies the alias of the target cursor. The value of cAlias defaults to the XMLTable Alias property, including when cAlias is an empty string ("").
oCursorAdapter
Specifies a pre-existing CursorAdapter object.

ApplyDiffgram attaches the temporary table-buffered cursor containing changes to the specified CursorAdapter object. ApplyDiffgram also applies any updates, such as modified, inserted, or deleted records, to the base table set for the CursorAdapter object or to the cursor matching the Alias property of the XMLTable object.

If you do not provide a value for oCursorAdapter, ApplyDiffgram automatically handles updates to the base table.

Note You can update the remote data source using the ApplyDiffgram method provided that the CursorAdapter is configured for such a purpose.
lPreserveChanges
Specifies that when you provide a custom CursorAdapter object, and ApplyDiffgram fails, whether to keep the cursor, with changes, attached to the CursorAdapter object and any changes to the properties of the CursorAdapter object intact.

The following table describes the values for lPreserveChanges.

lPreserveChanges | Description
True (.T.) | Keep the cursor with changes attached to the cursor adapter and the changes to the properties of the cursor adapter intact. (Default)
False (.F.) | Detach the cursor with changes and revert any changes that were made to the properties of the cursor adapter.
Reserved
Reserved for future use. The default value is 0.

Remarks

Visual FoxPro checks the XMLField Keyfield property when executing ApplyDiffgram.

Tip When you use automatic updating, you should set the appropriate XMLField Keyfield properties in the Fields collection to True (.T.) to improve update performance.

Visual FoxPro changes the properties for a custom CursorAdapter as follows:

  • If the Tables property is empty, Visual FoxPro sets it to the table specified by the cAlias parameter.
  • Visual FoxPro sets SendUpdates to True (.T.).
  • If the DataSource property is empty, Visual FoxPro sets it to "Native".
  • If the KeyFieldList property is empty, Visual FoxPro adds key fields only if specified. Otherwise, Visual FoxPro adds all fields.
  • If KeyFieldList is modified, Visual FoxPro sets the WhereType property to Key Fields (DB_KEY or 1).
  • If the UpdatableFieldList property is empty, Visual FoxPro adds all fields.
  • If the UpdateNameList property is empty, Visual FoxPro adds all fields and uses the table specified by the cAlias parameter as the base table.

After applying the DiffGram, Visual FoxPro restores all the listed property values to their previous states.

See Also

Methods | XMLTable Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | XMLField Class | Alias Property | CursorAdapter Class | Fields Collection (XMLTable) | CursorAdapter Object Properties, Methods, and Events

Applies To: XMLTable Class


Attach Method

Attaches an existing XML Document Object Model (DOM) document or DOM element, and, optionally, XML schema to the XMLAdapter object.

Attach also sets the XMLAdapter IXMLDOMElement property. In addition, if the XML schema is analyzed, Visual FoxPro repopulates the Tables collection with a new set of XMLTable objects and sets the following XMLAdapter properties to appropriate values:

  • XMLName
  • XMLNamespace
  • XMLPrefix
  • IsDiffgram
  • SOM
XMLAdapter.Attach( oDOM [, oSchema ] )

Parameters

oDOM
Specifies an existing Microsoft XML Core Services (MSXML) 4.0 DOM document object or IXMLDOMElement object.
oSchema
Specifies an existing MSXML 4.0 Schema Object Model (SOM) document object, a DOM document object with a schema node as the root element, or IXMLDOMElement object, which represents the schema.

If you specify a value for oSchema, Visual FoxPro disregards the value of XMLAdapter XMLSchemaLocation and analyzes the schema. Otherwise, XMLSchemaLocation determines whether XML schema is analyzed.

Remarks

The Attach method facilitates loading returned results from Web services where the data set is usually returned as two IXMLDOMNodes with Item(0) as the schema (oSchema) and Item(1) as the data (oDom). You can attach these two nodes instead of calling LoadXML against a string.

The following property settings affect how the Attach method is executed:

  • DisableEncode
  • MapN19_4ToCurrency
  • NoCpTrans
  • WrapCharInCDATA
  • WrapMemoInCDATA
  • XMLSchemaLocation

See Also

Methods | XMLAdapter Object Properties, Methods, and Events | IXMLDOMElement Property | Tables Collection (XMLAdapter) | XMLField Class | LoadXML Method

Applies To: XMLAdapter Class


AutoFit Method

Use to control automatic resizing of columns. AutoFit resizes all visible columns at the Grid or BROWSE levels and resizes the individual column at the Column level.

Object.AutoFit( )

Return Values

Boolean data type. AutoFit returns True (.T.) if columns are successfully resized and False (.F.) if not successfully resized.

Remarks

Setting the AllowAutoColumnFit property does not affect resizing performed by AutoFit at either the Grid or Column level. You can override AllowAutoColumnFit using AutoFit.

For Column objects, AutoFit works only with TextBox controls. When a column resizes, the Resize event for that column fires.

You can prevent the automatic resizing of a particular column by setting the Resizable property of that column to False (.F.).

Hidden grid columns, which have their Visible property set to False (.F.) and have a Width property value of 0, are not resized.

See Also

Methods | Fitting Columns to Data Automatically | AllowAutoColumnFit Property | Resizable Property

Applies To: Grid Control | BROWSE...NAME Command | Column Object


AutoOpen Method

Executes the CursorFill method with a default of no parameters. When the CursorAdapter object exists in a data environment, the data environment calls AutoOpen automatically from within the DataEnvironment OpenTables method.

CursorAdapter.AutoOpen()

Return Values

Logical data type. AutoOpen returns True (.T.) if successful. Otherwise, Visual FoxPro generates an error.

Remarks

You can override AutoOpen by using the NODEFAULT command and explicitly calling CursorFill.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | CursorFill Method | AutoOpenTables Property | NODEFAULT Command

See Also: CursorAdapter Class


Box Method

Draws a rectangle on a Form object.

Object.Box(nXCoord1, nYCoord1, nXCoord2, nYCoord2)

-Or-

Object.Box(nXCoord2, nYCoord2)

Parameters

nXCoord1, nYCoord1
Specifies the coordinates of the starting point for the rectangle. The ScaleMode method of the form determines the unit of measurement used. If you omit these arguments, the value of CurrentX and CurrentY are used.
nXCoord2, nYCoord2
Specifies the endpoint of the rectangle.

Remarks

The width of the lines drawn depends on the DrawWidth property setting. How a rectangle is drawn on the background depends on the settings of the DrawMode and DrawStyle properties. When the Box method is called, the CurrentX and CurrentY properties are set to the endpoint specified by the last two arguments.

See Also

CurrentX, CurrentY Properties | DrawMode Property | DrawStyle Property | DrawWidth Property | ScaleMode Property

Applies To: Form Object | _SCREEN


Build Method

Rebuilds a project or creates an application file (.app), dynamic-link library (.dll), or executable file (.exe) from a project.

Object.Build([cOutputName] [, nBuildAction] [, lRebuildAll]
[, lShowErrors] [, lBuildNewGUIDs])

Parameters

cOutputName
Specifies the name of the application, dynamic-link library, or executable file that is created.

If cOutputName includes a file extension and nBuildAction is omitted, the file extension in cOutputName determines the type of file built. For example, if the extension in cOutputName is ".exe", an executable file is created.

nBuildAction
Specifies that the project is rebuilt or generates an application, a dynamic-link library, or an executable file.

The following table lists the values for nBuildAction with a description of each.

nBuildAction | FoxPro.H Constant | Description
1 | BUILDACTION_REBUILD | (Default) Rebuilds the project
2 | BUILDACTION_BUILDAPP | Creates an .app
3 | BUILDACTION_BUILDEXE | Creates an .exe
4 | BUILDACTION_BUILDDLL | Creates a .dll
5 | BUILDACTION_BUILDMTDLL | Creates a multithreaded .dll

If cOutPutName doesn't include an extension, the appropriate extension is added.

lRebuildAll
Specifies whether files in the project are recompiled before an .app, .dll, or .exe is created. If lRebuildAll is True (.T.), the following are recompiled:
  • Program files
  • Format files
  • Source code in forms, labels, reports, and visual class libraries
  • Stored procedures in databases

If If lRebuildAll is False (.F.) or is omitted, files in the project are not recompiled before the .app, .dll, or .exe is created.

lShowErrors
Specifies whether compilation errors are displayed in an editing window after the build is complete. If lShowErrors is True (.T.), the errors are displayed. If lShowErrors is False (.F.) or is omitted, compilation errors aren't displayed.
lBuildNewGUIDs
Specifies whether new registry GUIDs (globally unique identifiers) are generated when an executable file or dynamic-link library is created. If lBuildNewGUIDs is True (.T.), new GUIDs are generated. If lBuildNewGUIDs is False (.F.) or is omitted, new GUIDs aren't generated. lBuildNewGUIDs is ignored if nBuildAction is less than 3.

Remarks

A logical True (.T.) is returned if the project is successfully rebuilt, or an .app, .dll, or .exe is successfully created without errors; otherwise False (.F.) is returned.

See Also

BUILD APP | BUILD DLL | BUILD EXE | BUILD PROJECT | CREATE PROJECT | MODIFY PROJECT | Refresh Method

Applies To: Project Object


ChangesToCursor Method

Creates a table-buffered cursor and populates it with changes, which come from the associated DiffGram.

Note ChangesToCursor is supported only for XMLTable objects in the XMLAdapter Tables collection. ChangesToCursor disregards XMLField objects when the XMLField Alias property is empty.
XMLTable.ChangesToCursor( [ cAlias [, lIncludeUnchangedData [, Reserved ]]] )

Parameters

cAlias
Specifies the alias name for the cursor to be created. The value of cAlias defaults to the XMLTable Alias property, including when cAlias is an empty string ("").
lIncludeUnchangedData
Specifies whether to include unchanged data in the created cursor. The following table lists the values for lIncludeUnchangedData.
lIncludeUnchangedData | Description
False (.F.) | Do not include unchanged data in the created cursor. (Default)
True (.T.) | Include unchanged data in the created cursor.
Reserved
Reserved for future use. The default value is 0.

Remarks

When mapping binary fields to Character data types, Visual FoxPro fills any remaining white space with 0x00 characters (CHR(0) or zeros) after decoding.

See Also

Methods | XMLTable Object Properties, Methods, and Events | Tables Collection (XMLAdapter) | Alias Property

Applies To: XMLTable Class


CheckIn Method

Checks in changes made to a file in a project under source code control.

Object.CheckIn( )

Remarks

True (.T.) is returned if the file is successfully checked in. False (.F.) is returned if the file could not be checked into source code control or the project is not under source code control.

See Also

AddToSCC Method | CheckOut Method | GetLatestVersion Method | RemoveFromSCC Method | UndoCheckOut Method

Applies To: File Object


CheckOut Method

Checks out a file in a project under source code control, allowing you to make changes to the file.

Object.CheckOut( )

Remarks

True (.T.) is returned if the file is successfully checked out of source code control. False (.F.) is returned if the file could not be checked out or the project is not under source code control.

See Also

AddToSCC Method | CheckIn Method | GetLatestVersion Method | RemoveFromSCC Method | UndoCheckOut Method

Applies To: File Object


Circle Method

Draws a circle or ellipse on a form.

Object.Circle (nRadius [, nXCoord, nYCoord [, nAspect]])

Parameters

nRadius
Specifies the radius of the circle or ellipse. The ScaleMode property of the form determines the unit of measurement used.
nXCoord, nYCoord
Specifies the coordinates for the center point of the circle or ellipse. The ScaleMode property of the form determines the units of measurement used.
nAspect
Specifies the aspect ratio of the circle. The default value is 1.0, which produces a perfect (nonelliptical) circle. Values greater than 1.0 produce a vertical ellipse; values less than 1.0 produce a horizontal ellipse.

Remarks

To control the width of the line used to draw the circle or ellipse, set the DrawWidth property.

To control the way the circle is drawn in the background, set the DrawMode and DrawStyle properties.

To fill a circle, set the FillColor and FillStyle properties of the form.

When the Circle method is invoked, CurrentX and CurrentY are set to the center point arguments, nXCoord, nYCoord.

See Also

BackColor Property | CurrentX, CurrentY Properties | DrawMode Property | DrawStyle Property | DrawWidth Property | FillColor Property | FillStyle Property | ForeColor Property | ScaleMode Property

Applies To: Form Object | _SCREEN


Class Browser Methods

The following methods are associated with the Class Browser.

AddClass( )
Copies a class from one class library (.vcx) file to another. Used after a drag-and-drop operation between instances of the Class Browser and dependent on the oSource property. If the specified class does not exist, a class is created.
AddFile( )
AddFile([cFileName][, lIgnoreRefresh])

Adds a class library (.vcx) or form (.scx) file to the Class Browser class list. If no parameters are passed, an AddFile dialog box appears by using the Class Browser GetFile( ) method. If lIgnoreRefresh is True (.T.), the Class Browser class list is not refreshed. If you are adding multiple files, you can wait until all classes are added before refreshing the list.

AddIn( )
AddIn(cName[, cProgram] [, cMethod] [, cFileFilter] [, cPlatform]
[, cComment])

Installs or removes the specified add-in to the Browser.dbf registration table.

Parameters

  • cName Specifies the name of the add-in. Not case-sensitive; however, when displayed on a menu, the value appears as entered.
  • cProgram Specifies the name of a program (.PRG), form (.scx), application (.APP), executable file (.EXE), or compiled program (.FXP) to run. If no extension is provided, the extension .PRG is assumed.
    Note If this argument is .NULL., the add-in is marked for deletion in Browser.dbf and disabled in the add-in shortcut menu.
  • cMethod Specifies a method name to use as an event hook. If empty, the add-in appears on the menu.
  • cFileFilter Specifies a list of class libraries and forms that enable the add-in. If empty, the add-in is available for all class libraries (.vcx) and forms (.scx).
  • cPlatform Specifies the platform the add-in is available on. If empty, the add-in is available on all platforms supported by Visual FoxPro.
  • cComment Specifies text stored in a memo field in the Browser.dbf.
AddInMenu( )
Expands the menu that displays the registered add-ins.
AddInMethod( )
AddInMethod(cObjMethod)

Executes any registered add-in for the specified object method.

Example: To change the default behavior of the Help button in the Class Browser, use the following code:

_OBROWSER.AddInMethod("cmdHelp.click")
AutoRefresh( )
Determines whether to refresh the display by checking for updated class library (.vcx) information in the selected class in the class list, and by checking the total number of records in the class library (.vcx) file being edited. This method runs when the Class Browser form is activated.
BinToInt( )
BinToInt([cBinaryValue])

Returns the integer equivalent of a string representing a binary value. For example, passing this method a cBinaryValue of "11001" would return 25.

CleanUpFile( )
Removes records from the class library (.vcx) file associated with the selected class in the class list.
ClearBrowser( )
Internal use only.
ClearClass( )
ClearClass([lClearAll])

Clears the class cache from memory with the CLEAR CLASS command for a specific class, or all classes displayed if lClearAll is set to True (.T.).

NewClass( )
Creates a subclass of the selected class in the class list.
DeactivateMenu( )
Deactivates the add-in popup menu.
DisplayMenu( )
DisplayMenu(tnMenuMode)

Displays the shortcut menu at the current mouse pointer location. If tnMenuMode is 0, the Class Browser form shortcut menu is displayed; if 1, the Class list shortcut menu; if 2, the Member list shortcut menu.

DoAddIn( )
DoAddIn([cAddInName])

Executes the specified add-in of the current or specific record of the table with the BROWSER alias.

FileMatch( )
FileMatch(cFileName, cFileList)

Compares the specified file against the specified file list to determine if the file is one associated with the add-in.

ExportClass( )
ExportClass([lShow] [, tcExportToFileName])

Generates and displays the definition source code of the selected class or the selected file in the class list.

Parameters

  • lShow Specifies whether to display the code. If the parameter lShow is True (.T.), the Class Browser window displays the code.
  • tcExportToFileName Specifies the name of the file to receive the code.
FindClass( )
FindClass([cFind])

Finds class text within a class.

FormAddObject( )
FormAddObject(oObject [, nXCoord] [, nYCoord] [, lActivateForm]
[, lDesignMode][, lNoShow] [, lNoErrors] [, lBuilder] [, oForm])

Adds an instance of the selected class in the class list to an external form.

Parameters

  • oObject Specifies a reference to the destination container. The values can be either "command" for the Command window, "screen" for the Visual FoxPro desktop, or "new". You can implement these options with the following commands:
    _oBrowser.FormAddObject("command")
_oBrowser.FormAddObject("-screen")
_oBrowser.FormAddObject("new")
  • nXCoord Specifies the horizontal position of the object inside the container. If no value is passed, the current mouse position is used.
  • nYCoord Specifies the vertical position of the object inside the container. If no value is passed, the current mouse position is used.
  • lActivateForm If True (.T.), the destination form is activated when the object is added to it; if False (.F.), the Class Browser remains active.
  • lDesignMode If True (.T.), the object reference is an object currently in the Form Designer or class designer.
  • lNoShow If True (.T.), the object reference is an object currently in the Form Designer or class designer.
  • lNoErrors Specifies whether errors generated at instantiation are ignored. If False (.F.), errors are displayed in the Class Browser.
  • lBuilder Specifies whether a custom builder is launched after the object is added to a container.
  • oForm Specifies the container to which an object is added. oForm, an optional parameter, is primarily used to contain the host object in design mode.
FormatMethods( )
FormatMethods(cMethods)

Formats the text of generated methods in the display of the class definition code.

FormatProperties( )
FormatProperties(cProperties [, lAddObjectMode])

Formats the text of generated properties in the display of the class definition source code.

GetFile( )
GetFile([cFileExt])

Opens the Class Browser GetFile( ) dialog box. The GetFile( ) method is used internally by the Open or Add buttons in the Class Browser. Whenever the Class Browser prompts for a class library (.vcx) or form (.scx), the GetFile( ) method is called internally.

GetTimeStamp( )
GetTimeStamp([ntimestamp])

Returns the character equivalent of a timestamp value. If no parameter is passed, returns the timestamp string of the currently selected file.

IndentText( )
IndentText(cCode)

Indents a block of text one tab.

IntToBin( )
IntToBin([nInteger])

Returns a string representing a binary value that is the equivalent of an integer value. For example, passing this method a nInteger of 25 would return "11001".

ModifyClass( )
Opens the selected class in the Class Designer.
MsgBox( )
MsgBox(cMessage [, nType] [, cTitle])

Displays the Class Browser message box. Similar to the Visual FoxPro MESSAGEBOX( ) function.

NewFile( )
NewFile([cFileName] [, lOpenFile])

Creates a new class library (.vcx) file. If no parameters are passed, the Open dialog box is displayed. If parameters are provided, a new class library (.vcx) is created and added to the class list in Class Browser.

OpenFile( )
OpenFile([cFileName])

Opens an existing class library (.vcx) or form (.scx) file. If a file name is not provided, the Open dialog box appears.

ProperBaseClass( )
ProperBaseClass(cBaseClass)

Returns the base class name in the proper case. For example, "combobox" would return as "ComboBox".

RedefineClass( )
RedefineClass([cAsClass] [, cClassLoc])

Changes the parent class of the selected class in the class list.

RefreshButtons( )
Refreshes the Class Browser command buttons based on the file type.
RefreshClassIcon( )
Reloads the class icon from the icon file.
RefreshClassList( )
RefreshClassList([cDefaultClass] [, lIgnoreTable])

Refreshes the class list.

RefreshClassListSubclass( )
For internal use only.
RefreshFileAttrib( )
Refreshes the file attribute status of the file name associated with the selected class in the class list.
RefreshCaption( )
Refreshes the Class Browser caption of a form.
RefreshDescriptions( )
Internal use only. Refreshes the descriptions of classes and members.
RefreshMembers( )
RefreshMembers([tcDefaultMember])

Refreshes the Member tabs to display information associated with the selected class in the class list and, if provided, the specified member.

RefreshParentClassBrowser( )
Refreshes the state of the ParentClass Browser toolbar.
RefreshPrefRecNo( )
Refreshes the Browser.dbf preference record pointer for the class library (.vcx) or form (.scx) file being edited.
RefreshRecNo( )
Refreshes the current record pointer of the class library (.vcx) or form (.scx) table for the file of the selected class.
RemoveClass( )
RemoveClass([lConfirm])

Removes the selected class in the class list from its associated class library (.vcx) file.

RenameClass( )
RenameClass([cToClass])

Changes the class name of the selected class in the class list.

ResetDefaults( )
Restores original display settings. This method is called when you choose Restore Defaults from the shortcut menu.
SavePreferences( )
Saves current preference settings to the Browser.dbf registration table.
ScaleResize( )
Scales the controls on the Class Browser form to fit after the form is resized using the Resize( ) event.
SeekClass( )
SeekClass([cClass][, cClassLibrary])

Moves the class list pointer to a specific class or index in the class list. Can use the numeric value of the visual position in the class list.

SeekMember( )
SeekMember(tcMember)

Moves the member list pointer to a specific member.

SeekParentClass( )
Displays the parent class of the selected class in the class list.
SetBusyState( )
SetBusyState(lBusyState)

Sets the lBusyStatus property to True (.T.) or False (.F.) based on the parameter received; also sets the mouse pointer shape to an arrow or hourglass.

SetFont( )
SetFont([cFontName][, nFontSize][, lFontBold][, lFontItalic])

Sets the font and font size used by the Class Browser for its form, controls, and dialog boxes. If you don't specify a font name or size, SetFont( ) opens the Get Font dialog box.

ShowMenu( )
ShowMenu(aMenu[, cOnSelection])

Displays a menu based on an array. If a menu is a single-dimension array, this method displays a list of all items in your menu. If the array is two-dimensional with an item and an action, it displays the menu items and when the item is selected, it executes the associated action.

TrimExt( )
TrimExt(cFileName [, lPlatformType])

Truncates the file name extension.

TrimFile( )
TrimFile(cFileName [, lPlatformType])

Truncates the file name and returns only the file name and path.

TrimPath( )
TrimPath(cFileName [, lTrimExt] [, lPlatformType])

Truncates the path name.

UpdateReferences( )
UpdateReferences(tcOldClassLoc, tcOldClass, tcNewClassLoc, tcNewClass
[, tlAllInstances])

Used to update references of classes (subclasses and object members) when renaming a class and when moving a class from one class browser to another.

Parameters

  • tcOldClassLoc Specifies the original contents of the ClassLoc field in the .vcx or .scx file.
  • tcOldClass Specifies the original contents of the Class field in the .vcx or .scx file.
  • tcNewClassLoc Specifies the new contents of the ClassLoc field in the .vcx or .scx file..
  • tcNewClass Specifies the new contents of the Class field in the .vcx or .scx file.
  • tlAllInstances If True (.T.) all files in all Class Browser windows are updated. If False (.F.) only the files in the current Class Browser window are updated.
VersionCheck( )
VersionCheck([lShowErrorMsg])

Validates the open class library (.vcx) or form (.scx) file.

ViewProperty( )
ViewProperty(cProperty)

Displays the value of a specific property of the selected class.

WildcardMatch( )
WildcardMatch(cMatchExpList, cExpressionSearched)

Compares strings for a wildcard match with the filters specified in the Type box.

See Also

Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Object Members | Class Browser Properties | Class Browser Window | Customizing the Class Browser | Initial Values of Class Browser Properties


CleanUp Method

Cleans up a project table by removing records marked for deletion and packing memo fields.

Object.CleanUp(lRemoveObjectCode)

Parameters

lRemoveObjectCode
Specifies if object code stored in the OBJECT field of the project table is removed. If lRemoveObjectCode is True (.T.), the object code is removed from the table. If lRemoveObjectCode is False (.F.) or is omitted, the object code isn't removed.

The OBJECT field contains object code for program (.prg), menu (.mnx), and query (.qpr) files in the project. If the object code stored in the OBJECT field of the project table is removed, the next time the project is rebuilt the source code is compiled and the object code is stored in the OBJECT field again.

Remarks

Every project has a corresponding table that contains project information. Use the CleanUp method to reduce the size of the table by removing records marked for deletion and packing memo fields. Cleaning up a project table reduces the time it takes to rebuild a large project or create an application file (.app), dynamic link library (.dll), or executable file (.exe) from a large project.

See Also

BUILD APP | BUILD DLL | BUILD EXE | Build Method | BUILD PROJECT | CREATE PROJECT | MODIFY PROJECT

Applies To: Project Object


Clear Method

Clears the contents of a ComboBox or ListBox control.

Object.Clear

Remarks

The Clear method removes all items from a ComboBox or ListBox control, but only if the RowSourceType property is set to 0 (None). Additionally, it sets the ListCount property to 0.

See Also

AddItem Method | RemoveItem Method | RowSourceType Property

Applies To: ComboBox | ListBox


ClearData Method

Clears all data and data formats from the OLE drag-and-drop DataObject object. Available at run time only.

oDataObject.ClearData

Remarks

The ClearData method can only be executed in the OLEStartDrag event; calling the ClearData method from the OLEDragDrop or OLE DragOver events generates an error.

See Also

GetData Method | GetFormat Method | OLE Drag-and-Drop Overview | SetData Method | SetFormat Method

Applies To: DataObject Object


CloneObject Method

Duplicates an object, including all the object's properties, events, and methods. Available only at design time.

Object.CloneObject(NewName)

Parameters

NewName
Specifies the name of the new, or duplicate, object.

See Also

SaveAs Method | SaveAsClass Method

Applies To: CheckBox Control | ComboBox Control | CommandButton Control | CommandGroup Control | Custom Object | EditBox Control | Grid Control | Image Control | Label Control | Line Control | ListBox Control | OLE Bound Control | OLE Container Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | Shape Control | Spinner Control | TextBox Control | Timer Control | ToolBar Object


Close Method

Closes a project and releases the project's ProjectHook and Project objects.

Object.Close( )

Remarks

Executing the Close method causes the project's ProjectHook.Destroy event to occur. After the ProjectHook.Destroy event occurs, the ProjectHook object is released, and then the Project object is released.

See Also

CLOSE Commands | Destroy Event | ProjectHook Object

Applies To: Project Object


CloseTables Method

Causes the tables and views associated with the data environment to close.

DataEnvironment.CloseTables

Remarks

Closes the tables and views associated with Cursor objects in the data environment. You can reopen the tables and views by calling the OpenTables method.

See Also

AfterCloseTables Event | AutoCloseTables Property | BeforeOpenTables Event | OpenTables Method

Applies To: DataEnvironment


Cls Method

Clears graphics and text from a form.

Object.Cls

Remarks

Cls clears text and graphics generated at run time with graphics and printing statements. Background bitmaps created using the Picture property and controls placed on the form at design time are not affected by the Cls method.

The Cls method resets the CurrentX and CurrentY properties to 0.

See Also

Circle Method | CurrentX, CurrentY Properties | Line Method | Picture Property

Applies To: Form Object | _SCREEN


CursorAttach Method

Attaches an existing cursor to the current instance of a CursorAdapter object.

CursorAdapter.CursorAttach( [ cAlias [, lInheritCursorProperties ] ] )

Parameters

cAlias
Specifies the alias of the cursor or table to be attached.

When cAlias is specified, CursorAttach populates the CursorAdapter Alias property with the alias of the attached cursor or table. When cAlias is not specified, CursorAttach attempts to attach the cursor or table, which must exist, specified by the current value of the CursorAdapter Alias property.

lInheritCursorProperties
Specifies whether you wish to keep or discard the properties of the cursor or table being attached. The following table lists the possible values for lInheritCursorProperties.
lInheritCursorProperties | Description
True (.T.) | Existing properties set for the cursor are inherited by the corresponding properties of the CursorAdapter object.
False (.F.) or empty | Existing properties set for the cursor are not copied into the corresponding properties of the CursorAdapter object.

This option adds flexibility when you are attaching a SQL Pass-Through, Remote View, or other cursor.

Return Values

Logical data type. CursorAttach returns True (.T.) if the cursor is attached successfully and False (.F.) if attachment fails.

Remarks

A cursor or table can have only one instance of a CursorAdapter object attached to it at any given time.

When Visual FoxPro attaches a cursor, you cannot change the cursor or table using the MODIFY STRUCTURE or SQL ALTER TABLE commands.

Calling CursorAttach closes the currently attached cursor. To preserve the currently attached cursor, call CursorDetach first.

Calling CursorAttach populates the Alias property of the CursorAdapter instance with the alias of the attached cursor or table.

Calling CursorAttach turns on BufferModeOverride (3) or BufferModeOverride (5), depending on the BufferModeOverride property for the CursorAdapter object, if not already set. If buffering is already turned on but is less granular than Optimistic Row Buffering, Visual FoxPro promotes buffering to Optimistic Row Buffering.

Visual FoxPro generates error messages under the following conditions:

  • If cAlias cannot be found.
  • If CursorAttach attempts to attach a cursor that is already attached to another instance of CursorAdapter.

The Tables property should not refer to a cursor that was attached to a CursorAdapter object by CursorAttach.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | Alias Property | ALTER TABLE - SQL Command | MODIFY STRUCTURE Command | CursorDetach Method | BufferModeOverride Property | Updating Remote Data with SQL Pass-Through

Applies To: CursorAdapter Class


CursorDetach Method

Frees the currently attached cursor from the current instance of CursorAdapter.

CursorAdapter.CursorDetach()

Return Values

Logical data type. CursorDetach returns True (.T.) if cursor is detached successfully and False (.F.) if not detached successfully.

Remarks

Visual FoxPro preserves all settings, such as buffering and so on, available to a normal cursor in the freed cursor.

Visual FoxPro preserves all unsaved changes. For example, you do not need to call the TABLEUPDATE( ) function before detaching the cursor.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | TABLEUPDATE( ) Function | BeforeCursorDetach Event | AfterCursorDetach Event | CursorAttach Method

Applies To: CursorAdapter Class


CursorFill Method

Executes the command in the SelectCmd property against the data source in the CursorAdapter DataSource property, creates a cursor, retrieves data, and performs any necessary data conversion according to the CursorAdapter DataSourceType and CursorSchema properties.

CursorAdapter.CursorFill( [ lUseCursorSchema [, lNoData [, nOptions [, Source ] ] ] ] )

Parameters

lUseCursorSchema
The following table lists the values for lUseCursorSchema.
lUseCursorSchema Description
True (.T.) Uses the schema in the CursorSchema property to create the cursor.
Note Visual FoxPro generates error messages when CursorSchema is required but is missing or invalid.
False (.F.) or empty Does not use the schema in the CursorSchema property to create the cursor.

Instead, CursorFill creates the cursor using the data types as normally determined by Visual FoxPro according to the CursorAdapter DataSourceType property.
lNoData
The following table lists the values for lNoData.
lNoData | Description
True (.T.) Create the cursor but do not fill it with data.

When the CursorAdapter DataSourceType property is "ADO", and SelectCmd contains parameters, CursorFill attempts to evaluate the parameters in SelectCmd. If CursorFill cannot evaluate the parameters, it uses null (.NULL.) values for the parameter values.

When the CursorAdapter DataSourceType property is "XML", CursorFill creates the cursor using the schema in the CursorSchema property, regardless of the value passed to lUseCursorSchema. If CursorSchema is empty or invalid, Visual FoxPro generates an error.
False (.F.) or empty | Create the cursor and fill it with data.

If you specify lNoData for CursorFill, and SelectCmd is a SQL SELECT command against a parameterized view, Visual FoxPro continues to prompt you for parameter input. This action is equivalent to the following statement:

SELECT * FROM "customers in specific country" WHERE 1=0
nOptions
Specifies numeric values or flags for creating the cursor. The values for nOptions are also used for the CursorRefresh method.

The following table lists values for nOptions depending on the setting of the CursorAdapter DataSourceType property.

DataSourceType | nOptions
"ADO" | An integer representing the Command type or Execution Enum values you want to set for the ActiveX Data Object (ADO) RecordSet Open method. The default value is -1.
"XML" | Any combination of valid XMLTOCURSOR( ) function flags except 8192, which is automatically set when the lUseCursorSchema parameter contains a value of True (.T.).
Source
Specifies a reference to an ADO Command or an open RecordSet object.

The ADO Command object must have its ActiveConnection property set to the appropriate and already open ADO Connection object. When an ADO Command object is passed to Source, Visual FoxPro sets the ADO Command CommandText property to value of the CursorAdapter SelectCmd property. Visual FoxPro parses any parameters in SelectCmd, and creates and sets parameter values in the ADO Command object. CursorFill method then executes in the following manner:

CursorAdapter.DataSource.Open( Source,,,,Options )

In this call, DataSource is the ADO RecordSet object in the CursorAdapter DataSource property, and Source is the ADO Command object referenced in this parameter.

The ADO RecordSet object must be open when passed to Source, CursorFill executes against the ADO RecordSet object and populates the cursor accordingly. In this case, only the CursorAdapter DataSourceType property must be set to "ADO". The CursorAdapter SelectCmd and DataSource properties are not used.

If you do not specify a value for Source, CursorFill executes in the following manner:

CursorAdapter.DataSource.Open( CursorAdapter.SelectCmd,,,,Options )

In this call, DataSource is the ADO RecordSet object in the CursorAdapter DataSource property. However, the ADO RecordSet object directly executes the current CursorAdapter SelectCmd property instead of using an ADO Command object. The ADO RecordSet must have its ActiveConnection property set to a valid ADO Connection object.

Return Values

Logical data type. CursorFill returns True (.T.) if the cursor is created successfully and False (.F.) if not created successfully.

Note If CursorFill returns False (.F.), the cursor is discarded. In this case, the BeforeCursorClose and AfterCursorClose events do not occur. To retrieve error information when CursorFill returns False (.F.), you must call the AERROR( ) function because the ON ERROR command does not execute.

Remarks

The following table lists how CursorFill behaves depending on how the CursorAdapter DataSourceType property is set.

DataSourceType | SelectCmd property behavior
"Native" | CursorFill executes SelectCmd, which must contain a SelectCmd a valid Visual FoxPro SQL SELECT command.
"ADO" CursorFill executes SelectCmd by calling the ADO RecordSet Open method. You must therefore set the CursorAdapter DataSource property to a valid ADO RecordSet object. If SelectCmd contains parameters, you must specify a valid ADO Command object in the CursorFill Source parameter.

Manually closing the cursor closes the associated ADO RecordSet. However, this does not apply if the cursor was obtained using the CursorAttach method.

CursorFill does not set the ADO RecordSet MaxRecords property to the CursorAdapter MaxRecords property.
"ODBC" | CursorFill executes SelectCmd using the connection handle of the DataSource property of the CursorAdapter object. Visual FoxPro returns the cursor using SQL Pass-Through. The name of the cursor corresponds to the alias obtained by calling This.Alias.
"XML" One of the following:
  • SelectCmd is an expression that evaluates to a valid XMLTable object. CursorFill calls the XMLTable ToCursor method, and the resulting cursor is attached.
  • SelectCmd is an expression, command, or function that returns XML. CursorFill uses the XMLTOCURSOR( ) function to transform the XML to a cursor. For more information, see the following list of additional remarks.

In addition, when DataSourceType is set to "XML", and SelectCmd is an expression, command, or function that returns XML:

  • The XML requirements are the same as those for the first parameter of the XMLTOCURSOR( ) function. You can specify these requirements by passing the appropriate XMLTOCURSOR( ) nFlags value to the CursorFill nOptions parameter. You can specify additional XMLTOCURSOR() flags or combine them as in XMLTOCURSOR().
  • CursorFill chooses between eExpression and cXMLFile from XMLTOCURSOR( ) based on nOptions:
    • If nOptions is 0, CursorFill processes XMLSource as eExpression and expects a memory variable containing a valid XML string or an expression that results in an XML string.
    • If nOptions is 512, CursorFill processes XMLSource as cXMLFile and expects a string literal with quotation marks ("") or a memory variable containing a valid file name.
  • The cCursorName parameter in XMLTOCURSOR( ) is always the current value in the Alias property for the CursorAdapter object.
  • If lUseCursorSchema is True (.T.), CursorFill automatically adds the 8192 flag to enforce use of the existing cursor for the XML.

When Visual FoxPro calls CursorFill, it closes the currently attached cursor, if it exists, and the work area that contains the newly created cursor becomes the active work area.

Note If you wish to preserve the currently attached cursor, call the CursorDetach method before calling CursorFill.

When Visual FoxPro attaches a cursor, you cannot change the cursor or table using the MODIFY STRUCTURE or SQL ALTER TABLE commands.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


CursorRefresh Method

Refreshes a cursor with current data from the data source. CursorRefresh re-executes the value of the SelectCmd parameter in the BeforeCursorRefresh event with respect to CursorAdapter DataSourceType.

Note If the SelectCmd parameter in the BeforeCursorRefresh event contains parameters, you can modify the scope of the rows that are returned through the original query by changing the parameters.
CursorAdapter.CursorRefresh()

Return Values

Logical data type. CursorRefresh returns True (.T.) if the cursor is repopulated successfully and False (.F.) if not repopulated successfully.

Remarks

CursorRefresh updates the following properties for the ADO or ODBC-based cursor from the following CursorAdapter properties:

  • AllowSimultaneousFetch
  • CompareMemo
  • FetchAsNeeded
  • FetchMemo
  • FetchSize
  • MaxRecords
  • Prepared
  • UseMemoSize

Visual FoxPro generates an error message when the cursor contains unsaved changes.

If the CursorAdapter DataSourceType property is "ADO" when executing the CursorAdapter CursorFill method, CursorRefresh behaves in the following manner:

  • CursorAdapter objecct has an attached cursor resulting from executing SelectCmd using CursorFill:
    • Sets the ADO Command CommandText property for the ADO RecordSet ActiveCommand object to the SelectCmd used to open the ADO RecordSet unless CommandText already contains this value.
    • Refreshes the Command object parameters collection and re-evaluates the parameter values.
    • Calls the ADO RecordSet Requery method and passes the same values in the nOptions parameter used by CursorFill to open the ADO RecordSet.
  • CursorAdapter object has an attached cursor resulting from passing an already open ADO RecordSet to the CursorFill Source parameter.
    • Calls the ADO RecordSet Requery method and pass the same value for the nOptions parameter used by CursorFill.

Example

Example 1

The following example illustrates retrieving results using ADO with a parameter and using CursorRefresh to refresh data. The connection string settings for SQL Server (localhost) and Visual FoxPro OLE DB Provider are the following:

* .ConnectionString = 'provider=SQLOLEDB.1;data source=localhost;'+
* 'initial catalog=Northwind;trusted_connection=yes'
CLEAR
LOCAL loConn AS ADODB.CONNECTION, ;
   loCommand AS ADODB.COMMAND, ;
   loException AS EXCEPTION, ;
   loCursor AS CURSORADAPTER, ;
   country, ;
   laErrors[1]
loConn = CREATEOBJECT('ADODB.Connection')
WITH loConn
   .ConnectionString = 'provider=vfpoledb;data source=' + ;
   HOME(2)+'northwind\Northwind.dbc'
   TRY
      .OPEN()
   CATCH TO loException
      MESSAGEBOX(loException.MESSAGE)
      CANCEL
   ENDTRY
ENDWITH
loCommand = CREATEOBJECT('ADODB.Command')
loCommand.ActiveConnection = loConn
loCursor = CREATEOBJECT('CursorAdapter')
WITH loCursor
   .ALIAS          = 'Customers'
   .DATASOURCETYPE = 'ADO'
   .SELECTCMD      = ;
   'select * from customers where country=?lcCountry'
   lcCountry       = 'Brazil'
   .DATASOURCE = CREATEOBJECT('ADODB.Recordset')
   .DATASOURCE.ActiveConnection = loConn
   llReturn = .CURSORFILL(.F., .F., 0, loCommand)
   IF llReturn
      BROWSE
      lcCountry = 'Canada'
      llReturn  = .CURSORREFRESH()
      IF llReturn
         BROWSE
      ENDIF llReturn
   ELSE
      AERROR(laErrors)
      MESSAGEBOX(laErrors[2])
   ENDIF llReturn
ENDWITH

The following example that illustrates using CursorRefresh with an already opened ADO Recordset. The connection string settings for SQL Server (localhost) and the Visual FoxPro OLE DB Provider are:

* .ConnectionString = 'provider=SQLOLEDB.1;data source=localhost;' + ;
* 'initial catalog=Northwind;trusted_connection=yes'
CLEAR
LOCAL loConn AS ADODB.CONNECTION, ;
   loCommand AS ADODB.COMMAND, ;
   loParam AS ADODB.PARAMETER, ;
   loRs AS ADODB.Recordset,;
   loException AS EXCEPTION, ;
   loCursor AS CURSORADAPTER, ;
   lcCountry, ;
   laErrors[1]
loConn = CREATEOBJECT('ADODB.Connection')
WITH loConn
   .ConnectionString = 'provider=vfpoledb;data source=' + ;
      HOME(2)+'northwind\Northwind.dbc'
   TRY
      .OPEN()
   CATCH TO loException
      MESSAGEBOX(loException.MESSAGE)
      CANCEL
   ENDTRY
ENDWITH
loCommand = CREATEOBJECT('ADODB.Command')
loCommand.CommandText = ;
   "SELECT * FROM customers WHERE Country = ?"
loParam = loCommand.CreateParameter("Country", 129, 1, 15, "")
loCommand.PARAMETERS.APPEND(loParam)
loCommand.PARAMETERS("Country") = "Brazil"
loCommand.ActiveConnection = loConn
loRs = loCommand.Execute()
loCursor = CREATEOBJECT('CursorAdapter')
WITH loCursor
   .ALIAS          = 'Customers'
   .DATASOURCETYPE = 'ADO'
   llReturn = .CURSORFILL(.F., .F., 0, loRs)
   IF llReturn
      BROWSE
      loRs.ActiveCommand.PARAMETERS("Country") = "Canada"
      llReturn  = .CURSORREFRESH()
      IF llReturn
         BROWSE
      ENDIF llReturn
   ELSE
      AERROR(laErrors)
      MESSAGEBOX(laErrors[2])
   ENDIF llReturn
ENDWITH

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | BeforeCursorRefresh Event

Applies To: CursorAdapter Class


DataToClip Method

Copies a set of records as text to the Clipboard.

ApplicationObject.DataToClip([nWorkArea | cTableAlias]
   [, nRecords] [, nClipFormat])

Property Values

nWorkArea
Specifies the work area number of the table for which records are copied to the Clipboard. If you omit cTableAlias and nWorkArea, records are copied to the Clipboard for the table open in the current work area.
cTableAlias
Specifies the alias of the table for which the records are copied to the Clipboard.
nRecords
Specifies the number of records copied to the Clipboard. If nRecords is greater than the number of remaining records in the table, all the remaining records are copied to the Clipboard. If nRecords and nClipFormat are omitted, the current record and all remaining records are copied to the Clipboard.
nClipFormat
Specifies how fields are delimited. The settings for nClipFormat are:
nClipFormat | Description
1 | (Default) Fields delimited with spaces
3 | Fields delimited with tabs

If nClipFormat is omitted, fields are delimited with spaces.

Remarks

The field names appear as the first line of the text copied to the Clipboard, followed by a separate line for each record.

See Also

Eval Method | SetVar Method | _CLIPTEXT System Variable

Applies To: Application Object | _VFP System Variable


DeleteColumn Method

Removes a Column object from a Grid control.

Grid.DeleteColumn[(nIndex)]

Parameters

nIndex
Specifies a number referencing the order of Columns in a Grid. If nIndex is not specified, the last Column in the Grid is removed.

See Also

AddColumn Method | AddObject Method | RemoveObject Method

Applies To: Grid


Dock Method

Positions the ToolBar object along a border of the main Visual FoxPro window.

ToolBar.Dock(nLocation [, X, Y])

Parameters

nLocation
Specifies where the toolbar is docked. The values for nLocation are:
Value | Constant | Description
–1 | TOOL_NOTDOCKED | Undocks the toolbar.
0 | TOOL_TOP | Positions the toolbar at the top of the main Visual FoxPro window.
1 | TOOL_LEFT | Positions the toolbar at the left side of the main Visual FoxPro window.
2 | TOOL_RIGHT | Positions the toolbar at the right side of the main Visual FoxPro window.
3 | TOOL_BOTTOM | Positions the toolbar at the bottom of the main Visual FoxPro window.
X, Y
Specifies the horizontal and vertical coordinates respectively of the docked position of the toolbar.

Remarks

Toolbars are docked along the borders of the main window. When a toolbar is docked, its title bar is hidden and its border is changed to a single line. The toolbar is also resized to a single row of buttons. The window is resized so that the toolbar does not obscure any information on the screen. For example, if the toolbar is docked at the top, the screen is moved down by the height of the toolbar.

Use the Move method to undock a toolbar. When using the Move method, the coordinates specified must be outside the dock area.

See Also

AfterDock Event | BeforeDock Event | Docked Property | Undock Event

Applies To: ToolBar


DoCmd Method

Executes a Visual FoxPro command for an instance of the Visual FoxPro application automation server.

ApplicationObject.DoCmd(cCommand)

Property Values

cCommand
Specifies the Visual FoxPro command to execute.

Remarks

cCommand must evaluate to a legal Visual FoxPro command.

See Also

DO | Eval Method | SetVar Method

Applies To: Application Object | _VFP System Variable


DoScroll Method

Scrolls the Grid control to simulate a user clicking the scroll bars.

Grid.DoScroll(nDirection)

Parameters

nDirection
The settings for nDirection are:
Scroll command | Scroll action
0 | Scroll up
1 | Scroll down
2 | Scroll page up
3 | Scroll page down
4 | Scroll left
5 | Scroll right
6 | Scroll page left
7 | Scroll page right

Remarks

The Scrolled event is triggered after the DoScroll method.

See Also

Scrolled Event

Applies To: Grid


DoVerb Method

Executes a verb on the specified object.

Object.DoVerb[(Verb)]

Parameters

Verb
The verb to execute on the object within the OLE container control. If not specified, the default verb is executed. The value of this argument can be one of the standard verbs supported by all objects or an index of the ObjectVerbs property array. Each object can support its own set of verbs.

The following values represent standard verbs supported by every object:

Value | Action
0 | The default action for the object.
–1 | Activates the object for editing. If the application that created the object supports in-place activation, the object is activated within the OLE container control.
–2 | Opens the object in a separate application window. If the application that created the object supports in-place activation, the object is activated in its own window.
–3 | For embedded objects, hides the application that created the object.
–4 | If the object supports in-place activation, activates the object for in-place activation and shows any user interface tools. If the object doesn't support in-place activation, the object doesn't activate, and an error occurs.
–5 | If the user moves the focus to the OLE container control, creates a window for the object and prepares the object to be edited. An error occurs if the object doesn't support activation on a single mouse click.
–6 | Used when the object is activated for editing to discard all record of changes that the object's application can undo.

Remarks

If you set the AutoActivate property to 2 (DoubleClick), the OLE container control automatically activates the current object when the user double-clicks the control.

Tip Although you can use the name of the verb (edit, open, play, and so on) to specify the verb to use with DoVerb, it is much faster to use the index (0, 1, 2, and so on).

Example

The following example adds an OLE Container control to a form, and uses the OleClass and DocumentFile properties to specify Microsoft Excel as the Automation server and a Microsoft Excel worksheet as the file to edit.

The DocumentFile property specifies a worksheet named Book1.xls in the EXCEL directory on drive C. This example will not work properly if the file and directory specified in the DocumentFile property do not exist; it may be necessary to modify the DocumentFile property to specify an existing directory and worksheet file.

* The DoVerb method is used to activate the worksheet for editing.

*frmMyForm = CREATEOBJECT('form')  && Create a form
*frmMyForm.Closable = .F.  && Disable the Control menu box

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject("oleObject","oleExcelObject")  && Add OLE object

frmMyForm.cmdCommand1.Visible=.T.  && Display the "Quit" Command button

frmMyForm.oleObject.Visible=.T.  && Display the OLE control
frmMyForm.oleObject.Height = 50  && OLE control height

frmMyForm.Show  && Display the form

frmMyForm.oleObject.DoVerb(-1)  && -1 for Edit

READ EVENTS  && Start event processing

DEFINE CLASS oleExcelObject as OLEControl
   OleClass ="Excel.Sheet"  && Server name
   DocumentFile = "C:\EXCEL\BOOK1.XLS"  && This file must exist
ENDDEFINE

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
ENDDEFINE

See Also

OLE Bound Control | OLE Container Control

Applies To: OLE Bound Control | OLE Container Control


Drag Method

Begins, ends, or cancels a drag operation.

Control.Drag [(nAction)]

Parameters

nAction
Indicates the action to perform. If you omit nAction, nAction is set to 1.

The settings for the Drag method are:

Setting | Description
0 | Cancel drag operation; restore original position of control.
1 | (Default) Begin dragging the control.
2 | End dragging — that is, drop the control.

Remarks

Usually, the MouseDown event procedure calls the Drag method to begin the dragging operation.

It's necessary to use the Drag method to control dragging only when the DragMode property of the control is set to 0 (Manual). You can use Drag on a control whose DragMode property is set to 1 (Automatic), but the MouseDown and MouseUp events are not triggered.

If you want the mouse pointer to change while the control is being dragged, use either the DragIcon property or the MousePointer property to define the pointer. The MousePointer property only has an effect if the DragIcon property is not set.

See Also

DragDrop Event | DragIcon Property | DragMode Property | MousePointer Property | Move Method

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox


Draw Method

Repaints a Form object.

Object.Draw

See Also

Paint Event

Applies To: Form | _SCREEN


Eval Method

Evaluates an expression and returns the result for an instance of the Visual FoxPro application automation server.

ApplicationObject.Eval(cExpression)

Return Values

Character, Numeric, Currency, Date, or Logical

Property Values

cExpression
Specifies the expression to evaluate. cExpression can be a literal character string, or a valid Visual FoxPro expression, variable, array element, or field of any data type, enclosed in quotation marks.

Remarks

cExpression must be a legal Visual FoxPro character expression.

See Also

DoCmd Method | SetVar Method

Applies To: Application Object | _VFP System Variable


GetData Method

Retrieves data from the OLE drag-and-drop DataObject object. Available at run time only.

oDataObject.GetData(nFormat | cFormat [, @ArrayName])

Parameters

nFormat | cFormat
Specifies the format of the data to retrieve. The following table lists the values for each data format and a description of each format. The DataObject automatically supports the following formats (more formats are available, but these may require additional programming to use). For more information about the data formats available, see the documentation for Visual C++® on the Microsoft Developer Network.
Data format* | nFormat| cFormat | Description
CF_TEXT | 1 | Text format.
CF_OEMTEXT | 7 | Text format containing characters in the OEM character set.
CF_UNICODETEXT | 13 | Unicode text format, available only under Windows NT 4.0 or later.
CF_FILES or CF_HDROP | 15 | A handle that identifies a list of files, such as a set of files dragged from the Windows Explorer.
CF_LOCALE | 16 | A handle to the locale identifier associated with text on the clipboard.
CFSTR_OLEVARIANTARRAY "OLE Variant Array" A Visual FoxPro array. Multiple values can be transferred in a single drag and drop operation with this format.

For example, this format can be used to drag a set of items in a list box to another list box.
CFSTR_OLEVARIANT | "OLE Variant" | A Visual FoxPro variant. All data types in Visual FoxPro are represented as variants. This format can be used to drag and drop Visual FoxPro data without losing the data type.
CFSTR_VFPSOURCEOBJECT | "VFP Source Object" | A reference to a Visual FoxPro object.

* Defined in FOXPRO.H.

@ArrayName
Specifies the name of the array in which the data is stored when the data can contain multiple values. The only data formats in which the data can contain multiple values are CF_FILES, CF_HDROP, and CFSTR_OLEVARIANTARRAY. For example, you can drag a set of files from the Windows Explorer onto a Visual FoxPro list box. Use the GetData method in the OLEDragDrop event of the list box to place the names of the files into an array, then use the AddItem method in a FOR … ENDFOR loop to add the contents of the array to the list box.

The array must exist before you can specify its name in the GetData method. If the array exists and isn't large enough to contain the data, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array.

Remarks

The value returned by the GetData method is determined by the format of the data specified with nFormat or cFormat. False (.F.) is returned if the DataObject doesn't contain data in the format you specify with nFormat or cFormat. True (.T.) is returned when the data is in a multiple value format such as CF_FILES, CF_HDROP, or CFSTR_OLEVARIANTARRAY. The data on the DataObject is returned when the data is in a single value format such as CF_TEXT, CFSTR_OLEVARIANT, or CFSTR_VFPSOURCEOBJECT.

The OLESetData event for a drag source is triggered if the data format you specify with nFormat or cFormat exists, but there is no data in the DataObject for that format. (The SetFormat method can be used to specify a data format before the corresponding data is placed on the DataObject with the SetData method.)

See Also

ClearData Method | GetFormat Method | OLE drag-and-drop Overview | OLESetData Event | SetData Method | SetFormat Method

Applies To: DataObject Object


GetFormat Method

Determines if data in a specified format is available on the OLE drag-and-drop DataObject. Available at run time only.

oDataObject.GetFormat(nFormat | cFormat)

Parameters

nFormat | cFormat
Specifies the format of the data to retrieve. The following table lists some of the formats with a description of each format. For more information about the data formats available, see the documentation for Visual C++ on the Microsoft Developer Network. You can also create your own format by specifying a unique character string for cFormat.
Data Format* | nFormat| cFormat | Description
CF_TEXT | 1 | Text format.
CF_OEMTEXT | 7 | Text format containing characters in the OEM character set.
CF_UNICODETEXT | 13 | Unicode text format, available only under Windows NT 4.0 or later.
CF_FILES or CF_HDROP | 15 | A handle that identifies a list of files, such as a set of files dragged from the Windows Explorer.
CFSTR_OLEVARIANTARRAY "OLE Variant Array" An array. Multiple values can be transferred in a single drag and drop operation with this format.

For example, this format can be used to drag a set of items in a list box to another list box.
CFSTR_OLEVARIANT | "OLE Variant" | A variant. All data types in Visual FoxPro are represented as variants. This format can be used to drag and drop Visual FoxPro data without losing the data type.
CFSTR_VFPSOURCEOBJECT | "VFP Source Object" | A reference to the Visual FoxPro drag source object.

* Defined in FOXPRO.H.

Remarks

The GetFormat method returns true (.T.) if the DataObject contains data in the format you specify with nFormat or cFormat; otherwise returns false (.F.).

See Also

ClearData Method | GetData Method | OLE drag-and-drop Overview | SetData Method | SetFormat Method

Applies To: DataObject Object


GetKey Method

Returns the key or index of an item in a collection depending on the value that is passed.

Collection.GetKey(eIndex)

Parameters

eIndex
Specifies a required expression that represents a position of an item in the collection. This expression can be one of two types:
  • Numeric. The eIndex expression must have a value from 1 to the value of the Count property of the collection.
  • String. The eIndex expression must correspond to the cKey that was specified for the item when it was added to the collection.

Return Value

The following table lists the return values for GetKey.

Return value | Condition
String (key) | When passing an index or integer value
Integer (index) | When passing a key or string
Empty string ("") | When passing an index that does not exist or if items were added to the collection without keys
0 | When passing a key that does not exist

Remarks

  • Because the GetKey method returns a value, you need to add a RETURN statement to the end of GetKey in the source code for any subclass you have modified. For example:
    RETURN DODEFAULT( eIndex )

    If you do not want to return the value, use the RETURN command without the DODEFAULT() function.

  • To determine if keys were specified when items were added to the collection, you can use the statement GetKey(1) and the EMPTY() function to check for an empty return value as follows:
    ? !EMPTY(Collection.GetKey(1))
  • To derive the index or key from an item in a collection from within a FOR EACH loop, use a normal FOR loop instead of a FOR EACH loop.
  • Visual FoxPro generates an error if the wrong type or no parameter is passed to GetKey.

Example

The following example illustrates the following tasks after creating a collection and adding items:

  • Check if items have keys.
  • Retrieve and display key for the second item.
CLEAR
LOCAL oItems AS Collection

oItems = NEWOBJECT("Collection")
oItems.Add("Daffodils", "flower2")
oItems.Add("Roses", "flower1", "flower2")
oItems.Add("Daisies", "flower3")
? !EMPTY(oItems.GetKey(1))
? oItems.GetKey(2)

See Also

Collection Object Properties, Methods, and Events | Collection Class | Count Property | RETURN Command | DODEFAULT( ) Function | FOR EACH ... ENDFOR Command | FOR Loops


GetLatestVersion Method

Gets the latest version of a file in a project from source code control and copies a read-only version to your local drive.

Object.GetLatestVersion( )

Remarks

The GetLatestVersion method does not check the file out.

True (.T.) is returned if source code control can successfully get the file. False (.F.) is returned if source code control cannot get the file or the project is not under source code control.

See Also

AddToSCC Method | CheckIn Method | CheckOut Method | RemoveFromSCC Method | UndoCheckOut Method

Applies To: File Object


GridHitTest Method

Returns, as output parameters, the components of a grid control corresponding to specified horizontal (X) and vertical (Y) coordinates.

Grid.GridHitTest(nXCoord_In, nYCoord_In
   [, nWhere_Out [, nRelRow_Out [, nRelCol_Out [, nView_Out]]]])

Parameters

nXCoord_In
Specifies the horizontal (X) position in pixels within the form containing the grid.
nYCoord_In
Specifies the vertical (Y) position in pixels within the form containing the grid.
nWhere_Out
An output parameter that contains a value corresponding to the grid component at the position specified with nXCoord_In and nYCoord_In. The following table lists the values for @nWhere_Out and the corresponding grid component.
@nWhere_Out | Grid component
0 | A grid component that cannot be determined.
1 | Column header.
2 | Between column headers.
3 | Cell.
4 | Reserved.
5 | SplitBar.
6 | Record deletion marker.
7 | Reserved
8 | Reserved.
9 | Reserved.
10 | Reserved.
11 | Box in upper left corner.
12 | Record marker.
13 | Column header sizing area.
14 | Row sizing area.
15 | Reserved.
16 | Horizontal scrollbar.
17 | Vertical scrollbar.
nRelRow_Out
An output parameter containing the relative grid row at the specified point.
nRelCol_Out
An output parameter containing the relative grid column at the specified point.
nView_Out
An output parameter containing a value corresponding to the grid pane containing the specified point. If the grid is split into two panes, this parameter contains 0 if the specified point is in the left pane, and contains 1 if the specified point is in the right pane. If the grid isn't split into separate panes, this parameter contains 1.

Remarks

The GridHitTest( ) method returns true (.T.) if the specified point is within the grid; otherwise false (.F.) is returned.

The GridHitTest( ) method can be used during mouse events or OLE drop target events to determine where the mouse pointer is positioned over the grid. The nRelRow_Out and nRelCol_Out parameters can be passed to the ActivateCell( ) method to activate a specific cell in the grid.

See Also

ActivateCell Method | ActiveColumn Property | ActiveRow Property | MCOL( ) | MROW( )

Applies To: Grid Control


Help Method

Opens the Help window.

ApplicationObject.Help([cFileName] [, nContextID] [, cHelpTopic])

Parameters

cFileName
Specifies the name of the Help file to open. Include a path with the Help file name if the Help file isn't in the default directory.
nContextID
Specifies the Help topic to display, based on the topic's context ID. nContextID is a context number in the MAP section of the help project file.
cHelpTopic
Specifies the Help topic to display. If you include just a partial spelling of a topic title, Visual FoxPro opens the Help window and displays the topic with the closest matching title.

Remarks

If none of the optional arguments are included, the main Help topic is displayed.

See Also

HELP | SET HELP

Applies To: Application Object, | _VFP System Variable


Hide Method

Hides a form, form set, or toolbar by setting the Visible property to false (.F.).

Object.Hide

Remarks

Controls on a hidden form are not accessible to the user, but are still available and can be accessed in code. Although they are not visible, controls contained in an invisible form retain their own Visible property setting.

When the Visible property of the form set is set to false (.F.), the user cannot see the Forms it contains. Forms in a hidden form set are not accessible to the user, but are still available and can be accessed in code. The Hide method for a form set does not set the Visible property of its child Forms, so when a form is contained in a form set, you must check the Visible property settings of both the form and form set to determine if the form is visible.

After a form set is hidden, Visual FoxPro activates the last active object. If no objects were active before the form set, the main Visual FoxPro window becomes active.

Calling the Hide Method for the _SCREEN system variable has no effect.

See Also

Activate Event | Deactivate Event | Enabled Property | GotFocus Event | Show Method | Visible Property

Applies To: Form | FormSet | _SCREEN | ToolBar


IndexToItemID Method

Returns an index for a given item ID.

 [nItemID =] Control.IndexToItemID(nIndex)

Parameters

nItemID
Specifies a unique identification number.
nIndex
Specifies a number that represents the position that an item is displayed in a control.

Remarks

Each item added to a ComboBox or ListBox has two identification numbers assigned to it:

  • The nItemID, a unique identification number.
  • The nIndex, an integer corresponding to the order in which items are displayed by the control: The first item in the list corresponds to nIndex = 1.

Initially, as items are added to the control, these two numbers are identical. But as items are sorted, removed, and added, these numbers are no longer identical.

Use the IndexToItemID method to return the nItemID number for a particular item in the control when you know its nIndex number.

See Also

AddItem Method | AddListItem Method | ItemIDToIndex Method

Applies To: ComboBox | ListBox


Item Method (Collection Class)

Returns a specific member object in the collection by numeric position or string key.

The member object can have any valid type that can be assigned to a memory variable. This includes simple data types, such as strings, numbers, dates, logical, or more complex ones such as Visual FoxPro and Component Object Model (COM) objects. The Item method for collection objects is typically used with FOR EACH...ENDFOR enumerations to reference members of the collection.

Collection.Item( eIndex )

Parameters

eIndex
Specifies a required expression that represents a position of an item in the collection. This expression can be one of two types:
  • Numeric. The eIndex expression must have a value from 1 to the value of the Count property for the collection.
  • String. The eIndex expression must correspond to the cKey that was specified for the item when it was added to the collection.

If eIndex does not match an existing member of the collection, an error occurs.

Return Value

Returns the specific item.

Remarks

If an incorrect type is passed for a specific parameter, an error occurs.

The Item method for collection objects returns a value, which is the item itself. Therefore, you need to add a RETURN statement to the end of the Item method in the source code for any subclass you have modified:

RETURN DODEFAULT(eIndex)

If you do not want to return the item, use the RETURN statement without the DODEFAULT() function.

The Item method for collection objects is the default method for a collection. Therefore, the following lines of code are equivalent:

? MyCollection(1)
? MyCollection.Item(1)
? MyCollection("myKey")

Example

The following example illustrates these tasks at run time:

  • Creates forms and a collection.
  • Adds forms to the collection.
  • Displays the name of each form in the collection.
  • Displays the number of forms in the collection.
  • Displays the name of the first item in the collection.
  • Displays the name of the first item in the collection using the Item method for collections.
loForm1 = CREATEOBJECT("myForm1")
loForm2 = CREATEOBJECT("myForm2")
loCol = CREATEOBJECT("myCollection")
loCol.Add(loForm1)
loCol.Add(loForm2)
? loCol(1).Name
? loCol.Item(1).Name

See Also

Collection Object Properties, Methods, and Events | Collection Class | FOR EACH ... ENDFOR Command | RETURN Command | DODEFAULT( ) Function


Item Method (File Object)

Returns an object reference to a specified file, project, or server in a files, projects, or servers collection.

Object.Item(nIndex)
nIndex
A number that specifies a file, project, or server in a files, projects, or servers collection. An "Invalid subscript reference" error is generated if nIndex is greater than the number of files, projects, or servers in a collection.

Remarks

Use the Name property with the Item property to determine the name of a file, project, or server and the directory in which it is contained.

See Also

Name Property

Applies To: Files Collection | Projects Collection | Servers Collection


ItemIDToIndex Method

Returns the value of nIndex, the position of an item in a control's list.

 [nIndex =]Control.ItemIDToIndex(nItemID)

Parameters

nItemID
The unique identification number associated with that item.

Remarks

Each item added to a combo box or list box has two numbers assigned to it:

  • The nItemID, a unique identification number.
  • The nIndex, an integer corresponding to the order in which items are displayed by the control. The first item in the list corresponds to nIndex = 1.

Initially, as items are added to the control, these two numbers are identical. But as items are sorted, removed, and added, these numbers are no longer identical.

Use the ItemIDToIndex method to retrieve the nIndex number for a particular item in the control's list when you know its nItemID number.

See Also

AddItem Method | AddListItem Method | IndexToItemID Method | ListItemID Property | List Property | ListCount Property

Applies To: ComboBox | ListBox


Line Method

Draws a line on a Form object.

Object.Line(nXCoord2, nYCoord2)

-or-

Object.Line(nXCoord1, nYCoord1, nXCoord2, nYCoord2)

Parameters

nXCoord1, nYCoord1
Specifies the coordinates of the starting point of the line. The unit of measurement is specified by the ScaleMode property of the form.
nXCoord2, nYCoord2
Specifies the coordinates of the endpoint of the line.

Remarks

The width of the line drawn depends on the setting of DrawWidth property. The way a line is drawn on the background depends on the setting of the DrawMode and DrawStyle properties. After the Line method runs, the CurrentX and CurrentY properties are set to nXCoord2, nYCoord2.

See Also

CurrentX, CurrentY Properties | DrawMode Property | DrawStyle Property | DrawWidth Property | ScaleMode Property

Applies To: Form | _SCREEN


Modify Method

Opens a file in a project for modification in the appropriate designer or editor.

Object.Modify([cClassName])

Parameters

cClassName
Specifies the name of the visual class to open for modification when Object is a .vcx visual class library.

Remarks

The Modify method returns true (.T.) if the file is successfully opened for modification; otherwise false (.F.) is returned.

The QueryModifyFile event occurs before the file is opened. If the QueryModifyFile event returns false (.F.), the file isn't opened and the Modify method returns false (.F.). If the QueryModifyFile method returns true (.T.), the file is opened and the Modify method returns true (.T.).

See Also

Add Method | Remove Method (File Object) | QueryModifyFile Event

Applies To: File Object


Move Method

Moves an object.

Object.Move (nLeft [, nTop [, nWidth [, nHeight]]])

Parameters

nLeft
Specifies the horizontal coordinate for the left edge of the object. nLeft is a single-precision value.
nTop
Specifies the vertical coordinate for the top edge of the object. nTop is a single-precision value.
nWidth
Specifies the new width of the object. nWidth is a single-precision value.
nHeight
Specifies the new height of the object. nHeight is a single-precision value.

Remarks

Only the nLeft argument is required. However, to include any other arguments, you must also include all arguments in the syntax before the argument you want to include. For example, you cannot specify nWidth without specifying nLeft and nTop. Any trailing arguments that are unspecified remain unchanged.

Moving a Form on the screen or moving a control on a form is always relative to the origin (0,0), which is the upper-left corner. When moving controls in a container, the coordinate system of the container is used.

See Also

Top Property | Width Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | _SCREEN | Shape | Spinner | TextBox | ToolBar


MoveItem Method

Moves an item to a new position in a list box.

ListBox.MoveItem(nItemIndex, nMoveBy)

Parameters

nItemIndex
Specifies the current index for the item you wish to move.
nMoveBy
Indicates how many positions the item should be moved. A positive value indicates downward movement. A negative number indicates upward movement.

Remarks

Calling the MoveItem method fires the OnMoveItem event.

The OnMoveItem event always fires once when the MoveItem method is called, however, movement of an item in the list box occurs only if the grid's RowSourceType property is set to 0 (None) or 1 (Value).

See Also

Methods | OnMoveItem Event | RowSourceType Property | MoverBars Property

Applies To: ListBox Control


NewObject Method

Adds a new class or object to an object directly from a .vcx visual class library or program.

Object.NEWOBJECT(cObjectName, cClassName [, cModule [, cInApplication
   [, eParameter1, eParameter2, ...]]])
cObjectName
Specifies the name used to reference the newly added class or object.
cClassName
Specifies the class or object from which the new class or object is added.
cModule
Specifies a .vcx visual class library or Visual FoxPro program (.prg, .mpr, .app, .exe, and so on) containing the class or object specified with cClassName. The default is a .vcx visual class library; you must include an extension if you specify a program.
Note A class library can have an alias. To specify a class or object from a class library with an alias, include the class library alias followed by a period and the object name.

If cModule is omitted, or is the empty string or the null value, Visual FoxPro searches for the class or object in the following order:

  • Visual FoxPro base classes.
  • User-defined class definitions in memory in the order they were loaded.
  • Classes in the current program.
  • Class libraries opened with SET CLASSLIB.
  • Classes in procedure files opened with SET PROCEDURE.
  • Classes in the Visual FoxPro program execution chain.
  • The OLE registry if SET OLEOBJECT is ON.
cInApplication
Specifies the Visual FoxPro application (.exe or .app) containing the .vcx visual class library you specify with cClassLibName. You must include an extension for the application. CInApplication is ignored if cModule is omitted, or if cInApplication is the empty string or the null value.
eParameter1, eParameter2, ...
Specifies optional parameters that are passed to the Init event procedure for the class or object.

Remarks

The NEWOBJECT method makes it possible for you to add a new class or object to an object without opening a .vcx visual class library or procedure file.

See Also

AddObject Method | AddProperty Method | Class Designer | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | DEFINE CLASS | NEWOBJECT( )

Applies To: Column | CommandGroup | Container Object | Custom | DataEnvironment | Form | FormSet | Grid | OptionGroup | Page | PageFrame | _SCREEN | ToolBar | Session Object


OLEDrag Method

Starts an OLE drag-and-drop operation.

PROCEDURE Object.OLEDrag(lDetectDrag)

Parameters

lDetectDrag
Specifies when the OLEStartDrag event is executed. If lDetectDrag is false (.F.), the OLEStartDrag event is immediately executed. If lDetectDrag is true (.T.), the OLEStartDrag event is executed after the user has pressed the mouse button for a sufficient period of time to indicate that a drag operation is occurring, or the mouse is moved a sufficient distance while the mouse button is pressed, again indicating that a drag operation is occurring.

If you don't specify a value for lDetectDrag, true (.T.) is automatically returned.

Remarks

OLEDrag is a drag source method.

See Also

OLE Drag-and-Drop Overview | OLEDragMode Property | OLEStartDrag Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OpenTables Method

Programmatically opens the tables and views associated with the data environment.

DataEnvironment.OpenTables

Parameters

DataEnvironment
Specifies the data environment associated with the form, form set, or report.

Remarks

The OpenTables method loads the data environment tables when the AutoOpenTables property of the data environment is set to false (.F.) or if the data environment has been unloaded using the CloseTables method. The OpenTables method acts like an event, that is it is called automatically if autoOpenTables = .T..

See Also

AfterCloseTables Event | AutoOpenTables Property | BeforeOpenTables Event | CloseTables Method

Applies To: DataEnvironment


Point Method

Returns the red-green-blue (RGB) color of the specified point on a form.

Object.Point ([nXCoord, nYCoord])

Parameters

nXCoord
Specifies the horizontal coordinate of the point, in the units specified in the ScaleMode property setting of the form.
nYCoord
Specifies the vertical coordinate of the point, in the units specified in the ScaleMode property setting of the form.

Remarks

If nXCoord or nYCoord is outside of the form, the Point method returns – 1.

See Also

Circle Method | Line Method | Print Method | PSet Method

Applies To: Form Object | _SCREEN System Variable


Print Method

Prints a character string on a form.

 [FormSet.] Object.Print [(cText)]

Parameters

cText
Specifies the character string to print. If you omit cText, a blank line is printed.

cText is printed on the form starting at the position specified by the CurrentX and CurrentY properties. When a carriage return is included, CurrentX is increased by the width of cText (same as the value returned by TextWidth) and CurrentY remains unchanged.

When the Print method is finished, the CurrentX and CurrentY properties are set to the point immediately after the last character printed.

Note This method is not supported if BITMAP=OFF.

See Also

CurrentX, CurrentY Properties | TextHeight Method | TextWidth Method

Applies To: Form | _SCREEN


PSet Method

Sets a point on a form or the main Visual FoxPro window to the foreground color.

 [FormSet.]Object.PSet([nXCoord, nYCoord])

Parameters

nXCoord
Specifies the horizontal coordinate of the point to set, in the unit of measurement specified by the ScaleMode property of the form.
nYCoord
Specifies the vertical coordinate of the point to set, in the unit of measurement specified by the ScaleMode property of the form.

Remarks

The size of the point drawn depends on the DrawWidth property. When DrawWidth is set to 1, the PSet method sets a single pixel to the specified color. When DrawWidth is set to a value greater than 1, the point is centered on the specified coordinates. The way the point is drawn depends on the setting of the DrawMode and DrawStyle properties.

When the PSet method is called, the CurrentX and CurrentY properties are set to the point specified by the arguments.

See Also

CurrentX, CurrentY Properties | DrawMode Property | DrawStyle Property | DrawWidth Property | ForeColor Property

Applies To: Form | _SCREEN


Quit Method

Ends an instance of Visual FoxPro.

ApplicationObject.Quit( )

Remarks

Call the Quit( ) method to return control to the application that created the instance of Visual FoxPro.

See Also

QUIT

Applies To: Application Object | _VFP System Variable


ReadExpression Method

Returns the expression entered for a property value in the Properties window. Available at design time and run time.

Object.ReadExpression(cPropertyName)

Parameters

cPropertyName
Specifies the name of the property to return the expression from.

See Also

WriteExpression Method

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


ReadMethod Method

Returns the text of the specified method. Available at design time.

Control.ReadMethod(cMethod)

Parameters

cMethod
Specifies the name of a method.

See Also

ReadExpression Method | WriteExpression Method | WriteMethod Method

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


Refresh Method

Repaints a form or control and refreshes any values, or refreshes a project's visual display.

[Form.]Object.Refresh

-or-

Project.Refresh([lUpdateSCCStatus])

Parameters

lUpdateSCCStatus
Logical data type. The lUpdateSCCStatus parameter specifies, for a project, if the source control status for each file under source control is updated. Visual FoxPro disregards lUpdateSCCStatus if no files in the project are under source control.

The following table lists the values for lUpdateSCCStatus.

lUpdateSCCStatus | Description
True (.T.) | Updates the source control status for each file in the project under source control.
False (.F.) or none | Does not update the source control status.

Remarks

Generally, Visual FoxPro automatically handles painting a form or control while no events are occurring. You can use the Refresh method when you want to update the form or control immediately, force a complete repaint of a form or control, or to update the value of a control.

You can also use the Refresh method when you want to display a form while another form is loading, or when you want to update the contents of a control. To update the contents of a combo box or a list box, use the Requery method.

Note When a form is refreshed, all controls on the form are also refreshed. When a page frame is refreshed, only the active page is refreshed.

When you call the Refresh method for a Label control, Visual FoxPro updates the Caption property and redraws the label.

When you call the Refresh method for a Shape control, Visual FoxPro redraws the shape.

When you call the Refresh method for projects, Visual FoxPro refreshes a project's visual display with any changes made to the project. For example, after programmatically adding files to the project with the Add method, you can call the Refresh method to display the newly added files in the project.

The Grid Refresh method visually updates the grid's record indicator even if the grid does not have focus.

See Also

Paint Event | Requery Method

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | FormSet | Grid | Header | Label | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Project Object | _SCREEN | Shape | Spinner | TextBox | ToolBar


Release Method

Releases a form, form set, or toolbar from memory.

Object.Release

Remarks

The Release method is useful when a form or form set is created with the DO FORM command and there is no variable by which to reference the form or form set.

You can use the forms collection of the Screen object to find the form or form set and call its Release method.

See Also

DO FORM

Applies To: Form | FormSet | _SCREEN | ToolBar


Remove Method (Collection Class)

Use to remove a member object from a collection.

The member object can have any valid type that can be assigned to a memory variable. This includes simple data types, such as strings, numbers, dates, logical, or more complex ones such as Visual FoxPro and Component Object Model (COM) objects.

Collection.Remove( eIndex )

Parameters

eIndex
Specifies an expression that represents a position of an item in the collection. This expression can be one of two types:
  • Numeric. The eIndex expression must have a value from 1 to the value of the Count property for the collection. If you pass a value of -1, Visual FoxPro removes all items in the collection.
  • String. The eIndex expression must correspond to the cKey that was specified for the item when it was added to the collection.

If eIndex does not match an existing member of the collection, an error occurs.

Remarks

  • If an incorrect type is passed for a specific parameter, an error occurs.
  • Include the NODEFAULT command in the Remove method for collection objects to prevent removing a particular item from the collection.

Example

The following example illustrates these tasks at run time:

  • Creates forms and a collection.
  • Adds forms to the collection.
  • Displays the number of forms in the collection.
  • Removes the first form from the collection.
  • Displays the current number of forms in the collection.
loForm1 = CREATEOBJECT("myForm1")
loForm2 = CREATEOBJECT("myForm2")
loCol = CREATEOBJECT("myCollection")
loCol.Add(loForm1)
loCol.Add(loForm2)
? loCol.Count
loCol.Remove(1)
? loCol.Count

See Also

Collection Object Properties, Methods, and Events | Collection Class | NODEFAULT Command


Remove Method (File Object)

Removes a file from its files collection and project.

Object.Remove( )

Remarks

The Remove method for file objects returns true (.T.) if the file is successfully removed from the project; otherwise false (.F.) is returned. Note that a warning isn't displayed when you use the Remove method to remove files from a project, including files that are under source code control.

The QueryRemoveFile event occurs before the file is removed from its Files collection and project. If the QueryRemoveFile event returns false (.F.), the file isn't removed from its Files collection and project and the Remove method returns false (.F.). If the QueryRemoveFile method returns true (.T.), the file is removed from its Files collection and project and the Remove method returns true (.T.).

See Also

Add Method (File Object) | Modify Method | QueryRemoveFile Event

Applies To: File Object


RemoveFromSCC Method

Removes a file in a project from source code control.

Object.RemoveFromSCC( )

Remarks

The RemoveFromSCC method returns true (.T.) if the file is successfully removed from source code control; otherwise false (.F.) is returned.

See Also

AddToSCC Method | CheckIn Method | CheckOut Method | GetLatestVersion Method | UndoCheckOut Method

Applies To: File Object


RemoveItem Method

Removes an item from a combo box or list box.

Control.RemoveItem(nIndex)

Parameters

nIndex
Specifies an integer corresponding to the order in which items are displayed in the control. For the first item in a list box or combo box, nIndex = 1.

See Also

AddItem Method | Clear Method | RemoveListItem Method

Applies To: ComboBox Control | ListBox Control


RemoveListItem Method

Removes an item from a combo box or list box.

Control.RemoveListItem(nItemId)

Parameters

nItemId
Specifies an integer representing the unique ID of the item in the control.

See Also

AddItem Method | Clear Method

Applies To: ComboBox Control | ListBox Control


RemoveObject Method

Removes a specified object from a container object at run time.

Object.RemoveObject(cObjectName)

Parameters

cObjectName
Specifies the name of an object to remove. If the object does not exist, an error occurs.

Remarks

When an object is removed, it disappears from the screen and can no longer be referenced.

See Also

AddObject Method | RemoveItem Method | RemoveListItem Method

Applies To: Column Object | CommandGroup Control | Container Object | Custom Object | DataEnvironment Object | Form Object | FormSet Object | Grid Control | OptionGroup Control | Page Object | PageFrame Control | _SCREEN System Variable | ToolBar Object


Requery Method

Requeries the row source to which the ListBox or ComboBox control is bound.

Control.Requery

Remarks

Use the Requery method to ensure a control contains the most recent data. The Requery method requeries the RowSource property and updates the list with the new values.

See Also

RowSource Property

Applies To: ComboBox | ListBox


RequestData Method

Creates an array containing data from a table open in an instance of Visual FoxPro.

ApplicationObject.RequestData([nWorkArea | cTableAlias] [, nRecords])

Return Values

Array

Property Values

nWorkArea
Specifies the work area number of the table from which data is stored in the array. If you omit cTableAlias and nWorkArea, data from the table open in the current work area is stored in the array.
cTableAlias
Specifies the alias of the table from which data is stored in the array.
nRecords
Specifies the number of records stored in the array, starting from the current record. If nRecords is omitted and sufficient memory is available, all records, starting from the current record, are stored in the array.

Remarks

Use the RequestData method to retrieve data from an instance of Visual FoxPro.

Example

The following example, run from within Visual FoxPro, creates a second instance of Visual FoxPro. The Customer table is opened in the second instance of Visual FoxPro.

An array containing data from the Customer table is created in the first instance of Visual FoxPro, and the contents of the array are displayed. The array contains data from the first 5 records in the Customer table. The second instance of Visual FoxPro is then closed.

oNewInstance = CREATEOBJECT('VisualFoxPro.Application')
oNewInstance.DoCmd "USE (HOME(2) + 'Data\Customer')"
aCustomerArray = oNewInstance.RequestData('Customer',5)
DISPLAY MEMORY LIKE aCustomerArray
oNewInstance.DoCmd('QUIT')

See Also

DataToClip Method

Applies To: Application Object | _VFP System Variable


Reset Method

Resets the Timer control so that it starts counting from 0.

Timer.Reset

See Also

Interval Property | Timer Event

Applies To: Timer


ResetToDefault Method

Restores a property, event, or method to its Visual FoxPro default setting. Available at run time and design time.

 [Form.]Object.ResetToDefault(cPropertyName | cEventName | cMethodName)

Property Values

cPropertyName
Specifies the name of the property to reset to the Visual FoxPro default setting.
cEventName
Specifies the name of the event to reset. All user-defined code in the event is deleted.
cMethodName
Specifies the name of the method to reset. All user-defined code in the method is deleted.

Remarks

ResetToDefault returns a property to the setting it had when first created. For example, if you have changed the font of a command button, calling this method for the caption resets the font to its default (Arial).

ResetToDefault removes all user-defined code from an event or method at design time.

ResetToDefault has no effect on member arrays, since there is no default value in a class.

ResetToDefault does not apply to Access/Assign methods since these are tied more closely to their associated property and therefore are treated differently than normal methods.

See Also

GETPEM( ) Function

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | _SCREEN | Shape | Session Object | Spinner | TextBox | Timer | ToolBar


Run Method

Runs or previews a file in a project.

Object.Run( )

Remarks

The Run method returns true (.T.) if the file is successfully run or previewed; otherwise false (.F.) is returned. Labels and reports are previewed by the Run method.

The QueryRunFile event occurs before the file is run or previewed. If NODEFAULT is specified in the QueryRunFileEvent, the file isn't run or previewed and the Run method returns false (.F.). Otherwise, the file is run or previewed and the Run method returns true (.T.).

Include NODEFAULT in the QueryRunFile event to prevent a file from being run or previewed.

See Also

QueryAddFile Event | QueryModifyFile Event | QueryRunFile Event | QueryRemoveFile Event | NODEFAULT Command

Applies To: File Object


SaveAs Method

Saves an object as an .scx file.

Object.SaveAs(cFileName [, oObjectName])

Parameters

cFileName
Specifies the .scx file to which you want to save the object.
oObjectName
Specifies a reference to a DataEnvironment object.

Remarks

Use the SaveAs method to create a form or form set and save it as an .scx file. The SaveAs method is only available during an interactive Visual FoxPro session.

When you use the SaveAs method, all the properties, events, and methods associated with the object are stored as as well. Note that only objects created from Visual FoxPro base classes can be saved. User-defined classes cannot be saved. See DEFINE CLASS for a listing of Visual FoxPro base classes.

See Also

SaveAsClass Method | SET CLASSLIB

Applies To: DEFINE CLASS | Form | FormSet | _SCREEN


SaveAsClass Method

Saves an instance of an object as a class definition in a class library.

Object.SaveAsClass(ClassLibName, ClassName [, Description])

Parameters

ClassLibName
Specifies the name of the .vcx file in which to store the class definition.
ClassName
Specifies the name assigned to the class.
Description
Specifies the optional description for the class.

Remarks

When you use the SaveAsClass method, all the properties, events, and methods associated with the object are stored as part of the class definition.

See Also

SaveAs Method | SET CLASSLIB

Applies To: CheckBox | Collection Class | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Custom | EditBox | Exception Class | Form | FormSet | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | PageFrame | ProjectHook Object | _SCREEN | Shape | Spinner | TextBox | Timer | ToolBar


SetAll Method

Assigns a property setting on all, or a certain class of, controls in a Container object.

Container.SetAll(cProperty, Value [, cClass])

Parameters

cProperty
Specifies the property to be set.
Value
Specifies the new setting for the property. The data type of Value depends on the property being set.
cClass
Specifies the class name (the class on which the object is based, not the Visual FoxPro base class for the object).

Remarks

Use the SetAll method to set a property for all, or a certain class of, controls in a Container. For example, to set the BackColor property on all the Column objects in a Grid control to red, issue the following:

Form1.Grid1.SetAll("BackColor", RGB(255, 0, 0), "Column")

You can also set the properties for objects that are contained by other objects within the container. To set the ForeColor property of the Headers that are contained by each Column object contained in a Grid control to green, issue the following:

Form1.Grid1.SetAll("ForeColor", RGB(0, 255, 0), "Header")

Example

The following example uses the SetAll method with the DynamicBackColor property to specify the background colors for the records in a Grid control. If the number of a record displayed in the Grid is even, the record's DynamicBackColor is white, otherwise its DynamicBackColor is green.

A Grid control is placed on a form, and the customer table is opened and its contents displayed in the grid. The Caption property is used to specify a different header caption (Customer ID) for the CUST_ID field. A command button is placed on the form to close the form.

CLOSE ALL  && Close tables and databases
OPEN DATABASE (HOME(2) + 'Data\testdata')

USE customer  IN 0  && Opens Customer table

frmMyForm = CREATEOBJECT('Form')  && Create a form
frmMyForm.Closable = .f.  && Disable the window pop-up menu

frmMyForm.AddObject('cmdCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject('grdGrid1','Grid')  && Add Grid control

frmMyForm.grdGrid1.Left = 25  && Adjust Grid position

frmMyForm.grdGrid1.SetAll("DynamicBackColor", "IIF(MOD(RECNO( ), 2)=0, RGB(255,255,255), RGB(0,255,0))", "Column")  && Alternate white and green records

frmMyForm.grdGrid1.Visible = .T.  && Grid control visible
frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.grdGrid1.Column1.Header1.Caption = 'Customer ID'

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close form
      CLOSE ALL  && Close table and database
ENDDEFINE

See Also

SaveAs Method | SaveAsClass Method

Applies To: Column | CommandGroup | Container Object | Form | FormSet | Grid | OptionGroup | Page | PageFrame | _SCREEN | ToolBar


SetData Method

Places data in the OLE drag-and-drop DataObject. Available at run time only.

oDataObject.SetData(eData [, nFormat | cFormat])

Parameters

eData
Specifies the data placed on the DataObject. If you omit the optional nFormat and cFormat arguments, Visual FoxPro places the data on the DataObject in the CF_TEXT and CFSTR_OLEVARIANT formats. If eData is an array, precede eData with an ampersand (@). An array is placed on the DataObject in the CFSTR_OLEVARIANTARRAY format. An error is generated if eData is an object reference or a general field, or the array contains an object reference.
nFormat | cFormat
Specifies the format of the data placed on the DataObject. The following table lists the values for some common data formats with a description of each format. You can specify a user-defined format with cFormat. In this case, eData must be of character type or a binary type created with CREATEBINARY( ).
Data format* | nFormat| cFormat | Description
CF_TEXT | 1 | Text format.
CF_OEMTEXT | 7 | Text format containing characters in the OEM character set.
CF_UNICODETEXT | 13 | Unicode text format, available only under Windows NT 4.0 or later.
CF_FILES or CF_HDROP | 15 | A handle that identifies a list of files, such as a set of files dragged from the Windows Explorer.
CFSTR_OLEVARIANTARRAY "OLE Variant Array" An array. Multiple values can be transferred in a single drag-and-drop operation with this format.

For example, this format can be used to drag a set of items in a list box to another list box.
CFSTR_OLEVARIANT | "OLE Variant" | A variant. All data types in Visual FoxPro are represented as variants. This format can be used to drag and drop Visual FoxPro data without losing the data type.
CFSTR_VFPSOURCEOBJECT | "VFP Source Object" | A reference to the Visual FoxPro drag source object.

* Defined in FOXPRO.H.

Remarks

The SetData method can only be executed in the OLEStartDrag and OLESetData events.

See Also

ClearData Method | CREATEBINARY( ) | GetData Method | GetFormat Method | OLE Drag-and-Drop Overview | OLEStartDrag Event | SetFormat Method

Applies To: DataObject Object


SetFocus Method

Assigns the focus to a control.

Control.SetFocus

Remarks

You cannot assign the focus to a control if the control's Enabled or Visible property is set to false (.F.), or the control's When event returns false (.F.). If the Enabled or Visible property has been set to false (.F.), you must first set it to true (.T.) before the control can receive the focus from the SetFocus method.

Once a control has the focus, any user input is directed to that control.

See Also

Enabled Property | GotFocus Event | LostFocus Event | Visible Property

Applies To: CheckBox | Column | ComboBox | CommandButton | Container Object | Control Object | EditBox | Grid | ListBox | OLE Bound Control | OLE Container Control | OptionButton | Page Object | Spinner | TextBox


SetFormat Method

Places a data format in the OLE drag-and-drop DataObject. Available at run time only.

oDataObject.SetFormat(nFormat | cFormat)

Parameters

nFormat | cFormat
Specifies the format of the data placed on the DataObject. The following table lists the values for some common data formats with a description of each format. You can also create your own format by specifying a unique character string for cFormat.
Data format* | nFormat| cFormat | Description
CF_TEXT | 1 | Text format.
CF_OEMTEXT | 7 | Text format containing characters in the OEM character set.
CF_UNICODETEXT | 13 | Unicode text format, available only under Windows NT 4.0 or later.
CF_FILES or CF_HDROP | 15 | A handle that identifies a list of files, such as a set of files dragged from the Windows Explorer.
CFSTR_OLEVARIANTARRAY "OLE Variant Array" An array. Multiple values can be transferred in a single drag-and-drop operation with this format.

For example, this format can be used to drag a set of items in a list box to another list box.
CFSTR_OLEVARIANT | "OLE Variant" | A variant. All data types in Visual FoxPro are represented as variants. This format can be used to drag and drop Visual FoxPro data without losing the data type.
CFSTR_VFPSOURCEOBJECT | "VFP Source Object" | A reference to the Visual FoxPro drag source object.

* Defined in FOXPRO.H.

Remarks

You can place a data format in the DataObject before placing the corresponding data on the DataObject. If you place a data format in the DataObject without corresponding data and invoke the GetData method in the OLEDragDrop event, the OLESetData event is executed for the drag source. The drag source can then place the data on the DataObject with the SetData method in the OLESetData event.

OLE drag-and-drop performance can be improved by placing just the data formats on the DataObject when a large amount of data is placed on the DataObject, when using data formats that aren't natively supported by Visual FoxPro, or when using a large number of formats.

The SetFormat method can only be executed in the OLEStartDrag and OLESetData events.

See Also

ClearData Method | GetData Method | GetFormat Method | OLE Drag-and-Drop Overview | OLEDragDrop Event | OLESetData Event | OLEStartDrag Event | SetData Method

Applies To: DataObject Object


SetMain Method

Sets the main file in a project.

Object.SetMain([cFileName])

Parameters

cFileName
Specifies a file in the project to set as the main file. The main file can be a program or a form. Be sure to include the file extension in cFileName. If cFileName is omitted or is an empty string, no file in the project is set as the main file.

Remarks

The SetMain method returns true (.T.) if the file you specify is set as the main file. False (.F.) is returned if the file you specify is not in the project or the file you specify is not the proper file type.

The main file is a program (.prg file) or form (.scx file) that serves as the execution starting point for a compiled application, and from which other components of your application are called. Typically, the main file sets the application's operational environment, runs menu programs or forms to display the application's interface, and establishes the event loop of the application with the READ EVENTS command. You must designate a main file in the Project Manager before you can create an application (.app) or executable file (.exe) from the project.

Note Specifying a file as the main file in a project also sets the project's MainFile property.

See Also

MainFile Property

Applies To: Project Object


SetVar Method

Creates a variable and stores a value to the variable for an instance of the Visual FoxPro application automation server.

ApplicationObject.SetVar(cVariableName, eValue)

Property Values

cVariableName
Specifies the name of the variable to create.
eValue
Specifies the value stored to the variable. If the variable specified with cVariableName already exists, the new value is store to the variable.

Remarks

While the DoCmd method can be used to set a variable to a character value, the SetVar method should be used to set a variable to other data types.

See Also

DoCmd Method | Eval Method | STORE

Applies To: Application Object | _VFP System Variable


SetViewPort Method

Sets the values of the ViewPortLeft and ViewPortTop properties for a form.

Object.SetViewPort(nLeft, nTop)

Parameters

nLeft
Specifies the value of the ViewPortLeft property for the form.
nTop
Specifies the value of the ViewPortTop property for the form.

Remarks

The SetViewPort method returns true (.T.) if the ViewPortLeft and ViewPortTop properties are successfully set; otherwise false (.F.) is returned. The SetViewPort method is ignored for forms that do not contain scroll bars.

The unit of measurement for the ViewPortLeft and ViewPortTop properties is determined by the form's ScaleMode property setting – pixels (the default) or foxels.

See Also

ScaleMode Property | ScrollBars Property | ViewPortLeft Property | ViewPortHeight Property | ViewPortTop Property | ViewPortWidth Property

Applies To: Form


Show Method

Displays a form and determines whether the form is modal or modeless.

 [FormSet.]Object.Show([nStyle])

Parameters

nStyle
Determines how a form is shown. The following values are valid:
Value | Description
1 | Modal. No user input (keyboard or mouse) can occur in any other form or in the menu until the modal form is hidden or released. The program must hide or release a modal form (usually in response to some user action) before further user input can occur. Although other forms in your application are disabled when a modal form is displayed, other applications are not.
2 | (Default) Modeless. Code that occurs after the Show method is run as it is encountered.

If you omit nStyle, the form is shown in the style specified by the WindowType property.

Remarks

The Show method sets a form or form set's Visible property to true (.T.) and makes the form the active object. If a form's Visible property is already set to true (.T.), the Show method makes it the active object.

If a form set is activated, the last active form in the form set also becomes active. If no form is active, the form that was added to the FormSet class definition first is made active.

Forms contained within a form set retain their Visible property setting. If a form's Visible property is set to false (.F.), the Show method for the form set does not show the form.

See Also

Activate Event | Hide Method | Visible Property | WindowType Property

Applies To: Form | FormSet | _SCREEN | ToolBar


ShowWhatsThis Method

Displays the Whats This Help topic specified for an object with the WhatsThisHelpID property.

Object.ShowWhatsThis

Property Values

Object
Specifies the object for which the Whats This Help topic is displayed.

Remarks

The ShowWhatsThis method is automatically called when the F1 key is pressed. If the WhatsThisHelp property is set to true (.T.), the Whats This Help topic for the object, specified with the WhatsThisHelpID property, is displayed. If the WhatsThisHelp property is set to false (.F.), the Help topic for the object, specified with the HelpContextID property, is displayed.

See Also

WhatsThisButton Property | WhatsThisMode Method | WhatsThisHelp Property | WhatsThisHelpID Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Shape | Spinner | TextBox | Timer | ToolBar


TextHeight Method

Returns the height of a text string as it would be displayed in the current font.

 [nHeight =] [Form.]TextHeight(cText)

Parameters

nHeight
Returns a value in pixels specifying the height of the text string.
cText
Specifies the character string for which the text height is determined.

Remarks

The TextHeight method determines the amount of vertical space required to display cText. The height returned includes the leading space above and below the character string, so you can use the height returned to calculate and position multiple lines of text within the form. If cText contains embedded carriage returns, the TextHeight method returns the cumulative height of the lines, including the leading space above and below each line.

See Also

FontSize Property | ScaleMode Property | TextWidth Method

Applies To: Form | _SCREEN


TextWidth Method

Returns the width of a text string as it would be displayed in the current font.

 [nWidth =] [Form.]TextWidth(cText)

Parameters

nWidth
Returns a value in pixels specifying the width of the text string.
cText
Specifies the character string for which the text width is determined.

Remarks

The TextWidth method determines the amount of horizontal space required to display cText.

See Also

FontSize Property | ScaleMode Property | TextHeight Method

Applies To: Form | _SCREEN


UndoCheckOut Method

Discards any changes made to a file and checks the file back into source code control.

Object.UndoCheckOut( )

Remarks

True (.T.) is returned if the changes to the file are successfully discarded and the file is checked back into source code control; otherwise a false (.F.) is returned.

See Also

AddToSCC Method | CheckIn Method | CheckOut Method | GetLatestVersion Method | RemoveFromSCC Method

Applies To: File Object


WhatsThisMode Method

Displays the What's This Help question mark mouse pointer and enables What's This Help mode.

 [Form.]Object.WhatsThisMode

Remarks

Calling the WhatsThisMode method changes the mouse pointer to an arrow with a question mark and enables What's This Help mode. Clicking an object displays the What's This Help topic specified by the WhatsThisHelpID property for the object. Pressing ESC disables the What's This Help mode and returns the mouse pointer to its original state.

See Also

HelpContextID Property | SET HELP | ShowWhatsThis Method | WhatsThisButton Property | WhatsThisHelp Property | WhatsThisHelpID Property

Applies To: Form


WriteExpression Method

Writes an expression to a property. Available at design time and run time.

Object.WriteExpression[cPropertyName, cExpression]

Parameters

cPropertyName
Specifies the name of the property to write the expression to.
cExpression
Specifies a character string that is written to the property sheet as an expression.

See Also

ReadExpression Method

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


WriteMethod Method

Writes the specified text to the specified method. Available at design time only.

Control.WriteMethod(cMethodName, cMethodText [,lCreateMethod])

Parameters

cMethodName
Specifies the name of the method to write the specified text to.
cMethodText
Specifies the text to write to the specified methods.
lCreateMethod
Specifies whether the method is created when it doesn't already exist. Because this method is useful only at design time, you must save the form or class before changes can be effective.

See Also

ReadExpression Method | ReadMethod Method | WriteExpression Method

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Custom | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | Timer | ToolBar


ZOrder Method

Places a specified form or control at the front or back of the z-order within its graphical level. Places a control contained by the ToolBar object at the front or back of the controls array that determines the order in which controls appear in the toolbar.

 [Object.]ZOrder([nOrder])

Property Values

nOrder
Specifies an integer indicating the position of the object relative to other objects. If you omit nOrder, the setting is 0.
Setting | Description
0 | (Default) The object is positioned at the front of the z-order.
1 | The object is positioned at the back of the z-order.

Remarks

There are two graphical layers associated with objects. The back layer is the drawing space, where the results of the graphics methods appear, and the front layer is the object layer. The contents of one layer covers the contents of the layer behind. The ZOrder method arranges objects only within the layer where the object appears.

Note For a Page object, the ZOrder method does not affect the PageOrder property setting. ZOrder only determines the Page that is on top and active.

For more information about using controls, see Using Controls.

See Also

AlwaysOnBottom Property | AlwaysOnTop Property | PageOrder Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | _SCREEN | Shape | Spinner | TextBox | ToolBar


Events

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

Activate Event

AfterBuild Event

AfterCloseTables Event

AfterCursorAttach Event

AfterCursorClose Event

AfterCursorDetach Event

AfterCursorFill Event

AfterCursorRefresh Event

AfterCursorUpdate Event

AfterDelete Event

AfterInsert Event

AfterUpdate Event

AfterDock Event

AfterRowColChange Event

B

BeforeCursorAttach Event

BeforeCursorClose Event

BeforeCursorDetach Event

BeforeCursorFill Event

BeforeCursorRefresh Event

BeforeCursorUpdate Event

BeforeDelete Event

BeforeInsert Event

BeforeDock Event

BeforeOpenTables Event

BeforeRowColChange Event

BeforeUpdate Event

C

Click Event

D

DBC_Activate Event

DBC_AfterAddTable Event

DBC_AfterAppendProc Event

DBC_AfterCloseTable Event

DBC_AfterCopyProc Event

DBC_AfterCreateConnection Event

DBC_AfterCreateOffline Event

DBC_AfterCreateTable Event

DBC_AfterCreateView Event

DBC_AfterDBGetProp Event

DBC_AfterDBSetProp Event

DBC_AfterDeleteConnection

DBC_AfterDropOffline Event

DBC_AfterDropTable Event

DBC_AfterModifyConnection

DBC_AfterModifyProc Event

DBC_AfterModifyTable

DBC_AfterModifyView

DBC_AfterOpenTable Event

DBC_AfterRemoveTable Event

DBC_AfterRenameConnection

DBC_AfterRenameTable

DBC_AfterRenameView

DBC_AfterValidateData Event

DBC_BeforeAddTable Event

DBC_BeforeAppendProc Event

DBC_BeforeCloseTable Event

DBC_BeforeCopyProc Event

DBC_BeforeCreateConnection Event

DBC_BeforeCreateOffline Event

DBC_BeforeCreateTable Event

DBC_BeforeCreateView Event

DBC_BeforeDBGetProp Event

DBC_BeforeDBSetProp Event

DBC_BeforeDeleteConnection Event

DBC_BeforeDropOffline Event

DBC_BeforeDropTable Event

DBC_BeforeModifyConnection Event

DBC_BeforeModifyProc Event

DBC_BeforeModifyTable Event

DBC_BeforeModifyView Event

DBC_BeforeOpenTable Event

DBC_BeforeRemoveTable Event

DBC_BeforeRenameConnection Event

DBC_BeforeRenameTable Event

DBC_BeforeRenameView Event

DBC_BeforeValidateData Event

DBC_CloseData Event

DBC_Deactivate Event

DBC_ModifyData Event

DBC_OpenData Event

DBC_PackData Event

DblClick Event

Deactivate Event

Deleted Event

Destroy Event

DoCmd Method

DownClick Event

DragDrop Event

DragOver Event

DropDown Event

E

Error Event

ErrorMessage Event

F

G

GotFocus Event

H

I

Init Event

InteractiveChange Event

J

K

KeyPress Event

L

Load Event

LostFocus Event

M

Message Event

MiddleClick Event

MouseDown Event

MouseEnter Event

MouseLeave Event

MouseMove Event

MouseUp Event

MouseWheel Event

Moved Event

N

O

OLECompleteDrag Event

OLEDragOver Event

OLEGiveFeedBack Event

OLESetData Event

OLEStartDrag Event

OnMoveItem Event

P

Paint Event

ProgrammaticChange Event

Q

QueryAddFile Event

QueryModifyFile Event

QueryNewFile Event

QueryRemoveFile Event

QueryRunFile Event

QueryUnload Event

R

RangeHigh Event

RangeLow Event

ReadActivate Event

ReadDeactivate Event

ReadShow Event

ReadValid Event

ReadWhen Event

Resize Event

RightClick Event

S

Scrolled Event

T

Timer Event

U

UIEnable Event

Undock Event

Unload Event

UpClick Event

V

Valid Event

W

When Event

X

Y

Z

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


Activate Event

Occurs when a Form, FormSet, Project, or Page object becomes active or when a Toolbar object is shown.

PROCEDURE Object.Activate

Remarks

Triggers for this event depend on the type of object:

  • A Form object is activated by a user action, such as clicking a form or a control or when the Show method for the Form object is called.
  • A FormSet object is activated when a form in the form set receives focus or when the Show method for the form set is called.
  • A ProjectHook is activated by a user action, such as clicking on the Project window, or by a command such as ACTIVATE WINDOW project.
  • A Page object is activated by user action, such as clicking the tab of the page or clicking a control contained in the page, or if the ActivePage property of the page frame containing it is set to the page's number.
  • A ToolBar object is activated when the Show method for the ToolBar is called.

If you use the Show method for a form set, all forms with their Visible property set to True (.T.) are shown. The Activate event is triggered first for the form set, then for the form, and then for the page.

See Also

ActivePage Property | Deactivate Event | GotFocus Event | LostFocus Event | SetFocus Method | Show Method | Visible Property

Applies To: _SCREEN System Variable | Form Object | FormSet Object | ProjectHook Object | Page Object | ToolBar Object


AfterBuild Event

Occurs after a project is rebuilt or an application file (.app), dynamic link library (.dll), or executable file (.exe) is created from a project.

PROCEDURE Object.AfterBuild
LPARAMETERS nError

Parameters

nError
The Visual FoxPro error number returned after the project is rebuilt or an .app, .dll, or.exe is created. If nError is 0, no errors occurred when the project was rebuilt or the .app, .dll, or.exe was created.

See Also

BeforeBuild Event | Build Method | BUILD PROJECT Command

Applies To: ProjectHook Object


AfterCloseTables Event

Occurs after the tables or views specified in the data environment for a form, form set, or report are released.

PROCEDURE DataEnvironment.AfterCloseTables

Remarks

For a form or form set, the AfterCloseTables event occurs after the form set's or form's Unload event occurs and after any tables or views that were opened by the data environment are closed.

For a report, the AfterCloseTables event occurs after any tables or views that were opened by the data environment are closed.

The AfterCloseTables event occurs whenever the CloseTables method is called. The Destroy event of the data environment and its associated objects occurs after the AfterCloseTables event.

See Also

CloseTables Method | Destroy Event | Unload Event

Applies To: DataEnvironment Object


AfterCursorAttach Event

Occurs immediately after the CursorAdapter object attempts to attach the cursor. You can use this event to perform tasks such as customize cursors and cursor adapters as appropriate and perform validations.

PROCEDURE Object.AfterCursorAttach
LPARAMETERS cAlias, lResult

Parameters

cAlias
Specifies the alias of the attached cursor or table.
lResult
Specifies True (.T.) if the cursor or table attached successfully and False (.F.) if not attached successfully.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | BeforeCursorAttach Event | CursorAttach Method

Applies To: CursorAdapter Class


AfterCursorClose Event

Occurs immediately after a cursor closes. You can use this event to reset CursorAdapter properties and so on.

PROCEDURE Object.AfterCursorClose
LPARAMETERS cAlias, lResult

Parameters

cAlias
Specifies the alias of the closed cursor or table.
lResult
Specifies True (.T.) if cursor or table closes successfully and False (.F.) if not closed successfully, for example, cursor contained unsaved changes.

Remarks

You must clear or reset the Alias property if you wish to remove its previous value. When an extended cursor closes, Visual FoxPro marks the CursorAdapter object as no longer attached to a cursor but does not clear the Alias property.

See Also

Methods | CursorAdapter Object Properties, Methods, and Events | Alias Property

Applies To: CursorAdapter Class


AfterCursorDetach Event

Occurs immediately after a CursorAdapter object detaches a cursor. You can use AfterCursorDetach to perform tasks such as reset cursor adapter properties and perform operations on the freed table.

PROCEDURE Object.AfterCursorAttach
LPARAMETERS cAlias, lResult

Parameters

cAlias
Specifies the alias of the detached cursor or table.
lResult
Specifies True (.T.) if the CursorAdapter CursorDetach method detaches the cursor or table successfully and False (.F.) if not detached successfully.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | BeforeCursorDetach Event | CursorDetach Method

Applies To: CursorAdapter Class


AfterCursorFill Event

Occurs immediately after a CursorAdapter object attempts to create a new cursor.

PROCEDURE Object.AfterCursorFill
LPARAMETERS lUseCursorSchema, lnoDataOnLoad, cSelectCmd, lResult

Parameters

lUseCursorSchema
Specifies the value in the lUseCursorSchema parameter from the CursorFill method.
lnoDataOnLoad
Specifies the value in the lNoData parameter from CursorFill.
cSelectCmd
Specifies the same SelectCmd parameter used by the BeforeCursorFill event.
lResult
Specifies the True (.T.) or False (.F.) value returned by CursorFill.

Remarks

If any of the first three parameters are changed in BeforeCursorFill, AfterCursorFill uses the changed values instead of actual values in the properties, which do not change.

Example

The following example illustrates using the AfterCursorFill event to set the index order from a preset property:

PROCEDURE AfterCursorFill
LPARAMETERS lUseCursorSchema, noDataOnLoad, cSelectCmd, lResult
SELECT(this.Alias)
SET ORDER TO (this.IndexOrder)
ENDPROC

See Also

Events | CursorAdapter Object Properties, Methods, and Events | CursorFill Method | SelectCmd Property | AfterCursorFill Event | BeforeCursorFill Event

Applies To: CursorAdapter Class


AfterCursorRefresh Event

Occurs after a CursorAdapter object attempts to refresh.

PROCEDURE Object.AfterCursorRefresh
LPARAMETERS cSelectCmd, lResult

Parameters

cSelectCmd
Specifies the current value of SelectCmd as established in the BeforeCursorFill event. For example, if the cSelectCmd parameter is changed in BeforeCursorFill, then the changed value of SelectCmd is used. However, the value in the SelectCmd property does not change.
lResult
Specifies the True (.T.) or False (.F.) value returned by the CursorRefresh method.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | SelectCmd Property | BeforeCursorFill Event | BeforeCursorRefresh Event | CursorRefresh Method

Applies To: CursorAdapter Class


AfterCursorUpdate Event

Occurs immediately after all intermediate AfterUpdate, AfterDelete, or AfterInsert events have occurred and before the TABLEUPDATE( ) function returns.

PROCEDURE Object.AfterCursorUpdate
LPARAMETERS nRows, lTableUpdateResult, cErrorArray

Parameters

nRows
Specifies the setting from the nRows parameter from a TABLEUPDATE( ) function operation.
lTableUpdateResult
Specifies the value returned by a TABLEUPDATE( ) operation.
cErrorArray
Contains the contents of the cErrorArray parameter from a TABLEUPDATE( ) operation. Visual FoxPro populates this array from TABLEUPDATE( ) only under the circumstances described by the cErrorArray description in the TABLEUPDATE( ) function.

Remarks

AfterCursorUpdate occurs once upon the completion of the update process. If multiple rows are being updated, the AfterUpdate, AfterInsert, and AfterDelete events occur for each updated row as appropriate.

You can call the AERROR() function to retrieve errors from upstream data sources.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | BeforeCursorUpdate Event | AfterDelete Event | AfterInsert Event | TABLEUPDATE( ) Function | AERROR( ) Function

Applies To: CursorAdapter Class


AfterDelete Event

Occurs immediately after a delete operation for a record is performed.

Note If batch updating is used, that is, CursorAdapter BatchUpdateCount property is greater than 1, AfterDelete does not occur.
PROCEDURE Object.AfterDelete
LPARAMETERS cFldState, lForce, cDeleteCmd, lResult

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE() returns a value of 121111. The number 1 in the first position indicates that the deletion status has not changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.
cDeleteCmd
Specifies the value of the cDeleteCmd parameter from the BeforeDelete event.
lResult
Specifies the value returned by running TABLEUPDATE( ) for this record. If lResult is True (.T.), the field states are cleared for this record. If lResult is False (.F.), the field states are not cleared for this record. You can change the value of lResult to override the result as returned.

Remarks

You can call the AERROR( ) function to retrieve errors from upstream data sources.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | BeforeDelete Event | AERROR( ) Function

Applies To: CursorAdapter Class


AfterDock Event

Occurs after a ToolBar object is docked.

PROCEDURE ToolBar.AfterDock

Remarks

The AfterDock event occurs when the user docks a ToolBar or when the Dock method is invoked.

See Also

BeforeDock Event | Dock Method | Undock Event

Applies To: ToolBar Object


AfterInsert Event

Occurs immediately after an insert operation for a record is performed.

Note If batch updating is used, that is, the CursorAdapter BatchUpdateCount property is greater than 1, AfterInsert does not occur.
PROCEDURE Object.AfterInsert
LPARAMETERS cFldState, lForce, cInsertCmd, lResult

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE() returns a value of 121111. The number 1 in the first position indicates that the deletion status has not changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE() function.
cInsertCmd
Specifies the value of the cInsertCmd parameter from the BeforeInsert event.
lResult
Specifies the value returned by running TABLEUPDATE( ) for this record. If lResult is True (.T.), the field states are cleared for this record. If lResult is False (.F.), the field states are not cleared for this record. You can change the value of lResult to override the result as returned.

Remarks

You can call the AERROR( ) function to retrieve errors from upstream data sources.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | BeforeInsert Event | AERROR( ) Function

Applies To: CursorAdapter Class


AfterRowColChange Event

Occurs when the user moves to another row or column in the Grid, after the new cell gets the focus, and after the When event of the object in the new row or column. The AfterRowColChange event doesn't fire unless the When event of the object in the new row or column returns true (.T.).

PROCEDURE Grid.AfterRowColChange
LPARAMETERS nColIndex

Parameters

nColIndex
Returns the index of the newly selected row or column.

Remarks

AfterRowColChange is triggered interactively by the mouse or keyboard, or programmatically, such as by calling the ActivateCell method.

Use this event to synchronize the two halves of a grid when the SplitBar property = .T., by adding This.Refresh.

You can query the RowColChange property in this event to determine the type of change that triggered the event.

See Also

ActivateCell Method | BeforeRowColChange Event | RowColChange Property | When Event | NODEFAULT Command

Applies To: Grid Control


AfterUpdate Event

Occurs immediately after an update operation for a record is performed.

Note If batch updating is used, that is, the CursorAdapter BatchUpdateCount property is greater than 1, AfterUpdate does not occur.
PROCEDURE Object.AfterUpdate
LPARAMETERS cFldState, lForce, nUpdateType, UpdateInsertCmd, DeleteCmd, lResult

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value as obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE( ) returns a value of 121111. The number 1 in the first position indicates the deletion status has not been changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.
nUpdateType
Specifies the value of the nUpdateType parameter from the BeforeUpdate event.
UpdateInsertCmd
Specifies the value of the UpdateInsertCmd parameter from the BeforeUpdate event.
DeleteCmd
Specifies the value of the DeleteCmd parameter from the BeforeUpdate event.
lResult
Specifies the value returned by running TABLEUPDATE( ) for this record.

The following table describes values for lResult.

lResult | Description
True (.T.) | Clears field states for the record.
False (.F.) | Does not clear field states for the record.

You can change the value of lResult to override the result as returned.

Remarks

You can call the AERROR( ) function to retrieve errors from upstream data sources.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | BeforeUpdate Event | AERROR( ) Function

Applies To: CursorAdapter Class


BeforeBuild Event

Occurs before a project is rebuilt or an application file (.app), dynamic link library (.dll), or executable file (.exe) is created from a project.

PROCEDURE Object.BeforeBuild
LPARAMETERS cOutputName, nBuildAction, lRebuildAll, lShowErrors, lBuildNewGuids

Parameters

cOutputName
Specifies the name of the application, dynamic link library, or executable file that is created.

If cOutputName includes a file extension and nBuildAction is omitted, the file extension in cOutputName determines the type of file built. For example, if the extension in cOutputName is ".exe" an executable file is created.

nBuildAction
Specifies that the project is rebuilt or generates an application, a dynamic link library, or an executable file.

The following table lists the values for nBuildAction with a description of each.

nBuildAction | FoxPro.h constant | Description
1 | BUILDACTION_REBUILD | Rebuilds the project
2 | BUILDACTION_BUILDAPP | Creates an .app
3 | BUILDACTION_BUILDEXE | Creates an .exe
4 | BUILDACTION_BUILDDLL | Creates a .dll
5 | BUILDACTION_BUILDMTDLL | Creates a multi-threaded .dll

nBuildAction takes precedence over the file extension specified in cOutPutName. For example, an executable file is created if nBuildAction is 3 and cOutputName doesn't specify an ".exe" extension.

lRebuildAll
Specifies whether files in the project are recompiled before an .app, .dll, or .exe is created. If lRebuildAll is True (.T.), the following are recompiled:
  • Program files
  • Format files
  • Source code in forms, labels, reports, and visual class libraries
  • Stored procedures in databases

If lRebuildAll is False (.F.) or is omitted, files in the project are not recompiled before the .app, .dll, or .exe is created.

lShowErrors
Specifies whether compilation errors are displayed in an editing window after the build is complete. If lShowErrors is True (.T.), the errors are displayed. If lShowErrors is False (.F.) or is omitted, compilation errors aren't displayed.
lBuildNewGUIDs
Specifies whether new registry GUIDs (globally unique identifiers) are generated when an executable file or dynamic link library is created. If lBuildNewGUIDs is True (.T.), new GUIDs are generated. If lBuildNewGUIDs is False (.F.) or is omitted, new GUIDs aren't generated. lBuildNewGUIDs is ignored if nBuildAction is less than 3.

Remarks

The parameters listed above are passed to the BeforeBuild event when you execute the Build method, when you issue the BUILD APP, BUILD DLL, BUILD EXE, or BUILD PROJECT commands, or when you choose OK in the Build Options dialog box. The parameters are passed by reference with the exception of the nBuildAction parameter, which is passed by value. You can change the values of these parameters within the BeforeBuild event to change how a project, .app, .dll, or .exe is created from the project.

Include NODEFAULT in the BeforeBuild event to prevent a project from being rebuilt or an application file (.app), dynamic link library (.dll), or executable file (.exe) from being created.

See Also

AfterBuild Event | Build Method | BUILD PROJECT Command | NODEFAULT Command

Applies To: ProjectHook Object


BeforeCursorAttach Event

Occurs immediately before the CursorAdapter object attempts to attach a cursor. You can use this event to perform any necessary operations before attaching the cursor or table, determine an alias to attach, and so on.

PROCEDURE Object.BeforeCursorAttach
LPARAMETERS cAlias

Parameters

cAlias
Specifies the alias of the cursor or table being attached.

Remarks

If the code in BeforeCursorAttach returns a value of False (.F.), the cursor attachment does not occur.

Note The CursorAdapter object respects any changes that might be made to the cAlias parameter by BeforeCursorAttach.

Example

The following example illustrates how to open a local view in BeforeCursorAttach so that you can attach the view to a CursorAdapter object:

PROCEDURE BeforeCursorAttach
OPEN DATABASE HOME(2)+"tastrade\data\tastrade.dbc"
USE 'product listing'
ENDPROC

Then make the following call to attach the view:

CursorAttach('product listing', .T.)

See Also

Events | CursorAdapter Object Properties, Methods, and Events | AfterCursorAttach Event | CursorAttach Method

Applies To: CursorAdapter Class


BeforeCursorClose Event

Occurs immediately before a cursor closes. You can use this event to perform any operations needed before closing a cursor or table, and so on.

PROCEDURE Object.BeforeCursorClose
LPARAMETERS cAlias

Parameters

cAlias
Specifies the alias of the cursor or table being closed.

Remarks

If the code in BeforeCursorClose returns a value of False (.F.), the cursor does not close, and Visual FoxPro generates an error message.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | AfterCursorClose Event

Applies To: CursorAdapter Class


BeforeCursorDetach Event

Occurs immediately before a CursorAdapter object detaches a cursor. You can use this event to perform any necessary operations before detaching the cursor or table.

PROCEDURE Object.BeforeCursorAttach
LPARAMETERS cAlias

Parameters

cAlias
Specifies the alias of the cursor or table being detached.

Remarks

If the code in BeforeCursorDetach returns a value of False (.F.), the cursor does not detach, and any return values are ignored.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | AfterCursorDetach Event | CursorDetach Method

Applies To: CursorAdapter Class


BeforeCursorFill Event

Occurs immediately before a CursorAdapter object attempts to attach a new cursor.

PROCEDURE Object.BeforeCursorFill
LPARAMETERS lUseCursorSchema, lNoDataOnLoad, cSelectCmd

Parameters

lUseCursorSchema
Specifies the value of the lUseCursorSchema parameter from the CursorFill method.
lNoDataOnLoad
Specifies the value of the lNoData property in CursorFill.
cSelectCmd
Specifies the current value of the SelectCmd property. You can change the value of the cSelectCmd parameter in this event. However, the value in the SelectCmd property does not change. If you change the value of the cSelectCmd parameter in this event, Visual FoxPro uses the changed value of cSelectCmd.

Remarks

Visual FoxPro stores the value changes, which are used by CursorFill. The CursorRefresh method uses the value of the SelectCmd parameter, not the SelectCmd property. This facilitates construction of custom queries "on the fly". For example, you can store a basic SELECT – SQL command in the SelectCmd property and add a WHERE clause to the SelectCmd parameter in this event without changing the underlying value of the property. The value of the SelectCmd parameter is then passed to the AfterCursorFill event.

If the code in BeforeCursorFill returns a value of False (.F.), CursorFill does not execute, and the currently attached cursor remains unclosed. However, if the code in BeforeCursorFill does not return false, the currently attached cursor closes, and CursorFill executes.

Changes made to these parameters take precedence over the original values stored in the respective properties or that are passed to CursorFill.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | CursorFill Method | SelectCmd Property | CursorRefresh Method | SelectCmd Property | SELECT - SQL Command | AfterCursorFill Event

Applies To: CursorAdapter Class


BeforeCursorRefresh Event

Occurs immediately before a CursorAdapter object attempts to refresh.

PROCEDURE Object.BeforeCursorRefresh
LPARAMETERS cSelectCmd

Parameters

cSelectCmd
Specifies the current value of SelectCmd as established in the BeforeCursorFill event. For example, if the cSelectCmd parameter is changed in BeforeCursorFill, then the changed value of SelectCmd is used. However, the value of the SelectCmd property does not change.

Remarks

If the code in BeforeCursorRefresh returns a value of False (.F.), the CursorAdapter object does not refresh.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | SelectCmd Property | BeforeCursorFill Event | AfterCursorRefresh Event

Applies To: CursorAdapter Class


BeforeCursorUpdate Event

Occurs immediately before the TABLEUPDATE( ) function executes.

PROCEDURE Object.BeforeCursorUpdate
LPARAMETERS nRows, lForce

Parameters

nRows
Specifies the setting of the nRows parameter from the TABLEUPDATE( ) function.
lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.

Remarks

BeforeCursorUpdate occurs once at the beginning of the update process. If multiple rows are being updated, the BeforeUpdate, BeforeInsert, and BeforeDelete events occur for each updated row as appropriate.

If code in BeforeCursorUpdate returns False (.F.), no update, insert, or delete operations occurs.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | TABLEUPDATE( ) Function | BeforeUpdate Event | BeforeInsert Event | BeforeDelete Event | AfterCursorUpdate Event

Applies To: CursorAdapter Class


BeforeDelete Event

Occurs immediately before a delete command for a record executes.

Note If batch updating is used, that is, the CursorAdapter BatchUpdateCount property is greater than 1, BeforeDelete does not occur.
PROCEDURE Object.BeforeDelete
LPARAMETERS cFldState, lForce, cDeleteCmd

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value as obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE( ) returns a value of 121111. The number 1 in the first position indicates the deletion status has not been changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.
cDeleteCmd
Specifies the value of the DeleteCmd property. Visual FoxPro uses the value of cDeleteCmd as the delete command, which you can change in this event. However, if you change the value of the cDeleteCmd parameter, the value of the DeleteCmd property does not change.

Remarks

If code in BeforeDelete returns False (.F.), the delete operation does not occur.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | DeleteCmd Property | AfterDelete Event

Applies To: CursorAdapter Class


BeforeDock Event

Occurs before the ToolBar object is docked.

PROCEDURE ToolBar.BeforeDock
LPARAMETERS nLocation

Parameters

nLocation
Specifies where the ToolBar will be docked. The values for nLocation are:
Value | FOXPRO.H Constant | Description
–1 | TOOL_NOTDOCKED | ToolBar will be undocked.
0 | TOOL_TOP | ToolBar will be docked at the top of the main Visual FoxPro window.
1 | TOOL_LEFT | ToolBar will be docked at the left side of the main Visual FoxPro window.
2 | TOOL_RIGHT | ToolBar will be docked at the right side of the main Visual FoxPro window.
3 | TOOL_BOTTOM | ToolBar will be docked at the bottom of the main Visual FoxPro window.

Remarks

The BeforeDock event occurs when the ToolBar is dragged to a docking region or when the Dock method is invoked.

BeforeDock is triggered before the ToolBar is redrawn so you can change the appearance of the toolbar. This is useful if the ToolBar has a control, such as a ComboBox, that you want to replace with a control of different proportions, such as a CommandButton, when the ToolBar is docked.

See Also

AfterDock Event | Dock Method | Undock Event | CommandButton Control

Applies To: ToolBar Object


BeforeInsert Event

Occurs immediately before an insert command for a record executes.

Note If batch updating is used, that is, the CursorAdapter BatchUpdateCount property is greater than 1, BeforeInsert does not occur.
PROCEDURE Object.BeforeInsert
LPARAMETERS cFldState, lForce, cInsertCmd

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value as obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE( ) returns a value of 121111. The number 1 in the first position indicates the deletion status has not been changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.
cInsertCmd
Specifies the value of the InsertCmd property. Visual FoxPro uses the value of cInsertCmd as the insert command, which you can change in this event. However, if you change the value of the cInsertCmd parameter, the value of the InsertCmd property does not change.

Remarks

If code in BeforeInsert returns False (.F.), the insert operation does not occur.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | InsertCmd Property | AfterInsert Event

Applies To: CursorAdapter Class


BeforeOpenTables Event

Occurs just before the tables and views associated with the data environment for a form set, form, or report are opened.

PROCEDURE DataEnvironment.BeforeOpenTables

Remarks

The BeforeOpenTables event occurs before the Load event for a form set or form.

See Also

AfterCloseTables Event | CloseTables Method | Load Event | OpenTables Method | Unload Event

Applies To: DataEnvironment Object


BeforeRowColChange Event

Occurs when the user changes the active row or column before the new cell gets the focus. It also occurs before the Valid event of the current object in the grid column and any rules in the database. Use NODEFAULT to prevent the active row and column in the grid from changing.

PROCEDURE Grid.BeforeRowColChange
LPARAMETERS nColIndex

Parameters

nColIndex
Returns the index of the column that is active before the row or column change.

Remarks

BeforeRowColChange is triggered interactively using the mouse or keyboard or programmatically, such as calling the ActivateCell method.

You can query the RowColChange property in this event to determine the type of change that triggered the event.

See Also

ActivateCell Method | AfterRowColChange Event | DEFINE CLASS [NODEFAULT] | RowColChange Property | Valid Event | NODEFAULT Command

Applies To: Grid Control


BeforeUpdate Event

Occurs immediately before an update command for a record executes.

Note If batch updating is used, that is, CursorAdapter BatchUpdateCount property is greater than 1, BeforeUpdate does not occur.
PROCEDURE Object.BeforeUpdate
LPARAMETERS cFldState, lForce, nUpdateType, cUpdateInsertCmd, cDeleteCmd

Parameters

cFldState
Specifies the field states of the row being processed. This is the same value as obtained from calling the following function:
GETFLDSTATE(-1)

For example, this value can be a character string consisting of deletion and edit status values for all fields in the table or cursor. If a table has five fields and only the first field has been edited, GETFLDSTATE( ) returns a value of 121111. The number 1 in the first position indicates the deletion status has not been changed.

lForce
Specifies the value of the lForce parameter from the TABLEUPDATE( ) function.
nUpdateType
Specifies a numeric value in the UpdateType property of the generated CursorAdapter object. The following table lists the possible values for nUpdateType.
nUpdateType | Description
1 | Update old data with new data. (Default)
2 | Update data by deleting old data and inserting new data.

Changing this value changes the behavior for the current record but does not change the value of the property. You need this value only if you are using automatic updating.

cUpdateInsertCmd
Specifies the value of the UpdateCmd or InsertCmd property as appropriate. Visual FoxPro uses the value of this parameter as the update or insert command, which you can change in this event. However, if you change the cUpdateInsertCmd parameter, the UpdateCmd and InsertCmd properties do not change.
cDeleteCmd
Specifies that cDeleteCmd is empty if the nUpdateType parameter is set to 1. Otherwise, set cDeleteCmd to the value of the DeleteCmd property. Visual FoxPro uses the value of cDeleteCmd as the delete command, which you can in this event. However, if you change the cDeleteCmd parameter, the value of the DeleteCmd property does not change.

Remarks

If code in BeforeUpdate returns False (.F.), the update operation does not occur.

See Also

Events | CursorAdapter Object Properties, Methods, and Events | GETFLDSTATE( ) Function | TABLEUPDATE( ) Function | UpdateType Property | UpdateCmd Property | InsertCmd Property | DeleteCmd Property | AfterUpdate Event

Applies To: CursorAdapter Class


Click Event

Occurs when you include code in a program that triggers the event, or when the user presses and releases the left mouse button while the pointer is over a control, changes the value of certain controls, or clicks in a blank area of a form.

PROCEDURE Object.Click

Remarks

The Click event occurs when the user:

  • Clicks a check box, command button, combo box, list box, or option button with the left mouse button.
  • Presses the SPACEBAR when a command button, option button, or check box has the focus.
  • Presses ENTER when a form has a command button with its Default property set to True (.T.).
  • Presses the access key for a control. For example, if the caption of a command button is "\<Go", pressing ALT+G triggers the Click event.
  • Clicks a blank area of a form. Click events on a form do not occur when the pointer is over the title bar, the Window menu icon, or the window borders.
  • Clicks the text entry area of a spinner.
  • Clicks a disabled control. The Click event occurs for the container on which the disabled control is placed.

The Click event also occurs as a result of code you include that issues the MOUSE command.

Example

The following example creates an OptionGroup control and places the control on a form. The OptionGroup control has three buttons, and depending on the option button you click, a circle, ellipse, or square appears. The ButtonCount property is used to specify the number of buttons in the OptionGroup. The Buttons and Caption properties are used to specify the text displayed next to each option button.

The Shape control is used to create the circle, ellipse, and square. The OptionGroup control's Click event uses a DO CASE ... ENDCASE structure and the Value property to display the appropriate shape when you click an option button.

frmMyForm = CREATEOBJECT('Form')  && Create a Form
frmMyForm.Closable = .F.  && Disable the window pop-up menu

frmMyForm.AddObject('cmdCommand1','cmdMyCmndBtn')  && Add Command button
frmMyForm.AddObject('opgOptionGroup1','opgMyOptGrp') && Add Option Group
frmMyForm.AddObject('shpCircle1','shpMyCircle')  && Add Circle Shape
frmMyForm.AddObject('shpEllipse1','shpMyEllipse')  && Add Ellipse Shape
frmMyForm.AddObject('shpSquare','shpMySquare')  && Add Box Shape

frmMyForm.cmdCommand1.Visible =.T.  && "Quit" Command button visible

frmMyForm.opgOptionGroup1.Buttons(1).Caption = "\<Circle"
frmMyForm.opgOptionGroup1.Buttons(2).Caption = "\<Ellipse"
frmMyForm.opgOptionGroup1.Buttons(3).Caption = "\<Square"
frmMyForm.opgOptionGroup1.SetAll("Width", 100) && Set Option group width
frmMyForm.opgOptionGroup1.Visible = .T.  && Option Group visible
frmMyForm.opgOptionGroup1.Click  && Show the circle

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS opgMyOptGrp AS OptionGroup  && Create an Option Group
   ButtonCount = 3  && Three Option buttons
   Top = 10
   Left = 10
   Height = 75
   Width = 100

   PROCEDURE Click
      ThisForm.shpCircle1.Visible = .F.  && Hide the circle
      ThisForm.shpEllipse1.Visible = .F.  && Hide the ellipse
      ThisForm.shpSquare.Visible = .F.  && Hide the square

      DO CASE
         CASE ThisForm.opgOptionGroup1.Value = 1
            ThisForm.shpCircle1.Visible = .T. && Show the circle
         CASE ThisForm.opgOptionGroup1.Value = 2
            ThisForm.shpEllipse1.Visible = .T.  && Show the ellipse
         CASE ThisForm.opgOptionGroup1.Value = 3
            ThisForm.shpSquare.Visible = .T.  && Show the square
      ENDCASE
ENDDEFINE

DEFINE CLASS cmdMyCmndBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
ENDDEFINE

DEFINE CLASS shpMyCircle AS SHAPE  && Create a circle
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 99
   BackColor = RGB(255,0,0)  && Red
ENDDEFINE

DEFINE CLASS shpMyEllipse AS SHAPE  && Create an ellipse
   Top = 35
   Left = 200
   Width = 100
   Height = 50
   Curvature = 99
   BackColor = RGB(0,128,0)  && Green
ENDDEFINE

DEFINE CLASS shpMySquare AS SHAPE  && Create a square
   Top = 10
   Left = 200
   Width = 100
   Height = 100
   Curvature = 0
   BackColor = RGB(0,0,255)  && Blue
ENDDEFINE

See Also

DblClick Event | MiddleClick Event | MOUSE | MouseDown Event | MouseUp Event | MouseWheel Event | Value Property

Applies To: CheckBox Control | ComboBox Control | CommandButton Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Form Object | Grid Control | Header Object | Image Control | Label Control | Line Control | ListBox Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | Shape Control | Spinner Control | TextBox Control | ToolBar Object


dbc_Activate Event

Occurs when a database becomes active.

PROCEDURE dbc_Activate(cDatabaseName)

-Or-

PROCEDURE dbc_Activate
LPARAMETERS cDatabaseName

Parameters

cDatabaseName
Specifies the name of the database being activated.

Remarks

You can have many Databases open at the same time but only one can be active at a time. A database can become active under several circumstances. To explicitly activate a database, use the SET DATABASE TO command. If several databases (with DBC Events turned on) are open, the dbc_Activate method runs only in the active database.

If you place DBC Events code in a program file, the code applies to any database that specifies that program file as its events file. In this case, DBC events method code can affect several databases at the same time. When you use DBC events in this way, use the cDatabaseName parameter in the event code to specify which database is being activated. This way you can use one block of method code to determine the activated database and then apply code appropriate to that database.

Return False (.F.) from this procedure to prevent the database from being activated.

Visual FoxPro will ignore a return of False (.F.) from this event during design time.

Example

PROCEDURE dbc_Activate ;
         (cDatabaseName)
? '     cDatabaseName  = ' + TRANSFORM(cDatabaseName) + ' - ' ;
                       + TYPE('cDatabaseName ')+' /end/ '
ENDPROC

See Also

dbc_Deactivate Event | SET DATABASE Command | dbc_CloseData Event | dbc_ModifyData Event | dbc_OpenData Event


dbc_AfterAddRelation Event

Occurs after a relation is successfully added to the database.

PROCEDURE dbc_AfterAddRelation(cRelationID, cTableName, cRelatedChild, cRelatedTable, cRelatedTag)

-or-

PROCEDURE dbc_AfterAddRelation
LPARAMETERS cRelationID, cTableName, cRelatedChild, cRelatedTable, cRelatedTag

Parameters

cRelationID
Specifies the Relation ID number stored in the database.
cTableName
Specifies the name of the parent table.
cRelatedChild
Specifies the name of the linked column in the child table.
cRelatedTable
Specifies the table containing the linked column.
cRelatedTag
Specifies the index tag of the parent table.

Remarks

You can use the dbc_AfterAddRelation event to verify appropriate values for cRelationID and the other parameters in a procedure that tracks, or manages access to the database after a relation is added to the database.

See Also

Enable or Disable DBC Events | dbc_BeforeAddRelation Event


dbc_AfterAddTable Event

Occurs after a table is added to an active database.

PROCEDURE dbc_AfterAddTable(cTableName, cLongTableName)

-Or-

PROCEDURE dbc_AfterAddTable
LPARAMETERS cTableName, cLongTableName

Parameters

cTableName
Specifies the name of the table being added to the database.
cLongTableName
Specifies the long name of the table being added to the database.

Remarks

You can add method code to the dbc_AfterAddTable event that performs functions like updating your data dictionary or sending an email to the database administrator.

This event does not occur when you create a table in the database.

Example

PROCEDURE dbc_AfterAddTable ;
         (cTableName, ;
          cLongTableName)
? '     cTableName     = ' + TRANSFORM(cTableName)     + ' - ' ;
                       + TYPE('cTableName ')
? '     cLongTableName = ' + TRANSFORM(cLongTableName) + ' - ' ;
                       + TYPE('cLongTableName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCreateTable Event |dbc_BeforeAddTable Event


dbc_AfterAppendProc Event

Occurs after the APPEND PROCEDURE command completes.

PROCEDURE dbc_AfterAppendProc(cFileName, nCodePage, lOverwrite)

-or-

PROCEDURE dbc_AfterAppendProc
LPARAMETERS cFileName, nCodePage, lOverwrite

Parameters

cFileName
Specifies the name of a text file from which the stored procedures have been appended.
nCodePage,
Specifies the code page of the text file from which the stored procedures were appended. Visual FoxPro copies the contents of the text file and, as it does so, automatically converts those contents to the code page you specify.
lOverWrite
Specifies whether the current stored procedures in the database were overwritten by those in the text file. If the OVERWRITE keyword was omitted from the APPEND PROCEDURE command, the current stored procedures in the database are appended to any existing stored procedures in the text file.

Remarks

You can use the dbc_AfterAppendProc event to track access to the database after stored procedure are appended.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterAppendProc ;
         (cFileName,;
          nCodePage,;
          lOverwrite)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:      ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cFileName       = ' + TRANSFORM(cFileName)  + ' - ' ;
                         + TYPE('cFileName')
 ? '     nCodePage       = ' + TRANSFORM(nCodePage)  + ' - ' ;
                         + TYPE('nCodePage')
 ? '     lOverwrite      = ' + TRANSFORM(lOverwrite) + ' - ' ;
                         + TYPE('lOverwrite')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeAppendProc Event


dbc_AfterCloseTable Event

Occurs after a table or view is closed.

PROCEDURE dbc_AfterCloseTable(cTableName)

-Or-

PROCEDURE dbc_AfterCloseTable
LPARAMETERS cTableName

Parameters

cTableName
Specifies the name of the table or view being closed.

Remarks

You can use the dbc_AfterCloseTable event to track access to the database after a table is closed in the current database.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterCloseTable ;
         (cTableName)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCloseTable Event


dbc_AfterCopyProc Event

Occurs after the COPY PROCEDURE command has completed.

PROCEDURE dbc_AfterCopyProc(cFileName, nCodePage, lAdditive)

-or-

PROCEDURE dbc_AfterCopyProc
LPARAMETERS cFileName, nCodePage, lAdditive

Parameters

cFileName
Specifies the name of the text file to which the stored procedures were copied.
nCodePage,
Specifies the code page of the program file to which the stored procedures are copied. Visual FoxPro copies the contents of the stored procedures in the database and, as it does so, automatically converts those contents to the code page you specify.
lAdditive
Specifies whether the ADDITIVE keyword was included in the COPY PROCEDURE command that triggered this event. If ADDITIVE was omitted, the stored procedures replaced the contents of the program file.

Remarks

You can use the dbc_AfterCopyProc event to track access to the database after a copy procedure completes.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterCopyProc ;
         (cFileName,;
          nCodePage,;
          lAdditive)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:      ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cFileName       = ' + TRANSFORM(cFileName)  + ' - ' ;
                         + TYPE('cFileName')
 ? '     nCodePage       = ' + TRANSFORM(nCodePage)  + ' - ' ;
                         + TYPE('nCodePage')
 ? '     lAdditive      = ' + TRANSFORM(lAdditive) + ' - ' ;
                         + TYPE('lAdditive')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCopyProc Event


dbc_AfterCreateConnection Event

Occurs after a connection has been created.

PROCEDURE dbc_AfterCreateConnection
(cConnectionName, cDataSourceName, cUserID, cPassWord, cConnectionString)

-Or-

PROCEDURE dbc_AfterCreateConnection
LPARAMETERS cConnectionName, cDataSourceName, cUserID, cPassWord,
 cConnectionString

Parameters

cConnectionName
Specifies the name of the connection that was created.
cDataSourceName
Specifies the name of the ODBC data source.
cUserID
Specifies your user identification for the ODBC data source.
cPassWord
Specifies your password for the ODBC data source.
cConnectionString
Specifies a connection string for the ODBC data source. You can use the connection string instead of explicitly including the ODBC data source, the user identification, and the password.

Remarks

You can use the dbc_AfterCreateConnection event to track attempted access to the database after a connection is created.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameters passed.
PROCEDURE dbc_AfterCreateConnection ;
         (cConnectionName, ;
          cDataSourceName, ;
          cUserID, ;
          cPassword, ;
          cConnectionString)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cConnectionName    = ' + TRANSFORM(cConnectionName)   + ' - ' ;
                           + TYPE('cConnectionName ')
? '     cDataSourceName    = ' + TRANSFORM(cDataSourceName)   + ' - ' ;
                           + TYPE('cDataSourceName ')
? '     cUserID            = ' + TRANSFORM(cUserID)           + ' - ' ;
                           + TYPE('cUserID ')
? '     cPassword          = ' + TRANSFORM(cPassword)         + ' - ' ;
                           + TYPE('cPassword ')
? '     cConnectionString  = ' + TRANSFORM(cConnectionString) + ' - ' ;
                           + TYPE('cConnectionString ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCreateConnection Event


dbc_AfterCreateOffline Event

Occurs after CREATEOFFLINE( ) has completed.

PROCEDURE dbc_AfterCreateOffline(cViewName, cPath)

-or-

PROCEDURE dbc_AfterCreateOffline
LPARAMETERS cViewName, cPath

Parameters

cViewName
Specifies the name of the existing view being taken offline.
cPath
Specifies the directory in which the offline view has been placed.

Remarks

You can use the dbc_AfterCreateOffline event to track access to the database after an offline view is created.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterCreateOffline ;
         (cViewName,;
          cPath)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cViewName =  ' + TRANSFORM(cViewName) + ' - ' ;
                  + TYPE('cViewName')
? '     cPath     =  ' + TRANSFORM(cPath)     + ' - ' ;
                  + TYPE('cPath') + ' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCreateOffline Event


dbc_AfterCreateTable Event

Occurs after a table is created in the active database.

PROCEDURE dbc_AfterCreateTable(cTableName, cLongTableName)

-Or-

PROCEDURE dbc_AfterCreateTable
LPARAMETERS cTableName, cLongTableName

Parameters

cTableName
Specifies the name of the table that was created.
cLongTableName
Specifies the long name for the table that was created.

Remarks

This event does not occur when you create a free table.

You can use the dbc_AfterCreateTable event to verify appropriate values for cTableName or cLongTableName, use those parameters in a procedure to track, or manage access to the database after a table is created in the database.

Example

PROCEDURE dbc_AfterCreateTable ;
         (cTableName, ;
          cLongTableName)
? '     cTableName      = ' + TRANSFORM(cTableName)     + ' - ' ;
                        + TYPE('cTableName ')
? '     cLongTableName  = ' + TRANSFORM(cLongTableName) + ' - ' ;
                        + TYPE('cLongTableName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCreateTable Event


dbc_AfterCreateView Event

Occurs after SQL view is created.

PROCEDURE dbc_AfterCreateView(cViewName, lRemote)

-or-

PROCEDURE dbc_AfterCreateView
LPARAMETERS cViewName, lRemote

Parameters

cViewName
Specifies the name of the view that was created.
lRemote
Specifies whether the view is remote.

Remarks

You can use the dbc_AfterCreateView event to track access to the database after a view is created.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterCreateView ;
         (cViewName, ;
          lRemote)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cViewName  = ' + TRANSFORM(cViewName) + ' - ' ;
                    + TYPE('cViewName ')
 ? '     lRemote    = ' + TRANSFORM(lRemote)   + ' - ' ;
                    + TYPE('lRemote')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeCreateView Event


dbc_AfterDBGetProp Event

Occurs after the DBGetProp( ) function completes.

PROCEDURE dbc_AfterDBGetProp(cName, cType, cProperty)

-or-

PROCEDURE dbc_AfterDBGetProp
LPARAMETERS cName, cType, cProperty

Parameters

cName
Specifies the value of the first parameter in the DBGetProp() function, the name of the database, field, named connection, table, or view for which DBGETPROP( ) returns information.
cType
Specifies the value of the second parameter in the DBGetProp() function, the object type of the item named in cName.
cProperty
Specifies the value of the third parameter in the DBGetProp() function, the property for which DBGETPROP( ) returns information.

For details on valid cType and cProperty values, see in Help.

Remarks

You can use the dbc_AfterDBGetProp event to track access to the database after DBGetProp runs.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterDBGetProp ;
         (cName,;
          cType,;
          cProperty)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC: ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cName     =  ' + TRANSFORM(cName)     + ' - ' + TYPE('cName')
 ? '     cType     =  ' + TRANSFORM(cType)     + ' - ' + TYPE('cType')
 ? '     cProperty =  ' + TRANSFORM(cProperty) + ' - ' + TYPE('cProperty')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDBGetProp Event | DBGETPROP( )


dbc_AfterDBSetProp Event

Occurs after the DBSetProp( ) function completes.

PROCEDURE dbc_AfterDBSetProp(cName, cType, cProperty, ePropertyValue)

-or-

PROCEDURE dbc_AfterDBSetProp
LPARAMETERS cName, cType, cProperty, ePropertyValue
cName
Specifies the value of the first parameter in the DBGetProp( ) function, the name of the database, field, named connection, table, or view for which DBSETPROP( ) changes the value.
cType
Specifies the value of the second parameter in the DBSetProp( ) function, the object type of the item named in cName.
cProperty
Specifies the value of the third parameter in the DBSetProp( ) function, the property for which DBSETPROP( ) changes the value.
ePropertyValue
Specifies the value of the fourth parameter in the DBSetProp( ) function, the value to be assigned to the property in cProperty.

For details on valid cType and cProperty values, see DBSETPROP( ) and DBGETPROP( ) in Help.

Remarks

You can use the dbc_AfterDBCSetProp event to track access to the database after DBGETPROP( ) runs.

Some property values can be changed using DBSetProp( ) or using a designer. For example, you can change the Comment property for a table using DBSetProp( ) as well as from the table designer. Because DBSetProp( ) makes changes directly to the database itself, dbc_BeforeModifyTable or dbc_AfterModifyTable will not catch changes made by DBSETPROP( ). To trap for changes that could be made either way, you would need to use dbc_BeforeDBSetProp, dbc_AfterDBSetProp, dbc_BeforeModifyTable, and dbc_AfterModifyTable to check for the appropriate changes.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterDBSetProp ;
         (cName,;
          cType,;
          cProperty,;
          ePropertyValue)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:     ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cName          = ' + TRANSFORM(cName)          + ' - ' + TYPE('cName')
 ? '     cType          = ' + TRANSFORM(cType)          + ' - ' + TYPE('cType')
 ? '     cProperty      = ' + TRANSFORM(cProperty)      + ' - ' + TYPE('cProperty')
 ? '     ePropertyValue = ' + TRANSFORM(ePropertyValue) + ' - ' + TYPE('ePropertyValue')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDBSetProp Event


dbc_AfterDeleteConnection Event

Occurs after a connection is deleted.

PROCEDURE dbc_AfterDeleteConnection(cConnectionName)

-or-

PROCEDURE dbc_AfterConnection
LPARAMETERS cConnectionName

Parameters

cConnectionName
Specifies the name of the connection being deleted.

Remarks

You can use the dbc_AfterDeleteConnection event to track access to the database after a connection is deleted from the database.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterDeleteConnection ;
          cItemName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cConnectionName    = ' + TRANSFORM(cConnectionName)        + ' - ' ;
                      + TYPE('cConnectionName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDeleteConnection Event


dbc_AfterDropOffline Event

Occurs after DROPOFFLINE( ) has completed.

PROCEDURE dbc_AfterDropOffline(cViewName, cPath)

-or-

PROCEDURE dbc_AfterDropOffline
LPARAMETERS cViewName, cPath

Parameters

cViewName
Specifies the name of the offline view taken back online.
cPath
Specifies the directory in which the offline view is located.

Remarks

You can use the dbc_AfterDropOffline event to track access to the database after an offline view is taken back online.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterDropOffline ;
         (cViewName,;
          cPath)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cViewName = ' + TRANSFORM(cViewName) + ' - ' ;
                  + TYPE('cViewName')
? '     cPath     = ' + TRANSFORM(cPath)     + ' - ' ;
                  + TYPE('cPath')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDropOffline Event


dbc_AfterDropRelation Event

Occurs after a relation is successfully dropped from a database.

PROCEDURE dbc_AfterDropRelation(cRelationID, cTableName, cRelatedChild, cRelatedTable, cRelatedTag)

-or-

PROCEDURE dbc_AfterDropRelation
LPARAMETERS cRelationID, cTableName, cRelatedChild, cRelatedTable, cRelatedTag

Parameters

cRelationID
Specifies the Relation ID stored in the database.
cTableName
Specifies the name of the parent table.
cRelatedChild
Specifies the name of the linked column in the child table.
cRelatedTable
Specifies the table containing the linked column.
cRelatedTag
Specifies the index tag of the parent table.

Remarks

You can use the dbc_AfterDropRelation event to verify appropriate values for cRelationID and the other parameters in a procedure that tracks, or manages access to the database after a relation is dropped from the database.

Return .F. from this procedure to prevent the relation from being dropped.

See Also

Enable or Disable DBC Events | dbc_BeforeDropRelation Event


dbc_AfterDropTable Event

Occurs after a table is removed from database and deleted from disk by the DROP TABLE command.

PROCEDURE dbc_AfterDropTable(cTableName, lRecycle)

-Or-

PROCEDURE dbc_AfterDropTable
LPARAMETERS cTableName, lRecycle

Parameters

cTableName
Specifies the table removed from the current database and deleted from disk.
lRecycle
Specifies whether the table was placed in the Windows Recycle Bin rather than immediately deleted from the disk.

Remarks

You can use the dbc_AfterDropTable event to verify an appropriate value for cTableName, use those parameters in a procedure to track, or manage access to the database after a table is removed from the database and from the disk.

If you delete a table by using DELETE FILE or the operating system, no event occurs.

Example

* Reports to the screen the event name, where it is called from, and
* the parameter values passed to it.
PROCEDURE dbc_AfterDropTable ;
         (cTableName, ;
          lRecycle)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName ')
? '     lRecycle   = ' + TRANSFORM(lRecycle)   + ' - ' ;
                   + TYPE('lRecycle')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDropTable Event


dbc_AfterDropView Event

Occurs after SQL view definition is removed from the current database.

PROCEDURE dbc_AfterDropView(cViewName)

-or-

PROCEDURE dbc_AfterDropView
LPARAMETERS cViewName

Parameters

cViewName
Specifies the name of the view deleted from the current database.

Remarks

DROP VIEW is almost identical to DELETE VIEW; DROP VIEW is the ANSI SQL standard syntax for deleting a SQL view. Both commands remove a view definition from the active database, but the syntax is slightly different.

You can use the dbc_AfterDropView event to track access to the database after a view definition is removed from the database.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterDropView ;
         (cViewName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cViewName  = ' + TRANSFORM(cViewName) + ' - ' ;
                    + TYPE('cViewName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeDropView Event


dbc_AfterModifyConnection Event

Occurs after a connection is modified.

PROCEDURE dbc_AfterModifyConnection(cConnectionName, lChanged)

-or-

PROCEDURE dbc_AfterModifyConnection
LPARAMETERS cConnectionName, lChanged

Parameters

cConnectionName
Specifies the name of the connection modified.
lChanged
Specifies whether a modification to the view was saved in the Connection Designer.

Remarks

You can use the dbc_AfterModifyView event to track or manage access to the database after connections are modified.

See Also

Enable or Disable DBC Events | dbc_BeforeModifyConnection Event


dbc_AfterModifyProc Event

Occurs after modifications have been made and the stored procedure editor for the database has been closed.

PROCEDURE dbc_AfterModifyProc( )

Remarks

You can use the dbc_AfterModifyProc event to track access to the database after the stored procedure is modified.

Example

* Reports to the screen Event name, where it is called.
PROCEDURE dbc_AfterModifyProc
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:    ' + SUBSTR(DBC(),RAT('\',DBC())+1)+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeModifyProc Event


dbc_AfterModifyTable Event

Occurs after a table is modified.

PROCEDURE dbc_AftermodifyTable(cTableName, lChanged)

-or-

PROCEDURE dbc_AfterModifyTable
LPARAMETERS cTableName, lChanged

Parameters

cTableName
Specifies the name of the table modified.
lChanged
Specifies whether a modification was saved in the Table Designer.

Remarks

You can use the dbc_AfterModifyTable event to track access to the database after tables are modified.

See Also

Enable or Disable DBC Events | dbc_BeforeModifyTable Event


dbc_AfterModifyView Event

Occurs after a view has been modified.

PROCEDURE dbc_AfterModifyView(cViewName, lChanged)

-or-

PROCEDURE dbc_AfterModifyView
LPARAMETERS cViewName, lChanged

Parameters

cViewName
Specifies the name of the view modified.
lChanged
Specifies whether a modification was saved in the View Designer.

Remarks

You can use the dbc_AfterModifyView event to track changes to a database as views are modified.

See Also

Enable or Disable DBC Events | dbc_BeforeModifyView Event


dbc_AfterOpenTable Event

Occurs after a table or view is opened.

PROCEDURE dbc_AfterOpenTable(cTableName)

-or-

PROCEDURE dbc_AfterOpenTable
LPARAMETERS cTableName

Parameters

cTableName
Specifies the name of the table or view that was opened.

Remarks

You can use the dbc_AfterOpenTable event to track access to the database after a table is opened in the database.

If the underlying tables are not open when a view is opened, this event occurs for both the tables and the view.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_AfterOpenTable ;
         (cTableName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' + TYPE('cTableName')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeOpenTable Event


dbc_AfterRemoveTable Event

Occurs after table removal is complete.

PROCEDURE dbc_AfterRemoveTable(cTableName, lDelete, lRecycle)

-Or-

PROCEDURE dbc_AfterRemoveTable
LPARAMETERS cTableName, lDelete, lRecycle

Parameters

cTableName
Specifies the name of the table that was removed from the database.
lDelete
Specifies whether the table was deleted instead of being converted to a free table.
lRecycle
Specifies whether the table was placed in the Windows Recycle Bin rather than immediately deleted from the disk. Some data, such as the table properties available only in tables contained in a database, is lost even if the table is only recycled rather than removed and deleted.

Remarks

You can use the dbc_AfterRemoveTable event to track access to the database after a table is removed from the database and from the disk.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameters passed.
PROCEDURE dbc_AfterRemoveTable ;
         (cTableName, ;
          lDelete, ;
          lRecycle)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName ')
? '     lDelete    = ' + TRANSFORM(lDelete)    + ' - ' ;
                   + TYPE('lDelete')
? '     lRecycle   = ' + TRANSFORM(lRecycle)   + ' - ' ;
                   + TYPE('lRecycle')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeRemoveTable Event


dbc_AfterRenameConnection Event

Occurs before a connection is renamed.

PROCEDURE dbc_AfterRenameConnection(cConnectionName, cNewName)

-or-

PROCEDURE dbc_AfterRenameConnection
LPARAMETERS cPreviousName, cNewName

Parameters

cPreviousName
Specifies the previous name of the connection.
cNewName
Specifies the new name of the connection.

Remarks

You can use the dbc_AfterRenameConnection event to track changes to the database as connections are renamed.

Return .F. from this procedure to prevent the connection from being renamed.

See Also

Enable or Disable DBC Events | dbc_BeforeRenameConnection Event


dbc_AfterRenameTable Event

Occurs before a table is renamed.

PROCEDURE dbc_AfterRenameTable(cPreviousName, cNewName)

-or-

PROCEDURE dbc_AfterRenameTable
LPARAMETERS cPreviouName, cNewName

Parameters

cPreviousName
Specifies the current name of the table.
cNewName
Specifies the new name of the table.

Remarks

You can use the dbc_AfterRenameTable event to track changes to the database as tables are renamed.

Example

PROCEDURE dbc_AfterRenameTable;
   (cPreviousName, ;
    cNewName)
 ? '>>   ' + PROGRAM()
 ?? 'in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1
 ? '     Current DBC:    ' + SUBSTR(DBC(),RAT('\',DBC())+1
 ? '     cPreviousName = ' + TRANSFORM(cPreviousName)    + ' – ' + TYPE('cPreviousName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeRenameTable Event


dbc_AfterRenameView Event

Occurs before a view is renamed.

PROCEDURE dbc_AfterRenameView(cPreviousName, cNewName)

-or-

PROCEDURE dbc_AfterRenameView
LPARAMETERS cPreviousName, cNewName

Parameters

cPreviousName
Specifies the current name of the view.
cNewName
Specifies the new name of the view.

Remarks

You can use the dbc_AfterRenameView event to track changes to the database when views are renamed.

See Also

Enable or Disable DBC Events | dbc_BeforeRenameView Event


dbc_AfterValidateData Event

Occurs after VALIDATE DATABASE completes.

PROCEDURE dbc_AfterValidateData
(lRecover, lNoConsole, lPrint, lFile [, cFilename])

-or-

PROCEDURE dbc_AfterValidateData
LPARAMETERS lRecover, lNoConsole, lPrint, lFile [, cFilename]

Parameters

lRecover
Specifies whether the RECOVER keyword was included in the VALIDATE DATABASE command that triggered this event.
lNoConsole
Specifies whether the NOCONSOLE keyword was included in the VALIDATE DATABASE command that triggered this event.
lPrint
Specifies whether the PRINT keyword was included in the VALIDATE DATABASE command that triggered this event.
lFile
Specifies whether the TO FILE clause was included in the VALIDATE DATABASE command that triggered this event.
cFilename
Specifies the name of the output file named in the TO FILE clause of the VALIDATE DATABASE command. cFilename is optional, but if you omit it and use the TO FILE clause of VALIDATE DATABASE, you will receive the error "Must specify additional parameters." If you do not use TO FILE and include the cFilename parameter, it will be passed a value of .F.

Remarks

You can use the dbc_AfterValidateData event to track access to the database after data are validated.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameters passed.
PROCEDURE dbc_AfterValidateData ;
         (lRecover, ;
          lNoConsole, ;
          lPrint, ;
          lFile, ;
          cFileName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     lRecover   = ' + TRANSFORM(lRecover)   + ' - ' ;
                    + TYPE('lRecover')
 ? '     lNoConsole = ' + TRANSFORM(lNoConsole) + ' - ' ;
                    + TYPE('lNoConsole')
 ? '     lPrint     = ' + TRANSFORM(lPrint)     + ' - ' ;
                    + TYPE('lPrint')
 ? '     lFile      = ' + TRANSFORM(lFile)      + ' - ' ;
                    + TYPE('lFile')
 ? '     cFileName  = ' + TRANSFORM(cFileName)  + ' - ' ;
                    + TYPE('cFileName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeValidateData Event


dbc_BeforeAddRelation Event

Occurs before a relation is added to the database.

PROCEDURE dbc_BeforeAddRelation(cRelationID, cTableName, cRelatedChild,
   cRelatedTable, cRelatedTag)

-or-

PROCEDURE dbc_BeforeAddRelation
LPARAMETERS cRelationID, cTableName, cRelatedChild, cRelatedTable,
   cRelatedTag

Parameters

cRelationID
Specifies the Relation ID number stored in the database.
cTableName
Specifies the name of the parent table.
cRelatedChild
Specifies the name of the linked column.
cRelatedTable
Specifies the table containing the linked column.
cRelatedTag
Specifies the index tag of the parent table.

Remarks

You can use the dbc_BeforeAddRelation event to verify appropriate values for the parameters in a procedure that tracks, or manages access to the database before a relation is added to the database.

Return .F. from this procedure to prevent the relation from being added.

See Also

Enable or Disable DBC Events | dbc_AfterAddRelation Event


dbc_BeforeAddTable Event

Occurs before an existing free table is added to the active database.

You can use the dbc_BeforeAddTable event to execute code before the table is added to a database. This is useful for programming needs such as controlling whether or under what conditions a table is added to the database or to log the addition of the table.

Note This event does not occur when you create a table in the database.
PROCEDURE dbc_BeforeAddTable(cTableName, cLongTableName)

-or-

PROCEDURE dbc_BeforeAddTable
LPARAMETERS [cTableName, cLongTableName]

Parameters

cTableName,
Specifies the name of the table being added.
cLongTableName
Specifies the long name to be given to the table.

Remarks

To prevent the table from being added to the database, return a value of False (.F.) from this procedure.

Example

PROCEDURE dbc_BeforeAddTable ;
         (cTableName, ;
          cLongTableName)
? '     cTableName     = ' + TRANSFORM(cTableName)     + ' - ' ;
                       + TYPE('cTableName ')
? '     cLongTableName = ' + TRANSFORM(cLongTableName) + ' - ' ;
                       + TYPE('cLongTableName ')
userID      = SUBSTR(SYS(0),AT('#',SYS(0))+2)
IF UPPER(userID) = 'MYALIAS'   && only one user can add tables.
   RETURN .T.
ENDIF
   RETURN .F.
ENDIF
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterAddTable | dbc_BeforeRemoveTable | dbc_AfterRemoveTable


dbc_BeforeAppendProc Event

Occurs before an APPEND PROCEDURES command completes.

PROCEDURE dbc_BeforeAppendProc(cFileName, nCodePage, lOverwrite)

-or-

PROCEDURE dbc_BeforeAppendProc
LPARAMETERS cFileName, nCodePage, lOverwrite

Parameters

cFileName
Specifies the name of a text file from which the stored procedures are to be appended.
nCodePage,
Specifies the code page of the text file from which the stored procedures are to be appended. Visual FoxPro copies the contents of the text file and, as it does so, automatically converts those contents to the code page you specify.
lOverwrite
Specifies whether the OVERWRITE keyword was included in the APPEND PROCEDURE command. If OVERWRITE was omitted, the current stored procedures in the database are appended to the existing stored procedures, otherwise they replace any existing procedures.

Remarks

You can use the dbc_BeforeAppendProc to track attempted access to the database before stored procedures are appended.

Return .F. from this procedure to prevent the contents of the text file from being appended to the database stored procedures.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeAppendProc ;
         (cFileName,;
          nCodePage,;
          lOverwrite)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:      ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cFileName       = ' + TRANSFORM(cFileName)  + ' - ' ;
                         + TYPE('cFileName')
 ? '     nCodePage       = ' + TRANSFORM(nCodePage)  + ' - ' ;
                         + TYPE('nCodePage')
 ? '     lOverwrite      = ' + TRANSFORM(lOverwrite) + ' - ' ;
                         + TYPE('lOverwrite')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterAppendProc Event


dbc_BeforeCloseTable Event

Occurs before the table or view is closed.

PROCEDURE dbc_BeforeCloseTable(cTableName)

-Or-

PROCEDURE dbc_BeforeCloseTable
LPARAMETERS cTableName

Parameters

cTableName
Specifies the name of the table or view being closed.

Remarks

You can use the dbc_BeforeCloseTable event to track access to the database before a table is closed in the current database.

Return .F. from this procedure to prevent the table from being closed.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeCloseTable ;
         (cTableName)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCloseTable Event


dbc_BeforeCopyProc Event

Occurs before the COPY PROCEDURE command begins.

PROCEDURE dbc_BeforeCopyProc(cFileName, nCodePage, lAdditive)

-or-

PROCEDURE dbc_BeforeCopyProc
LPARAMETERS cFileName, nCodePage, lAdditive

Parameters

cFileName
Specifies the name of a text file to which the stored procedures are to be copied.
nCodePage,
Specifies the code page of the text file to which the stored procedures are to be copied. Visual FoxPro copies the contents of the text file and, as it does so, automatically converts those contents to the code page you specify.
lAdditive
Specifies whether the ADDITIVE keyword was included in COPY PROCEDURE command that triggered this event.

Remarks

You can use the dbc_BeforeCopyProc event to track attempted access to the database before stored procedure are copied.

Return .F. from this procedure to prevent the stored procedures from being copied.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeCopyProc ;
         (cFileName,;
          nCodePage,;
          lAdditive)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:      ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cFileName       = ' + TRANSFORM(cFileName)  + ' - ' + TYPE('cFileName')
 ? '     nCodePage       = ' + TRANSFORM(nCodePage)  + ' - ' + TYPE('nCodePage')
 ? '     lAdditive = ' + TRANSFORM(lAdditive) + ' - ' + TYPE('lAdditive')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCopyProc Event


dbc_BeforeCreateConnection Event

Occurs before a new connection is created.

PROCEDURE dbc_BeforeCreateConnection( )

Remarks

You can add code in the dbc_BeforeCreateConnection event to track attempted access to the database before a connection is created, or to prevent the creation of a connection.

Return .F. from this procedure to prevent the connection from being created.

Example

* Reports to the screen Event name and where it is called from.
PROCEDURE dbc_BeforeCreateConnection
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
RETURN .F.    && Prevents user from creating a connection.
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCreateConnection Event


dbc_BeforeCreateOffline Event

Occurs before a view is taken offline

PROCEDURE dbc_BeforeCreateOffline(cViewName, cPath)

-Or-

PROCEDURE dbc_BeforeCreateOffline
LPARAMETERS cViewName, cPath

Parameters

cViewName
Specifies the name of the view being taken offline.
cPath
Specifies the directory in which the offline view is placed and the name of the offline view.

Remarks

You can use the dbc_BeforeCreateOffline event to verify appropriate values for cViewName and cPath or use those parameters in a procedure to track attempted access to the database before an offline view is created.

Return .F. from this procedure to prevent the view from taken offline.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeCreateOffline ;
         (cViewName,;
          cPath)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cViewName =  ' + TRANSFORM(cViewName) + ' - ' ;
                  + TYPE('cViewName')
? '     cPath     =  ' + TRANSFORM(cPath)     + ' - ' ;
                  + TYPE('cPath')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCreateOffline Event


dbc_BeforeCreateTable Event

Occurs before a table is created in the active database.

PROCEDURE dbc_BeforeCreateTable(cTableName, cLongTableNameT)

-Or-

PROCEDURE dbc_BeforeCreateTable
LPARAMETERS cTableName, cLongTableName

Parameters

cTableName
Specifies the name of the table being created.
cLongTableName
Specifies the long name to be given to the table.

Remarks

This event does not occur when you create a free table.

You can use the dbc_BeforeCreateTable event to verify appropriate values for cTableName or cLongTableName. Use those parameters in a procedure to track, or manage access before a table is created in the database.

Return .F. from this procedure to prevent the table from being created.

Example

PROCEDURE dbc_BeforeCreateTable ;
         (cTableName, ;
          cLongTableName)
? '     cTableName     = ' + TRANSFORM(cTableName)     + ' - ' ;
                       + TYPE('cTableName ')
? '     cLongTableName = ' + TRANSFORM(cLongTableName) + ' - ' ;
                       + TYPE('cLongTableName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCreateTable Event


dbc_BeforeCreateView Event

Occurs before a SQL view (updateable cursor) is created.

PROCEDURE dbc_BeforeCreateView(cViewName)

-or-

PROCEDURE dbc_BeforeCreateView
LPARAMETERS cViewName)

Parameters

cViewName
Specifies the name of the view being created.

Remarks

You can use the dbc_BeforeCreateView event to track attempted access to the database before a view is created.

Return .F. from this procedure to prevent the view from being created.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameters passed.
PROCEDURE dbc_BeforeCreateView ;
         (cViewName, ;
          lRemote)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cViewName =  ' + TRANSFORM(cViewName) + ' - ' ;
                   + TYPE('cViewName ')+' /end/ '
*RETURN .f.
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterCreateView Event


dbc_BeforeDBGetProp Event

Occurs before the DBGetProp( ) function runs.

PROCEDURE dbc_BeforeDBGetProp(cName, cType, cProperty)

-or-

PROCEDURE dbc_BeforeDBGetProp
LPARAMETERS cName, cType, cProperty

Parameters

cName
Specifies the value of the first parameter in the DBGetProp( ) function, the name of the database, field, named connection, table, or view for which DBGETPROP( ) returns information.
cType
Specifies the value of the second parameter in the DBGetProp( ) function, the object type of the item named in cName.
cProperty
Specifies the value of the third parameter in the DBGetProp( ) function, the property for which DBGETPROP( ) returns information.

Remarks

You can use the dbc_BeforeDBGetProp event to track attempted access to the database before DBGetProp( ) runs.

Return .F. from this procedure to prevent the property value from being returned to DBGetProp(). This will cause the DBGetProp() function to return NULL.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeDBGetProp ;
         (cName,;
          cType,;
          cProperty)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC: ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cName     =  ' + TRANSFORM(cName)     + ' - ' + TYPE('cName')
 ? '     cType     =  ' + TRANSFORM(cType)     + ' - ' + TYPE('cType')
 ? '     cProperty =  ' + TRANSFORM(cProperty) + ' - ' + TYPE('cProperty')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterDBGetProp Event | DBGETPROP( )


dbc_BeforeDBSetProp Event

Occurs before DBSetProp( ) runs.

PROCEDURE dbc_BeforeDBSetProp(cName, cType, cProperty, ePropertyValue)

-or-

PROCEDURE dbc_BeforeDBSetProp
LPARAMETERS cName, cType, cProperty, ePropertyValue
cName
Specifies the value of the first parameter in the DBGetProp( ) function, the name of the database, field, named connection, table, or view for which DBSETPROP( ) changes the value.
cType
Specifies the value of the second parameter in the DBSetProp( ) function, the object type of the item named in cName.
cProperty
Specifies the value of the third parameter in the DBSetProp( ) function, the property for which DBSETPROP( ) changes the value.
ePropertyValue
Specifies the value of the fourth parameter in the DBSetProp( ) function, the value to be assigned to the property in cProperty.

For details on valid cType and cProperty values, see DBSETPROP( ) and DBGETPROP( ) in Help.

Remarks

You can use the dbc_BeforeDBSetProp event to track attempted access to the database before DBSETPROP( ) runs.

Return .F. from this procedure to prevent the property value from being set. This will cause the DBSetProp() function to return .F..

Some property values can be changed using DBSetProp( ) or using a designer. For example, you can change the Comment property for a table using DBSetProp( ) as well as from the table designer. Because DBSetProp( ) makes changes directly to the database itself, dbc_BeforeModifyTable or dbc_AfterModifyTable will not catch changes made by DBSETPROP( ). To trap for changes that could be made either way, you would need to use dbc_BeforeDBSetProp, dbc_AfterDBSetProp, dbc_BeforeModifyTable, and dbc_AfterModifyTable to check for the appropriate changes.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeDBSetProp ;
         (cName,;
          cType,;
          cProperty,;
          ePropertyValue)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC:     ' + SUBSTR(DBC(),RAT('\',DBC())+1)
 ? '     cName          = ' + TRANSFORM(cName)          + ' - ' + TYPE('cName')
 ? '     cType          = ' + TRANSFORM(cType)          + ' - ' + TYPE('cType')
 ? '     cProperty      = ' + TRANSFORM(cProperty)      + ' - ' + TYPE('cProperty')
 ? '     ePropertyValue = ' + TRANSFORM(ePropertyValue) + ' - ' + TYPE('ePropertyValue')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterDBSetProp Event


dbc_BeforeDeleteConnection Event

Occurs before a connection is deleted.

PROCEDURE dbc_BeforeDeleteConnection(cConnectionName)

-or-

PROCEDURE dbc_BeforeDeleteConnection
LPARAMETERS cConnectionName

Parameters

cConnectionName
Specifies the name of the connection.

Remarks

You can use the dbc_BeforeDeleteConnection event to track attempted access to the database before connections are deleted.

Return .F. from this procedure to prevent the connection from being deleted.

See Also

Enable or Disable DBC Events | dbc_AfterDeleteConnection Event


dbc_BeforeDropOffline Event

Occurs immediately before a DROPOFFLINE( ) function, which returns an offline view on line.

PROCEDURE dbc_BeforeDropOffline(cViewName, cPath)

-or-

PROCEDURE dbc_BeforeDropOffline
LPARAMETERS cViewName, cPath

Parameters

cViewName
Specifies the name of the offline view being taken back online.
cPath
Specifies the directory in which the offline view is located.

Return .F. from this procedure to prevent returning the view online.

Remarks

You can use the dbc_BeforeDropOffline event to track attempted access to the database before an offline view is taken back online.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeDropOffline ;
         (cViewName,;
          cPath)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cViewName =  ' + TRANSFORM(cViewName) + ' - ' ;
                  + TYPE('cViewName')
? '     cPath     =  ' + TRANSFORM(cPath)     + ' - ' ;
                  + TYPE('cPath')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterDropOffline Event


dbc_BeforeDropRelation Event

Occurs before a relation is dropped from a database.

PROCEDURE dbc_BeforeDropRelation(cRelationID, cTableName, cRelatedChild,
   cRelatedTable, cRelatedTag)

-or-

PROCEDURE dbc_BeforeDropRelation
LPARAMETERS [cRelationID, cTableName, cRelationChild, cRelatedTable,
   cRelatedTag]

Parameters

cRelationID
Specifies the Relation ID stored in the database.
cTableName
Specifies the name of the parent table.
cRelatedChild
Specifies the name of the linked column in the child table.
cRelatedTable
Specifies the child table containing the linked column.
cRelatedTag
Specifies the index tag of the parent table.

Remarks

You can use the dbc_BeforeDropRelation event to verify appropriate values for cRelationID and the other parameters in a procedure that tracks, or manages access to the database before a relation is dropped from the database.

Return .F. from this procedure to prevent the relation from being dropped.

See Also

Enable or Disable DBC Events | dbc_AfterDropRelation Event


dbc_BeforeDropTable Event

Occurs before the specified table is removed from the active database and deleted from disk with the DROP TABLE command.

PROCEDURE dbc_BeforeDropTable(cTableName, lRecycle)

-Or-

PROCEDURE dbc_BeforeDropTable
LPARAMETERS cTableName, lRecycle

Parameters

cTableName
Specifies the table being removed from the current database and deleted from disk.
lRecycle
Specifies whether the table is to be placed in the Microsoft Windows Recycle Bin rather than immediately deleted from the disk. Some data, such as the table properties available only in tables contained in a database, are lost even if the table is only recycled rather than removed and deleted.

Remarks

You can use the dbc_BeforeDropTable event to verify an appropriate value for cTableName, and use those parameters in a procedure to track, or manage access to the database before the table is removed from the database and the disk.

If you delete a table by using DELETE FILE or the operating system, no event occurs.

Return .F. from this procedure to prevent the table from being dropped.

Example

* Reports the name of the method, where it came from and what the
* parameter values were.
PROCEDURE dbc_BeforeDropTable ;
         (cTableName, ;
          lRecycle)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName ')
? '     lRecycle   = ' + TRANSFORM(lRecycle)   + ' - ' ;
                   + TYPE('lRecycle')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterDropTable Event


dbc_BeforeDropView Event

Occurs before a View is removed from the current database.

PROCEDURE dbc_BeforeDropView(cViewName)

-or-

PROCEDURE dbc_BeforeDropView
LPARAMETERS cViewName

Parameters

cViewName
Specifies the name of the view to be deleted from the current database.

Remarks

DROP VIEW is almost identical to DELETE VIEW; DROP VIEW is the ANSI SQL standard syntax for deleting a SQL view. Both commands remove a view definition from the active database, but the syntax is slightly different.

You can use the dbc_BeforeDropView event to track attempted access to the database before a view is removed from the database.

Return .F. from this procedure to prevent the view from being dropped.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeDropView ;
         (cViewName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cViewName =  ' + TRANSFORM(cViewName) + ' - ' ;
                   + TYPE('cViewName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterDropView Event


dbc_BeforeModifyConnection Event

Occurs before a connection is modified.

PROCEDURE dbc_BeforeModifyConnection(cConnectionName)

-or-

PROCEDURE dbc_BeforeModifyConnection
LPARAMETERS cConnectionName

Parameters

cViewName
Specifies the name of the connection modified.

Remarks

You can use the dbc_BeforeModifyView event to track attempted access to the database before connections are modified.

Return .F. from this procedure to prevent the connection from being modified.

See Also

Enable or Disable DBC Events | dbc_AfterModifyConnection Event


dbc_BeforeModifyProc Event

Occurs before the stored procedures in the open database are modified.

PROCEDURE dbc_BeforeModifyProc( )

Remarks

You can use the dbc_BeforeModiProc event to track attempted access to the database before the stored procedures are modified.

Return .F. from this procedure to prevent the stored procedures from being modified.

Example

* Reports to the screen Event name, and where it is called from.
PROCEDURE dbc_BeforeModifyProc
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? DBC()
RETURN .F. && prevents modification of stored procedures.
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterModifyProc Event


dbc_BeforeModifyTable Event

Occurs before a table is modified.

PROCEDURE dbc_BeforeModifyTable(cTableName)

-or-

PROCEDURE dbc_BeforeModifyTable
LPARAMETERS cTableName

Parameters

cTableName
Specifies the name of the table modified.

Remarks

You can use the dbc_BeforeModifyTable event to track attempted access to the database before tables are modified.

Return .F. from this procedure to prevent the table from being modified.

See Also

Enable or Disable DBC Events | dbc_AfterModifyTable Event


dbc_BeforeModifyView Event

Occurs before a view has been modified.

PROCEDURE dbc_BeforeModifyView(cViewName)

-or-

PROCEDURE dbc_BeforeModifyView
LPARAMETERS cViewName

Parameters

cViewName
Specifies the name of the view modified.

Remarks

You can use the dbc_BeforeModifyView event to track attempted access to the database before Views are modified.

Return .F. from this procedure to prevent the view from being modified.

See Also

Enable or Disable DBC Events | dbc_AfterModifyView Event


dbc_BeforeOpenTable Event

Occurs before a table or view contained in the database is opened.

PROCEDURE dbc_BeforeOpenTable(cTableName)

-Or-

PROCEDURE dbc_BeforeOpenTable
LPARAMETERS cTableName

Parameters

cTableName
Specifies the name of the table or view being opened.

Remarks

You can use method code in the dbc_BeforeOpenTable event to track attempted access before a table is opened in the database. This event occurs anytime a table or view in the database is opened either explicitly by the USE command or implicitly by other commands such as SELECT.

If the underlying tables are not open when a view is opened, this event occurs for both the tables and the view.

Return .F. from this procedure to prevent the table from being opened.

Example

* Reports the method name, where it is called from and the
* value of the paramater cTableName.
PROCEDURE dbc_BeforeOpenTable ;
         (cTableName)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                    + TYPE('cTableName')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterOpenTable Event


dbc_BeforeRemoveTable Event

Occurs before a table is removed from the database.

PROCEDURE dbc_BeforeRemoveTable(cTableName, lDelete, lRecycle)

-Or-

PROCEDURE dbc_BeforeRemoveTable
LPARAMETERS cTableName, lDelete, lRecycle

Parameters

cTableName
Specifies the name of the table being removed from the database.
lDelete
Specifies whether the table is deleted rather than converted to a free table.
lRecycle
Specifies whether the table is placed in the Windows Recycle Bin rather than immediately deleted from the disk. Some data, such as the table properties available only in tables contained in a database, is lost even if the table is only recycled rather than removed and deleted.

Remarks

You can use the dbc_BeforeRemoveTable event to track, or manage access to the database before a table is removed from the database and from the disk.

Return .F. from this procedure to prevent the table from being removed.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeRemoveTable ;
         (cTableName, ;
          lDelete, ;
          lRecycle)
? '>>   ' + PROGRAM()
?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
? '     cTableName = ' + TRANSFORM(cTableName) + ' - ' ;
                   + TYPE('cTableName ')
? '     lDelete    = ' + TRANSFORM(lDelete)    + ' - ' ;
                   + TYPE('lDelete')
? '     lRecycle   = ' + TRANSFORM(lRecycle)   + ' - ' ;
                   + TYPE('lRecycle')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterRemoveTable Event


dbc_BeforeRenameConnection Event

Occurs before a connection is renamed.

PROCEDURE dbc_BeforeRenameConnection(cPreviousName,cNewName)

-or-

PROCEDURE dbc_BeforeRenameConnection
LPARAMETERS cPreviousName, cNewName

Parameters

cPreviousName
Specifies the current name of the connection.
cNewName
Specifies the new name of the connection.

Remarks

You can use the dbc_BeforeRenameConnection event to track attempted access to the database before connections are renamed.

Return .F. from this procedure to prevent the connection from being renamed.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_BeforeRenameConnection ;
         (cPreviousName, cNewName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     cPreviousName = ' + TRANSFORM(cPreviousName)    + ' - ' ;
                       + TYPE('cPreviousName ')
 ? '     cNewName      = ' + TRANSFORM(cNewName)         + ' - ' ;
                       + TYPE('cNewName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterRenameConnection Event


dbc_BeforeRenameTable Event

Occurs before a table is renamed.

PROCEDURE dbc_BeforeRenameTable(cPreviousName, cNewName)

-or-

PROCEDURE dbc_BeforeRenameTable
LPARAMETERS cPreviousName, cNewName

Parameters

cPreviousName
Specifies the current name of the table.
cNewName
Specifies the new name of the table.

Remarks

You can use the dbc_BeforeRenameTable event to track attempted access to the database before a connection, is renamed, or to prevent renaming of a table.

Return .F. from this procedure to prevent the table from being renamed.

Example

PROCEDURE dbc_BeforeRenameTable;
   (cPreviousName, ;
    cNewName)
 ? '>>   ' + PROGRAM()
 ?? 'in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1
 ? '     Current DBC:    ' + SUBSTR(DBC(),RAT('\',DBC())+1
 ? '     cPreviousName = ' + TRANSFORM(cPreviousName)     + ' – ' +
TYPE('cPreviosName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterRenameTable Event


dbc_BeforeRenameView Event

Occurs before a view is renamed.

PROCEDURE dbc_BeforeRenameView(cPreviousName, cNewName)

-or-

PROCEDURE dbc_BeforeRenameView
LPARAMETERS cPreviousName, cNewName

Parameters

cPreviousName
Specifies the current name of the view.
cNewName
Specifies the new name of the view.

Remarks

You can use the dbc_BeforeRenameView event to track attempted access to the database before views are renamed.

Return .F. from this procedure to prevent the view from being renamed.

See Also

Enable or Disable DBC Events | dbc_AfterRenameView Event


dbc_BeforeValidateData Event

Occurs immediately before the VALIDATE DATABASE command runs.

PROCEDURE dbc_BeforeValidateData
(lRecover, lNoConsole, lPrint, lFile [, cFilename])

-or-

PROCEDURE dbc_BeforeValidateData
LPARAMETERS lRecover, lNoConsole, lPrint, lFile [, cFilename]

Parameters

lRecover
Specifies whether the RECOVER keyword was included in the VALIDATE DATABASE command that triggered this event.
lNoConsole
Specifies whether the NOCONSOLE keyword was included in the VALIDATE DATABASE command that triggered this event.
lPrint
Specifies whether the PRINT keyword was included in the VALIDATE DATABASE command that triggered this event.
lFile
Specifies whether the FILE keyword was included in the VALIDATE DATABASE command that triggered this event.
cFilename
Specifies the name of the output file named in the TO FILE clause of the VALIDATE DATABASE command. cFilename is optional, but if you omit it and use the TO FILE clause of VALIDATE DATABASE, you will receive the error "Must specify additional parameters." If you do not use TO FILE and include the cFilename parameter, it will be passed a value of .F..

Remarks

You can use the dbc_BeforeValidateData event to track attempted access to the database before data are validated.

Return .F. from this procedure to prevent the database from being validated.

Example

* Reports to the screen Event name, where it is called from and ;
* the parameters passed.
PROCEDURE dbc_BeforeValidateData;
         (lRecover, ;
          lNoConsole, ;
          lPrint, ;
          lFile, ;
          cFileName)
 ? '>>   ' + PROGRAM()
 ?? ' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     lRecover   = ' + TRANSFORM(lRecover)   + ' - ' ;
                    + TYPE('lRecover')
 ? '     lNoConsole = ' + TRANSFORM(lNoConsole) + ' - ' ;
                    + TYPE('lNoConsole')
 ? '     lPrint     = ' + TRANSFORM(lPrint)     + ' - ' ;
                    + TYPE('lPrint')
 ? '     lFile      = ' + TRANSFORM(lFile)      + ' - ' ;
                    + TYPE('lFile')
 ? '     cFileName  = ' + TRANSFORM(cFileName)  + ' - ' ;
                    + TYPE('cFileName ')+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | dbc_AfterValidateData Event


dbc_CloseData Event

Occurs when a database closes.

PROCEDURE dbc_CloseData(cDatabaseName, lAll)

-Or-

PROCEDURE dbc_CloseData
LPARAMETERS cDatabaseName, lAll

Parameters

cDatabaseName
Specifies the name of the target database.
lAll
Specifies whether the ALL keyword was included in the CLOSE DATABASES command. If DBC Events is turned on, this event occurs whenever a database is closed whether or not it is closed explicitly with the CLOSE DATABASES command.

Remarks

You can use the dbc_CloseData event to verify appropriate values for cDatabaseName and lAll or use those parameters in a procedure to track access to the database when the database is about to be closed

When several databases are closed at one time, the dbc_CloseData method for each database is fired in turn. Therefore, if you issue the CLOSE DATABASES ALL command, several different CloseData events occur and several different dbc_CloseData methods can be executed.

Return .F. from this procedure to prevent the database from being closed.

Example

PROCEDURE dbc_CloseData ;
         (cDatabaseName,;
          lAll)
? '     cDatabaseName = ' + TRANSFORM(cDatabaseName) + ' - ' ;
                      + TYPE('cDatabaseName')
? '     lAll          = ' + TRANSFORM(lAll)          + ' - ' ;
                      + TYPE('lAll')+' /end/ '
RETURN .F.     && This will prevent database closure.
ENDPROC

See Also

Enable or Disable DBC Events | dbc_BeforeAddTable Event | dbc_Activate Event


dbc_Deactivate Event

Occurs when a database ceases to be active.

PROCEDURE dbc_Deactivate(cDatabaseName)

-Or-

PROCEDURE dbc_Deactivate
LPARAMETERS cDatabaseName

Parameters

cDatabaseName
Specifies the name of the database being deactivated.

Remarks

You can have many Databases open at the same time but only one can be active at a time. Several situations can deactivate a database. To explicitly deactivate a database without activating another database, use the SET DATABASE TO command without arguments.

If several databases (with DBC Events turned on) are open, when one is deactivated the dbc_Deactivate method in that database is executed.

If you place DBC Events code in a program file, the code applies to any database that specifies that program file as its events file. In such program code, use the cDatabaseName parameter to determine which database called the event. This way, you can use one block of method code to determine the deactivated database and then apply code appropriate to that database.

Return .F. from this procedure to prevent the database from being deactivated. Because closing a database implicitly deactivates it, this will also prevent the database from being closed.

Example

PROCEDURE dbc_Deactivate ;
         (cDatabaseName)
? '     cDatabaseName = ' + TRANSFORM(cDatabaseName) + ' - ' ;
                      + TYPE('cDatabaseName')+' /end/ '
ENDPROC

See Also

dbc_Activate DBC Event | SET DATABASE Command | dbc_CloseData Event | dbc_ModifyData Event | dbc_OpenData Event


dbc_ModifyData Event

Occurs immediately after MODIFY DATABASE is issued. Use to prevent opening of the database designer window.

PROCEDURE dbc_ModifyData(cDatabaseName, lNoWait, lNoEdit )

-Or-

PROCEDURE dbc_ModifyData
LPARAMETERS [cDatabaseName, lNoWait, lNoEdit ]

Parameters

CDatabaseName
Specifies the name of the Database being modified.
lNoWait
Specifies whether the NOWAIT keyword was included in the MODIFY DATABASE command, which would cause the program execution to continue after the Database Designer is opened.
lNoEdit
Specifies whether the NOEDIT keyword was included in the MODIFY DATABASE command, which would prevent editing of the database.

Remarks

You can use the dbc_ModifyData event to track access to the database when the database is modified. Return .F. from this procedure to prevent the database from being modified.

Example

PROCEDURE dbc_ModifyData ;
         (CDatabaseName, ;
            lNoWait, ;
            lNoEdit)
? '     cDatabaseName = ' + cDatabaseName + ' - ' ;
                      + TYPE('cDatabaseName ')
 ? '     lNoWait       = ' + TRANSFORM(lNoWait) + ' - ' ;
                       + TYPE('lNoWait')
 ? '     lNoEdit       = ' + TRANSFORM(lNoEdit) + ' - ' ;
                       + TYPE('lNoEdit')+' /end/ '
* Stop user from changing the database in the Designer.
IF lNoEdit
   RETURN .T.
ELSE
   RETURN .F.
ENDIF
ENDPROC

See Also

MODIFY DATABASE | Enable or Disable DBC Events | Database Designer | Modifying Database Architecture


dbc_OpenData Event

Occurs when a database is opened explicitly by the OPEN DATABASE command or implicitly by another command such as MODIFY DATABASE or USE <Table> with a table contained in a closed database

PROCEDURE dbc_OpenData (cDatabaseName, lExclusive, lNoUpdate, lValidate )

-Or-

PROCEDURE dbc_OpenData
LPARAMETERS [cDatabaseName, lExclusive, lNoUpdate, lValidate ]

Parameters

cDatabaseName
Specifies the name of the database being opened.
lExclusive
Specifies whether the database is being opened in exclusive mode.
lNoUpdate
Specifies whether the NOUPDATE keyword was included in the OPEN DATABASE command, which means the database is being opened in read only mode.
lValidate
Specifies whether the VALIDATE keyword was included in the OPEN DATABASE command, which causes the database to be validated as it is opened.

Remarks

You can use the dbc_OpenData event to track attempted access to the database as the database opens.

By returning false, this method prevents the database from being opened.

Example

PROCEDURE dbc_OpenData ;
         (cDatabaseName, ;
          lExclusive, ;
          lNoUpdate, ;
          lValidate)
 ? '     cDatabaseName = ' + TRANSFORM(cDatabaseName) + ' - ' ;
                       + TYPE('cDatabaseName')
 ? '     lExclusive    = ' + TRANSFORM(lExclusive) + ' - ' ;
                       + TYPE('lExclusive')
 ? '     lNoUpdate     = ' + TRANSFORM(lNoUpdate)  + ' - ' ;
                       + TYPE('lNoUpdate')
 ? '     lValidate     = ' + TRANSFORM(lValidate)  + ' - ' ;
                       + TYPE('lValidate'
ENDPROC

See Also

Enable or Disable DBC Events | OPEN DATABASE Command | MODIFY DATABASE Command


dbc_PackData Event

Occurs before the PACK DATABASE command runs.

PROCEDURE dbc_PackData( )

Remarks

You can use the dbc_PackData event to track access to the database before a PACK DATABASE runs.

Return .F. from this procedure to prevent the database from being packed. You will get a "File access denied" error when attempting to pack the database when returning .F..

Example

* Reports to the screen Event name, where it is called from and ;
* the parameter passed.
PROCEDURE dbc_PackData
 ? '  -  ' + PROGRAM()
 ??' in ' + SUBSTR(SYS(16),RAT('\',SYS(16))+1)
 ? '     Current DBC: ' + SUBSTR(DBC(),RAT('\',DBC())+1)+' /end/ '
ENDPROC

See Also

Enable or Disable DBC Events | PACK DATABASE Command


DblClick Event

Occurs when the user presses and releases the mouse button twice in quick succession.

PROCEDURE Object.DblClick

Remarks

The DblClick event also occurs when you select an item in a list box or a combo box and press ENTER.

If DblClick does not occur within the system's double-click time limit, the object recognizes another Click event. Therefore, when you attach procedures for these related events, make sure that their actions do not conflict. Controls that do not receive DblClick events may receive two single clicks instead of a double-click.

Note If the mouse has more than one button, you can distinguish between the left, right, and middle mouse buttons using the MouseDown and MouseUp events.

See Also

Click Event | MouseDown Event | MouseUp Event

Applies To: CheckBox Control | ComboBox Control | CommandGroup Control | Container Object | Control Object | EditBox Control | Form Object | Grid Control | Header Object | Image Control | Label Control | Line Control | ListBox Control | OptionButton Control | OptionGroup Control | Page Object | PageFrame Control | Shape Control | Spinner Control | TextBox Control | ToolBar Object


Deactivate Event

Occurs when a container object, such as a form, is no longer active because none of its contained objects has the focus.

PROCEDURE Object.Deactivate

Remarks

The Activate and Deactivate events occur only when you are moving the focus within an application. Moving focus to or from a form in another application does not trigger either event. The Deactivate event does not occur when unloading a form.

When a new object is activated, programmatically or interactively, the Deactivate event for the previously active object occurs, and the Activate event for the new object occurs.

For Form objects, clicking the Visual FoxPro desktop causes a form's Deactivate event to occur and deactivates an active user form. This improvement provides better integration with the BINDEVENT( ) function for activating and deactivating forms.

For ToolBar objects, Deactivate occurs when the toolbar is hidden using the Hide method.

For ProjectHook objects, Deactivate occurs when you click away from the Project window or call the ACTIVATE WINDOW command for a different window.

See Also

Activate Event | Hide Method | LostFocus Event | Show Method | Visible Property | BINDEVENT() Function

Applies To: Form | FormSet | Page | ProjectHook Object | ToolBar


Deleted Event

Occurs when the user marks a record for deletion or unmarks a record marked for deletion.

PROCEDURE Grid.Deleted
LPARAMETERS nRecNo

Parameters

nRecNo
Returns the record number of the row being deleted.

See Also

DELETE | DeleteMark Property

Applies To: Grid


Destroy Event

Occurs when an object is released.

PROCEDURE Object.Destroy

Remarks

The Destroy event for a container object triggers before the Destroy event for any of its contained objects; the container's Destroy event can refer to its contained objects before they are released.

See Also

AddObject Method | CREATEOBJECT( ) | Init Event | RELEASE | QueryUnload Event | Unload Event | Release Method

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | Container Object | Control Object | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


DownClick Event

Occurs when the user clicks the down arrow of a Spinner control, the drop-down arrow of a ComboBox control, or the down arrow in the drop-down list of a ComboBox control.

PROCEDURE Control.DownClick

See Also

UpClick Event

Applies To: ComboBox | Spinner


DragDrop Event

Occurs when a drag-and-drop operation is completed.

PROCEDURE Object.DragDrop
LPARAMETERS oSource, nXCoord, nYCoord

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter. Visual FoxPro passes the DragDrop event parameters in the following order:

oSource
References the control being dragged. You can refer to properties and methods of the control with this parameter.
nXCoord, nYCoord
Contains the horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the Form when data is dropped on a drop target. These coordinates are expressed in terms of the Form's coordinate system in the unit of measurement specified by the ScaleMode property of the Form.

Remarks

A drag-and-drop operation is completed when a control is dragged over another control or form and the mouse button is released, or when the Drag method with its nAction argument set to 2 (Drop) is called for the control.

Use a DragDrop event to control what happens after a drag operation is complete. For example, you can move the source control to a new location or copy a file from one location to another.

Note The DragDrop event involves two objects, a control being dragged and a target object. The DragDrop event is triggered for the target object, not the control being dragged. Use the DragMode property and Drag method to specify how dragging is to be initiated. Once dragging is initiated, you can handle events that precede a DragDrop event with a DragOver event.

See Also

Drag Method | DragIcon Property | DragMode Property | DragOver Event | MouseDown Event | MouseUp Event | MouseMove Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


DragOver Event

Occurs when a control is being dragged over a target object.

PROCEDURE Object.DragOver
LPARAMETERS oSource, nXCoord, nYCoord, nState

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter; otherwise an error occurs. Visual FoxPro passes the DragOver event parameters in the following order:

oSource
Contains a reference to the control being dragged. You can refer to properties and methods of the control with this parameter.
nXCoord, nYCoord
Contains the horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the Form when data is dragged over a drop target. These coordinates are expressed in terms of the Form's coordinate system in the unit of measurement specified by the ScaleMode property of the Form. '
nState
Contains a number that represents the transition state of the control being dragged in relation to the target object:
Setting | Description
0 | Enter. The control is being dragged within the range of a target.
1 | Leave. The control is being dragged out of the range of a target.
2 | Over. The control has moved from one position in the target to another.
Use nState to determine actions at key transition points. For example, you can highlight a possible target on nState = 0 (Enter) and restore the object's appearance on nState = 1 (Leave).

When an object receives a DragOver event with nState = 0 (Enter):

  • A DragDrop event is triggered if the source control is dropped on a target object.
  • Another DragOver event is triggered with nState = 1 (Leave) if the source control is not dropped on a valid target.

Remarks

The object under the drag icon is the target object and responds to the DragOver event. You can use this event to monitor when the mouse pointer enters, leaves, or is directly over a target object.

Use a DragOver event to determine what happens after dragging is initiated and before a control is dropped onto a target. For example, you can verify a valid target range by highlighting the target, by setting the BackColor, or ForeColor property or by displaying a special pointer.

See Also

Drag Method | DragDrop Event | DragIcon Property | DragMode Property | MouseDown Event | MouseUp Event | MouseMove Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


DropDown Event

Occurs when the list portion of a ComboBox control is about to drop down after the drop-down arrow is clicked.

PROCEDURE ComboBox.DropDown

Remarks

Use a DropDown event procedure to make final updates to the list portion of a ComboBox before the user makes a selection. This enables you to add or remove items from the list using the AddItem or RemoveItem method. This flexibility is useful if you want controls to interact at run time. For example, what you want to appear in the list portion of a ComboBox depends on what the user chooses in an OptionGroup.

See Also

AddItem Method | DownClick Event | RemoveItem Method

Applies To: ComboBox


Error Event

Occurs when there is a run-time error in a method. The Error event makes it possible for an object to handle errors.

PROCEDURE Object.Error
LPARAMETERS nError, cMethod, nLine

Parameters

nError
Contains the Visual FoxPro error number.
cMethod
Contains the name of the method that caused the error. However, if a method calls a user-defined function, and an error occurs within that function, cMethod contains the name of the user-defined function, rather than the name of the method that called the function.
nLine
Contains the line number within the method or user-defined function that caused the error.

Remarks

The Error event overrides the ON ERROR routine and allows each object to trap and handle errors internally.

Note The Error event occurs only when the error occurs in code. Additionally, the Error event does not occur if the Error Event method does not contain code.

Any errors that occur in an object's Error event must be handled by the object and are not escalated to an ON ERROR routine or TRY...CATCH...FINALLY handler.

Note The Error event does not occur if an ON ERROR routine is on the call stack.

See Also

ON ERROR Command | TRY...CATCH...FINALLY Command

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


ErrorMessage Event

Included for backward compatibility with FoxPro 2.x. Use the Valid Event instead.


GotFocus Event

Occurs when an object receives the focus, either by user action or through code.

PROCEDURE Object.GotFocus

Remarks

Use the GotFocus event to specify actions to occur when an object receives the focus. For example, by attaching a GotFocus event to each control on a Form, you can guide a user by displaying brief instructions or status bar messages. You can also provide visual cues by enabling, disabling, or showing other controls that depend on the control that has the focus.

A control receives the focus by user action, such as a mouse click, or when the SetFocus method is called in code.

Note An object can receive the focus only if its Enabled and Visible properties are set to true (.T.). To customize the keyboard interface for moving the focus, set the tab order or specify access keys for controls on a form. The GotFocus event occurs after the Activate event for the control's container.

See Also

Activate Event | ActiveControl Property | Click Event | Deactivate Event | Enabled Property | LostFocus Event | SetFocus Method | TabIndex Property | TabStop Property | Visible Property | Applies To: CheckBox | ComboBox | CommandButton | Container Object | Control Object | EditBox | Form | ListBox | OLE Bound Control | OLE Container Control | OptionButton | Spinner | TextBox


Init Event

Occurs when an object is created.

PROCEDURE Object.Init
[LPARAMETERS Param1, Param2,...]

Parameters

Param1, Param2...
Parameters are optional, but if parameters are passed, you must include an LPARAMETERS or PARAMETERS statement that lists each parameter. Otherwise, Visual FoxPro generates an error.

Remarks

For form sets and other container objects, the Init events for all the contained objects are triggered before the container's Init event, so you can access the contained objects within the container's Init event. The Init event for each contained object occurs in the order it was added to the container object.

To prevent a control from being created, return false (.F.) from the Init event. The Destroy event will not be triggered. For example, the following code returns false (.F.) if the Invoice table is not available:

PROCEDURE INIT
  IF NOT FILE("INVOICE.DBF")
  ERROR 'Initialization Failed: File not found'
  RETURN .F.
  ELSE
  USE INVOICE IN 0 AGAIN
  THIS.WorkArea = SELECT()
  ENDIF
ENDPROC

See Also

AddObject Method | CREATEOBJECT( ) | Load Event

Applies To: CheckBox | Collection Class | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | Cursor | CursorAdapter Class | Custom | DataEnvironment | EditBox | Exception Class | Form | FormSet | Grid | Header | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Relation | Session Object | Shape | Spinner | TextBox | Timer | ToolBar


InteractiveChange Event

Occurs when the user changes the value of a control using the keyboard or the mouse.

PROCEDURE Control.InteractiveChange

Remarks

This event occurs each time the object's value changes interactively. For example, as a user types in a text box, the InteractiveChange event is triggered after each keystroke.

See Also

Click Event

Applies To: CheckBox | ComboBox | CommandGroup | EditBox | ListBox | OptionGroup | Spinner | TextBox


KeyPress Event

Occurs when the user presses and releases a key. You can use the KeyPress event for intercepting keystrokes entered in a control. You can also test keystrokes immediately for validity or format characters as they are typed. Use the KeyPreview property to create global keyboard-handling routines.

PROCEDURE Object.KeyPress
LPARAMETERS nKeyCode, nShiftAltCtrl

Parameters

nKeyCode
Contains a number that identifies the key pressed. For a list of codes for special keys and key combinations, see INKEY( ).
nShiftAltCtrl
Sets a particular bit if a modifier key is held down while pressing the key specified by nKeyCode. Valid modifier keys are the SHIFT, CTRL, and ALT keys.

The following table lists the modifier key values for nShiftAltCtrl.

nShiftAltCtrl | Modifier key
1 | SHIFT
2 | CTRL
4 | ALT

This parameter is the sum of the bits with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. This parameter indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed. For example, if both CTRL and ALT are pressed, the value of nShiftAltCtrl is 6.

Remarks

The KeyPress event does not occur for any combination of keys with the ALT key.

The object with the focus receives the KeyPress event.

A form can receive the KeyPress event in three special cases:

  • The form contains no controls, or none of its controls is visible and enabled.
  • The form's KeyPreview property is set to True (.T.). The form first receives the KeyPress event, and then the control with focus receives the event.
  • The control on the form cannot process a keystroke, for example, when TAB is pressed to move the focus to the next control.

If the AllowCellSelection property for a grid is set to True (.T.), Visual FoxPro disregards the Grid KeyPress event and uses the event at the individual cell level.

See Also

INKEY( ) | KeyPreview Property

Applies To: CheckBox | ComboBox | CommandButton | EditBox | Form | Grid | ListBox | OptionButton | Spinner | TextBox


Load Event

Occurs just before an object is created.

PROCEDURE Object.Load

Remarks

The Load event occurs first for the form set and then for the contained forms. The Load event occurs before the Activate and GotFocus events.

To prevent a form from being created, return false (.F.) from the Load event; the Destroy event will not be executed.

See Also

Activate Event | GotFocus Event | Unload Event

Applies To: Form | FormSet


LostFocus Event

Occurs when an object loses the focus.

PROCEDURE Object.LostFocus

Remarks

The timing of this event occurs depends on the type of object:

  • A control loses the focus by user action, such as tabbing to or clicking another control, or by changing the focus in code using the SetFocus method. A Grid loses the focus when a user presses CTRL+TAB in Microsoft Windows or CONTROL+TAB on the Macintosh to exit the Grid.
  • A form loses the focus when the form has no controls, all its controls have their Enabled and Visible properties set to false (.F.), or another form gets the focus.

For forms, the LostFocus event occurs before the Deactivate event.

See Also

Deactivate Event | Enabled Property | GotFocus Event | Visible Property

Applies To: CheckBox | ComboBox | CommandButton | Container Object | Control Object | EditBox | Form | ListBox | OLE Bound Control | OLE Container Control | OptionButton | Spinner | TextBox


Message Event

Included for backward compatibility. Use the StatusBarText property instead.


MiddleClick Event

Occurs when the user clicks the middle mouse button on a three-button mouse over a control.

PROCEDURE Control.MiddleClick

See Also

Click Event | DblClick Event | DragDrop Event | DragOver Event | DropDown Event | Enabled Property | KeyPress Event | MouseDown Event | MouseMove Event | MouseUp Event | Scrolled Event | Undock Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container | Control | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


MouseDown Event

Occurs when the user presses a mouse button.

PROCEDURE Object.MouseDown
LPARAMETERS nButton, nShift, nXCoord, nYCoord

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter. Visual FoxPro passes the MouseDown event parameters in the following order:

nButton
Contains a number that specifies which button was pressed to trigger the event: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when the mouse is pressed. The valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Modifier key values for nShift

Windows key | Value
SHIFT | 1
CTRL | 2
ALT | 4

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while pressing the mouse button, the nShift argument contains 2. But If the user holds CTRL+ALT while pressing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are expressed in terms of the form's coordinate system in the unit of measurement specified by the ScaleMode property of the form.

Remarks

Use a MouseDown procedure to specify actions to occur when a given mouse button is pressed. Unlike the Click and DblClick events, you can use the MouseDown event to distinguish between the left, right, and middle mouse buttons. You can also write code for mouse-keyboard combinations that use the modifier keys.

Tip You can use a MouseMove event to respond to an event caused by moving the mouse. The nButton argument for MouseDown and MouseUp differs from the nButton argument used for MouseMove. For MouseDown or MouseUp, the nButton argument indicates exactly one button per event; for MouseMove, it indicates the current state of all buttons.

See Also

Click Event | DblClick Event | MiddleClick Event | MouseMove Event | MousePointer Property | MouseUp Event | MouseWheel Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


MouseEnter Event

Occurs when a mouse cursor moves into a control

PROCEDURE Object.MouseEnter
LPARAMETERS nButton, nShift, nXCoord, nYCoord

Parameters

nButton
Contains a number that specifies which button was pressed to trigger the event: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when the mouse is pressed. The valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Modifier key values for nShift

Windows key | Value
SHIFT | 1
CTRL | 2
ALT | 4

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while pressing the mouse button, the nShift argument contains 2. But If the user holds CTRL+ALT while pressing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are expressed in terms of the form's coordinate system in the unit of measurement specified by the ScaleMode property of the form.

Remarks

You can use this and the MouseLeave event to create rollover and mouseover behaviors as in DHTML.

A control receives a MouseEnter event when the user moves the mouse into a control from a mouse position that was previously outside the control. In the case of overlapping or intersecting controls, the topmost control in the z-order receives the event.

A MouseEnter event is passed to objects on forms or toolbars. Forms and toolbars themselves do not receive this event.

See Also

MouseLeave Event | Click Event | DblClick Event | MiddleClick Event | MouseMove Event | MousePointer Property | MouseUp Event | MouseWheel Event

Applies To: CheckBox | OptionButton | OptionGroup | CommandButton | CommandGroup | ComboBox | ListBox | Grid | Header | Spinner | TextBox | EditBox | Label | Line | Container Object | Shape | Image | Page | PageFrame Control


MouseLeave Event

Occurs when a mouse cursor exits a control

PROCEDURE Object.MouseLeave
LPARAMETERS nButton, nShift, nXCoord, nYCoord

Parameters

nButton
Contains a number that specifies which button was pressed to trigger the event: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when the mouse is pressed. The valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Modifier key values for nShift

Windows key | Value
SHIFT | 1
CTRL | 2
ALT | 4

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while pressing the mouse button, the nShift argument contains 2. But If the user holds CTRL+ALT while pressing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are expressed in terms of the form's coordinate system in the unit of measurement specified by the ScaleMode property of the form.

Remarks

You can use this and the MouseEnter event to create rollover and mouseover behaviors as in DHTML.

A control receives a MouseLeave event when the user moves the mouse out of the control from a mouse position that was previously inside the control. In the case of overlapping or intersecting controls, the topmost control in the z-order receives the event.

A MouseLeave event is passed to objects on forms or toolbars. Forms and toolbars themselves do not receive this event.

See Also

MouseEnter Event | Click Event | DblClick Event | MiddleClick Event | MouseMove Event | MousePointer Property | MouseUp Event | MouseWheel Event

Applies To: CheckBox | OptionButton | OptionGroup | CommandButton | CommandGroup | ComboBox | ListBox | Grid | Header | Spinner | TextBox | EditBox | Label | Line | Container Object | Shape | Image | Page | PageFrame Control


MouseMove Event

Occurs when the user moves the mouse over an object.

PROCEDURE Object.MouseMove
LPARAMETERS nButton, nShift, nXCoord, nYCoord

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter. Visual FoxPro passes the MouseMove event parameters in the following order:

nButton
Contains a number that specifies which mouse button was being held down as the mouse was moved, as listed in the following table:

Mouse button values for nButton

Windows | nButton Value
Left mouse button | 1
Right mouse button | 2
Middle mouse button | 4

If more than one mouse button is held down as the mouse is moved, nButton contains the sum of the values for the mouse buttons. For example, if both the left and right mouse buttons are pressed, the value of nButton is 3.

nShift
Contains a number specifying the state of modifier keys when the mouse is moved. In Visual FoxPro for Windows, the valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Modifier key values for nShift

Windows key | Value
SHIFT | 1
CTRL | 2
ALT | 4

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, in Visual FoxPro for Windows, if the user holds CTRL while pressing the mouse button, the nShift argument contains 2. But if the user holds CTRL+ALT while pressing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are always expressed in terms of the form's coordinate system, in the unit of measurement specified in the ScaleMode property setting.

The MouseMove event is triggered continually as the mouse pointer moves across objects.

Note You can use MouseDown and MouseUp events to respond to events caused by pressing and releasing mouse buttons. The nButton parameter for MouseMove differs from the nButton parameter for MouseDown and MouseUp. For MouseMove, the nButton parameter indicates the current state of all buttons; a single MouseMove event can indicate that some, all, or no buttons are pressed. For MouseDown or MouseUp, the nButton parameter indicates exactly one button per event. Avoid moving a window inside a MouseMove event procedure; it can cause cascading events and generate run-time errors, such as a stack overflow. MouseMove events are triggered when the window moves underneath the pointer. A MouseMove event can be triggered even if the mouse is stationary.

See Also

Click Event | DblClick Event | MiddleClick Event | MousePointer Property | MouseDown Event | MouseUp Event | MouseWheel Event

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


MouseUp Event

Occurs when the user releases a mouse button.

PROCEDURE Object.MouseUp
LPARAMETERS nButton, nShift, nXCoord, nYCoord

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter. Visual FoxPro passes the MouseUp event parameters in the following order.

nButton
In Visual FoxPro for Windows, contains a number that specifies which button was released to trigger the event: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when the mouse is released. In Visual FoxPro for Windows, the valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Modifier key values for nShift

Windows key | Value
SHIFT | 1
CTRL | 2
ALT | 4

If more than one modifier key is held down when the mouse is released, the nShift argument contains the sum of the values for the modifier keys. For example, in Visual FoxPro for Windows, if the user holds CTRL while releasing the mouse button, the nShift argument contains 2. But if the user holds CTRL+ALT while releasing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are always expressed in terms of the form's coordinate system in the unit of measurement specified by the ScaleMode property of the form.

Remarks

Use a MouseUp procedure to specify actions to occur when a given mouse button is released. Unlike the Click and DblClick events, the MouseUp event makes it possible for you to distinguish between the left, right, and middle mouse buttons. You can also write code for mouse-keyboard combinations that use the modifier keys.

You can use a MouseMove procedure to respond to an event caused by moving the mouse.

Note The nButton argument for MouseDown and MouseUp differs from the nButton argument used for MouseMove. For MouseDown or MouseUp, the nButton argument indicates exactly one button per event; for MouseMove, it indicates the current state of all buttons.

See Also

Click Event | DblClick Event | MiddleClick Event | MouseDown Event | MouseMove Event | MousePointer Property | MouseWheel Event | ScaleMode Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


MouseWheel Event

Occurs when the user rotates the mouse wheel on a mouse device that has a wheel.

PROCEDURE Object.MouseWheel
LPARAMETERS nDirection, nShift, nXCoord, nYCoord

Parameters

You must include an LPARAMETERS or PARAMETERS statement in the event procedure and specify a name for each parameter. Visual FoxPro passes the MouseWheel event parameters in the following order.

nDirection
Contains a mouse device dependent number that indicates the direction the mouse wheel is rotated. A negative value indicates the mouse wheel is rotated backwards; a positive value indicates the mouse wheel is rotated forwards.
nShift
Contains a number specifying the state of modifier keys when the mouse wheel is rotated. The valid modifier keys are the SHIFT, CTRL, and ALT keys.

The values returned in nShift for individual modifier keys are listed in the following table.

Value | Key
1 | SHIFT
2 | CTRL
4 | ALT

If more than one modifier key is held down when the mouse wheel is rotated, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while rotating the mouse wheel, the nShift argument contains 2. But if the user holds CTRL+ALT while rotating the mouse wheel, the nShift argument contains 6.

nXCoord, nYCoord
Contains the current horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the form. These coordinates are always expressed in terms of the form's coordinate system, in the unit of measurement specified in the ScaleMode property setting.

See Also

Click Event | MiddleClick Event | MousePointer Property | MouseDown Event | MouseUp Event

Applies To: CheckBox | Column | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


Moved Event

Occurs when an object is moved to a new position or a container object's Top or Left property settings have been changed programmatically.

PROCEDURE Object.Moved

Remarks

Occurs when an object is moved to a new position or when the settings for the Top or Left properties have been changed in code.

See Also

ColumnOrder Property | Left Property | Top Property

Applies To: Column | Container Object | Control Object | Form | Grid | OLE Bound Control | OLE Container Control | PageFrame | ToolBar


OLECompleteDrag Event

Occurs when data is dropped on the drop target or the OLE drag-and-drop operation is canceled.

PROCEDURE Object.OLECompleteDrag
LPARAMETERS nEffect

Property Values

nEffect
A value passed from the OLEDragDrop event, corresponding to the action performed when data is dropped on the drop target. The following table lists the values for nEffect with a description of each action.
nEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drop target did not accept the data or the drop operation was canceled.
1 | DROPEFFECT_COPY | Data was copied from the drag source to the drop target.
2 | DROPEFFECT_MOVE | Data was moved from the drag source to the drop target.
4 | DROPEFFECT_LINK | Data was linked from the drag source to the drop target.

Remarks

OLECompleteDrag is a drag source event, and is the last event to occur during an OLE drag-and-drop operation. Including NODEFAULT prevents a text move from deleting the text.

This event allows the drag source to determine the action performed on the data on the drop target. The drop target can set nEffect in its OLEDragDrop event and the drag source can perform the appropriate action based on the value of nEffect. For example, if the data was moved to the drop target, the drag source should remove the data from itself.

See Also

OLE Drag-and-Drop Overview | OLEDragDrop Event | OLEDropMode Property | NODEFAULT Command

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OLEDragDrop Event

Occurs when data is dropped on a drop target and the drop target's OLEDropMode property is set to 1 – Enabled.

PROCEDURE Object.OLEDragDrop
LPARAMETERS oDataObject, nEffect, nButton,
 nShift,   nXCoord, nYCoord

Property Values

oDataObject
An object reference to OLE drag-and-drop DataObject, used with the GetData and GetFormat methods to return data and data formats in the DataObject.
nEffect
A value passed to the OLECompleteDrag event, indicating the action performed when data is dropped on the drop target. nEffect is initially a value that indicates the OLE drag-and-drop operations supported by the drag source. Within the OLEDragDrop event you can change the value of nEffect , which is passed to the OLECompleteDrag event. If you change the value of nEffect, be sure to include NODEFAULT in the event code to prevent the default behavior. The following table lists the values for nEffect that you can pass to the OLECompleteDrag event with a description of each action.
nEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drop target did not accept the data or the drop operation was canceled.
1 | DROPEFFECT_COPY | Data was copied from the drag source to the drop target.
2 | DROPEFFECT_MOVE | Data was moved from the drag source to the drop target.
4 | DROPEFFECT_LINK | Data was linked from the drag source to the drop target.
nButton
Contains a number that specifies which mouse button was released to drop the data on the target: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when the mouse was released to drop the data on the drop target. The valid modifier keys are the SHIFT, CTRL, and ALT keys. The values returned in nShift for individual modifier keys are listed in the following table.
nShift | Modifier key
1 | SHIFT
2 | CTRL
4 | ALT

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while releasing the mouse button, the nShift argument contains 2. But If the user holds CTRL+ALT while releasing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the Form when the mouse button was released to drop the data on the drop target. These coordinates are expressed in terms of the Form's coordinate system in the unit of measurement specified by the ScaleMode property of the Form.

Remarks

OLEDragDrop is a drop target event that only occurs when the OLEDropMode property for the control or object is set to 1 – Enabled. This event does not occur if the OLEDropMode property is set to 0 – Disabled or 2 – Pass to Container.

If you perform your own drop processing in the OleDragDrop event, include NODEFAULT to prevent the default drop from occuring. In this case, you must then set the resulting nEffect value.

See Also

OLE Drag-and-drop Overview | OLECompleteDrag Event | OLEDropMode Property | NODEFAULT Command

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLEDragOver Event

Occurs when data is dragged over a drop target and the drop target's OLEDropMode property is set to 1 – Enabled.

PROCEDURE Object.OLEDragOver
LPARAMETERS oDataObject, nEffect, nButton,
 nShift,   nXCoord, nYCoord, nState

Property Values

oDataObject
An object reference to OLE drag-and-drop DataObject, used with the GetData and GetFormat methods to return data and data formats in the DataObject.
nEffect
A value passed to the OLEGiveFeedback event, indicating the action performed if data is dropped on the drop target. nEffect is initially a value that indicates the OLE drag-and-drop operations supported by the drag source. The following table lists the values for nEffect with a description of each action.
nEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drop target doesn't accept the data or the drop operation is canceled.
1 | DROPEFFECT_COPY | Data is copied from the drag source to the drop target.
2 | DROPEFFECT_MOVE | Data is moved from the drag source to the drop target.
4 | DROPEFFECT_LINK | Data is linked from the drag source to the drop target.
nButton
Contains a number that specifies which mouse button is pressed when data is dragged over a drop target: 1 (left), 2 (right), or 4 (middle).
nShift
Contains a number specifying the state of modifier keys when data is dragged over a drop target. The valid modifier keys are the SHIFT, CTRL, and ALT keys. The values returned in nShift for individual modifier keys are listed in the following table.
nShift | Modifier key
1 | SHIFT
2 | CTRL
4 | ALT

If more than one modifier key is held down when the mouse is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while releasing the mouse button, the nShift argument contains 2. But, if the user holds CTRL+ALT while releasing the mouse button, the nShift argument contains 6.

nXCoord, nYCoord
Contains the horizontal (nXCoord) and vertical (nYCoord) position of the mouse pointer within the Form when data is dragged over a drop target. These coordinates are expressed in terms of the Form's coordinate system in the unit of measurement specified by the ScaleMode property of the Form.
nState
Contains a number specifying the direction in which the data is dragged – into the control or object, within the control or object, or out of the control or object. The values for nState are listed in the following table.
nState | Description
0 | Data is dragged into the control or object. The OLEDropEffects and OLEDropHasData properties can be set when nState is zero.
1 | Data is dragged out of the control or object.
2 | Data is dragged within the control or object.

Remarks

OLEDragOver is a drop target event that only occurs when the OLEDropMode property for the control or object is set to 1 – Enabled. This event does not occur if the OLEDropMode property is set to 0 – Disabled or 2 – Pass to Container.

Note that you should avoid creating wait states in the OLEDragOver event with commands and functions such as WAIT WINDOW and MESSAGEBOX( ).

See Also

OLE Drag-and-Drop Overview | OLEGiveFeedBack Event | OLEDropEffects Property | OLEDropHasData Property | OLEDropMode Property

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLEGiveFeedback Event

Occurs after every OLEDragOver event. Allows the drag source to specify the type of OLE drag-and-drop operation and the visual feedback.

PROCEDURE Object.OLEGiveFeedback
LPARAMETERS nEffect, eMouseCursor

Property Values

nEffect
The action performed when data is dropped on the drop target. The value of nEffect is set by the drop target in its OLEDragOver event. The following table lists the values for nEffect with a description of each action.
nEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drop target cannot accept the data.
1 | DROPEFFECT_COPY | Drop results in a copy.
2 | DROPEFFECT_MOVE | Drop results in a move.
4 | DROPEFFECT_LINK | Drop results in a link.
eMouseCursor
Specifies the mouse pointer displayed during the OLE drag-and-drop operation. eMouseCursor can be a character or numeric value. eMouseCursor is an output parameter and is set to zero on entry into event.

If eMouseCursor is a character value, it's assumed that the character value is the name of a graphics file of type .ani, .cur, or .ico. If eMouseCursor is a numeric value, the value specifies the mouse pointer displayed. The following table lists the numeric values for eMouseCursor with a description of each mouse pointer.

eMouseCursor | Foxpro.h constant | Description
0 | MOUSE_DEFAULT | Shape determined by the object. (Default)
1 | MOUSE_ARROW | Arrow.
2 | MOUSE_CROSSHAIR | Cross. A cross-hair pointer.
3 | MOUSE_IBEAM | I-Beam.
4 | MOUSE_ICON_POINTER | Icon. A small white square within a black square.
5 | MOUSE_SIZE_POINTER | Size. A four-pointed arrow pointing north, south, east, west.
6 | MOUSE_SIZE_NE_SW | Size NE SW. A double arrow pointing northeast and southwest.
7 | MOUSE_SIZE_N_S | Size NS. A double arrow pointing north and south.
8 | MOUSE_SIZE_NW_SE | Size NW SE. A double arrow pointing northwest and southeast.
9 | MOUSE_W_E | Size WE. A double arrow pointing west and east.
10 | MOUSE_UP_ARROW | Up Arrow.
11 | MOUSE_HOURGLASS | Hourglass.
12 | MOUSE_NO_DROP | No Drop.
13 | MOUSE_HIDE_POINTER | Hide Pointer.
14 | MOUSE_ARROW2 | Arrow.
15 | MOUSE_ARROW_HOURGLASS | Arrow and hourglass.
16 | MOUSE_ARROW_QUESTION | Arrow and question mark.

Remarks

OLEGiveFeedback is a drag source event that lets you provide visual feedback to the user. You can change the mouse cursor to indicate the operation that occurs when the mouse is positioned over the drag source or the drop target. Including NODEFAULT has no effect on the behavior of this method.

Note that you should avoid creating wait states in the OLEGiveFeedback event with commands and functions such as WAIT WINDOW and MESSAGEBOX( ).

See Also

OLE Drag-and-Drop Overview | OLEDragOver Event | NODEFAULT Command

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | ProjectHook Object | Shape | Spinner | TextBox | ToolBar


OLESetData Event

Occurs on a drag source when a drop target calls the GetData method.

PROCEDURE Object.OLESetData
LPARAMETERS oDataObject, eFormat

Property Values

oDataObject
An object reference to OLE drag-and-drop DataObject, used with the SetData method to place data in the DataObject.
eFormat
A numeric or character value that indicates the format of the data the GetData method requests. The drag source uses this value to determine the format of the data to place in the DataObject. See the GetData method for a table that lists the numeric or character values for each data format and a description of each format.

Remarks

OLESetData is a drag source event. Including NODEFAULT has no effect on the behavior of this method.

The OLESetData event occurs when the GetData method is executed. Within the OLESetData event you can place data in the DataObject in the specified format with the SetData method. This technique is called "delay rendering" and allows you to put data on the DataObject only when it is requested.

See Also

GetData Method | OLE Drag-and-Drop Overview | OLESetData Event | SetData Method | NODEFAULT Command

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OLEStartDrag Event

Occurs when the OLEDrag method is called.

PROCEDURE Object.OLEStartDrag
LPARAMETERS oDataObject, nEffect

Property Values

oDataObject
An object reference to OLE drag-and-drop DataObject. You can call any of the DataObject methods from within the OLEStartDrag event.
nEffect
The OLE drag operations supported by the drag source. The following table lists the values for nEffect with a description of each action. nEffect is an output parameter and is set to three on entry into event, so you should provide the value for nEffect in this event. For example, to allow only copy operations, set nEffect to 1 (DROPEFFECT_COPY).
nEffect | Foxpro.h constant | Description
0 | DROPEFFECT_NONE | Drag source did not support any drag operations.
1 | DROPEFFECT_COPY | Drag source supports Copy operations.
2 | DROPEFFECT_MOVE | Drag source supports Move operations (the default).
4 | DROPEFFECT_LINK | Drag source supports link operations.

A drag source can support multiple drag operations by adding multiple values together for nEffect. For example, if nEffect is 3, the drag source supports both copy and move drag operations (3 = 1 (copy) + 2 (move)).

Remarks

OLEStartDrag is a drag source event. Including NODEFAULT has no effect on the behavior of this method.

See Also

OLE Drag-and-Drop Overview | OLEDrag Method | OLEDragMode Property | NODEFAULT Command

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Form | Grid | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


OnMoveItem Event

Occurs when you select and move an item up or down in a list box using the mouse, keyboard, or programmatically with the MoveItem method.

PROCEDURE OnMoveItem
LPARAMETERS nSource, nShift, nCurrentIndex, nMoveBy

Parameters

nSource
Contains a number that specifies how the event is triggered.
nSource | Description
0 | Keyboard
1 | Left mouse button
2 | Right mouse button
4 | Middle mouse button
8 | Programmatically triggered by the MoveItem method
nShift
Contains a number that specifies which modifier keys, SHIFT, CTRL, and ALT, are also pressed when the mouse button is pressed. The following table lists the values returned by nShift for individual modifier keys.
nShift | Description
1 | SHIFT
2 | CTRL
4 | ALT

If more than one modifier key is held down when the mouse button is pressed, the nShift argument contains the sum of the values for the modifier keys. For example, if the user holds CTRL while pressing the mouse button, the nShift argument contains a value of 2. However, if the user holds down CTRL+ALT while pressing the mouse button, the nShift argument contains a value of 6.

nCurrentIndex
Contains the current index of the item being moved.
nMoveBy
Indicates how many positions the item is being moved. A positive value indicates downward movement. A negative number indicates upward movement.

The nMoveBy parameter always has a value of 1 or -1 if the user is moving a list item using the keyboard. It usually has a value of 1 or -1 if the user is moving a list item using the mouse. However, nMoveBy indicates the position to which the item is moved if the user drags the mouse outside the bounds of the list box and then back to a remote position.

Remarks

OnMoveItem occurs after selecting and moving an item by pressing CTRL+UP ARROW, CTRL+DOWN ARROW or by using the mouse, or when calling the MoveItem method programmatically. OnMoveItem occurs after every subsequent move but before the list box displays the item movement. However, OnMoveItem occurs only once when calling the MoveItem method programmatically.

Note You can move ListBox control items only if the grid's RecordSourceType property is set to 0 (None) or 1 (Value).

To prevent movement from occurring, return False (.F.) from the code in the OnMoveItem event.

See Also

Events | MoveItem Method | RecordSourceType Property | MoverBars Property

Applies To: ListBox Control


Paint Event

Occurs when a form or toolbar is repainted.

PROCEDURE Object.Paint

Remarks

A form or toolbar is repainted when part or all of the form or toolbar is exposed after it has been moved or sized, or after a window that was covering the form or toolbar has been moved.

Using a Refresh method in a Resize event forces repainting of the entire object every time a user resizes the form or toolbar.

Using a Paint event for certain tasks can cause a cascading event. In general, avoid using a Paint event for the following:

  • Moving or sizing a form or control.
  • Changing any variables that affect size or appearance, such as setting an object's BackColor property.
  • Calling the Refresh method.
    Note A Resize event may be more appropriate for some of these tasks.

See Also

Circle Method | ClipControls Property | Line Method | Print Method | PSet Method | Refresh Method | Resize Event

Applies To: Form | ToolBar


ProgrammaticChange Event

Occurs when the value of a control is changed in code.

PROCEDURE Control.ProgrammaticChange

Remarks

Setting Selected or SelectedID properties on a Listbox control fires the Programmatic Change event after setting ListItem or ListItemID properties.

See Also

InteractiveChange Event | Value Property

Applies To: CheckBox | ComboBox | CommandGroup | EditBox | ListBox | OptionGroup | Spinner | TextBox


QueryAddFile Event

Occurs just before a file is added to a project.

PROCEDURE Object.QueryAddFile
LPARAMETERS cFileName

Parameters

cFileName
Contains the name of the file to add to the project. cFileName is passed to the QueryAddFile event after the Add method is executed, you choose Add in the Project Manager, or you choose Add File from the Project menu.

Remarks

Include NODEFAULT in the QueryAddFile event to prevent a file from being added to the project.

See Also

Add Method | QueryModifyFile Event | QueryRemoveFile Event | QueryRunFile Event | QueryNewFile Event | NODEFAULT Command

Applies To: ProjectHook Object


QueryModifyFile Event

Occurs just before a file is modified in a project.

PROCEDURE Object.QueryModifyFile
LPARAMETERS oFile, cClassName

Parameters

oFile
Contains an object reference to the file to modify. oFile is passed to the QueryModifyFile event after the Modify method is executed, you choose Modify in the Project Manager, or you choose Modify File from the Project menu.
cClassName
Contains the name of the class to modify if the file is a .vcx visual class library.

Remarks

Include NODEFAULT in the QueryModifyFile event to prevent a file from being modified in the project.

See Also

Modify Method | QueryAddFile Event | QueryRemoveFile Event | QueryRunFile Event | QueryNewFile Event | NODEFAULT Command

Applies To: ProjectHook Object


QueryNewFile Event

Occurs when the New button is pressed in the Project Manager, just before a file is added to a project.

PROCEDURE Object.QueryNewFile
LPARAMETERS cFileType

Parameters

cFileType
Specifies the file type selected in Project Manager when the New button was pressed. These values are the same as the File object Type property.

QueryNewFile event is also supported on database container items, a special case, by the following cFileType values.

Value | FoxPro.H Constant | File type | Extension
d | FILETYPE_DATABASE | Database | .dbc
D | FILETYPE_FREETABLE | Free table | .dbf
Q | FILETYPE_QUERY | Query | .qpr
K | FILETYPE_FORM | Form | .scx
R | FILETYPE_REPORT | Report | .frx
B | FILETYPE_LABEL | Label | .lbx
V | FILETYPE_CLASSLIB | Visual class Library | .vcx
P | FILETYPE_PROGRAM | Program | .prg
M | FILETYPE_MENU | Menu | .mnx
T | FILETYPE_TEXT | Text file | varies

The following table describes cFileType values for items specific to the DBC container. Except for the DBC table, which adds a table to the project, these items affect only the DBC.

Value | DBC Type | Extension
p | Stored Procedure
t | DBC table | .dbf
c | Connection
r | Remote View
l | Local View

Remarks

Addition of Visual FoxPro libraries (.FLL files) and applications (.APP files) do not call the QueryNewFile event.

Since this event does not directly add files to the project, if you wish to add other files when QueryNewFile is called, you should do this explicitly with your own code, using the Project Objects File Collection Add. For example, you could do this if you wanted the QueryNewFile event to call a Wizard, which you created, when adding a new file of a specific type.

Example

     _VFP.ActiveProject.Files.Add(mynewfile)

See Also

File Object | Type | Project Object | QueryAddFile Event | QueryModifyFile Event | QueryRemoveFile Event | QueryRunFile Event


QueryRemoveFile Event

Occurs just before a file is removed from a project.

PROCEDURE Object.QueryRemoveFile
LPARAMETERS oFile, cClassName, lDeleteFile

Parameters

oFile
Contains an object reference to the file to remove from the project. oFile is passed to the QueryRemoveFile event after the Remove method is executed, you choose Remove in the Project Manager, or you choose Remove File from the Project menu.
cClassName
Contains the name of the class to remove if the file is a .vcx visual class library.
lDeleteFile
Contains a logical value that indicates if the file is to be deleted from disk as well as the project. lDeleteFile contains false (.F.) if Remove (remove from project) is chosen in the dialog that is displayed when you attempt to remove a file from a project. lDeleteFile contains true (.T.) if Delete (remove from project and delete from disk) is chosen in the dialog.

Remarks

Include NODEFAULT in the QueryRemoveFile event to prevent a file from being removed from the project.

See Also

QueryAddFile Event | QueryModifyFile Event | QueryRunFile Event | QueryNewFile Event | Remove Method (File Object) | NODEFAULT Command

Applies To: ProjectHook Object


QueryRunFile Event

Occurs just before a file is executed or a report or label is previewed in a project.

PROCEDURE Object.QueryRunFile
LPARAMETERS oFile

Parameters

oFile
Contains an object reference to the file to execute or preview. oFile is passed to the QueryRunFile event after the Run method is executed, you choose Run or Preview in the Project Manager, or you choose Run File or Preview File from the Project menu.

Remarks

Include NODEFAULT in the QueryRunFile event to prevent a file from being executed or previewed.

See Also

QueryAddFile Event | QueryModifyFile Event | QueryRemoveFile Event | QueryNewFile Event | Run Method | NODEFAULT Command

Applies To: ProjectHook Object


QueryUnload Event

Occurs before a form is unloaded.

PROCEDURE Form.QueryUnload

Remarks

The QueryUnload event occurs before the Destroy event. The ReleaseType property is set prior to the QueryUnload event being called.

The QueryUnload event occurs when CLEAR WINDOWS, RELEASE WINDOWS, or QUIT is executed in code, or when the user double-clicks the window pop-up menu icon or chooses Close from the window pop-up menu on a form.

Note The QueryUnload event does not occur if you issue the RELEASE command on the form in code or invoke the form's Release method.

Issuing NODEFAULT in the QueryUnload event procedure prevents the form from unloading.

See Also

CLEAR | ControlBox Property | DEFINE CLASS | Destroy Event | QUIT | RELEASE | Release Method | RELEASE WINDOWS | ReleaseType Property | Unload Event | Closable Property | NODEFAULT Command

Applies To: Form


RangeHigh Event

For a spinner or text box, occurs when the control loses the focus. For a combo box or list box, occurs when the control receives the focus.

PROCEDURE Object.RangeHigh

Remarks

A RangeHigh event can return a numeric value to Microsoft Visual FoxPro through a RETURN statement. For a spinner or a text box with a numeric value, if the value returned to Visual FoxPro is less than the value entered in the control, the control retains the focus. For a combo box or list box, the value returned to Visual FoxPro specifies which item in the control is initially selected, For example, if 2 is returned to Visual FoxPro, the second item in the control is initially selected.

See Also

KeyboardHighValue, KeyboardLowValue Properties | RangeLow Event | RETURN | SpinnerHighValue, SpinnerLowValue Properties,

Applies To: ComboBox | ListBox | Spinner | TextBox


RangeLow Event

For a spinner or text box, occurs when the control loses the focus. For a combo box or list box, occurs when the control receives the focus.

PROCEDURE Object.RangeLow

Remarks

A RangeLow event can return a numeric value to Visual FoxPro through a RETURN statement. For a spinner or a text box with a numeric value, if the value returned to Visual FoxPro is greater than the value entered in the control, the control retains the focus. For a combo box or list box, the value returned to Visual FoxPro specifies which item in the control is initially selected, For example, if 2 is returned to Visual FoxPro, the second item in the control is initially selected.

See Also

KeyboardHighValue, KeyboardLowValue Properties | RangeHigh Event | RETURN | SpinnerHighValue, SpinnerLowValue Properties

Applies To: ComboBox | ListBox | Spinner | TextBox


ReadActivate Event

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadDeactivate Event

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadShow Event

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadValid Event

Included for backward compatibility with READ. Use the Form Designer instead of READ.


ReadWhen Event

Included for backward compatibility with READ. Use the Form Designer instead of READ.


Resize Event

Occurs when an object is resized.

PROCEDURE Object.Resize

Remarks

You can trigger the Resize interactively or in code by setting the Height and Width properties.

For a Column object, you can trigger Resize in code by setting the Width property for the column.

You can also trigger the Resize event by using event binding. For more information, see Event Binding for Visual FoxPro Objects and BINDEVENT( ) Function.

See Also

Height Property | Paint Event | Width Property | BINDEVENT( ) Function

Applies To: _SCREEN System Variable | Column | Container Object | Control Object | Form | Grid | OLE Bound Control | OLE Container Control | PageFrame | ToolBar


RightClick Event

Occurs when the user clicks the right (secondary) mouse button over a control in Microsoft Windows.

PROCEDURE Control.RightClick

See Also

Click Event | DblClick Event | DragDrop Event | DragOver Event | DropDown Event | Enabled Property | KeyPress Event | MouseDown Event | MouseMove Event | MouseUp Event | Scrolled Event | Undock Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container | Control | EditBox | Form | Grid | Header | Image | Label | Line | ListBox | OptionButton | OptionGroup | Page | PageFrame | Shape | Spinner | TextBox | ToolBar


Scrolled Event

Occurs in a Grid control or form when the horizontal or vertical scroll bars are clicked or a scroll box is moved.

PROCEDURE Object.Scrolled
LPARAMETERS nDirection

Parameters

nDirection
Specifies how the user scrolled through the contents of a Grid control or a form. The possible values are:
Value | User scrolled using…
0 | Up arrow on vertical scroll bar
1 | Down arrow on vertical scroll bar
2 | Vertical scroll bar in area above the scroll box
3 | Vertical scroll bar in area below the scroll box
4 | Left arrow on vertical scroll bar
5 | Right arrow on vertical scroll bar
6 | Horizontal scroll bar in area to the left of the scroll box
7 | Horizontal scroll bar in area to the right of the scroll box

Remarks

The Scrolled event also occurs for a grid if you call the DoScroll method from within a program. The Scrollbars property determines if a form has scroll bars.

Avoid creating wait states (for example, WAIT WINDOW) within the Scrolled event because screen painting problems can occur when the grid or form is scrolled.

The Scrolled event does not fire in reaction to the keyboard arrow keys.

See Also

ActiveColumn Property | ActiveRow Property | DoScroll Method | RelativeColumn Property | RelativeRow Property | ScrollBars Property

Applies To: Form | Grid


Timer Event

Occurs when the number of milliseconds specified in the Interval property has elapsed.

PROCEDURE Timer.Timer

See Also

Interval Property | Reset Method

Applies To: Timer


UIEnable Event

Occurs for all objects contained within a page whenever the page is activated or deactivated.

PROCEDURE Object.UIEnable
LPARAMETERS lEnable

Parameters

lEnable
Contains a logical value that specifies whether the page that the object is contained within is being activated or deactivated. If lEnable is true (.T.), the page that the object is contained within is being activated (becoming the active page). If lEnable is false (.F.), the page is being deactivated (becoming the inactive page).

Remarks

Use the UIEnable event to specify any action you want to occur for an object or control when the page that it is contained within is activated or deactivated.

The UIEnable event does not occur for pages when the form is initially activated. The UIEnable event occurs only when a page is programmatically or interactively activated or deactivated.

See Also

Activate Event | Deactivate Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | Container Object | Control Object | EditBox | Grid | Image | Label | Line | ListBox | OLE Bound Control | OLE Container Control | OptionGroup | PageFrame | Shape | Spinner | TextBox


UnDock Event

Occurs when the toolbar is dragged from its docked position.

PROCEDURE ToolBar.Undock

See Also

AfterDock Event | BeforeDock Event | Dock Method

Applies To: ToolBar


Unload Event

Occurs when an object is released.

Unload is the last event to occur before a form set or form is released.

PROCEDURE Object.Unload

Remarks

Unload occurs after the Destroy event and after all the contained objects have been released. In addition, Unload occurs depending on the type of object:

  • Form objects are released in code when the object variable that refers to the form is released or when its form set is released.
  • Form set objects are released in code when the object variable that refers to the form set is released.

If a container object, such as a form set, contains objects, the Unload event for the container object occurs after the Unload events for the objects it contains. For example, a form set containing one form that contains one control (a CommandButton) is released in this order:

  1. FormSet Destroy event
  2. Form Destroy event
  3. CommandButton Destroy event
  4. Form Unload event
  5. FormSet Unload event

To return a value to the TO VarName clause in the DO FORM command, use the RETURN command in the Unload event. For more information, see DO FORM Command.

See Also

Destroy Event | QueryUnload Event | Destroy Event | DO FORM Command | RETURN Command

Applies To: Form | FormSet


UpClick Event

Occurs when the user clicks the up arrow of a Spinner control or in the drop-down list of a ComboBox control.

PROCEDURE Control.UpClick

See Also

DownClick Event

Applies To: ComboBox | Spinner


Valid Event

Occurs before a control loses the focus.

PROCEDURE Control.Valid

Remarks

If the Valid event returns true (.T.), the control can lose focus - focus might not pass to another control. If the Valid event returns false (.F.), the control does not lose focus.

The Valid event can also return a numeric value. Returning a numeric value has one of three effects:

  • If 0 is returned, the control does not lose focus.
  • If a positive value is returned, the value specifies the number of controls the focus advances.
  • If a negative value is returned, the value specifies the number of controls the focus moves back. For example, if the Valid event returns –1, the previous control gets the focus.

See Also

LostFocus Event | When Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | EditBox | Grid | ListBox | OptionButton | OptionGroup | Spinner | TextBox


When Event

Occurs before a control receives the focus.

PROCEDURE Control.When

Remarks

If the When event returns true (.T.), the default control receives the focus. If the When event returns false (.F.), the control does not receive the focus. The order of events when a control gains the focus is:

  1. When event
  2. GotFocus event

For ListBox controls, the When event occurs each time a user moves the focus between items in the list by clicking on items or by moving the selection with the arrow keys.

Note The Grid control does not have a GotFocus event, so only When fires.

For all other controls, the When event occurs when an attempt is made to move the focus to the control.

See Also

GotFocus Event | Valid Event

Applies To: CheckBox | ComboBox | CommandButton | CommandGroup | EditBox | Grid | ListBox | OptionButton | OptionGroup | Spinner | TextBox


Functions

Visual FoxPro contains functions in the following categories as well as additional functions:

Character Functions
Lists functions that operate on character data.
Data Conversion Functions
Lists functions that convert data from one data type to another.
Date and Time Functions
Lists functions that generate and manipulate date and time data.
COM Functions
Lists the commands and functions that make it possible for you to access COM objects and servers.
Numeric Functions
Lists functions that operate on or return numeric data.
XML Functions
Describes functions that make it possible for data manipulations between Visual FoxPro and Extensible Markup Language (XML) data.
Supported Visual FoxPro Commands and Functions in the OLE DB Provider
Lists commands and functions you can use in the OLE DB Provider.
Unsupported Visual FoxPro Commands and Functions in the OLE DB Provider
Lists commands and functions not supported in the OLE DB Provider.

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

ABS( ) Function

ACLASS( ) Function

ACOPY( ) Function

ACOS( ) Function

ADATABASES( ) Function

ADBOBJECTS( ) Function

ADDBS( ) Function

ADDPROPERTY( ) Function

ADEL( ) Function

ADIR( ) Function

ADLLS( ) Function

ADOCKSTATE( ) Function

AELEMENT( ) Function

AERROR( ) Function

AEVENTS() Function

AFIELDS( ) Function

AFONT( ) Function

AGETCLASS( ) Function

AGETFILEVERSION( ) Function

AINS( ) Function

AINSTANCE( ) Function

ALANGUAGE( ) Function

ALEN( ) Function

ALIAS( ) Function

ALINES( ) Function

ALLTRIM( ) Function

AMEMBERS( ) Function

AMOUSEOBJ( ) Function

ANETRESOURCES( ) Function

APRINTERS( ) Function

APROCINFO( ) Function

ASC( ) Function

ASCAN( ) Function

ASELOBJ( ) Function

ASESSIONS( ) Function

ASIN( ) Function

ASORT( ) Function

ASTACKINFO( ) Function

ASUBSCRIPT( ) Function

AT( ) Function

AT_C( ) Function

ATAGINFO( ) Function

ATAN( ) Function

ATC( ) Function

ATCC( ) Function

ATCLINE( ) Function

ATLINE( ) Function

ATN2( ) Function

AUSED( ) Function

AVCXCLASSES( ) Function

B

BAR( ) Function

BARCOUNT( ) Function

BARPROMPT( ) Function

BETWEEN( ) Function

BINDEVENT() Function

BINTOC( ) Function

BITAND( ) Function

BITCLEAR( ) Function

BITLSHIFT( ) Function

BITNOT( ) Function

BITOR( ) Function

BITRSHIFT( ) Function

BITSET( ) Function

BITTEST( ) Function

BITXOR( ) Function

BOF( ) Function

C

CANDIDATE( ) Function

CAPSLOCK( ) Function

CDOW( ) Function

CDX( ) Function

CEILING( ) Function

CHR( ) Function

CHRSAW( ) Function

CHRTRAN( ) Function

CHRTRANC( ) Function

CMONTH( ) Function

CNTBAR( ) Function

CNTPAD( ) Function

COL( ) Function

COM Functions

COMARRAY( ) Function

COMCLASSINFO( ) Function

COMPOBJ( ) Function

COMPROP( ) Function

COMRETURNERROR( ) Function

COS( ) Function

CPCONVERT( ) Function

CPCURRENT( ) Function

CPDBF( ) Function

CREATEBINARY( ) Function

CREATEOBJECT( ) Function

CREATEOBJECTEX( ) Function

CREATEOFFLINE( ) Function

CTOBIN( ) Function

CTOD( ) Function

CTOT( ) Function

CURDIR( ) Function

CURSORGETPROP( ) Function

CURSORSETPROP( ) Function

CURSORTOXML( ) Function

CURVAL( ) Function

D

DATE( ) Function

DATETIME( ) Function

DAY( ) Function

DBC( ) Function

DBF( ) Function

DBGETPROP( ) Function

DBSETPROP( ) Function

DBUSED( ) Function

DDE Functions

DDEAbortTrans( ) Function

DDEAdvise( ) Function

DDEEnabled( ) Function

DDEExecute( ) Function

DDEInitiate( ) Function

DDELastError( ) Function

DDEPoke( ) Function

DDERequest( ) Function

DDESetOption( ) Function

DDESetService( ) Function

DDESetTopic( ) Function

DDETerminate( ) Function

DEFAULTEXT( ) Function

DELETED( ) Function

DESCENDING( ) Function

DIFFERENCE( ) Function

DIRECTORY( ) Function

DISKSPACE( ) Function

DisplayPath( ) Function

DMY( ) Function

DODEFAULT( ) Function

DOW( ) Function

DRIVETYPE( ) Function

DROPOFFLINE( ) Function

DTOC( ) Function

DTOR( ) Function

DTOS( ) Function

DTOT( ) Function

E

EDITSOURCE( ) Function

EMPTY( ) Function

EOF( ) Function

ERROR( ) Function

EVALUATE( ) Function

EVENTHANDLER( ) Function

EVL( ) Function

EXECSCRIPT( ) Function

EXP( ) Function

F

FCHSIZE( ) Function

FCLOSE( ) Function

FCOUNT( ) Function

FCREATE( ) Function

FDATE( ) Function

FEOF( ) Function

FERROR( ) Function

FFLUSH( ) Function

FGETS( ) Function

FIELD( ) Function

FILE( ) Function

FILETOSTR( ) Function

FILTER( ) Function

FKLABEL( ) Function

FKMAX( ) Function

FLDLIST( ) Function

FLOCK( ) Function

FLOOR( ) Function

FONTMETRIC( ) Function

FOPEN( ) Function

FOR( ) Function

FORCEEXT( ) Function

FORCEPATH( ) Function

FOUND( ) Function

FPUTS( ) Function

FREAD( ) Function

FSEEK( ) Function

FSIZE( ) Function

FTIME( ) Function

FULLPATH( ) Function

FUNCTION Command

FV( ) Function

FWRITE( ) Function

G

GETBAR( ) Function

GETCOLOR( ) Function

GETCP( ) Function

GETDIR( ) Function

GETENV( ) Function

GETFILE( ) Function

GETFLDSTATE( ) Function

GETFONT( ) Function

GETINTERFACE( ) Function

GETNEXTMODIFIED( ) Function

GETOBJECT( ) Function

GETPAD( ) Function

GETPEM( ) Function

GETPICT( ) Function

GETPRINTER( ) Function

GETWORDCOUNT( ) Function

GETWORDNUM( ) Function

GETCURSORADAPTER( ) Function

GOMONTH( ) Function

H

HEADER( ) Function

HOME( ) Function

HOUR( ) Function

I

IDXCOLLATE( ) Function

IIF( ) Function

IMESTATUS( ) Function

INDBC( ) Function

INDEXSEEK( ) Function

INKEY( ) Function

INLIST( ) Function

InputBox( ) Function

INSMODE( ) Function

INT( ) Function

ISALPHA( ) Function

ISBLANK( ) Function

ISCOLOR( ) Function

ISDIGIT( ) Function

ISEXCLUSIVE( ) Function

ISFLOCKED( ) Function

ISLEADBYTE( ) Function

ISLOWER( ) Function

ISMOUSE( ) Function

ISNULL( ) Function

ISREADONLY( ) Function

ISRLOCKED( ) Function

ISUPPER( ) Function

J

JUSTDRIVE( ) Function

JUSTEXT( ) Function

JUSTFNAME( ) Function

JUSTPATH( ) Function

JUSTSTEM( ) Function

K

KEY( ) Function

KEYMATCH( ) Function

L

LASTKEY( ) Function

LEFT( ) Function

LEFTC( ) Function

LEN( ) Function

LENC( ) Function

LIKE( ) Function

LIKEC( ) Function

LINENO( ) Function

LOADPICTURE( ) Function

LOCFILE( ) Function

LOCK( ) Function

LOG( ) Function

LOG10( ) Function

LOOKUP( ) Function

LOWER( ) Function

LTRIM( ) Function

LUPDATE( ) Function

M

MAX( ) Function

MCOL( ) Function

MDOWN( ) Function

MDX( ) Function

MDY( ) Function

MEMLINES( ) Function

MEMORY( ) Function

MENU( ) Function

MESSAGE( ) Function

MESSAGEBOX( ) Function

MIN( ) Function

MINUTE( ) Function

MLINE( ) Function

MOD( ) Function

MONTH( ) Function

MRKBAR( ) Function

MRKPAD( ) Function

MROW( ) Function

MTON( ) Function

MWINDOW( ) Function

N

NDX( ) Function

NEWOBJECT( ) Function

NORMALIZE( ) Function

NTOM( ) Function

NUMLOCK( ) Function

NVL( ) Function

O

OBJNUM( ) Function

OBJTOCLIENT( ) Function

OBJVAR( ) Function

OCCURS( ) Function

OEMTOANSI( ) Function

OLDVAL( ) Function

ON( ) Function

ORDER( ) Function

OS( ) Function

P

PAD( ) Function

PADL( ) | PADR( ) | PADC( ) Functions

PARAMETERS( ) Function

PAYMENT( ) Function

PCOL( ) Function

PCOUNT( ) Function

PEMSTATUS( ) Function

PI( ) Function

POPUP( ) Function

PRIMARY( ) Function

PRINTSTATUS( ) Function

PRMBAR( ) Function

PRMPAD( ) Function

PROGRAM( ) Function

PROMPT( ) Function

PROPER( ) Function

PROW( ) Function

PRTINFO( ) Function

PUTFILE( ) Function

PV( ) Function

Q

Quarter( ) Function

R

RAISEEVENT() Function

RAND( ) Function

RAT( ) Function

RATC( ) Function

RATLINE( ) Function

RDLEVEL( ) Function

READKEY( ) Function

RECCOUNT( ) Function

RECNO( ) Function

RECSIZE( ) Function

REFRESH( ) Function

RELATION( ) Function

REPLICATE( ) Function

REQUERY( ) Function

RGB( ) Function

RGBSCHEME( ) Function

RIGHT( ) Function

RIGHTC( ) Function

RLOCK( ) Function

ROUND( ) Function

ROW( ) Function

RTOD( ) Function

RTRIM( ) Function

S

SAVEPICTURE( ) Function

SCHEME( ) Function

SCOLS( ) Function

SEC( ) Function

SECONDS( ) Function

SEEK( ) Function

SELECT( ) Function

SET( ) Function

SETFLDSTATE( ) Function

SIGN( ) Function

SIN( ) Function

SKPBAR( ) Function

SKPPAD( ) Function

SOUNDEX( ) Function

SPACE( ) Function

SQLCANCEL( ) Function

SQLCOLUMNS( ) Function

SQLCOMMIT( ) Function

SQLCONNECT( ) Function

SQLDISCONNECT( ) Function

SQLEXEC( ) Function

SQLGETPROP( ) Function

SQLMORERESULTS( ) Function

SQLPREPARE( ) Function

SQLROLLBACK( ) Function

SQLSETPROP( ) Function

SQLSTRINGCONNECT( ) Function

SQLTABLES( ) Function

SQRT( ) Function

SROWS( ) Function

STR( ) Function

STRCONV( ) Function

STREXTRACT( ) Function

STRTOFILE( ) Function

STRTRAN( ) Function

STUFF( ) Function

STUFFC( ) Function

SUBSTR( ) Function

SUBSTRC( ) Function

SYS( ) Functions Overview

SYSMETRIC( ) Function

T

TABLEREVERT( ) Function

TABLEUPDATE( ) Function

TAG( ) Function

TAGCOUNT( ) Function

TAGNO( ) Function

TAN( ) Function

TARGET( ) Function

TEXTMERGE( ) Function

TIME( ) Function

TRANSFORM( ) Function

TRIM( ) Function

TTOC( ) Function

TTOD( ) Function

TXNLEVEL( ) Function

TXTWIDTH( ) Function

TYPE( ) Function

U

UNBINDEVENTS() Function

UNIQUE( ) Function

UPDATED( ) Function

UPPER( ) Function

USED( ) Function

V

VAL( ) Function

VARREAD( ) Function

VARTYPE( ) Function

VERSION( ) Function

W

WBORDER( ) Function

WCHILD( ) Function

WCOLS( ) Function

WDOCKABLE( ) Function

WEEK( ) Function

WEXIST( ) Function

WFONT( ) Function

WLAST( ) Function

WLCOL( ) Function

WLROW( ) Function

WMAXIMUM( ) Function

WMINIMUM( ) Function

WONTOP( ) Function

WOUTPUT( ) Function

WPARENT( ) Function

WREAD( ) Function

WROWS( ) Function

WTITLE( ) Function

WVISIBLE( ) Function

X

XMLTOCURSOR( ) Function

XMLUPDATEGRAM( ) Function

Y

YEAR( ) Function

Z

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


Character Functions

These functions operate on character data.

$ Operator

ALLTRIM( ) Function

ASC( ) Function

AT( ) Function

AT_C( ) Function

ATC( ) Function

ATCC( ) Function

ATCLINE( ) Function

ATLINE( ) Function

BETWEEN( ) Function

CHR( ) Function

CHRTRAN( ) Function

CHRTRANC( ) Function

CPCONVERT( ) Function

CTOD( ) Function

DIFFERENCE( ) Function

DTOC( ) Function

EMPTY( ) Function

EVALUATE( ) Function

GETWORDCOUNT( ) Function

GETWORDNUM( ) Function

INLIST( ) Function

ISALPHA( ) Function

ISDIGIT( ) Function

ISLEADBYTE( ) Function

ISLOWER( ) Function

ISUPPER( ) Function

LEFT( ) Function

LEFTC( ) Function

LEN( ) Function

LENC( ) Function

LIKE( ) Function

LIKEC( ) Function

LOWER( ) Function

LTRIM( ) Function

MAX( ) Function

MIN( ) Function

NORMALIZE( ) Function

OCCURS( ) Function

PADL( ) | PADR( ) | PADC( ) Functions

PROPER( ) Function

RAT( ) Function

RATC( ) Function

RATLINE( ) Function

REPLICATE( ) Function

RIGHT( ) Function

RIGHTC( ) Function

RTRIM( ) Function

SOUNDEX( ) Function

SPACE( ) Function

STR( ) Function

STRCONV( ) Function

STRTOFILE( ) Function

STRTRAN( ) Function

STUFF( ) Function

STUFFC( ) Function

SUBSTR( ) Function

SUBSTRC( ) Function

SYS(10) - String from Julian Day Number

SYS(15) - Character Translation

SYS(2007) - Checksum Value

TEXTMERGE( ) Function

TRANSFORM( ) Function

TRIM( ) Function

TXTWIDTH( ) Function

TYPE( ) Function

UPPER( ) Function

VARTYPE( ) Function


Data Conversion Functions

These functions convert data from one data type to another.

CHR( ) Function

CTOD( ) Function

CURVAL( ) Function

CURSORToXML( ) Function

DTOC( )

MTON( ) Function

NTOM( ) Function

NVL( ) Function

STR( )

SYS(10) - String from Julian Day Number

SYS(15) - Character Translation

TEXTMERGE( ) Function

TRANSFORM( ) Function

TTOC( ) Function

TTOD( ) Function

VAL( ) Function

VARTYPE( ) Function


Date and Time Functions

These functions generate and manipulate date and time data.

BETWEEN( ) Function

CDOW( ) Function

CMONTH( ) Function

CTOD( ) Function

CTOT( ) Function

DATE( ) Function

DATETIME( ) Function

DAY( ) Function

DMY( ) Function

DOW( ) Function

DTOC( ) Function

DTOS( ) Function

DTOT( ) Function

EMPTY( ) Function

FDATE( ) Function

FTIME( ) Function

GOMONTH( ) Function

HOUR( ) Function

INLIST( ) Function

MAX( ) Function

MDY( ) Function

MIN( ) Function

MINUTE( ) Function

MONTH( ) Function

QUARTER( ) Function

SEC( ) Function

SECONDS( ) Function

SET HOURS Command

SET MARK TO Command

SET SECONDS Command

SYS(1) - Julian System Date

SYS(2) - Seconds Since Midnight

SYS(10) - String from Julian Day Number

SYS(11) - Julian Day Number

TIME( ) Function

TTOC( ) Function

TTOD( ) Function

WEEK( ) Function

YEAR( ) Function


COM Functions

These functions make it possible for you to access COM objects and servers.

COMCLASSINFO( ) Function

COMARRAY( ) Function

COMRETURNERROR( ) Function

COMPROP( ) Function

CREATEOBJECT( ) Function

CREATEOBJECTEX( ) Function

GETOBJECT( ) Function

DEFINE CLASS Command

GETINTERFACE( ) Function

EVENTHANDLER( ) Function


Numeric Functions

These functions operate on or return numeric data.

% Operator

ABS( ) Function

ACOS( ) Function

ASIN( ) Function

ATAN( ) Function

ATN2( ) Function

BETWEEN( ) Function

BITAND( ) Function

BITCLEAR( ) Function

BITLSHIFT( ) Function

BITNOT( ) Function

BITOR( ) Function

BITRSHIFT( ) Function

BITSET( ) Function

BITTEST( ) Function

BITXOR( ) Function

CALCULATE Command

CEILING( ) Function

COS( ) Function

DTOR( ) Function

EMPTY( ) Function

EXP( ) Function

FLOOR( ) Function

FV( ) Function

INLIST( ) Function

INT( ) Function

LOG( ) Function

LOG10( ) Function

MAX( ) Function

MIN( ) Function

MOD( ) Function

PAYMENT( ) Function

PI( ) Function

PV( ) Function

RAND( ) Function

ROUND( ) Function

RTOD( ) Function

SET DECIMALS Command

SIGN( ) Function

SIN( ) Function

SQRT( ) Function

TAN( ) Function

VAL( ) Function


XML Functions

You can more easily implement data exchange through XML formatting by using functions such as XMLUPDATEGRAM( ), CURSORTOXML( ), and XMLTOCURSOR( ). Whether you import XML data using XMLTOCURSOR( ) or export data using CURSORTOXML( ), your XML documents are valid when they are well-formed.

Note The MSXML parser is required to use XML functions in Visual FoxPro.

Well-Formed Documents

Any XML document produced by Visual FoxPro is well-formed, which means that it conforms to the basic rules of XML:

  • Each XML document must have a unique root element (an element encompassing the entire document).
  • All start and end tags match. XML tags are case-sensitive.
  • For each start tag, a corresponding end tag exists. Empty elements can be denoted by a special shorthand tag.
  • Elements do not overlap. In other words, start and end tags must be properly nested within other elements.
  • Certain reserved characters are part of the XML syntax and are not interpreted as themselves if used in the data portion of an element. You need to substitute a special character sequence, referred to as "entity" in XML, as follows:
    Character Data type Entity encoding
    & (ampersand)
    < (left angle bracket)
    > (right angle bracket)
    " (quotation mark)
    ' (apostrophe)     		String
    String
    String
    String
    String     		Replace with &amp;
    Replace with &lt;
    Replace with &gt;
    Replace with &quot;
    Replace with &apos;

    For other data types, entity encoding follows these rules:

    Data type | Character and entity encoding
    Date | Must follow the ISO 8601 format
    Numbers | Punctuation must use U.S. English rules. For example, you must use a period as a decimal separator. Numbers can include exponents.
    Boolean | False = 0, True = 1. (SQL XML returns 0 and1)
    BLOB | Use MIME Base64 encoding

The following is an example of a well-formed XML document:

<?xml version="1.0"?>
<Data>
<ORDER>
 <CUSTOMER>Nancy Davolio</CUSTOMER>
  <ITEM>Mom&apos;s Boston Crab Meat</ITEM>
 <PRICE>$10.00</PRICE>
 <QUANTITY>1 Bottle</QUANTITY>
 </ORDER>
</Data>

where:

<?xml version="1.0"?>
Specifies a declaration that this is an XML document and gives the version number. The declaration is optional, but recommended in any XML document.
<ORDER>
Specifies the root element, which encompasses the entire document.
<CUSTOMER> ... </CUSTOMER>
Specifies a start tag and an end tag set, which together describes an element of data, in this case, the customer's name.
Note Each tag set, such as <CUSTOMER> ... </CUSTOMER>, has both start and end tags, is case sensitive, and is properly nested. Also notice the entity &apos; which will be transformed to an apostrophe (') when the data is imported by the receiving application. The apostrophe has a special purpose in an XML document, and can be misinterpreted if used directly in the text. The converted data will be displayed as Mom's Boston Crab Meat.

You can use white space throughout the document to enhance readability.

If you specify a schema while exporting from Visual FoxPro, the exported XML documents are considered to be valid XML. This means that in addition to being well-formed, the documents conform to a defined schema.

When you import XML using XMLTOCURSOR( ), Visual FoxPro uses an external or internal schema to determine the cursor or table structure. When no schema is provided, Visual FoxPro uses a "best guess" method to interpret XML data. This involves two passes through the XML, one to determine data structure and one to perform the actual conversion. Note that the XML, in addition to being well-formed, must generally conform to a format that can be interpreted as a table. Well-formed XML that is not easily deconstructed into a table format will fail to import.

Schemas

Schemas describe the structure of data in a common format that customers, other Web browsers, and any number of XML-enabled software programs can recognize. The description defines the rules of an XML data document including element names and data types, which elements can appear in combination, and which attributes are available for each element. Schemas provide a model for an XML data document which defines the arrangement of tags and text within all documents referencing the schema. Visual FoxPro supports XML Schema Definition (XSD), a basic infrastructure for describing the type and structure of XML documents.

By using a schema you can ensure that any XML document that is used to import or export data contains specific data and conforms to a defined structure. You can also provide the schema to other businesses and applications so that they can structure any data they provide to you and they, in turn, can provide their schema to you.

Visual FoxPro supports the W3C XSD schema format. Following is an example of XSD schema as output by CURSORTOXML( ) function:

<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<xsd:schema id="VFPSchema" targetNamespace="http://microsoft.com" xmlns="http://microsoft.com" xmlns:xsd="http://www.w3.org/2000/10/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" elementFormDefault="qualified">
   <xsd:element name="atxm">
      <xsd:complexType>
         <xsd:all>
            <xsd:element name="ikey" minOccurs="0" type="xsd:int"/>
            <xsd:element name="nc00" minOccurs="0">
               <xsd:simpleType>
                  <xsd:restriction base="xsd:decimal">
                     <xsd:precision value="10"/>
                     <xsd:scale value="4"/>
                  </xsd:restriction>
               </xsd:simpleType>
            </xsd:element>
            <xsd:element name="mc03" minOccurs="0">
               <xsd:simpleType>
                  <xsd:restriction base="xsd:string">
                     <xsd:maxLength value="2147483647"/>
                  </xsd:restriction>
               </xsd:simpleType>
            </xsd:element>
            <xsd:element name="cc04" minOccurs="0">
               <xsd:simpleType>
                  <xsd:restriction base="xsd:string">
                     <xsd:maxLength value="128"/>
                  </xsd:restriction>
               </xsd:simpleType>
            </xsd:element>
            <xsd:element name="lc05" minOccurs="0" type="xsd:boolean"/>
            <xsd:element name="fc06" minOccurs="0" type="xsd:double"/>
            <xsd:element name="yc07" minOccurs="0" type="xsd:decimal"/>
            <xsd:element name="ic08" minOccurs="0" type="xsd:int"/>
            <xsd:element name="bc09" minOccurs="0" type="xsd:double"/>
            <xsd:element name="dc10" minOccurs="0" type="xsd:date"/>
            <xsd:element name="tc11" minOccurs="0"
type="xsd:timeInstant"/>
            <xsd:element name="ts12" minOccurs="0">
               <xsd:simpleType>
                  <xsd:restriction base="xsd:binary">
                     <xsd:encoding value="base64"/>
                  </xsd:restriction>
               </xsd:simpleType>
            </xsd:element>
         </xsd:all>
      </xsd:complexType>
   </xsd:element>
   <xsd:element name="VFPData" msdata:lsDataSet="true">
      <xsd:complexType>
         <xsd:choice maxOccurs="unbounded">
            <xsd:element ref="atxm"/>
         </xsd:choice>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

The XSD schema format is based on the May 2, 1991 W3C Recommendation of the XSD Schema specification: "Primer, Structures, and Datatypes". For details, see http://www.w3.org/TR/2001/REC-xmlschema-0-20010502/ and related documents.

Currently, Visual FoxPro exports XML in the following formats:

  • Element-centric Each field in a resulting or source cursor or table is represented by a subelement of the top-level element.
    <?xml version="1.0" encoding="Windows-1252" standalone="yes" ?>
<!-- Note targetNamespace in root (VfpData) element. If set to default (""), xmlns attrib is not written -->
<VfpData xmlns="http://www.microsoft.com">
   <alltypesxm>
      <ikey>2</ikey>
      <nc00>1.1111</nc00>
      <mc03>H1111111111111111111</mc03>
      <cc04>H111111111111111111</cc04>
      <lc05>true</lc05>
      <fc06>-1111000</fc06>
      <yc07>-111111111.1111</yc07>
      <ic08>-11111111</ic08>
      <bc09>-111111111111.1</bc09>
      <dc10>1999-03-02T08:00:00</dc10>
      <tc11>1999-03-02T09:01:01</tc11>
      <ts12>AAAAAAAAAr8=</ts12>
   </alltypesxm>
</VfpData>
  • Attribute-centric The cursor is identified by the keyword "VFPData" and each field in a resulting or source cursor or table is represented by an attribute of the VFPData element.
    <?xml version="1.0" encoding="Windows-1252" ?>
<!-- Note targetNamespace in root element -->
<VFPData xmlns="http://www.microsoft.com">
   <atxm_attr ikey="2" nc00="12345.1111"
      mc03="H1111111111111111111" cc04="H111111111111111111" lc05="1"
      fc06="-1111000.0000" yc07="-111111111.1111" ic08="-11111111"
      bc09="-111111111111.100000" dc10="1999-03-02"
      tc11="1999-03-02T01:01:01" ts12="AAAAAAAAAr0=" />
   <atxm_attr ikey="3" nc00="2.1111" mc03="H2222222222222222222"
      cc04="H222222222222222222" lc05="1" fc06="22220000.0000"
      yc07="2222222222.2222" ic08="222222222"
      bc09="222222222222.2200000"
      tc11="2000-10-03T02:02:02" ts12="AAAAAAAAAr8=" />
</VFPData>
  • Raw Each row in a resulting or source cursor or table is represented by an XML element with the generic identifier "row", and each column value is mapped to an attribute of the row element where the attribute name is equal to the column name. This format is identical to Attribute-centric except for "row" as the name of the top-level element.
    <?xml version="1.0"?>
<!-- Note no targetNamespace in root element -->
<VFPData>
   <row CustomerID="CACTU" CompanyName="Cactus Comidas para llevar"
      ContactName="Patricio Simpson" ContactTitle="Sales Agent"
      Address="Cerrito 333" City="Buenos Aires" PostalCode="1010"
      Country="Argentina" Phone="(1) 135-5555" Fax="(1) 135-4892"/>
</VFPData>

Data Type Mapping

The following table describes the mapping of Visual FoxPro data to XSD types.

Visual FoxPro type | XSD type | Comments
Character String with restriction
<xsd:maxLength value="128"/>
Currency | Decimal
Numeric Decimal with restriction
 <xsd:precision value="10"/>
      <xsd:scale value="4"/>
 Precision is the number of digits excluding the decimal point.
Float Decimal with restriction
<xsd:precision value="10"/>
      <xsd:scale value="4"/>
Date | date
DateTime | timeInstant
Double | double
Integer | int
Logical | boolean
Memo String with restriction
<xsd:maxLength value="2147483647"/>
General | Not supported
Character (binary) Binary with restriction
<xsd:encoding value="base64"/>
Memo (binary) Binary with restriction
<xsd:encoding value="base64"/>

See Also

CURSORTOXML( ) Function | XMLTOCURSOR( ) Function | XMLUPDATEGRAM( ) Function | VFPXMLProgID Property


$ Operator

Returns True (.T.) if a character expression is contained in another character expression; otherwise, returns False (.F.).

cSearchFor $ cSearchIn

Return Values

Logical

Parameters

cSearchFor
Specifies the expression looked for within cSearchIn.
cSearchIn
Specifies the expression that is searched to see if it contains cSearchFor.

If cSearchFor is found in cSearchIn, $ returns True (.T.); otherwise, it returns False (.F.). cSearchFor and cSearchIn can be character-type variables or array elements, character-type fields, character string literals, or memo fields of any length.

Memo fields can be manipulated like character expressions, fields in tables, variables, or array elements. For example, if MEMO_FLD is a memo field, the following is acceptable:

LIST FOR 'FOX' $ UPPER(memo_fld)

Remarks

If the character expression is not found, False (.F.) is returned. The $ operator is case-sensitive and is not Rushmore optimizable.

Example

The following example creates a table called memotest containing one memo field. Three records are appended to the table. LIST is used to display the three records. The dollar sign ($) is used to list the records that contain the string "FOX". The files created for the example are then deleted.

CLOSE DATABASES
CLEAR
CREATE TABLE memotest (Text C(3), Memo M)
INSERT INTO  memotest (Text, Memo) VALUES ('Fox', 'Fox')
INSERT INTO  memotest (Text, Memo) VALUES ('Cat', 'Cat')
INSERT INTO  memotest (Text, Memo) VALUES ('FOX', 'FOX')
LIST FIELDS  Memo, Text FOR 'FOX' $ UPPER(Memo)
USE
DELETE FILE memotest.dbf
DELETE FILE memotest.fpt

See Also

% Operator | DELETE FILE Command | CREATE TABLE – SQL Command | Using Rushmore Query Optimization to Speed Data Access | AT( ) | Operators | ATLINE( ) | RAT( ) | RATLINE( ) | OCCURS( ) | INLIST( ) Function


% Operator

Returns the remainder (modulus) obtained by dividing one numeric expression into another.

nDividend % nDivisor

Parameters

nDividend
Specifies the dividend (numeric expression being divided). The number of decimal places in nDividend determines the number of decimal places in the result.
nDivisor
Specifies the divisor (the numeric expression dividing the dividend nDividend). A positive number is returned if nDivisor is positive; a negative number if nDivisor is negative. nDivisor cannot be zero.

Remarks

The modulus operator (%) and MOD( ) return identical results.

The modulus operator (%) is an arithmetic operator. Other arithmetic operators are: + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation). When these operators are combined in a numeric expression, % has the same precedence as * and /.

For a further discussion of operators and their order of precedence, see the Operators topic.

Example

? 36 % 10         && Displays 6
? (4*9) % (90/9)      && Displays 6
? 25.250 % 5.0      && Displays 0.250
? IIF(YEAR(DATE( )) % 4 = 0, 'Summer Olympics this year';
   , 'No Summer Olympics this year')

See Also

MOD( ) Function | $ Operator | Operators | Numeric Operators | Creating Numeric Expressions


:: Scope Resolution Operator

Runs a parent class method from within a subclass method.

cClassName::cMethod

Remarks

The :: operator is used to execute a parent class method from within a subclass method. When you create a subclass, the subclass methods are automatically inherited from the parent class. The :: operator makes it possible for you to execute the parent class method in the subclass method and then perform additional processing for the subclass method. The subclass definitions in the example demonstrate how the :: operator is used to execute the parent class method within a subclass method.

For additional information about the :: scope resolution operator, see Object-Oriented Programming.

Example

The following example creates a form and adds two command buttons to the form. By clicking either button, you can exit the form – the second button, cmdAnotherButton, calls the Click procedure from cmdQuit. This action is possible because of subclassing. The scope resolution operator calls the parent class code for the subclassed object.

frmMyForm = CREATEOBJECT("Form")
frmMyForm.Width  = 450
frmMyForm.Height   = 100
frmMyForm.Caption  = "Scope Resolution Example"
frmMyForm.AutoCenter =.T.
frmMyForm.AddObject("cmdQuit","cmdQuitButton")
frmMyForm.AddObject("cmdAnother","cmdAnotherButton")
frmMyForm.SHOW       && Display the form
READ EVENTS        && Start event processing

The following example defines two command buttons. The first button will be used to subclass the second button. The subclassing can be seen by the FontBold and ForeColor properties which are defined for cmdQuit, but never explicitly set for the cmdAnotherButton. We are defining cmdAnotherButton to be a subclass of the cmdQuitButton. As a result, this button will pick up all the attributes defined above for cmdQuitButton.

DEFINE CLASS cmdQuitButton AS CommandButton
  Caption  = "\<Quit"   && Caption on command button
  Left   = 175    && Left edge of button
  Top    = 60     && Position for top of button
  Height   = 25     && Button height
  Visible  = .T.    && Show button on form
  FontItalic = .T.    && Turn on italic text
  ForeColor  = RGB(0,0,255) && Change button text color

  PROCEDURE Click
  WAIT WINDOW "Executing the CLICK procedure for cmdQuit." TIMEOUT 1
  CLEAR EVENTS     && Stop event processing
ENDDEFINE
DEFINE CLASS cmdAnotherButton AS cmdQuitButton

  Caption = "Click to quit"
  Left  = 175
  Top   = 30
  Height  = 25

  PROCEDURE Click
  WAIT WINDOW "Click event for button: cmdAnotherButton" TIMEOUT 1
  cmdQuitButton::Click
ENDDEFINE

See Also

ADD CLASS Command | CREATE CLASS Command | CREATE CLASSLIB Command | CREATEOBJECT( ) Function | DEFINE CLASS Command | DODEFAULT( ) Function | GETOBJECT( ) Function | MODIFY CLASS Command | RELEASE CLASSLIB Command | SET CLASSLIB Command | WITH ... ENDWITH Command


ABS( ) Function

Returns the absolute value of the specified numeric expression.

ABS(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression whose absolute value ABS( ) returns.

Example

? ABS(-45)       && Displays 45
? ABS(10-30)     && Displays 20
? ABS(30-10)     && Displays 20
STORE 40 TO gnNumber1
STORE 2 TO gnNumber2
? ABS(gnNumber2-gnNumber1)     && Displays 38

See Also

INT( ) Function | ROUND( ) Function | SIGN( ) Function


ACLASS( ) Function

Places an object's class name and its ancestor class names into a variable array.

ACLASS(ArrayName, oExpression)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array into which the class names are placed. If you specify the name of an array that doesn't exist, Microsoft Visual FoxPro automatically creates the array. If you specify the name of an existing array that isn't large enough to hold all the parent names, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, the array size is truncated. If you specify the name of an existing two-dimensional array, the array is redimensioned to a one-dimensional array.
oExpression
Specifies an object whose class name and ancestor class names are placed into the array. oExpression can be any object expression, such as an object reference, an object variable, or an object array element.

Remarks

ACLASS( ) creates a one-dimensional array containing the class name of the specified object and its ancestor class names. The first array element contains the class name of the object, the second element contains the name of the object's parent class, the third element contains the name of the object's grandparent class, and so on.

ACLASS( ) returns the number of class names in the array. ACLASS( ) returns 0 if the array cannot be created.

Example

The following example creates two custom classes named FormChild and FormGrandChild from the Visual FoxPro Form base class. ACLASS( ) is used to create an array named gaNewarray containing the class names, which are then displayed.

CLEAR
frmMyForm = CREATEOBJECT("FormGrandChild")
FOR nCount = 1 TO ACLASS(gaNewarray, frmMyForm)    && Creates an array
   ? gaNewarray(nCount)  && Displays the names of the classes
ENDFOR
RELEASE frmMyForm

DEFINE CLASS FormChild AS FORM
ENDDEFINE

DEFINE CLASS FormGrandChild AS FormChild
ENDDEFINE

See Also

ADD CLASS Command | AMEMBERS( ) Function | CREATE CLASS Command |CREATE CLASSLIB Command | CREATEOBJECT( ) Function | DEFINE CLASS Command


ACOPY( ) Function

Copies elements from one array to another array.

ACOPY(SourceArrayName, DestinationArrayName
[, nFirstSourceElement [, nNumberElements [, nFirstDestElement ]]])

Return Values

Numeric

Parameters

SourceArrayName, DestinationArrayName
Specifies the source array SourceArrayName from which elements are copied one-to-one to the destination array DestinationArrayName. The elements in the source array replace the elements in the destination array.

The arrays can be one- or two-dimensional. If the destination array doesn't exist, Visual FoxPro automatically creates it. In such a case, the size of the destination array will be the same as that of the source array. If the destination array already exists, it is redimensioned to the size of the source array.

Note You can refer to an element in a two-dimensional variable array in two ways: The first uses two subscripts to specify the row and column position of the element in the array; the other uses a single-element number. This function and others that manipulate two-dimensional arrays require single-element numbers (here, nFirstSourceElement and nFirstDestElement). Use AELEMENT( ) to return the proper element number for a two-dimensional array from its row and column subscripts.
nFirstSourceElement
Specifies the first element number in the source array to be copied; inclusive (element number nFirstSourceElement is included in the copying). If nFirstSourceElement isn't included, copying begins with the first element in the source array.
nNumberElements
Specifies the number of elements copied from the source array. If nNumberElements is –1, all elements of the source array beginning with element nFirstSourceElement are copied.
nFirstDestElement
Specifies the first element in the destination array to be replaced.

Remarks

ACOPY( ) returns the number of elements copied to the destination array.

Example

The following example creates an array from selected records in the customer table and then uses ACOPY( ) to create a new array.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

SELECT DISTINCT company ;
   FROM customer ;
   ORDER BY company ;
   WHERE country = 'Germany';
   INTO ARRAY gaCompanies
= ACOPY(gaCompanies, gaCompaniesTemp)  && Make a copy of the array
CLEAR
DISPLAY MEMORY LIKE gaCompaniesTemp

See Also

ADEL( ) Function | AELEMENT( ) Function | AINS( ) | ASCAN( ) Function | ASORT( ) Function | DIMENSION Command


ACOS( ) Function

Returns the arc cosine of a specified numeric expression.

ACOS(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies a numeric expression whose arc cosine ACOS( ) returns. The value of nExpression can range from –1 through +1. The value returned by ACOS( ) ranges from 0 through pi (3.141592). The number of decimal places ACOS( ) returns is determined by SET DECIMALS.

Use RTOD( ) to convert radians to degrees.

Remarks

The arc cosine is returned in radians.

Example

CLEAR
? RTOD(ACOS(0))  && Displays 90.00
STORE -1 to gnArcAngle
? RTOD(ACOS(gnArcAngle))  && Displays 180.00
? RTOD(ACOS(SQRT(2)/2))  && Displays 45.00

See Also

ASIN( ) Function | ATAN( ) Function | ATN2( ) Function | ACOS( ) Function | DTOR( ) Function | RTOD( ) Function | SET DECIMALS Command | SIN( ) Function | TAN( ) Function


ADATABASES( ) Function

Places the names of all open databases and their paths into a variable array.

ADATABASES(ArrayName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the database information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists and ADATABASES( ) returns 0 because no databases are open, an existing array remains unchanged. If the array doesn't exist, and ADATABASES( ) returns 0, the array is not created.

Remarks

The names of all open databases are placed into a variable array.

ADATABASES( ) creates a two-dimensional array. The first column of the array contains the names of the open databases, and the second column contains the paths to the databases.

ADATABASES( ) returns the number of database names (rows) in the array. If no databases are open, ADATABASES( ) returns 0 and the array isn't created.

Example

The following example opens the testdata database, and then uses ADATABASES( ) to create an array named gaDatabase containing the names of all open databases.

SET PATH TO (HOME(2) + 'data\')     && Sets path to database
OPEN DATABASE testdata && Opens the database
CLEAR
? ADATABASES(gaDatabase)     && Creates an array of open databases
DISPLAY MEMORY LIKE gadatabase  && Displays the contents of the array
CLOSE DATABASES

See Also

CREATE DATABASE | DISPLAY DATABASE | LIST DATABASE | MODIFY DATABASE | OPEN DATABASE


ADBOBJECTS( ) Function

Places the names of named connections, relations, tables, or SQL views in the current database into a variable array.

ADBOBJECTS(ArrayName, cSetting)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array in which the names are placed. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the names, Visual FoxPro automatically increases the size of the array to accommodate the names. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists and ADBOBJECTS( ) returns 0 because no names are found, the array remains unchanged. If the array doesn't exist, and ADBOBJECTS( ) returns 0, the array is not created.

A one-dimensional array is created when you specify CONNECTION, TABLE, or VIEW for cSetting. Each row in the one-dimensional array contains the name of a connection, table, or view in the database.

A two-dimensional array is created when you specify RELATION for cSetting. Each row in the two-dimensional array corresponds to a relationship in the database. The first column in an array row contains the name of the child table and the second column in an array row contains the name of the parent table. The third column contains the name of the index tag for the child table and the fourth column contains the name of the index tag for the parent table.

The fifth column in an array row contains referential integrity information. This column is empty if the relation has no referential integrity rules. If the relationship does have referential integrity rules, the column contains characters corresponding to the type of referential integrity rules for updates, deletions, and insertions.

The first character indicates the type of update rule, the second character indicates the type of deletion rule, and the third character indicates the type of insertion rule.

Possible values for updates and deletions are "C" for cascade, "R" for restrict, and "I" for ignore. Possible values for insertions are "R" for restrict, and "I" for ignore. For example, if a relation has cascaded updates, restricted deletions, and ignores insertion referential integrity rules, the column contains "CRI".

cSetting
Specifies the names to place in the variable array. The following table lists the values for cSetting and the corresponding names placed in the array:
cSetting | Names
CONNECTION | Connection names
RELATION | Table relationships
TABLE | Table names
VIEW | View names

The CONNECTION, RELATION, TABLE, and VIEW settings cannot be abbreviated.

Remarks

A database must be open and current when ADBOBJECTS( ) is issued; otherwise Visual FoxPro generates an error message.

Example

The following example opens the testdata database and uses ADBOBJECTS( ) to create an array named gaTables containing names of tables in the database. The tables names are then displayed.

* Close any open databases
CLOSE DATABASES

* Clear desktop to prepare for displaying the array
CLEAR

* Open sample testdata database
OPEN DATABASE (HOME(2) + 'Data\testdata')

* Function call with cSetting for table names
=ADBOBJECTS(gaTables, "TABLE")

* Displays array gaTables created by ADBOBJECTS( ) function
DISPLAY MEMORY LIKE gaTables

See Also

ADATABASES( ) | CREATE | CREATE CONNECTION | CREATE DATABASE | CREATE SQL VIEW | CREATE TABLE - SQL | DISPLAY DATABASE | INDBC( ) | LIST DATABASE | MODIFY DATABASE | SET DATABASE


ADDBS( ) Function

Adds a backslash (if needed) to a path expression.

ADDBS(cPath)

Return Values

Character

Parameters

cPath
Specifies the path name to which to add the backslash.

Example

The following code creates a form that allows entry of a directory path and converts that entry to a fully-qualified pathname using the ADDBS() function.

PUBLIC ofrmADDBS

ofrmADDBS=NEWOBJECT("frmADDBS")
ofrmADDBS.Show
RETURN

DEFINE CLASS frmADDBS AS form

   Top = 0
   Left = 0
   Height = 200
   Width = 353
   Caption = "frmADDBS"
   Name = "frmADDBS"

   ADD OBJECT txtpath AS textbox WITH ;
      Height = 23, ;
      Left = 8, ;
      TabIndex = 1, ;
      Top = 24, ;
      Width = 328, ;
      Name = "txtPath"

   ADD OBJECT label1 AS label WITH ;
      AutoSize = .T., ;
      Caption = "Enter a path expression:", ;
      Height = 17, ;
      Left = 8, ;
      Top = 4, ;
      Width = 135, ;
      TabIndex = 4, ;
      Name = "Label1"

   ADD OBJECT cmdclose AS commandbutton WITH ;
      Top = 166, ;
      Left = 252, ;
      Height = 27, ;
      Width = 84, ;
      Caption = "Close", ;
      TabIndex = 3, ;
      Name = "cmdClose"

   ADD OBJECT txtaddbspath AS textbox WITH ;
      Height = 23, ;
      Left = 7, ;
      ReadOnly = .T., ;
      TabIndex = 5, ;
      TabStop = .F., ;
      Top = 121, ;
      Width = 328, ;
      Name = "txtADDBSPath"

   ADD OBJECT label2 AS label WITH ;
      AutoSize = .T., ;
      Caption = "The same expression after ADDBS()", ;
      Height = 17, ;
      Left = 7, ;
      Top = 101, ;
      Width = 201, ;
      TabIndex = 6, ;
      Name = "Label2"

   ADD OBJECT cmdapplyaddbs AS commandbutton WITH ;
      Top = 60, ;
      Left = 216, ;
      Height = 27, ;
      Width = 120, ;
      Caption = "Apply ADDBS()", ;
      TabIndex = 2, ;
      Name = "cmdApplyADDBS"

   PROCEDURE cmdclose.Click
      THISFORM.Release()
   ENDPROC

   PROCEDURE cmdapplyaddbs.Click
      THISFORM.txtADDBSPath.Value=ADDBS(ALLTRIM(THISFORM.txtPath.Value))
      THISFORM.Refresh()
   ENDPROC

ENDDEFINE

See Also

DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


ADDPROPERTY( ) Function

Adds a new property to an object at run time.

You can use ADDPROPERTY( ) to add properties and their values to valid Visual FoxPro objects, including those created from Visual FoxPro classes, COM classes, and the SCATTER...NAME command.

ADDPROPERTY(oObjectName, cPropertyName, [, eNewValue ])

Parameters

oObjectName
Specifies the name of the object to which the property is added.

If oObjectName is not a valid object, Visual FoxPro generates the appropriate message.

cPropertyName
Specifies the name of the new property to add to the object.

If the property with the name you specify does not exist, the property is created and added.

eNewValue
Specifies the value to set for the new property.

If you omit eNewValue, and the property exists, Visual FoxPro leaves the value of the property unchanged. If you omit eNewValue, and the property is new, Visual FoxPro sets the value of the new property to False (.F.).

Return Values

Logical data type. The following table describes the return values for ADDPROPERTY( ) and the behavior when you attempt to add a property that already exists for an object.

Return value Description
True (.T.) When ADDPROPERTY( ) adds the property successfully.

When the new property is an array property, and the array already exists, ADDPROPERTY( ) redimensions the array with the dimensions specified by cPropertyName. If you specify a value with eNewValue, all elements in the array are set to that value. If you omit eNewValue, all array elements are set to False (.F.).

If the new property is not an array property, but the existing property is an array property. The property remains an array property with the same dimensions. If you specify a value with eNewValue, all elements in the array are set to that value. If you omit eNewValue, all array elements are set to False (.F.).

If the new property is not an array property, and the existing property is not an array property or is not a read-only Visual FoxPro native property. If you specify a value with eNewValue, the existing property is set to that value. If you omit eNewValue, the existing property value remains unchanged.

If the specified property is already a member of the object but is marked as Hidden or Protected. Visual FoxPro generates an error, "Property name is not found (Error 1734)", and the property is not set to the value passed to ADDPROPERTY( ).
False (.F.) When ADDPROPERTY( ) did not add the property successfully.

If the property is an array property, and the existing property is not an array property. The existing property remains unchanged.

Remarks

You can create property arrays using ADDPROPERTY( ) for an object. When you do so, every element in the array is initialized with eNewValue, if provided. Otherwise, the value of each property in the array is set to False (.F.). For more information about creating a property array for an object, see the Examples section.

Visual FoxPro adds the new property as a Public property. You cannot specify the property as Protected or Hidden.

If the existing property is a read-only Visual FoxPro native property, such as the BaseClass property, Visual FoxPro generates an error, "Property name is read-only (Error 1743)".

If the property name is not valid, for example, the property name contains a space or other illegal characters, Visual FoxPro generates an error, "Incorrect property name (Error 1470)".

For object instances derived from native Visual FoxPro classes, ADDPROPERTY( ) respects the visibility setting of the intrinsic AddProperty method. If AddProperty is marked as Hidden or Protected, ADDPROPERTY( ) does not create the new property and returns False (.F.). If the AddProperty method is marked as Public (default), ADDPROPERTY( ) creates the property and returns True (.T.). This protects the original class design.

Note This does not apply to COM objects created with Visual FoxPro OLEPUBLIC classes.

ADDPROPERTY( ) does not work when using the FOR EACH command with object references. However, you can use the AddProperty method instead.

Examples

Example 1

The following example adds a new property to an object created with the SCATTER command.

USE customers
SCATTER NAME oCust
ADDPROPERTY(oCust,"MyProperty")

Example 2

The following example creates a property array for the object, oMyForm, and displays its contents, 1 and "Two".

oMyForm = CREATEOBJECT('Form')
ADDPROPERTY(oMyForm, 'MyArray(2)', 1)
oMyForm.MyArray(2) = "Two"
CLEAR
? oMyForm.MyArray(1)
? oMyForm.MyArray(2)

See Also

Functions | AddProperty Method | SCATTER Command | REMOVEPROPERTY( ) Function


ADEL( ) Function

Deletes an element from a one-dimensional array, or a row or column from a two-dimensional array.

ADEL(ArrayName, nElementNumber [, 2])

Return Values

Numeric

Parameters

ArrayName
Specifies the array from which the element, row, or column is deleted.
nElementNumber
Specifies the number of the element, row, or column to delete from the array. If the array is multidimensional, nElementNumber will specify the row. You must include the optional 2 argument to delete a column from the array.
Tip For more information on how to reference elements in an array, see DIMENSION.
2
Deletes a column from the array.

Remarks

Deleting an element or row from an array doesn't change the size of the array; instead, the trailing elements, rows, or columns are moved towards the start of the array, and the last element, row, or column in the array is set to False (.F.). If you delete a column, values of the elements in the deleted column are set to False (.F.), but trailing elements are not moved.

If the element, row, or column is successfully deleted, 1 is returned.

Example

The following example creates and fills an array, then searches for a particular company name, which, if found, is removed from the array.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer     && Open customer table
SELECT company FROM customer ;
   WHERE country = 'UK' ;
   INTO ARRAY gaCompanies
gnCount = _TALLY
gcName = 'Seven Seas Imports'
CLEAR
DISPLAY MEMORY LIKE gaCompanies
gnPos = ASCAN(gaCompanies, gcName)   && Search for company
IF gnPos != 0
   * Company found, remove it from the array
   = ADEL(gaCompanies, gnPos)
   gnCount = gnCount - 1
ENDIF
DISPLAY MEMORY LIKE gaCompanies

See Also

ACOPY( ) | ADIR( ) | AELEMENT( ) | AFIELDS( ) | AINS( ) | ALEN( ) | ASCAN( ) | ASORT( ) | ASUBSCRIPT( ) | DIMENSION


ADIR( ) Function

Places information about files into an array and then returns the number of files.

ADIR(ArrayName [, cFileSkeleton [, cAttribute [, nFlag]]])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array. If the array you include doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists and ADIR( ) returns 0 because no matching files are found, the array remains unchanged. If the array doesn't exist and ADIR( ) returns 0, the array isn't created.

The following table describes the contents and data type of each column in the array:

Column | Array contents | Data type
1 | File names | Character
2 | File sizes | Numeric
3 | Dates last modified | Date
4 | Times last modified | Character
5 | File attributes | Character

The last array column contains the file attributes of the matching files. Each file attribute is expressed by a letter; a file can have more than one attribute. The following table indicates the file attribute represented by each letter:

Letter | Attribute
A | Archive – Read/Write
H | Hidden
R | Read-only
S | System
D | Directory
cFileSkeleton
Specifies a file skeleton so you can store information about files with names or extensions that match a search criterion. For example, the criterion can be all tables, all text files, all files with names that have A as their first letter, and so on. Such general searches are done by including the wildcards * and ? in cFileSkeleton. A question mark represents a single character; an asterisk represents any number of characters. You can use any number of wildcards in any position within the file skeleton.

You can specify a drive and/or directory to search for matching file names. If you don't specify a drive and a directory, Visual FoxPro places information about files in the current directory into the array.

cAttribute
Specifies the inclusion of subdirectories and hidden or system files.

cAttribute can contain any combination of D, H, and S. Including D returns subdirectory names of the current directory in addition to file names that match the file skeleton specified in cFileSkeleton. Including H returns information about hidden files that match the file skeleton specified in cFileSkeleton. Including S returns information about system files that match the file skeleton specified in cFileSkeleton.

Include an empty string in cFileSkeleton to return just subdirectory names, hidden files or system files.

You can include V in cAttribute to return the volume name of the current drive. Only the volume name is returned to the array if V is included with D, H, or S. The volume name is stored in the first array element and the remainder of the array is truncated.

nFlag
Specifies whether the display provides DOS naming or actual case sensitivity.
nFlag | Description
0 | (Default) Display represents the full file name in uppercase
1 | Display represents original Case in names
2 | Display follows DOS 8+3 naming convention

Remarks

For each file, ADIR( ) places into the array the file name, size, date last modified, time last modified, and attributes.

Example

The following example uses ADIR( ) to create an array containing database information. The names of the databases are then displayed.

CLOSE DATABASES
SET DEFAULT TO (HOME(2) + 'Data')

gnDbcnumber = ADIR(gaDatabase, '*.DBC')  && Create array

CLEAR
FOR nCount = 1 TO gnDbcnumber  && Loop for number of databases
   ? gaDatabase(nCount,1)  && Display database names
ENDFOR
SET PATH TO HOME( )  && Set path to Visual FoxPro directory

See Also

ADEL( ) | AELEMENT( ) | AFIELDS( ) | AINS( ) | ALEN( ) | ANETRESOURCES( ) | ASCAN( ) | ASORT( ) | ASUBSCRIPT( ) | DIMENSION | DIR or DIRECTORY


ADLLS( ) Function

Returns an array containing the names of functions loaded by DECLARE DLLs.

ADLLS(ArrayName)

Parameters

Arrayname
Specifies the name of the array. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the database information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array. If no DLL functions have been declared, the array is not created, and an existing array is not modified.

Return Value

Numeric

Remarks

The numeric value returned by the ADLLS function specifies the number of DLL loaded functions. If no alias is provided, the 2nd element returns the same value as the 1st element (function name).

The array created by the ADLLS function has the following format:

Column | Field Info | Data Type
1 | Function Name | Character
2 | Function Alias | Character
3 | Library Name | Character

For details about how to declare functions, see the DECLARE - DLL Command

See Also

Arrays | CLEAR Commands | DISPLAY DLLS Command | LIST DLLS Command | DISPLAY STATUS Command


ADOCKSTATE( ) Function

Retrieves the dock state of any dockable Integrated Development Environment (IDE) windows or toolbars.

ADOCKSTATE( ArrayName [, 1 | 2 ] )

Parameters

ArrayName
Specifies an array to populate with the dock state of a dockable window. The array contains the following information.
Element | Description
1 | Name of the IDE window or toolbar
2 Dock state:

1 - Docked

0 - Undocked
3 | Dock position. For values, see DOCK WINDOW Command.
4 | Docked window, or name of the window to which the specified window is docked if tab or link-docked. This element does not apply to toolbars.
1
Return only IDE windows.
2
Return only toolbars.

Return Values

Numeric data type. ADOCKSTATE( ) returns the number of rows populated or 0 if none found.

Remarks

The array populated can contain both system and user-defined toolbars.

For toolbars or windows docked to the Visual FoxPro desktop, the fourth array element contains the desktop name, which you can retrieve using the _VFP Caption property.

Note If a toolbar appears between the Visual FoxPro desktop and a window docked to the Visual FoxPro desktop, the fourth element contains the name of the toolbar.

If a window or toolbar is not docked, the fourth element contains an empty string.

The first element in each row for a user-defined toolbar contains the Caption property value for that toolbar.

For tab-docked windows, the leftmost window is the anchor window and contains details about how the entire container is docked. Visual FoxPro traverses the windows from left to right.

For link-docked windows, the upper left window in a link-docked container contains details about how the entire container is docked. The following rules determine docking order:

  • Visual FoxPro traverses the link-docked container beginning with upper leftmost window.
  • Visual FoxPro continues traversing windows from top to bottom followed by from left to right. A link-docked container might consist of multiple inner containers. Thus, the ordering of windows in the ADOCKSTATE( ) array might appear different.
  • The position contained in the third element of the array is relative to the window referenced in first element of the array.
  • Visual FoxPro traverses all link-docked windows first and tab-docked windows second. Essentially, Visual FoxPro makes two passes through a linked container. The first pass is for link-docked windows, and the second is for the tab-docked windows. Visual FoxPro includes only the leftmost tab-docked window in the first pass for link-docked windows.
  • Visual FoxPro traverses a tab-docked container from left to right.

If the third element in the array is set to -1 (not docked), the container is not docked. If the container is docked to the desktop, the third element in the array contains the position in which the container is docked to the Visual FoxPro desktop as referenced in the fourth element of the array.

For example, the following code creates an array, opens and docks several windows, and produces an array as shown:

CLEAR ALL
PUBLIC aa
DIMENSION aa[1]
ACTIVATE WINDOW Command
ACTIVATE WINDOW Trace
ACTIVATE WINDOW Document
ACTIVATE WINDOW Properties
ACTIVATE WINDOW Watch
ACTIVATE WINDOW Locals
SET
DOCK WINDOW View POSITION -1
DOCK WINDOW Command POSITION -1
DOCK WINDOW Trace POSITION -1
DOCK WINDOW Document POSITION -1
DOCK WINDOW Properties POSITION -1
DOCK WINDOW Watch POSITION -1
DOCK WINDOW Command POSITION 1 WINDOW View
DOCK WINDOW Trace POSITION 1 WINDOW Command
DOCK WINDOW Document POSITION 3 WINDOW View
DOCK WINDOW Properties POSITION 3 WINDOW Trace
DOCK WINDOW Watch POSITION 4 WINDOW Command
DOCK WINDOW Locals POSITION 3 WINDOW Command
ADOCKSTATE(aa,1)

The resulting array appears as follows:

Row | First element | Second element | Third element | Fourth element
1 | Trace | 1 | -1 |
2 | Properties | 1 | 3 | Trace
3 | Watch | 1 | 2 | Trace
4 | Locals | 1 | 3 | Watch
5 | View | 1 | 2 | Watch
6 | Document View | 1 | 3 | View
7 | Command | 1 | 4 | Watch

Visual FoxPro displays docking information for debugger windows in the debugger. If a window is undocked, Visual FoxPro shows the name, dock state (0) and position (-1). If a window is docked, Visual FoxPro shows only the name, dock state (1), position, and window ("Visual FoxPro Debugger").

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the ADOCKSTATE( ) function.

Example

The following example shows the return results of ADOCKSTATE( ) when no toolbars or windows have been previously docked, for example, after deleting the FoxUser resource files or when Visual FoxPro is newly installed. Make sure the Command window is open.

CLEAR
dockNum = ADOCKSTATE(dockState)
? dockNum   && Returns 2 because Standard toolbar also exists.
? dockState(1)  && Outputs "COMMAND".
? dockState(4)  && Outputs an empty string because the Command
                && window is not docked.
? dockState(5)  && Outputs "Standard".
? dockState(8)  && Outputs "Microsoft Visual FoxPro" because the
                && Standard toolbar is docked to the Microsoft
                && Visual FoxPro desktop.

The following example shows how to use the DOCK WINDOW command to dock the Command window to the Visual FoxPro desktop window and use ADOCKSTATE( ) to obtain the dock state of the Command window. First, make sure the Command window is open. After docking the Command window, you can see that the Standard toolbar and Command windows are docked to the Microsoft Visual FoxPro desktop window. The position of the toolbars or windows in the array returned by ADOCKSTATE( ) can vary depending on the order in which the toolbars or windows are docked.

CLEAR
DOCK WINDOW Command POSITION 0
dockNum = ADOCKSTATE(dockState)
? dockNum   && Returns 2 because Standard toolbar also exists.
? dockState(1)  && Outputs "Standard".
? dockState(4)  && Outputs "Microsoft Visual FoxPro".
? dockState(5)  && Outputs "COMMAND".
? dockState(8)  && Outputs "Microsoft Visual FoxPro".

See Also

Functions | Caption Property | DOCK WINDOW Command | Docked Property | Docking Windows


AELEMENT( ) Function

Returns the number of an array element from the element's subscripts.

AELEMENT(ArrayName, nRowSubscript [, nColumnSubscript])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array whose element number you want to return.
nRowSubscript
Specifies the row subscript. If the array is one-dimensional, AELEMENT( ) identically returns nRowSubscript.

If you include just nRowSubscript and it is greater than the number of rows in the array, Visual FoxPro generates an error message.

nColumnSubscript
Specifies the column subscript. If the array is two-dimensional, include both nRowSubscript and nColumnSubscript.

Remarks

You can refer to an element in a two-dimensional array in one of two ways. The first method uses two subscripts to specify the row and column position of the element in the array, and the second method uses a single-element number. AELEMENT( ) returns the element number when supplied with an element's row and column subscripts.

The Visual FoxPro functions ADEL( ), ADIR( ), AFIELDS( ), AINS( ), ALEN( ), ASCAN( ), ASORT( ), and ASUBSCRIPT( ) can manipulate two-dimensional arrays and require that elements be referred to by their element number. AELEMENT( ) facilitates conversion from subscripts to an element number for use by these functions. The corresponding row and column subscripts can be returned from an element number with ASUBSCRIPT( ).

The following example illustrates the creation of an array with two rows and three columns. DISPLAY MEMORY shows the contents of the elements of the array listed in element number order.

DIMENSION gaMyArray(2,3)
DISPLAY MEMORY LIKE gaMyArray
gaMyArray   Pub  A
  ( 1, 1)   L  .F. (element number 1)
  ( 1, 2)   L  .F. (element number 2)
  ( 1, 3)   L  .F. (element number 3)
  ( 2, 1)   L  .F. (element number 4)
  ( 2, 2)   L  .F. (element number 5)
  ( 2, 3)   L  .F. (element number 6)

An element can be referred to by its subscripts or its element number. The commands STORE 'INVOICE' TO gaMyArray(2, 1) and STORE 'INVOICE' TO gaMyArray(4) both store the character string INVOICE to the same array element.

In one-dimensional arrays, an element number is identical to its single-row subscript. It isn't necessary to use AELEMENT( ) with one-dimensional arrays.

See Also

ADEL( ) | ADIR( ) | AFIELDS( ) | AINS( ) | ALEN( ) | ASCAN( ) | ASORT( ) | ASUBSCRIPT( ) | DIMENSION | DISPLAY MEMORY


AERROR( ) Function

Creates a variable array containing information about the most recent Visual FoxPro, OLE, or ODBC error.

AERROR(ArrayName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array that AERROR( ) creates.

Remarks

AERROR( ) creates an array with seven columns and returns the number of rows in the array. The type of error that occurred determines the number of rows in the array.

The following table describes the contents of each element when a Visual FoxPro error occurs. When a Visual FoxPro error occurs, the array contains one row.

Element number | Description
1 | Numeric. The number of the error. Identical to the value returned by ERROR( ).
2 | Character. The text of the error message. Identical to the value returned by MESSAGE( ).
3 | The null value. However, if the error has an additional error parameter, contains the text of the error parameter. Almost identical to the value returned by SYS(2018), the difference being that AERROR( ) returns mixed case but SYS(2018) returns all uppercase.
4 | The null value. However, as appropriate, contains the number of the work area in which the error occurred.
5 | The null value. However, if a trigger failed (error 1539), contains one of the following numeric values:1 – Insert trigger failed.2 – Update trigger failed.3 – Delete trigger failed.
6 | The null value.
7 | The null value.

The following table describes the contents of each element when OLE errors numbered 1427 or 1429 occur. When these OLE errors occur, the array contains one row.

Element number | Description
1 | Numeric. Contains 1427 or 1429.
2 | Character. The text of the Visual FoxPro error message.
3 | Character. The text of the OLE error message.
4 | Character. The application name (for example, Microsoft Excel).
5 | The null value or Character. Contains the name of the application's Help file where more information about the error can be found if the information is available from the application; otherwise contains the null value.
6 | The null value or Character. Contains the Help context ID for the appropriate Help topic if the information is available from the application; otherwise contains the null value.
7 | Numeric. An OLE 2.0 exception number.

The following table describes the contents of each element when an ODBC error numbered 1526 occurs. When an ODBC error occurs, the array contains two or more rows; one row for each ODBC error.

Element number | Description
1 | Numeric. Contains 1526.
2 | Character. The text of the error message.
3 | Character. The text of the ODBC error message.
4 | Character. The current ODBC SQL state.
5 | Numeric. The error number from the ODBC data source.
6 | Numeric. The ODBC connection handle.
7 | The null value.

Example

The following example uses ON ERROR to specify an error handling routine named errhand. An error is generated by issuing a misspelled command (BRWS). The errhand error handling routine uses AERROR( ) to create an array containing error information, and this information is then displayed.

ON ERROR DO errhand     && errhand is the error handler procedure

BRWS  && Causes a syntax error
ON ERROR  && Restore system error handler

PROCEDURE errhand
   = AERROR(aErrorArray)  && Data from most recent error
   CLEAR
   ? 'The error provided the following information'  && Display message
   FOR n = 1 TO 7  && Display all elements of the array
      ? aErrorArray(n)
   ENDFOR

See Also

COMRETURNERROR( ) | CREATE TRIGGER | ERROR | ERROR( ) | MESSAGE( ) | ON ERROR | SYS(2018) – Error Message Parameter | Error Messages A-Z | Error Messages by Number


AEVENTS() Function

You can use the AEVENTS() function to retrieve the number of existing event bindings.

AEVENTS( ArrayName [, 0 | oEventObject ] )

Parameters

ArrayName
Specifies the name of the array that contains the results of AEVENTS().
0
Specifies that AEVENTS() returns a three-element array containing an object reference to the current event source, the name of the triggered event, and how the event was triggered.
Column | Description | Type
1 | Event source | Object reference
2 | Event | String
3 Event type, or how event was raised. 0 - System

1 - RAISEEVENT( ) function

2 - Method call

The third array element indicates how an event was triggered. If the event is a property, this value can be 1 or 2. The value is 2 if the property is set or assigned.

oEventObject
Specifies an object reference. If you specify an object reference, AEVENTS() returns a five-column array that contains the events raised and the delegate methods for oEventObject. Each row in ArrayName represents a binding. The following table describes the information in each of the five columns.
Column | Description | Type
1 .T. if second element is the event source

.F. if second element is the event handler

 Logical
2 | Event source if you pass the event handler to oEventObject; otherwise, event handler if you pass the event source to oEventObject. | Object reference
3 | Event | String
4 | Delegate method | String
5 | BINDEVENT() flags | Integer

When you pass oEventObject, the number of bindings returned by AEVENTS() should equal the number of unbound events returned by the UNBINDEVENTS() function when passing only the oEventObject parameter.

Return Values

Numeric data type. AEVENTS() returns the number of event bindings, each of which appear as a row in ArrayName.

Remarks

If AEVENTS() returns 0, and the array does not exist, Visual FoxPro does not create the array. Visual FoxPro changes or alters an existing array only if valid results are returned. The array remains unchanged under the following conditions:

  • No events exist.
  • You specify a value of 0 as the second parameter, and AEVENTS() does not appear within an event or oEventObject has no bindings.

Example

The following example shows how to use AEVENTS( ) to retrieve the number of existing event bindings. BINDEVENTS( ) keeps the Class Browser positioned to the right side of the Visual FoxPro desktop, regardless of how the desktop is resized. For more information, see BINDEVENT() Function.

UNBINDEVENTS( ) detaches the Resize event of the _SCREEN system variable from the object, oHandler. AEVENTS( ) returns the number of event bindings before BINDEVENT( ) and after UNBINDEVENTS( ) in an array called myArray:

PUBLIC oHandler
oHandler=NEWOBJECT("myhandler")
DO (_browser)

BINDEVENT(_SCREEN,"Resize",oHandler,"myresize")
AEVENTS(myArray,oHandler)
numRows=ALEN(myArray,1)
numCols=ALEN(myArray,2)
WAIT "Rows in array: " + TRANSFORM(numRows) WINDOW AT 20,20
WAIT "Cols in array: " + TRANSFORM(numCols) WINDOW AT 20,20
FOR count1 = 1 TO numRows
   FOR count2 = 1 TO numCols
      WAIT myArray[count1,count2] WINDOW AT 20,20
   ENDFOR
ENDFOR

UNBINDEVENTS(_SCREEN,"Resize",oHandler,"myresize")
AEVENTS(myArray,oHandler)
numRows=ALEN(myArray,1)
numCols=ALEN(myArray,2)
WAIT "Rows in array: " + TRANSFORM(numRows) WINDOW AT 20,20
WAIT "Cols in array: " + TRANSFORM(numCols) WINDOW AT 20,20
FOR count1 = 1 TO numRows
   FOR count2 = 1 TO numCols
      WAIT myArray[count1,count2] WINDOW AT 20,20
   ENDFOR
ENDFOR

DEFINE CLASS myhandler AS Session
   PROCEDURE myresize
   _obrowser.left = _SCREEN.Width - _obrowser.width
   RETURN
ENDDEFINE

See Also

Functions | Event Binding for Visual FoxPro Objects | BINDEVENT() Function | UNBINDEVENTS() Function | RAISEEVENT() Function


AFIELDS( ) Function

Places information about the structure of the current table into an array and returns the number of fields in the table.

AFIELDS( ArrayName [, nWorkArea | cTableAlias ] )

Parameters

ArrayName
Specifies an array into which information about the table structure is placed.

If the array you specify does not exist, Visual FoxPro automatically creates it. If the array exists and is not large enough to contain all the information returned by AFIELDS( ), the size of the array is automatically increased to accommodate the information.

nWorkArea
Specifies the work area of the table for which structure information is placed into an array.
cTableAlias
Specifies the alias of the table for which structure information is placed into an array.

If you omit nWorkArea and cTableAlias, structure information is placed in an array for the table in the currently selected work area.

Return Values

Numeric data type. AFIELDS( ) returns the number of fields in the table. The array contains 18 columns and has the same number of rows as fields in the table.

The following table describes the content of each column in the first row of the array and the data type of the information stored in each column. Values for table-specific properties in columns 10 through 16 only appear in the first row of the array. One row is created for each field in the table.

Column number | Field info | Data type
1 | Field name | Character
2 | Field type: C = Character D = Date L = Logical M = Memo N = Numeric F = Float I = Integer B = Double Y = Currency T = DateTime G = General | Character
3 | Field width | Numeric
4 | Decimal places | Numeric
5 | Null values allowed | Logical
6 | Code page translation not allowed | Logical
7 | Field validation expression | Character
8 | Field validation text | Character
9 | Field default value | Character
10 | Table validation expression | Character
11 | Table validation text | Character
12 | Long table name | Character
13 | Insert trigger expression | Character
14 | Update trigger expression | Character
15 | Delete trigger expression | Character
16 | Table comment | Character
17 | NextValue for autoincrementing | Numeric
18 | Step for autoincrementing | Numeric

Remarks

If the fields in the table use autoincrementing, the Step value is greater than 0.

You can use COPY STRUCTURE EXTENDED to place similar information into a table instead of an array.

Example

The following example creates an array named gaMyArray, which contains information about the fields in the Customer table. The names of the fields are displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open Customer table.

gnFieldcount = AFIELDS(gaMyArray)  && Create array.
CLEAR
FOR nCount = 1 TO gnFieldcount
   ? gaMyArray(nCount,1)  && Display field names.
ENDFOR

See Also

ADEL( ) | ADIR( ) | AELEMENT( ) | AINS( ) | ALEN( ) | ALTER TABLE – SQL | ASCAN( ) | ASORT( ) | ASUBSCRIPT( ) | Autoincrementing Field Values in Tables | COPY STRUCTURE EXTENDED | CREATE | CREATE TABLE | DIMENSION


AFONT( ) Function

Places information about available fonts into an array.

AFONT(ArrayName [, cFontName [, nFontSize | nFontCharSet [, nFlags ]]])

Return Values

Logical data type. Returns True (.T.) if array is successfully created. Otherwise, returns False (.F.).

Parameters

ArrayName
Specifies the variable array into which the names of available fonts are placed. If the array is not large enough to contain all the fonts, Visual FoxPro automatically increases the size of the array. If you specify an existing two-dimensional array, Visual FoxPro changes the array to a one-dimensional array.
cFontName
Specifies a font for which information is placed into the array.

If the font you specify supports only discrete font sizes (8-point, 10-point, ...), the font sizes are stored to the array, and AFONT( ) returns True (.T.). If the font you specify in cFontName is scalable (supports fractional font-size values), the array has a single element containing –1, and AFONT( ) returns True (.T.).

If the font you specify is not available, the array is not created, and AFONT( ) returns False (.F.).

nFontSize
Specifies a size for the font specified in cFontName.

If the font size nFontSize is available for the font specified in cFontName, the array has a single element containing a True (.T.) value, and AFONT( ) returns True (.T.). If the font size is not available for the specified font, the array is not created, and AFONT( ) returns False (.F.).

nFontCharSet
Specifies a character set for the font specified in cFontName. If the font character set specified is available for the font specified in cFontName, the array has a single element containing a True (.T.) value, and AFONT( ) returns True (.T.). If the font character set is not available for the specified font, the array is not created, and AFONT( ) returns False (.T.).
nFlags
You can specify an nFlags value of 1, which populates the array with the character sets available for a specified font.

Remarks

AFONT( ) places the names of available fonts into an array. You can also use AFONT( ) to determine available font sizes or if a font is scalable. Use GETFONT( ) to display a dialog containing available fonts, font sizes, and styles.

The nFlags parameter controls whether the third parameter passed is treated as the font size or font character set. If you do not pass an nFlag value, or if nFlag is 0 (for the first bit), then the third parameter is treated as a font size value. If nFlag is 1, then the third parameter is treated as a font character set.

If the third parameter passed is -1, and nFlag is 0 or not passed, the array is updated with all available font sizes for the font specified in cFontName for non-proportional fonts such as MS Sans Serif, and AFONT( ) returns True (.T.).

Note This behavior is new in Visual FoxPro 8.0. In previous versions, if you specified any negative or positive font size for a non-proportional font, AFONT( ) returns False (.F.). This new behavior is equivalent to passing only the first two parameters.

Additionally, if the third parameter passed is 0, and nFlag is 0 or not passed for a non-proportional font, AFONT( ) returns False (.F.). This behavior is also new in Visual FoxPro 8.0. The behavior for proportional fonts such as TrueType or OpenType (Arial) has not changed.

If the third parameter passed is -1, and nFlag is 1, the array is updated with all available font character sets for the font specified in cFontName.

If only ArrayName was passed in versions earlier than Visual FoxPro 8.0, the array populated in AFONT( ) included extra fonts that were really part of a single font family. For example, the array might have included the following Arial fonts under Visual FoxPro 7.0:

  • Arial
  • Arial Baltic
  • Arial Black
  • Arial CE
  • Arial CYR
  • Arial Greek
  • Arial Narrow
  • Arial Tur

Many of these fonts are not included in a standard Font Picker dialog box such as the GETFONT( ) function. In this version of Visual FoxPro, the array in AFONT( ) excludes these extra fonts. For example, the array only includes the following fonts:

  • Arial
  • Arial Baltic
  • Arial Black

Example

The following example uses AFONT( ) to create an array containing the names of all available fonts. The name of each font is displayed, along with an example of the font. If there are more than 10 fonts installed, only the first 10 are displayed.

CLEAR
=AFONT(gaFontArray)  && Array containS font names.
gnNumFonts = ALEN(gaFontArray)  && Number of fonts
IF gnNumFonts > 10
   gnNumFonts = 10  && Display first 10 fonts.
ENDIF

FOR nCount = 1 TO gnNumFonts
   ? ALLTRIM(gaFontArray(nCount))  && Display font name.
   ?? '  This is an example of ' ;
      + ALLTRIM(gaFontArray(nCount)) FONT gaFontArray(nCount), 8
ENDFOR

See Also

FONTMETRIC( ) | GETFONT( ) | TXTWIDTH( ) | SYSMETRIC( ) | WFONT( )


AGETCLASS( ) Function

Displays class libraries in the Open dialog box and creates an array containing the name of the class library and class chosen.

AGETCLASS(ArrayName [, cLibraryName [, cClassName [, cTitleText
[, cFileNameCaption [, cButtonCaption]]]]])

Parameters

ArrayName
Specifies the name of the array in which the names of the class library and class are placed. The following table lists the contents of each element of the array created when you chose a class.
Element | Contents
1 | File name of the class library chosen.
2 | Name of the class chosen.
cLibraryName
Specifies the name of the class library initially selected when the Open dialog is displayed. cLibraryName can be a visual (.vcx) or program (.prg) -based class library.

The class library name you specify is displayed in the File name text box. An error is generated if the class library you specify doesn't exist or cLibraryName is the empty string or the null value.

cClassName
Specifies the name of the class initially selected in the Class name list when the Open dialog is displayed. If the class you specify doesn't exist, the first class in the Class name list is selected. An error is generated if you omit cLibraryName or cClassName is the null value.
cTitleText
Specifies the text displayed in the title bar of the Open dialog. By default, "Open" is the text displayed.
cFileNameCaption
Specifies the text displayed next to the File name text box. By default, "File name:" is the text displayed.
cButtonCaption
Specifies the caption for the OK button.

Return Values

Logical data type. AGETCLASS( ) returns True (.T.), if you chose a class, and creates a one-dimensional array containing two elements. The first element contains the file name of the class library chosen; the second element contains the name of the class chosen. AGETCLASS returns False (.F.) if you exit the Class Library dialog box by pressing ESC, choosing Cancel, or clicking the Close button.

Remarks

If the array you specify does not exist, Visual FoxPro automatically creates the array.

If the array exists and is not large enough to contain the names of the class library and class, Visual FoxPro automatically increases the size of the array.

If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists, and AGETCLASS( ) returns False (.F.) because the Class Library dialog box was closed by pressing ESC, choosing Cancel, or clicking the Close button, the array remains unchanged.

If the array does not exist, and AGETCLASS( ) returns false (.F.), the array is not created.

Visual FoxPro does not support AGETCLASS( ) in its run-time libraries.

Example

The following example creates an array named aClassLib. The directory is changed to the \Samples subdirectory that contains the sample class libraries. AGETCLASS( ) is used to display a dialog with the Buttons class library and the VCR class selected. If you choose the Modify button, the name of the class library and class you select is stored in the array. The class is then opened in the Class designer.

LOCAL aClassLib(2)  && Create an array, initialized to .F.
cCurrentDir = CURDIR( )  && Save the current directory.
CD HOME(2) + 'CLASSES'  && Switch directories.

AGETCLASS(aClassLib, 'BUTTONS.VCX', 'VCR', 'Modify Class', ;
   'Class File:', 'Modify')  && Display the dialog.
CD (cCurrentDir)  && Switch to the previous directory.

IF TYPE('aClassLib(2)') = 'C'  && Class chosen?
   MODIFY CLASS (aClassLib(2)) OF (aClassLib(1))  && Open to modify.
ENDIF

See Also

ACLASS( ) Function | AMEMBERS( ) Function | AVCXCLASSES( ) Function | CREATE CLASS Command


AGETFILEVERSION( ) Function

Creates an array containing information about files with Windows version resources such as .exe, .dll, and .fll files, or automation servers created in Visual FoxPro.

AGETFILEVERSION(ArrayName, cFileName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array in which the file information is placed. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain the file information, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array.

The following table lists the contents of each element of the array.

Element | Contents
1 | Comments
2 | Company Name
3 | File Description
4 | File Version
5 | Internal Name
6 | Legal Copyright
7 | Legal Trademarks
8 | Original File Name
9 | Private Build
10 | Product Name
11 Product Version

The format of this value is dependent on the version of Visual FoxPro. For details, see VERSION( ) Function.
12 | Special Build
13 | OLE Self Registration (contains "OLESelfRegister" if the file supports self-registration; otherwise contains the empty string)
14 | Language (derived from the Translation Code)
15 Translation Code

For example, you can use the following code to determine the Locale ID for the Visual FoxPro executable file:

DIMENSION aFiles[1]
AGETFILEVERSION(aFiles,"VFP8.EXE")
? EVAL("0x"+LEFT(aFiles[15],4))
** Returns 1033 for US version
cFileName
Specifies the name, and optionally the path, of the target file.

Remarks

AGETFILEVERSION( ) is typically used to get information about files with Windows version resources such as .exe, .dll, and .fll files, or automation servers created in Visual FoxPro. You must specify a value for at least one item in the EXE Version dialog Box for a Visual FoxPro automation server to have Windows version resources.

AGETFILEVERSION( ) returns the number of elements in the array. If the file you specify does not exist or does not contain Windows version resources, zero is returned and the array (if already created) remains unchanged.

The minimum number of characters to which AGETFILEVERSION( ) can be abbreviated is 5 characters.

See Also

ADIR( ) Function | DIR or DIRECTORY Command | GETFILE( ) Function


AINS( ) Function

Inserts an element into a one-dimensional array, or a row or column into a two-dimensional array.

AINS(ArrayName, nElementNumber [, 2])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array into which the element is inserted.
nElementNumber
Specifies where the new element, row, or column is inserted into the array.

To insert an element into a one-dimensional array, include ArrayName and the element nElementNumber where the insertion occurs. The new element is inserted just before element nElementNumber. To insert a row into a two-dimensional array, include ArrayName and the number of the row nElementNumber where the insertion occurs. The new row is inserted just before row nElementNumber.

For more information on referencing an array element by its subscripts, see DIMENSION Command.

2
Inserts a column into a two-dimensional array. The new column is inserted just before the column specified with nElementNumber.

Remarks

Inserting an element, row, or column into an array does not change the size of the array. The trailing elements, rows, or columns are shifted toward the end of the array and the last element, row, or column in the array is dropped from it. The newly inserted element, row, or column is initialized to false (.F.).

AINS( ) returns 1 if the element, row, or column is successfully inserted.

Example

The following example creates and fills an array with company names and scans the array for a specific company name. If the company name isn't found, it inserts the missing company name into the array.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer     && Open customer table
SELECT company FROM customer ;
   WHERE country = 'Germany' ;
   INTO ARRAY gaCompanies

gnCount = _TALLY
gcName = 'Seven Seas Imports'
CLEAR
DISPLAY MEMORY LIKE gaCompanies

IF ASCAN(gaCompanies, gcName) = 0  && Search for company
*** Company not found-add it ***
   DIMENSION gaCompanies[gnCount+1,1]
   = AINS(gaCompanies, gnCount-1)
   gaCompanies[gnCount-1] = gcName
ENDIF
DISPLAY MEMORY LIKE gaCompanies

See Also

ACOPY( ) Function | ADEL( ) Function | ADIR( ) Function | AELEMENT( ) Function | AFIELDS( ) Function | ALEN( ) Function | ASCAN( ) Function | ASORT( ) Function | ASUBSCRIPT( ) Function | DIMENSION Command


AINSTANCE( ) Function

Places instances of a class into a variable array and returns the number of instances placed in the array.

AINSTANCE(ArrayName, cClassName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array into which the instances are placed. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the instances, Visual FoxPro automatically increases the size of the array to accommodate the instances. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists and AINSTANCE( ) returns 0 because no instances are found, the array remains unchanged. If the array doesn't exist and AINSTANCE( ) returns 0, the array is not created.

Only class instances assigned to variables and array elements with CREATEOBJECT( ) or NEWOBJECT( ) are placed into the array.

cClassName
Specifies a Visual FoxPro base class name or a user-defined class name. The following table lists the Visual FoxPro base classes you can specify for cClassName:
Base Class Names
CheckBox | Line
Column | ListBox
ComboBox | OLEControl
CommandButton | OLEBoundControl
CommandGroup | OptionButton
Container | OptionGroup
Control | Page
Cursor | PageFrame
Custom | ProjectHook
DataEnvironment | Relation
EditBox | Separator
Form | Session
FormSet | Shape
Grid | Spinner
Header | TextBox
Hyperlink | Timer
Image | ToolBar

Example

In the following example, CREATEOBJECT( ) is used to create two instances of the Visual FoxPro Form base class. AINSTANCE( ) is used to create an array named gaMyArray that contains the variable references (goINSTANCE1 and goINSTANCE2) for each form instance. The contents of the array are then displayed.

CLEAR ALL
goINSTANCE1 = CREATEOBJECT('Form')
goINSTANCE2 = CREATEOBJECT('Form')

CLEAR
? AINSTANCE(gaMyArray, 'Form')  && Returns 2, two form instances
DISPLAY MEMORY LIKE gaMyArray  && Displays the references

See Also

ADD CLASS COMMAND | AMEMBERS( ) Function | CREATE CLASS COMMAND | CREATE CLASSLIB COMMAND | CREATEOBJECT( ) FUNCTION | DEFINE CLASS COMMAND


ALANGUAGE( ) Function

Returns an array containing the names of all valid Visual FoxPro commands, functions, or base classes.

ALANGUAGE(ArrayName, nType)

Parameters

ArrayName
Specifies the name of the array to contain the language items. If the array doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the data, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array.
nType
Specifies the type of language item returned, according to the following list:
Value Description Array Type
1 Commands One-dimensional:
Command name
2 Functions
Two-dimensional:
Function name [M] nParamR [- nParamT]

The matchFlag, M, specifies that you must use the full
function name in code.
nParamR specifies the number of required parameters. nParamT specifies total number of possible parameters.

3 Base classes
One-dimensional:
Base Class name
4 DBC Events
One-dimensional:
DBC event name (The displayed name omits the "DBC_" prefix of the event name.)

Remarks

The ALANGUAGE( ) function returns an array of all valid Visual FoxPro commands and functions. To return object information, use the AMEMBERS( ) function.

Examples

Use the ALANGUAGE( ) function to access Visual FoxPro functions as in the following code:

   ALANGUAGE(FuncArr,2)

The resulting array, FuncArr, will contain the following values:

   JUSTSTEM, M1

JUSTSTEM( ) cannot be abbreviated and it requires one parameter.

   KEYMATCH, 1-4

KEYMATCH( ) can be abbreviated to four characters, and has one required, and three optional parameters (total = 4).

   LASTKEY, 0

LASTKEY( ) can be abbreviated and requires no parameters.

See Also

Command and Function Usage | LASTKEY( ) Function | KEYMATCH( ) Function | JUSTSTEM( ) Function


ALEN( ) Function

Returns the number of elements, rows, or columns in an array.

ALEN(ArrayName [, nArrayAttribute])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array. If you include only the array name, ALEN( ) returns the number of elements in the array.
nArrayAttribute
Determines whether ALEN( ) returns the number of elements, rows or columns in the array according to the following values for nArrayAttribute:
0 | Returns the number of elements in the array. Omitting nArrayAttribute is identical to specifying 0.
1 | Returns the number of rows in the array.
2 | Returns the number of columns in the array. If the array is a one-dimensional array, ALEN( ) returns 0 (no columns).

Example

The following example uses AFONT( ) to create an array containing the names of all available fonts. ALEN( ) is used to determine the number of rows in the array. The name of each font is displayed, along with an example of the font. If more than 10 fonts are installed, only the first 10 are displayed.

CLEAR
=AFONT(gaFontArray)  && Array containing font names
gnNumFonts= ALEN(gaFontArray)  && Number of fonts
IF gnNumFonts > 10
   gnNumFonts = 10  && Display first 10 fonts
ENDIF

FOR nCount = 1 TO gnNumFonts
   ? ALLTRIM(gaFontArray(nCount))  && Display font name
   ?? '  This is an example of ' ;
      + ALLTRIM(gaFontArray(nCount)) FONT gaFontArray(nCount), 8
ENDFOR

See Also

ADEL( ) Function | ADIR( ) Function | AELEMENT( ) Function | AFIELDS( ) Function | AINS( ) Function | ASCAN( ) Function | ASORT( ) Function | ASUBSCRIPT( ) Function | DIMENSION Command | STORE Command | AFONT( ) Function


ALIAS( ) Function

Returns the table alias of the current or specified work area.

ALIAS([nWorkArea | cTableAlias])

Return Values

Character

Parameters

nWorkArea
Specifies the work area number for which ALIAS( ) returns the table alias.
cTableAlias
Specifies the table alias for which ALIAS( ) returns the table alias.

If you omit nWorkArea or cTableAlias, ALIAS( ) returns the alias of the table open in the current work area. An empty string is returned if a table isn't open in the current or specified work area.

Example

The following example opens the customer table and displays its alias. The customer table is opened again in another work area, is assigned an alias of MyCustomer, and the alias is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer     && Open customer table
CLEAR
? ALIAS( )  && Display the alias
SELECT 0
USE customer AGAIN ALIAS MyCustomer  && Different alias
? ALIAS( )  && Display the alias

See Also

DBF( ) Function | SELECT( ) Function | Working with Table Aliases | Alias Property


ALINES( ) Function

Copies each line in a character expression or memo field to a corresponding row in an array.

ALINES( ) provides an easy way to parse lines in a character expression or memo field. While you can also use MLINES( ) to parse a character expression or memo field, ALINES( ) is faster and requires less programming. Also, ALINES( ) is not affected by the value of SET MEMOWIDTH.

ALINES(ArrayName, cExpression [, lTrim] [cParseChar, ,… ,cParseChar])

Parameters

ArrayName
Specifies the name of the array to which the lines in the character expression or memo field are copied.

If the array you specify does not exist, Visual FoxPro automatically creates the array. If the array exists but is not large enough to contain all the lines in the memo field, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array.

cExpression
Specifies the character expression or memo field containing the lines copied to the array. All character expressions are case-sensitive.

If cExpression is the empty string or the null value, an array with a single row is created and the row contains the empty string. You can use double-byte expressions.

lTrim
Specifies that leading and trailing blanks are removed from the lines copied to the array. If lTrim is true (.T.), leading and trailing blanks are removed from the lines. If lTrim is false (.F.) or is omitted, leading and trailing blanks are not removed.
cParseChar
Specifies one or more character strings that terminate the elements in cExpression. The maximum number of strings permitted in cParseChar is 23. The maximum length for each string is 11 characters.

A line feed (CHR(10)) or carriage return (CHR(13)) character denotes the end of a line. The end of the line can also be denoted with either combination of these two characters (CHR(10) + CHR(13) or CHR(13) + CHR(10)). The default behavior for ALINES( ) is to ignore CHR(13) and CHR(10) when you specify one or more values for cParseChar, unless you also specify the end of line characters.

Return Values

Numeric. ALINES( ) returns the number of rows in the array, or, identically, the number of lines in the character expression or memo field.

Remarks

The first line of the character expression or memo field is copied to the first row of the array, the second line of the character expression or memo field is copied to the second row of the array, and so on.

You must have sufficient memory to copy the lines in a large memo field to an array. Visual FoxPro generates an error message if you lack sufficient memory.

If you want to perform a case-insensitive parse, you can follow one of the following examples.

? ALINES(aMyArray,UPPER(employee.notes), "R.")
? ALINES(aMyArray,employee.notes, "R.", "r.")

Example

The following example opens the Employee table in the Testdata.dbc sample database. ALINES( ) copies the lines in the Notes memo field to an array named aMyArray, and then the contents of the array is displayed.

In this example, ALINES( ) returns 1 because the employee description was typed into the memo field without pressing ENTER after any of the sentences.

CLOSE DATABASES
CLEAR
SET TALK OFF
OPEN DATABASE (HOME(2) + 'data\testdata')
USE employee  && Open Employee table

? ALINES(aMyarray,employee.notes,CHR(13))  && Displays 1
? ALINES(aMyarray,employee.notes,".")  && Displays 7
? ALINES(aMyarray,employee.notes,",")  && Displays 4
? ALINES(aMyarray,employee.notes," ")  && Displays 75
? ALINES(aMyarray,employee.notes,".", ",")  && Displays 10
? ALINES(aMyArray, employee.notes)  && Displays 1
? aMyArray(1)

See Also

MEMLINES( ) Function | _MLINE System Variable | SCATTER Command | MLINE( ) Function | SET MEMOWIDTH Command | ATCLINE( ) Function | ATLINE( ) Function | COPY MEMO Command | MODIFY MEMO Command


ALLTRIM( ) Function

Removes leading and trailing blanks from the specified character expression and returns the trimmed expression as a character string.

ALLTRIM(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which leading and trailing blanks are removed.

Remarks

ALLTRIM( ) can be used to ensure that blanks are removed from data entered by a user.

Example

The following example uses AFONT( ) to create an array containing the names of all available fonts. ALLTRIM( ) is used to remove leading and trailing spaces from the font names. The trimmed name of each font is displayed along with an example of the font. If more than 10 fonts are installed, only the first 10 are displayed.

CLEAR
=AFONT(gaFontArray)  && Array containing font names
gnNumFonts= ALEN(gaFontArray)  && Number of fonts
IF gnNumFonts > 10
   gnNumFonts = 10  && Display first 10 fonts
ENDIF

FOR nCount = 1 TO gnNumFonts
   ? ALLTRIM(gaFontArray(nCount))  && Display font name
   ?? '  This is an example of ' ;
      + ALLTRIM(gaFontArray(nCount)) FONT gaFontArray(nCount), 8
ENDFOR

See Also

LTRIM( ) | RTRIM( ) | TRIM( ) | AFONT( )


AMEMBERS( ) Function

Places the names of properties, procedures, and member objects for an object into a variable array.

AMEMBERS(ArrayName, oObjectName | cClassName [, nArrayContentsID] [, cFlags])

Return Values

Numeric

Parameters

ArrayName
Specifies the array into which the names of the member properties for oObjectName are placed. If you specify the name of an array that doesn't exist, the array is automatically created. If the array isn't large enough to contain all the names, Visual FoxPro automatically increases the size of the array.
oObjectName
Specifies the object whose member properties are placed in the variable array specified with ArrayName. oObjectName can be any expression that evaluates to an object, such as an object reference, an object variable, or an object array element.
cClassName
Specifies the Visual FoxPro class whose member properties are placed in the variable array specified with ArrayName.
nArrayContentsID 0 | 1 | 2 | 3
0 specifies that the array contains a single column of property names. Omitting the nArrayContentsID parameter is the same as passing a 0.

1 specifies that the array contains the names of the properties of the object or class, as well as the methods and member objects. The resulting array is two-dimensional with the second column specifying what type of member is listed in the first column. The possible values for the second column are Property, Event, Method, or Object.

2 specifies that the array contains the names of objects that are members of a native Visual FoxPro object specified with oObjectName. The resulting array is one-dimensional.

This option provides a method to determine the names of child objects in a container such as all Form objects in a form set or controls in a form.

3 specifies that the array contains information about one or more objects. You can pass an object reference to either a native Visual FoxPro object or to a COM object.

Note A value of 3 for this parameter is not supported in .app or .exe applications.

The array returned when you specify this parameter consists of four columns as described in the following table:

Column | Description
1 | Name of the event or method
2 | Property type (for example, PROPERTYPUT, PROPERTYGET, PROPERTYPUTREF, METHOD)
3 | Function signature (parameters and their types, and the function return type). This information is similar to the Quick Info text provided in IntelliSense expansion of a method.
4 | Help string

If you omit nArrayContentsID, AMEMBERS( ) returns a one column array of properties.

cFlags
Specify the filtering applied to the array returned by the AMEMBERS( ) function. cFlags will not function when AMEMBERS( ) is passed a COM object (the value of ArrayContentsID is 3). Some flags are mutually exclusive so that if you use more than one cFlag, use them in the following groupings:
[P | H | G] [N | U] [C] [I | B] [R]

The following tables describe the valid values for cFlags.

Value | Filter Flags
P | Protected properties, methods, or events
H | Hidden properties, methods, or events
G | Public properties, methods, or events
N | Native (Intrinsic) properties, methods, or events
U | User-Defined (Extrinsic) properties, methods, or events
C | Changed properties (but not changed array properties)
I | Inherited properties, methods, or events
B | Base properties, methods, or events (using the AddProperty method)
R | Read-Only Properties

The default configuration for the filtering specified by cFlags is logical OR between flags. You can change this by using the special "+" cFlags.

Value | Special Flags
# | Adds a new column to the output array with the corresponding cFlags value.
+ | Performs logical AND between filter flags.

Remarks

AMEMBERS( ) returns the number of objects, properties, and procedures for the object, or 0 if the array cannot be created. If you omit the optional 1, 2, or 3 flag parameters, a one-dimensional array is created containing the properties of oObjectName.

You can pass COM object references to the AMEMBERS( ) function, but when you do so, you must also pass a value of 3 in the third (flag) parameter, as in the following example.

oExcel = CREATEOBJECT("excel.application")
= AMEMBERS(gaPropArray, oExcel, 3)

Example

The following example uses CREATEOBJECT( ) to create a Form object named goForm1. AMEMBERS( ) is used to create an array named gaPropArray containing the properties available for the form; the properties are then displayed.

CLEAR
goForm1 = CREATEOBJECT("Form")  && Creates a Form
= AMEMBERS(gaPropArray, goForm1, 1)  && Array containing Form properties
DISPLAY MEMORY LIKE gaPropArray  && Display the Form properties

See Also

ADD CLASS | AINSTANCE( ) | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | DEFINE CLASS


AMOUSEOBJ( ) Function

Creates an array containing information about the mouse pointer position and the object over which the mouse pointer is positioned.

AMOUSEOBJ(ArrayName [, 1])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array containing the mouse pointer information. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the lines in the memo field, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array.

The array that is created contains four rows. The following table describes the contents of each row in the array:

Array row | Description
1 | Contains an object reference to the object over which the mouse pointer is positioned when AMOUSEOBJ( ) is executed.
2 | Contains an object reference to the container of the object over which the mouse pointer is positioned when AMOUSEOBJ( ) is executed.
3 | Contains the horizontal (X) coordinate in pixels of the mouse pointer, relative to the container of the object over which the mouse pointer is positioned when AMOUSEOBJ( ) is executed.
4 | Contains the vertical (Y) coordinate in pixels of the mouse pointer, relative to the container of the object over which the mouse pointer is positioned when AMOUSEOBJ( ) is executed.

Note that the first and second rows in the array can contain the same values if the mouse is positioned over a generic container such as a pageframe.

[, 1]
This optional parameter specifies that the mouse pointer information contained in the array is relative to the current form (THISFORM). If this option is included, the second array row always contains an object reference to the current form, and the third and fourth rows contain the mouse pointer coordinates relative to the current form.

Remarks

AMOUSEOBJ( ) can also be used to determine where the mouse pointer is positioned during design time. The following table lists the design time element and the values contained in each row of the array:

Design-time element | Array contents
Form and Class Designers | Row 1 – Object reference to the control.Row 2 – Object reference to the form.Row 3 – Mouse pointer horizontal (X) coordinate relative to the form.Row 4 – Mouse pointer vertical (Y) coordinate relative to the form.
Project Manager | Row 1 – Object reference to the project.Row 2 – Object reference to the project.Row 3 – Zero.Row 4 – Zero.
Visual FoxPro Desktop | Row 1 – Object reference to the desktop.Row 2 – Object reference to the desktop.Row 3 – Mouse pointer horizontal (X) coordinate relative to the desktop.Row 4 – Mouse pointer vertical (Y) coordinate relative to the desktop.

AMOUSEOBJ( ) returns 4 (the number of rows in the array) if the mouse pointer is positioned over an area listed above. If the mouse pointer is positioned over an area other than those listed above, AMOUSEOBJ( ) returns zero and if the array you specify already exists, it remains unchanged. If the array you specify doesn't exist, it isn't created.

See Also

MCOL( ) | MROW( ) | SYS(1270) - Object Location | ASELOBJ( ) Function


ANETRESOURCES( ) Function

Places the names of network shares or printers into an array and then returns the number of resources.

ANETRESOURCES(ArrayName, cNetworkName, nResourceType)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array containing the network share or printer information. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array.

If the array exists and ANETRESOURCES( ) returns 0 because no network shares or printers are found, the array remains unchanged. If the array doesn't exist and ANETRESOURCES( ) returns 0, the array isn't created.

cNetworkName
Specifies the name of the network or domain for which share or printer information is returned. The network name should be in the format "\\NetworkName." You do not have to be connected to the network you specify, and specifying a network doesn't connect you to the network. If you specify a domain name, ANETRESOURCES( ) returns an array of members or resources from that domain.
nResourceType
Specifies the type of network resource for which information is returned. The names of shares on the network are returned if nResourceType evaluates to 1. The names of printers on the network are returned if nResourceType evaluates to 2. A value of 0 returns the name of any resource.

Remarks

ANETRESOURCES( ) returns the number of network shares or printers found (identical to the number of rows in the array). ANETRESOURCES( ) returns zero if there are no shares or printers for the network of the type you specify, or the network you specify doesn't exist.

Note Before Windows 2000, share names were limited to twelve characters in length. If you run ANETRESOURCES( ) on a computer that uses an operating system earlier than Windows 2000, ANETRESOURCES( ) will not return any shares that are on computers running Windows 2000 or later that have share names longer than twelve characters.

Refer to the WNetOpenEnum and WNetEnumResource Win32 API functions for more details.

See Also

ADIR( ) | APRINTERS( ) | GETPRINTER( )


ANSITOOEM( ) Function

Included for backward compatibility. Use GETCP( ) instead.


APRINTERS( ) Function

Places the names of printers currently installed in the Windows Print Manager into a variable array.

APRINTERS(ArrayName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array containing the names of the installed printers and their ports. If the array you include doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain all the printer information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists and APRINTERS( ) returns 0 because no printers are installed, the array remains unchanged. If the array doesn't exist and APRINTERS( ) returns 0, the array isn't created.

Remarks

APRINTERS( ) creates a two-dimensional array. The first column of the array contains the names of the currently installed printers, and the second column contains the ports to which the printers are connected.

APRINTERS( ) returns the number of installed printers. If no printer is installed, it returns 0.

Visual FoxPro obtains the names of the installed printers and their ports from Windows. However, Visual FoxPro doesn't check to see if the printers are actually connected to your machine.

Example

The following example uses APRINTERS( ) to create an array named gaPrinters that contains the names and ports of installed printers. The printers and their ports are then displayed. If no printer is installed, a message is displayed.

IF APRINTERS(gaPrinters) > 0  && If there are installed printer drivers
   CLEAR  && Clear the main Visual FoxPro window
   DISPLAY MEMORY LIKE gaPrinters && Display the printers and ports
ELSE  && Otherwise, no printer are installed
   WAIT WINDOW 'No printers installed.'
ENDIF

See Also

GETPRINTER( ) | PRINTSTATUS( ) | PRTINFO( ) | SET PRINTER


APROCINFO( ) Function

Creates an array containing Visual FoxPro language elements contained in a program file

APROCINFO(ArrayName, cFileName [, nType])

Return Values

Returns the number of rows added to the array.

Parameters

ArrayName
Specifies the name of the array to be created.
cFileName
Specifies the filename of the program that this function traverses.
nType
Specifies the type of information returned in cArrayName. The following table specifies valid nType values and describes the information returned by each nType value.
nType Description Array Details
0 (default Populates the array with all document information. Column1 – Doc View content

Column2 – line

Column3 – type

Column4 – indentation

Indentation is used with preprocessor directives to show nested levels of #IF type statements.
1 Populates the array with only the class definitions in the document. Column1 – class name

Column2 – line

Column3 – parentclass

Column4 - is OLEpublic
2 Populates the array with only class procedure information (class definition excluded) Column1 – Doc View content

Column2 – line
3 Populates the array with #define and other preprocessor directives in the document. Column1 – Doc View content

Column2 – line

Column3 – type

The following table describes the "type" values returned in Column3 for nType values of 0 and 3.

nType | Description
Define | #DEFINE preprocessor directive
Directive | Other preprocessor directives, such as #IF
Class | Class definition line
Procedure | Procedure, Method or Event

Remarks

Visual FoxPro automatically creates the array you specify if it doesn't already exist. Visual FoxPro automatically increases or truncates the size of the array to accommodate the returned information. This function supports program (PRG) files only.

See Also

Working with Arrays | Arrays | Array Manipulation | EDITSOURCE( ) Function | #DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | Modifying a Class Definition | Document View Window


ASC( ) Function

Returns the ANSI value for the leftmost character in a character expression.

ASC(cExpression)

Return Values

Numeric

Parameters

cExpression
Specifies the character expression containing the character whose ANSI value ASC( ) returns. Any characters after the first character in cExpression are ignored by ASC( ).

Remarks

ASC( ) returns the position of the character in the character table of the current code page. Every character has a unique ANSI value in the range from 0 to 255.

Example

The following example displays the characters A through J and uses ASC( ) to display their corresponding ANSI values.

STORE 'ABCDEFGHIJ' TO gcANSI  && 10 characters
CLEAR
FOR nCOUNT = 1 TO 10
   ? SUBSTR(gcANSI, nCount,1)  && Display a character
   ?? ASC(SUBSTR(gcANSI, nCount)) && Display ANSI value
ENDFOR

See Also

CHR( ) | SET ANSI Command | ANSITOOEM( ) | OEMTOANSI( )


ASCAN( ) Function

Searches an array for an element containing the same data and data type as an expression.

ASCAN(ArrayName, eExpression [, nStartElement [, nElementsSearched [, nSearchColumn [, nFlags ]]]])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array to search.
eExpression
Specifies the general expression to search for.
nStartElement
Specifies the element number at which the search begins. The element number you specify is included in the search. If you omit nStartElement, the entire array is searched by default.
nElementsSearched
Specifies the number of elements that are searched. If you omit nStartElement and nElementsSearched, the search begins with the first array element and continues to the last array element if you do not specify nSearchColumn.
Note You can refer to an element in a two-dimensional variable array in one of two ways. The first method uses two subscripts to specify the row and column position of the element in the array; the other method uses an element number. This function and others that manipulate two-dimensional arrays require element numbers (nStartElement and nElementsSearched). Use AELEMENT( ) to return the element number from row and column subscripts in a two-dimensional array.
nSearchColumn
Specifies the array column to search. This is often useful in arrays created by functions such as AFIELDS( ).

You can use 0 or a negative number for nSearchColumn to impose a search of the entire array. If you use a value greater than 0 for nSearchColumn, ASCAN( ) treats the specified column as a one-dimensional array, using each data row as an element in the search. For instance, the following example searches only the 3rd and 4th elements of column 2 (instead of the entire array).

? ASCAN(abc,"M",3,2,2)

Visual FoxPro generates an error if nSearchColumn is a number larger than the number of available columns.

nFlags
Specifies additional search criteria to apply to the scan function. Default scans are case-sensitive.

The number you specify in nFlags provides a bit-value that determines the case sensitivity or exactness setting of a scan according to the following table:

NFlag | Bit | Description
0 | 0000 | Behavior existing in Visual FoxPro 6 or earlier
1 | 0001 | Case Insensitive
2 | 0010 | Current behavior existing in the previous version of Visual FoxPro
3 | 0011 | Case Insensitive
4 | 0100 | Exact OFF
5 | 0101 | Case Insensitive; Exact OFF
6 | 0110 | Exact ON
7 | 0111 | Case Insensitive; Exact ON
8 | 1000 | Return row number
9 | 1001 | Case Insensitive; return row number
10 | 1010 | Return row number
11 | 1011 | Case Insensitive; return row number
12 | 1100 | Return row number; Exact OFF
13 | 1101 | Case Insensitive; Return row number; Exact OFF
14 | 1110 | Return row number; Exact ON
15 | 1111 | Case Insensitive; Return row number; Exact ON

The bit values are as follows:

Bit | Description
0 | Case Insensitive bit
1 | Exactness ON bit (Only effective if bit 2 is set)
2 | Override system Exact setting bit
3 | Return row number if 2D array

nFlags applies only to the ASCAN( ) function and does not affect settings for SET EXACT.

Remarks

If a match is found, ASCAN( ) returns the number of the element containing the expression. If a match cannot be found, ASCAN( ) returns 0.

The criteria for a successful match of character data are determined by the setting of the system SET EXACT if nFlag with bit 2 is not set. If SET EXACT is ON, an element must match the search expression character for character and have the same length. If SET EXACT is OFF, and an element and search expression match until the end of the expression is reached, the match is successful. For more information on match criteria for character strings, see the string comparison table in the SET EXACT topic.

In Visual FoxPro 6, the nStartElement and nElementsSearched parameters are optional. The nStartElement must be > 0 while nElementsSearched can be any value. In order to accommodate the nSearchColumn parameter, you will need to bypass these parameters by passing a value of –1.

The nStartElement and nElementsSearched parameters take on special meaning if the value of nSearchColumn is greater than 0. In Visual FoxPro 6, they are always referenced to the entire array. Beginning with Visual FoxPro 7, if a positive nSearchColumn is passed, the values of nStartElement and nElementsSearched are referenced to the single one-dimensional array represented by the nSearchColumn. For example, the following would only search the 3rd and 4th elements of column 2, and not the entire array:

? ASCAN(abc,"M",3,2,2)

Example

The following example creates and fills an array with company names, and then uses ASCAN( ) to search for a particular company name. If the company name is found, it is removed from the array.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer     && Open customer table
SELECT company FROM customer ;
   WHERE country = 'UK' ;
   INTO ARRAY gaCompanies
gnCount = _TALLY
gcName = 'Seven Seas Imports'
CLEAR
DISPLAY MEMORY LIKE gaCompanies*
gnPos = ASCAN(gaCompanies, gcName) && Search for company
IF gnPos != 0
   *** Company found, remove it from the array ***
   = ADEL(gaCompanies, gnPos)
   gnCount = gnCount - 1
ENDIF
DISPLAY MEMORY LIKE gaCompanies

See Also

ACOPY( ) | ADEL( ) | ADIR( ) | AELEMENT( ) | AFIELDS( ) | AINS( ) | ASORT( ) | ASUBSCRIPT( ) | DIMENSION | SET EXACT


ASELOBJ( ) Function

Places an object reference for the currently selected control or container that exists in the Form Designer, Class Designer, or code editing window into a specified variable array. When calling ASELOBJ( ) in a code editing window, the array also includes elements for forms (.scx), visual class libraries (.vcx), and #INCLUDE file names. You can also use ASELOBJ( ) to create control builders.

ASELOBJ( ArrayName, [ 1 | 2 | 3 ] )

Parameters

ArrayName
Specifies the name of the array you want to use.
1
Creates a one-element array containing an object reference to the container for the currently active and selected control.

For example, if the currently active and selected control is a spinner on a form, the array contains an element with the value "FORM." When calling ASELOBJ( ) in the Command window, include this argument.

Note When a page frame is selected, ASELOBJ( ) returns the name of the current page.
2
Creates a one-element array containing an object reference to the DataEnvironment object for the form. The DataEnvironment object makes it possible for you to determine the data environment properties of the form.
3
Creates three-element array containing information in context with the currently active code editing window: object reference to a container object, the full path and name of the .scx or .vcx file, and the full path and name of the #INCLUDE file, if available.

If no code editing window is active, the ASELOBJ( ) uses information from the most recently activated class or Form designer. This is similar to behavior of ASELOBJ(,1) except the array contains the additional elements. This includes when ASELOBJ(,3) is used in the Command window because no code editing window is active when the Command window is active.

The following table shows the order in which these elements appear.

Array element | Description
1 | Object reference to container object
2 | Full path and name of .scx or .vcx file
3 Full path and name of #INCLUDE file, if available
Note If no #INCLUDE file is available, the third element contains an empty string.

Return Values

Numeric data type. ASELOBJ( ) returns 1 if successful or 0 if unsuccessful.

Remarks

If no controls are selected, and the argument, 1, is omitted, ASELOBJ( ) returns 0 and does not create the array. If no controls exist on the form, ASELOBJ( ) does not recognize the form as the selected control. If no controls are currently selected and the argument, 1, is included, ASELOBJ( ) returns 1.

If the array does not exist, Visual FoxPro automatically creates the array.

If the array exists but is not large enough to contain all the information, Visual FoxPro automatically increases the size of the array to accommodate the information. If the array is larger than needed, Visual FoxPro truncates the array.

If the array exists, and ASELOBJ( ) returns 0 because no controls are selected, the array remains unchanged. If the array does not exist, and ASELOBJ( ) returns 0, the array is not created.

Example

Before running the following example, open a new form in the Form Designer and add one or more controls with Caption properties, such as a Label or CommandButton, to the form. Select a number of these controls and then run the example. ASELOBJ( ) displays the names of the selected controls, and then changes the captions of the selected controls.

gnobjects = ASELOBJ(gaSelected)     && Create array of control names
IF gnobjects > 0  && 0 indicates no controls selected
   CLEAR
   DISPLAY MEMORY LIKE gaSelected     && Displays selected controls
   FOR nCnt = 1 TO gnobjects
      ? gaSelected(nCnt).Caption + ' => New Caption ' ;
         + LTRIM(STR(nCnt))  && Display old and new caption
      gaSelected(nCnt).Caption = 'New Caption ' ;
         + ALLTRIM(STR(nCnt))  && Assign new caption
   NEXT
ENDIF

See Also

CREATE FORM | DataEnvironment Object | Form Designer | _ObjectReference( ) API Library Routine | AMOUSEOBJ( ) Function


ASESSIONS( ) Function

Creates an array of existing data session IDs.

ASESSIONS(ArrayName)

Return Values

Numeric. Returns the number of data sessions.

Parameters

ArrayName
Specifies the array that contains the data session IDs.

Remarks

If the array does not exist, Visual FoxPro automatically creates and populates it. Visual FoxPro automatically resizes the array to accommodate current data sessions.

See Also

Array Manipulation | Commands that Scope to a Data Session | Using Data Sessions


ASIN( ) Function

Returns in radians the arc sine of a numeric expression.

ASIN(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression whose arc sine ASIN( ) returns. The value of nExpression can range from +1 through –1, and the value ASIN( ) returns can range from –pi/2 through +pi/2 ( –1.57079 to 1.57079). The number of decimal places in the display of the result can be specified with SET DECIMALS.

Remarks

Use RTOD( ) to convert radians to degrees.

Example

CLEAR
? RTOD(ASIN(0))  && Returns 0.00
STORE 1 to gnArcAngle
? RTOD(ASIN(gnArcAngle))  && Returns 90.00
? RTOD(ASIN(SQRT(2)/2))  && Returns 45.00

See Also

RTOD( ) | SET DECIMALS | SIN( ) | Creating Numeric Expressions


ASORT( ) Function

Sorts elements in an array in ascending or descending order.

ASORT(ArrayName [, nStartElement [, nNumberSorted [, nSortOrder [, nFlags]]])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array to sort.
nStartElement
Specifies the starting element of the sort. If you omit nStartElement, the array is sorted starting with the first array element by default. If the array is one-dimensional, the sort includes nStartElement. If the array is two-dimensional, the starting element nStartElement determines both the row where the sort begins and the column that determines the sort order of the rows.
Note You can refer to an element in a two-dimensional array in one of two ways. The first method uses two subscripts to specify the row and column position of the element in the array; the other method uses an element number. This function and others that manipulate two-dimensional arrays require element numbers (in ASORT( ) the numeric expressions nStartElement and nNumberSorted). You can use AELEMENT( ) to return the element number from row and column subscripts in a two-dimensional array.

The following example illustrates that the starting element nStartElement determines how the rows in a two-dimensional array are sorted. A small array named gaArray is created and sorted twice. The first sort begins with the first element of gaArray; the rows are sorted based on the values contained in the first column of the array. The second sort begins with the fourth element of gaArray; the rows are sorted based on the values contained in the second column.

The first sort begins with the first row. The second sort begins with the second row. You can use DISPLAY MEMORY to display the contents of the array; in these examples tables are used to graphically display the results of the sorts.

These commands create the array named gaArray:

DIMENSION gaArray(3,2)
gaArray(1) = 'G'
gaArray(2) = 'A'
gaArray(3) = 'C'
gaArray(4) = 'Z'
gaArray(5) = 'B'
gaArray(6) = 'N'

gaArray looks like this:

Column 1 | Column 2
Row 1 | G | A
Row 2 | C | Z
Row 3 | B | N

The array is then sorted by ASORT( ) starting with the first element (1,1) in the array. The elements in the first column are placed in ascending order by rearranging the rows of the array.

=ASORT(gaArray,1)

Note the new order of the rows:

Column 1 | Column 2
Row 1 | B | N
Row 2 | C | Z
Row 3 | G | A

The array is then sorted starting with the fourth element (2,2) in the array. The elements in the second column are placed in order by rearranging the array rows.

=ASORT(gaArray,4)

Note the difference in the order of the rows:

Column 1 | Column 2
Row 1 | B | N
Row 2 | G | A
Row 3 | C | Z
nNumberSorted
Specifies the number of elements that are sorted in a one-dimensional array, or the number of rows that are sorted in a two-dimensional array. For example, if the array is one-dimensional and nStartElement is 2, indicating that the sort starts with the second array element, and nNumberSorted is 3, indicating that the sort should include three elements, the second, third and fourth array elements are sorted. If nNumberSorted is –1 or is omitted, all array elements from the starting element nStartElement through the last element in the array are sorted.

If the array is two-dimensional, nNumberSorted designates the number of rows to sort, beginning with the row containing the starting element nStartElement. For example, if nStartElement is 2 and nNumberSorted is 3, the row containing the second array element and the following two rows are sorted. If nNumberSorted is –1 or is omitted, all array rows beginning with the row containing the starting element nStartElement through the last array row are sorted.

nSortOrder
Specifies the sort order (ascending or descending) for the elements in the array. By default, array elements are sorted in ascending order. If nSortOrder is 0 or is omitted, the array elements are sorted in ascending order. If nSortOrder is any positive value, the array elements are sorted in descending order.
nFlags
Specifies case-sensitive search criteria to apply to the sort function. Valid values are 0 (the default) and 1. ASORT( ) uses the current collate sequence (see SET COLLATE) to determine the sort order. Certain collate sequences (such as "GENERAL") are not case-sensitive, and specifying nFlags = 0 will not cause a case-sensitive sorting.

The nFlags parameter is only useful when the current collate sequence is case-sensitive (such as "MACHINE"), and you wish to do a non-case-sensitive sort.

The number you specify in nFlags provides a bit-value that determines the case sensitivity of a sort according to the following table:

nFlag | Bit | Description
0 | 000 | Case-sensitive sort
1 | 001 | Case insensitive sort
Note If you specify nFlags, you can omit the other parameters by passing them in as -1.

Remarks

All elements included in the sort must be of the same data type. One-dimensional arrays are sorted by their elements; two-dimensional arrays are sorted by their rows. When a two-dimensional array is sorted, the order of the rows in the array is changed so that the elements in a column of the array are in ascending or descending order.

If the sort is successful, 1 is returned; otherwise –1 is returned.

Example

The following example copies the contact field from the customer table to an array named gaContact. The first 20 contacts in the array are displayed, the array is sorted, and the contacts are displayed again in sorted order.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer  && Open customer table

COUNT TO gnCount  && Number of contacts
DIMENSION gaContact(gnCount,1)  && Create a contact array
COPY TO ARRAY gaContact FIELD contact     && Fill the array

CLEAR
? 'Contact names:'
?
FOR nCount = 1 TO 20
   ? gaContact(nCount)  && Display first 20 contacts
ENDFOR
= ASORT(gaContact)     && Sort the array

?
? 'Sorted Contact names:'
?
FOR nCount = 1 TO 20
   ? gaContact(nCount)  && Display first 20 contacts, sorted
ENDFOR

See Also

ACOPY( ) | ADEL( ) | ADIR( ) | AELEMENT( ) | AFIELDS( ) | AINS( ) | ALEN( ) | ASCAN( )


ASTACKINFO( ) Function

Creates an array and populates it with information about the current state of the call stack.

AStackInfo(ArrayName)

Parameters

ArrayName
Specifies the name of the array that will contain the information about the examined object. The following table describes the information returned by the ASTACKINFO( ) function:
Array Element | Description
1 | Call Stack Level
2 | Current program filename
3 | Module or Object name
4 | Module or Object Source filename
5 | Line number in the object source file
6 | Source line contents

Return Value

Numeric

Remarks

ASTACKINFO( ) populates an array with information about the entire calling stack. It combines functionality of SYS(16) and Program( ) while adding new support for line numbers at each call stack level. The value returned is the number of program levels or rows of the returned array.

ASTACKINFO( ) only populates the 6th array element if source line contents are available, otherwise it will be left empty.

ASTACKINFO( ) provides, in the 2nd and 4th elements respectively, the name of the current file and, if the file is bound in an APP or other separate file, a full path name to the binding program.

The 4th element contains the original source file information. For objects, this is same information returned by SYS(16), even when bound inside of applications.

Note For PRG files it may be difficult to gather this information. In that case we simply display the 2nd element similar to what SYS(16) does today.

Example

A modeless form bound in an APP file (myAppl.app) with a button from buttons.vcx class (also in the APP). The developer runs myAppl.app in Visual FoxPro to display the form (the form remains open because this is not run time Visual FoxPro). When the user clicks the button to run the report, the report (which exists outside of myAppl.app) calls a query form in its BeforeOpenTables event.

This query form (getcusts.scx), which resides inside of myAppl.app, issues a call to ASTACKINFO( ) [then displays the resulting array as in the following example].

ASTACKINFO(myarray)
DISPLAY MEMO LIKE myarray
myArray
(1,1)   1                                    && Stack level = 1
(1,2)   c:\vfp\myAppl.app                        && Current program
(1,3) frmRerport.PrintReport.Click         && Object
(1,4) c:\vfp\myclasses\buttons.vct         && Object source file name
(1,5) 42                              && Line number in the source
(1,6) THISFORM.DoReport()                  && in the source
(2,1)   2                                    && Stack level = 2
(2,2) c:\vfp\myAppl.app
(2,3) frmRerport.DoReport
(2,4) c:\vfp\forms\frmRerport.sct         && Module source file name
(2,5) 31
(2,6) DO RunListReport                     && in the source
(3,1)   3                                    && Stack level = 3
(3,2) c:\vfp\myAppl.app
(3,3)
(3,4) c:\vfp\programs\runlisterport.prg   && Module source file name
(3,5) 12
(3,6) REPORT FORM myreport1.frx            && in the source
(4,1)   4                                    && Stack level = 4
(4,2) c:\vfp\reports\myreport1.frt
(4,3) myreport1.DataEnvironment.BeforeOpenTables
(4,4) c:\vfp\reports\myreport1.frt          && Module source file name
(4,5) 31
(4,6) DO FORM getcusts                     && in the source
(5,1)   5                                    && Stack level = 5
(5,2) c:\vfp\myAppl.app
(5,3) getcusts.init
(5,4) c:\vfp\forms\getcusts.sct            && Module source file name
(5,5) 2
(5,6) ASTACKINFO(myarray)                  && in the source

See Also

Arrays | Objects | Call Stack Window | LINENO( ) | PROGRAM( )


ASUBSCRIPT( ) Function

Returns the row or column subscript of an element from the element's number.

ASUBSCRIPT(ArrayName, nElementNumber, nSubscript)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array.
nElementNumber
Specifies the element number.
nSubscript
Determines if the row or column subscript is returned.

If the array is one-dimensional, include the element number in nElementNumber and 1 in nSubscript. ASUBSCRIPT( ) identically returns nElementNumber.

If the array is two-dimensional, include both the element number nElementNumber and a value of 1 or 2 in nSubscript. Specifying 1 in nSubscript returns the row subscript of the element, and specifying 2 returns the column subscript.

For more information on how to reference elements in an array, see DIMENSION.

Remarks

You can refer to elements in two-dimensional variable arrays in one of two ways. The first method uses two subscripts to specify the row and column position of the element in the array. The second method uses an element number. Use ASUBSCRIPT( ) to obtain an element's row or column subscript from the element's number.

In the following example, an array with two rows and three columns is created. DISPLAY MEMORY shows the contents of the elements of the array listed in element number order.

DIMENSION gaMyArray(2,3)
DISPLAY MEMORY LIKE gaMyArray
GAMYARRAY  Pub  A
  ( 1, 1)   L  .F. (element number 1)
  ( 1, 2)   L  .F. (element number 2)
  ( 1, 3)   L  .F. (element number 3)
  ( 2, 1)   L  .F. (element number 4)
  ( 2, 2)   L  .F. (element number 5)
  ( 2, 3)   L  .F. (element number 6)

Each of these commands stores the character string INVOICE to the same array element:

STORE 'INVOICE' TO gaMyArray(2, 1)
STORE 'INVOICE' TO gaMyArray(4)

In one-dimensional arrays, an element's number is identical to its single row subscript. It isn't necessary to use ASUBSCRIPT( ) with one-dimensional arrays.

See Also

ADEL( ) | ADIR( ) | AELEMENT( ) | AFIELDS( ) | AINS( ) | ALEN( ) | ASCAN( ) | ASORT( ) | DIMENSION | DISPLAY MEMORY


AT( ) Function

Returns the beginning numeric position of the first occurrence of a character expression or memo field within another character expression or memo field, counting from the leftmost character.

AT(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that AT( ) searches for in cExpressionSearched.
cExpressionSearched
Specifies the character expression cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size.

nOccurrence
Specifies which occurrence (first, second, third, and so on) of cSearchExpression is searched for in cExpressionSearched. By default, AT( ) searches for the first occurrence of cSearchExpression (nOccurrence = 1). Including nOccurrence lets you search for additional occurrences of cSearchExpression in cExpressionSearched. AT( ) returns 0 if nOccurrence is greater than the number of times cSearchExpression occurs in cExpressionSearched.

Remarks

AT( ) searches the second character expression for the first occurrence of the first character expression. It then returns an integer indicating the position of the first character in the character expression found. If the character expression isn't found, AT( ) returns 0.

The search performed by AT( ) is case-sensitive. To perform a search that isn't case-sensitive, use ATC( ).

Example

STORE 'Now is the time for all good men' TO gcString
STORE 'is the' TO gcFindString
CLEAR
? AT(gcFindString,gcString)  && Displays 5
STORE 'IS' TO gcFindString
? AT(gcFindString,gcString)  && Displays 0, case-sensitive

See Also

AT_C( ) | ATC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | ATCC( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | $ Operator | OCCURS( ) | INLIST( )


AT_C( ) Function

Returns the beginning numeric position of the first occurrence of a character expression or memo field within another character expression or memo field, counting from the leftmost character.

AT_C(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that AT_C( ) searches for in cExpressionSearched.
cExpressionSearched
Specifies the character expression cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size.

nOccurrence
Specifies which occurrence (first, second, third, and so on) of cSearchExpression is searched for in cExpressionSearched. By default, AT_C( ) searches for the first occurrence of cSearchExpression (nOccurrence = 1). Including nOccurrence lets you search for additional occurrences of cSearchExpression in cExpressionSearched. AT_C( ) returns 0 if nOccurrence is greater than the number of times cSearchExpression occurs in cExpressionSearched.

Remarks

AT_C( ) searches the second character expression for the first occurrence of the first character expression. It then returns an integer indicating the position of the first character in the character expression found. If the character expression isn't found, AT_C( ) returns 0.

AT_C( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, AT_C( ) is equivalent to AT( ).

The search performed by AT_C( ) is case-sensitive. To perform a search that isn't case-sensitive, use ATCC( ).

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

ATCC( ) | AT( ) | ATC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | ATCC( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | $ Operator | OCCURS( ) | INLIST( )


ATAGINFO( ) Function

Creates an array that contains information about the names, number, and types of indexes and key expressions.

ATagInfo(ArrayName [,cCDXName [, nWorkArea | cTableAlias]])

Parameters

ArrayName
Specifies the name of the array to be created. Visual FoxPro creates the array if it does not already exist.
cCDXName
Specifies the name of the compound index file for which ATAGINFO( ) returns information. If you specify the empty string ("") for cCDXName, ATAGINFO( ) returns the number of tags in all open .cdx files and all open .idx files for the selected table.
nWorkArea
Optional. Specifies the work area containing the table for which ATAGINFO( ) returns information.
cTableAlias
Optional. Specifies the alias of the table for which ATAGINFO( ) returns information. If you omit cTableAlias and nWorkArea the function uses the table in the current workarea.

Return Value

Numeric

Remarks

ATAGINFO( ) returns the number of .cdx compound index file tags and open .idx single-entry index files, and creates an array containing the tag name, tag Type (Primary/Candidate/Unique/Regular), the Key expression, filter, and order.

Column | Content | Data type
1 | Tag name (.idx name, if open) | Character
2 | Tag type (Primary, Candidate, Unique, or Regular | Character
3 | Key expression | Character
4 | Filter | Character
5 | Order (Ascending or Descending) | Character
6 | Collate sequence | Character

See Also

DESCENDING( ) | TAG( ) Function | TAGCOUNT( ) Function | TAGNO( ) Function | Tag Property


ATAN( ) Function

Returns in radians the arc tangent of a numeric expression.

ATAN(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies a numeric expression whose arc tangent ATAN( ) returns. nExpression can be any value. The value returned by ATAN( ) can range from –pi/2 through +pi/2 (–1.57079 to 1.57079). The number of decimal places displayed in the value returned by ATAN( ) is determined by SET DECIMALS.

Remarks

Use RTOD( ) to convert radians to degrees.

Example

CLEAR
? ATAN(0)  && Displays 0.00
STORE PI( )/2 to gnAngle
? ATAN(gnAngle)  && Displays 1.00
? ATAN(PI( )/2)  && Displays 1.00
? ATAN(DTOR(90))  && Displays 1.00

See Also

ATN2( ) | RTOD( ) | SET DECIMALS | TAN( ) | Creating Numeric Expressions


ATC( ) Function

Returns the beginning numeric position of the first occurrence of a character expression or memo field within another character expression or memo field, without regard for the case of these two expressions.

ATC(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that ATC( ) searches for in cExpressionSearched.
cExpressionSearched
Specifies the character expression cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size.

nOccurrence
Specifies which occurrence (first, second, third, and so on) of cSearchExpression is searched for in cExpressionSearched. By default, ATC( ) searches for the first occurrence of cSearchExpression (nOccurrence = 1). Including nOccurrence lets you search for additional occurrences of cSearchExpression in cExpressionSearched.

Remarks

ATC( ) searches the second character expression for the occurrence of the first character expression, without concern for the case (upper or lower) of the characters in either expression. Use AT( ) to perform a case-sensitive search.

ATC( ) returns an integer corresponding to the position where the first character of the character expression is found. If the character expression isn't found, ATC( ) returns 0.

Example

STORE 'Now is the time for all good men ... ' TO gcString
STORE 'IS THE' TO gcFindString
CLEAR
? ATC(gcFindString, gcString)  && Displays 5
STORE 'is' TO gcFindString
? ATC(gcFindString, gcString)  && Displays 5
? ATC('now',gcString)  && Displays 1

See Also

AT( ) | AT_C( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( )


ATCC( ) Function

Returns the beginning numeric position of the first occurrence of a character expression or memo field within another character expression or memo field, without regard for the case of these two expressions.

ATCC(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that ATCC( ) searches for in cExpressionSearched.
cExpressionSearched
Specifies the character expression cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size.

nOccurrence
Specifies which occurrence (first, second, third, and so on) of cSearchExpression is searched for in cExpressionSearched. By default, ATCC( ) searches for the first occurrence of cSearchExpression (nOccurrence = 1). Including nOccurrence lets you search for additional occurrences of cSearchExpression in cExpressionSearched.

Remarks

ATCC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, ATCC( ) is equivalent to ATC( ).

ATCC( ) searches the second character expression for the occurrence of the first character expression, without concern for the case (upper or lower) of the characters in either expression. Use AT_C( ) to perform a case-sensitive search.

ATCC( ) returns an integer corresponding to the position where the first character of the character expression is found. If the character expression isn't found, ATCC( ) returns 0.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT( ) | AT_C( ) | ATC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( )


ATCLINE( ) Function

Returns the line number of the first occurrence of a character expression or memo field within another character expression or memo field, without regard for the case (upper or lower) of the characters in either expression.

ATCLINE(cSearchExpression, cExpressionSearched)

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that ATCLINE( ) searches for in cExpressionSearched.
cExpressionSearched
Specifies the character expression cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size. Use MLINE( ) to return the line containing the matching character expression.

Tip ATCLINE( ) offers a convenient way to search memo fields.

Remarks

If the search is successful, ATCLINE( ) returns the number of the line containing the first character expression. If the search is unsuccessful, ATCLINE( ) returns 0.

The line number that ATCLINE( ) returns is determined by the value of SET MEMOWIDTH, even if cExpressionSearched isn't a memo field. For more information, see SET MEMOWIDTH.

Use ATLINE( ) to perform a case-sensitive search.

Example

Example 1 locates the first time a character string occurs in a memo field, displays the first and last names of the employee, and the line of the memo containing the character string.

Example 2 demonstrates how the memo width affects ATCLINE( ).

* Example 1
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee  && Open employee table

CLEAR
STORE 'JAPANESE' TO gcFindString  && Case insensitive
LOCATE FOR ATCLINE(gcFindString, notes) != 0
? First_Name
?? Last_Name
? MLINE(notes, ATCLINE(gcFindString, notes))

* Example 2
STORE '1234567890ABCDEFGHIJ' TO gcString
SET MEMOWIDTH TO 20
? ATCLINE('AB', gcString)  && Displays 1
SET MEMOWIDTH TO 10
? ATCLINE('AB', gcString)  && Displays 2

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) Function | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | MLINE( ) | SET MEMOWIDTH


ATLINE( ) Function

Returns the line number of the first occurrence of a character expression or memo field within another character expression or memo field, counting from the first line.

ATLINE(cSearchExpression, cExpressionSearched)

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that Microsoft Visual FoxPro looks for in cExpressionSearched.
cExpressionSearched
Specifies the character expression that cSearchExpression searches for.

Both cSearchExpression and cExpressionSearched can be memo fields of any size.

Use MLINE( ) to return the line containing the matching character expression as a character string.

Tip ATLINE( ) offers a convenient way to search memo fields.

Remarks

ATLINE( ) searches the second character expression for the occurrence of the first character expression. ATLINE( ) performs a case-sensitive search. Use ATCLINE( ) to perform a search that isn't case-sensitive.

If the search is successful, ATLINE( ) returns the number of the line where the match occurs. If the search is unsuccessful, ATLINE( ) returns 0.

The line number that ATLINE( ) returns is determined by the value of SET MEMOWIDTH, even if cExpressionSearched isn't a memo field. For more information, see SET MEMOWIDTH.

Example

Example 1 locates the first time a character string occurs in a memo field, displays the first and last names of the employee, and the line of the memo containing the character string.

Example 2 demonstrates how the memo width affects ATLINE( ).

* Example 1
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee  && Open employee table

CLEAR
STORE 'Japanese' TO gcFindString  && Case sensitive
LOCATE FOR ATLINE(gcFindString, notes) != 0
? First_Name
?? Last_Name
? MLINE(notes, ATLINE(gcFindString, notes))

* Example 2
STORE '1234567890ABCDEFGHIJ' TO gcString
SET MEMOWIDTH TO 20
? ATLINE('AB', gcString)  && Displays 1
SET MEMOWIDTH TO 10
? ATLINE('AB', gcString)  && Displays 2

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) Function | ATCLINE( ) Function | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | MLINE( ) | SET MEMOWIDTH | $ Operator | OCCURS( ) | INLIST( )


ATN2( ) Function

Returns the arc tangent in all four quadrants from specified values.

ATN2(nYCoordinate, nXCoordinate)

Return Values

Numeric

Parameters

nYCoordinate
Specifies the y coordinate.
nXCoordinate
Specifies the x coordinate.

Remarks

ATN2( ) returns the angle (in radians) between the line y = 0 and the line connecting the specified coordinates and the origin (0, 0) of the coordinate system.

ATN2( ) returns a value between – pi/2 and +pi/2.

You can convert the value returned by ATN2( ) to degrees with RTOD( ). You can specify the number of decimal places that are displayed in the result with SET DECIMALS.

Example

CLEAR
? PI( )  && Displays 3.14
? ATN2(0,-1)  && Displays 3.14
STORE COS(PI( )) TO gnXCoord
STORE SIN(PI( )) TO gnYCoord
? ATN2(gnYCoord,gnXCoord)  && Displays 3.14
? ATN2(gnYCoord,gnXCoord)/PI( )  && Displays 1.00

See Also

ATAN( ) | DTOR( ) | RTOD( ) | SET DECIMALS | TAN( )


AUSED( ) Function

Places table aliases and work areas for a data session into a variable array.

AUSED(ArrayName [, nDataSessionNumber])

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array containing the table aliases and work areas for a data session. If the array you specify does not exist, Visual FoxPro automatically creates the array. If the array exists and is not large enough to contain all the table aliases and work areas, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array. If the array exists, and AUSED( ) returns 0 because no tables are open in the data session, the array remains unchanged. If the array does not exist, and AUSED( ) returns 0, the array is not created.
nDataSessionNumber
Specifies the data session number for which AUSED( ) returns the table aliases and work areas. If you omit nDataSessionNumber, AUSED( ) returns information about the current data session. Use SET DATASESSION to specify the current data session.

Remarks

AUSED( ) returns the number of rows in the array, which is identical to the number of tables open in the data session.

AUSED( ) creates a two-dimensional array and places the aliases of tables open for the data session in the first column of the array. The second column of the array contains the tables' corresponding work area numbers.

The table aliases are placed into the array in reverse order that they were opened in. For example, the first array element contains the alias of the last table opened, and the last array element contains the alias of the first table opened. This ordering is useful when using TABLEUPDATE( ) on views that contain views. For example:

FOR  x = 1 TO AUSED(atbl,1)
TABLEUPDATE(0,.T.,x)
NEXT

Example

The following example uses AUSED( ) to create an array named gaInuse that contains the table aliases and work areas for tables open in the current data session. The number of open tables for the current data session is displayed, and the table aliases and work areas are then displayed.

OPEN DATABASE (HOME(2) + 'Data\testdata') EXCLUSIVE
USE Customer IN 0
CLEAR
? AUSED(gaInuse)
DISPLAY MEMORY LIKE gaInuse
CLOSE DATABASES

See Also

ALIAS( ) | SET DATASESSION | USE | Working with Table Aliases


AVCXCLASSES( ) Function

Places the information about classes in a class library into an array.

AVCXCLASSES(ArrayName, cLibraryName)

Return Values

Numeric

Parameters

ArrayName
Specifies the name of the array in which the class information is placed. If the array you specify doesn't exist, Visual FoxPro automatically creates the array. If the array exists and isn't large enough to contain the class names and base classes, Visual FoxPro automatically increases the size of the array. If the array is larger than necessary, Visual FoxPro truncates the array.

The array contains a row for each class in the class library, and each row contains 11 columns containing information about the class. The following table lists the class information in each column.

Column | Class information | .VCX field name
1 | Class name. | OBJNAME
2 | Base class of the class. | BASECLASS
3 | Parent class name of the class. | CLASS
4 | Relative path and file name of the parent class library. | CLASSLOC
5 | Relative path and file name of the bitmap for a custom class icon. | RESERVED4
6 | Relative path and file name for a custom Project Manager or Class Browser class icon. | RESERVED5
7 | ScaleMode of the class, Pixels or Foxels. | RESERVED6
8 | Description of the class. | RESERVED7
9 | Relative path and file name for the #INCLUDE file for the class. | RESERVED8
10 | User-defined information for the class. | USER
11 | Logical true (.T.) if the class is OLEPUBLIC, otherwise logical false (.F.). | RESERVED2
cLibraryName
Specifies the name of the class library for which AVCXCLASSES( ) places class information into the array specified with ArrayName. cLibraryName can contain a path to the class library. An error is generated if the class library you specify doesn't exist.

Remarks

AVCXCLASSES( ) returns the number of rows in the array (the number of classes in the class library).

Example

The following example uses AVCXCLASSES( ) to create and populate an array named aClasses with the names and base classes of the classes in the Buttons class library. DISPLAY MEMORY lists the contents of the array in the main Visual FoxPro window.

ACTIVATE SCREEN
CLEAR

? AVCXCLASSES(aClasses, '\VFP\SAMPLES\CLASSES\BUTTONS.VCX')
*** Displays 5

FOR nColCount = 1 TO ALEN(aClasses,2) && Loop through columns
   ? aClasses(1, nColCount) && Each column of the 1st class
NEXT

*** Displays the following:
*
* cmdCancel
* commandbutton
* cmdok
* buttons.vcx
* cancel.bmp
* cancel.bmp
* Pixels
* Release Form or Form Set
*
*
* .F.

See Also

ACLASS( ) | AGETCLASS( ) | AMEMBERS( ) | CREATE CLASS


BAR( ) Function

Returns the number of the most recently chosen item from a menu defined with DEFINE POPUP or a menu item chosen from a Visual FoxPro menu.

BAR( )

Return Values

Numeric

Remarks

Each item on a menu is assigned a number with DEFINE BAR. When a menu item is chosen from the menu, BAR( ) returns the number assigned to that item. A program can branch to other routines based on the value that BAR( ) returns.

BAR( ) returns 0 if there is no active menu or if the user presses ESC to exit the menu.

Example

The following example uses BAR( ) to pass the number of a menu item to a procedure. The current system menu bar is saved to memory with SET SYSMENU SAVE, and then all system menu titles are removed with SET SYSMENU TO.

Two menu titles are created with DEFINE PAD; DEFINE POPUP is used to create a menu for each menu title. DEFINE BAR is used to create items on each menu. When you choose a menu title, ON PAD uses ACTIVATE POPUP to activate the corresponding menu.

When you choose an item from a menu, ON SELECTION POPUP uses BAR( ) and POPUP( ) to pass the item number and menu title to the choice procedure. The choice procedure displays the number of the chosen item and the name of the menu containing the item, and the original Visual FoxPro system menu is restored with SET SYSMENU TO DEFAULT.

*** Name this program BAR_EXAM.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD padConv OF _MSYSMENU ;
   PROMPT '\<Conversions' COLOR SCHEME 3 ;
   KEY ALT+C, ''
DEFINE PAD padCard OF _MSYSMENU ;
   PROMPT 'Card \<Info' COLOR SCHEME 3 ;
   KEY ALT+I, ''
ON PAD padConv OF _MSYSMENU ACTIVATE POPUP popConv
ON PAD padCard OF _MSYSMENU ACTIVATE POPUP popCard
DEFINE POPUP popConv MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF popConv PROMPT 'Ar\<ea' KEY CTRL+E, '^E'
DEFINE BAR 2 OF popConv PROMPT '\<Length' ;
   KEY CTRL+L, '^L'
DEFINE BAR 3 OF popConv PROMPT 'Ma\<ss' ;
   KEY CTRL+S, '^S'
DEFINE BAR 4 OF popConv PROMPT 'Spee\<d' ;
   KEY CTRL+D, '^D'
DEFINE BAR 5 OF popConv PROMPT '\<Temperature' ;
   KEY CTRL+T, '^T'
DEFINE BAR 6 OF popConv PROMPT 'T\<ime' ;
   KEY CTRL+I, '^I'
DEFINE BAR 7 OF popConv PROMPT 'Volu\<me' ;
   KEY CTRL+M, '^M'
*** Here is where the POPCONV menu uses the BAR( ) function
*** to pass a bar number to the procedure called choice below.
ON SELECTION POPUP popConv;
   DO choice IN bar_exam WITH BAR( ), POPUP( )
DEFINE POPUP popCard MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF popCard PROMPT '\<View Charges' ;
   KEY ALT+V, ''
DEFINE BAR 2 OF popCard PROMPT 'View \<Payments' ;
   KEY ALT+P, ''
DEFINE BAR 3 OF popCard PROMPT 'Vie\<w Users' ;
   KEY ALT+W, ''
DEFINE BAR 4 OF popCard PROMPT '\-'
DEFINE BAR 5 OF popCard PROMPT '\<Charges ';
   KEY ALT+C
DEFINE BAR 6 OF popCard PROMPT '\-'
DEFINE BAR 7 OF popCard PROMPT 'E\<xit ';
   KEY ALT+X
*** Here is where the POPCARD menu uses the BAR( ) function
*** to pass a bar number to the procedure called choice below.
ON SELECTION POPUP popCard;
   DO choice IN bar_exam WITH BAR( ), POPUP( )
*** The procedure choice uses the gnBar parameter
*** to contain the value passed by the BAR( ) function.
PROCEDURE choice
PARAMETERS gnBar, gcPopup
WAIT WINDOW 'You chose bar #' + LTRIM(STR(gnBar)) + ;
   ' from popup ' + gcPopup NOWAIT
SET SYSMENU TO DEFAULT

See Also

ACTIVATE POPUP | CNTBAR( ) | DEFINE BAR | DEFINE POPUP | GETBAR( ) | MRKBAR( ) | ON BAR | ON SELECTION BAR | PRMBAR( )


BARCOUNT( ) Function

Included for compatibility with dBASE.


BARPROMPT( ) Function

Included for compatibility with dBASE.


BETWEEN( ) Function

Determines whether the value of an expression lies between the values of two other expressions of the same data type.

BETWEEN(eTestValue, eLowValue, eHighValue)

Return Values

Logical or null value

Parameters

eTestValue
Specifies the expression whose value BETWEEN( ) tests. If the value of eTestValue is greater than or equal to the value of eLowerValue and less than or equal to the value of eHighValue, BETWEEN( ) returns True (.T.). Otherwise, BETWEEN( ) returns False (.F.). BETWEEN( ) returns the null value if either eLowValue or eHighValue are the null value.
eLowValue
Specifies the lower value in the range BETWEEN( ) evaluates.
eHighValue
Specifies the upper value in the range BETWEEN( ) evaluates.

Remarks

BETWEEN( ) returns a value of True (.T.) if the value of a character, date, datetime, numeric, float, integer, double, or currency expression lies between the values of two other expressions of the same data type. If the value of the expression doesn't lie between the values of two other expressions, BETWEEN( ) returns False (.F.). BETWEEN( ) returns the null value if either eLowValue or eHighValue is the null value.

Example

The following example scans the orders table for all records in the order_amt field with values between 950 and 1000 inclusive and displays the cust_id field and the order_amt field.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE orders  && Open order table

CLEAR
SCAN FOR BETWEEN(order_amt,950,1000)
   ? cust_id, order_amt
ENDSCAN

See Also

MAX( ) | MIN( ) | SET TRBETWEEN Command


BINDEVENT() Function

You can use BINDEVENT() to bind events, properties, or methods from native Visual FoxPro objects to other Visual FoxPro objects. To bind events from Component Object Model (COM) objects, use the EVENTHANDLER() function.

Note The ActivePage property is not supported when using BINDEVENT( ).
BINDEVENT(oEventSource, cEvent, oEventHandler, cDelegate [, nFlags])

Parameters

oEventSource
Specifies the event source, which must be a valid Visual FoxPro object.
cEvent
Specifies the name of the event, method, or property you want to bind.
oEventHandler
Specifies the object, which must be a valid Visual FoxPro object, handling the event.
cDelegate
Specifies the method, or "delegate", that handles the event for oEventHandler.

The delegate method must have the same parameters as the event specified in cEvent. You can call the AEVENTS() function to retrieve an object reference to the event source. If the delegate method does not have enough parameters to handle those passed by the event, Visual FoxPro generates an error.

nFlags
Specifies an additive bit flag you can set for the event binding operation.
nFlags | Bits | Description
0 | 00 | Call delegate code before event code. (Default)
1 | 01 | Call event code before delegate code.
2 | 10 | Do not trigger event (call delegate code) when a simple method call occurs.
31 | 11 | Call event code before delegate code. Do not trigger event (call delegate code) when simple method calls occur.

1If you use an nFlags value of 1, the value returned by a method call to the event is not that of the event, rather that of the last delegate invoked. The event gets called before any of the delegates, so the return value of the delegate is the remaining value on the stack. Therefore, it is recommended that the delegate method contain the same return value as that of the event itself. In Visual FoxPro, a procedure that has no explicit RETURN statement returns an implicit value of True (.T.). This is an issue only if the event was triggered by method call and not via normal interactive mode or RAISEEVENT() call.

The following table shows whether an event is raised when Bit 1 is off or on.

Event type | OFF (Default) | ON
Interactive | YES | YES
Programmatic | YES | NO
RAISEEVENT( ) | YES | YES

Return Values

Numeric data type. BINDEVENT() returns the number of bindings for the object's event.

Remarks

You can bind to any valid Visual FoxPro object event, property, or method, including the Access and Assign methods. However, the event and delegate methods must be public, not protected or hidden, members of the class.

You cannot bind to an event with parameters that are passed by reference. Though calling BINDEVENT( ) succeeds, raising the event, for example, using RAISEEVENT( ), fails.

When you bind to a property, you should bind to it directly and not to the Assign method. If you bind directly to the Assign method, be aware that Access and Assign methods are marked as Protected and are not visible except within the class.

Note If you bind to a property that has an Assign method, the delegate method might trigger twice. The first time is when the property assignment call is made. The second time is when the property is actually set, within the Assign method, to the parameter that is passed. The delegate method should be aware of this possibility.

Normal rules of inheritance apply. If the delegate method does not contain any code, Visual FoxPro traverses up the parent hierarchy.

An event handler is called when an event occurs or if it is called as a method. Calling the event as a method triggers the event unless you specify a nFlags value of 2 or 3.

By default, Visual FoxPro calls the delegate method before the event. However, you can change the default behavior by using an nFlags setting.

If you specify a property as the event you want to bind, Visual FoxPro binds that property to an implicit Assign method. When the value of the property changes, Visual FoxPro triggers an event.

If an invalid parameter is passed, Visual FoxPro generates the error, "Function argument value, type, or count is invalid." However, if a problem occurs during the binding operation, Visual FoxPro does not generate an error. You can retrieve the return value of BINDEVENT( ) to check the number of bindings.

Certain control events such as GotFocus, LostFocus, InteractiveChange, and ProgrammaticChange do not work if the second bit of the nFlags parameter is set, for example, nFlags set to 2. These events are treated as method calls internally by Visual FoxPro, even though they are considered events. The same behavior applies to the Refresh method of an object on a form that is called when the form's Refresh method is called. Certain events such as When and Valid require code in the event for it to occur.

BINDEVENT( ) does not directly support the Value property because it is handled by Visual FoxPro in a special way. You should use the InteractiveChange and ProgrammaticChange events instead.

If the original event contains a NODEFAULT command, Visual FoxPro still processes the event because it is possible that the delegate method is called before the event. NODEFAULT applies only to native Visual FoxPro events.

If you make an exact duplicate BINDEVENT() call, Visual FoxPro disregards the call but still returns the number of bindings for the object's event. If you change the nFlags setting, you can call BINDEVENT( ) to rebind the event.

Example

The following example shows how you can keep the Class Browser positioned to the right side of the Visual FoxPro desktop, regardless of how the desktop is resized. BINDEVENT( ) associates the Resize event of the _SCREEN system variable, or Visual FoxPro desktop, with oHandler, which uses myresize as its delegate. The code for myresize runs when the Resize event is triggered.

PUBLIC oHandler
oHandler=NEWOBJECT("myhandler")
DO (_browser)
BINDEVENT(_SCREEN,"Resize",oHandler,"myresize")

DEFINE CLASS myhandler AS Session
   PROCEDURE myresize
      IF ISNULL(_obrowser) THEN
         UNBINDEVENT(THIS)
      ELSE
         _obrowser.left = _SCREEN.Width - _obrowser.width
      ENDIF
   RETURN
ENDDEFINE

See Also

Functions | Event Binding for Visual FoxPro Objects | UNBINDEVENTS() Function | RAISEEVENT() Function | AEVENTS() Function


BINTOC( ) Function

Converts an integer value to a binary character representation.

BINTOC(nExpression [, nSize])

Return Values

Character

Parameters

nExpression
Specifies the integer value to convert.
nSize
Specifies the length in characters of the returned character string.

nSize also determines the value you can specify for nExpression. The following table lists the permissible values for nSize and the corresponding range of values for nExpression:

nSize | nExpression Range
1 | –128 to 127
2 | –32,768 to 32,767
4 (default) | –2,147,483,648 to 2,147,483,647

If nSize is omitted, BINTOC( ) returns a character string composed of four characters.

Remarks

BINTOC( ) can be used to reduce the size of indexes for numeric fields containing integer data. For example, a numeric field named iPartCode might contain an integer value from 1 to 127, which corresponds to a parts classification code. BINTOC( ) lets you convert the value in the numeric field to a single character representation. For example, the following command creates an index with a one-character index key:

INDEX ON BINTOC(nPartCode,1) TAG PartCode

See Also

CTOBIN( ) Function | CREATEBINARY( ) Function | Integer Field Type


BITAND( ) Function

Returns the result of a bitwise AND operation performed on two or more numeric values.

BITAND(nExpression1, nExpression2, … nExpression26)

Return Values

Numeric

Parameters

nExpression1, nExpression2,... nExpression26
Specifies the numeric values on which the bitwise AND operation is performed. If nExpressions are not integers, they are converted to integers before the bitwise AND operation is performed. A maximum of 26 parameters can be passed.

Remarks

BITAND( ) compares each bit in nExpressionN to the corresponding bit in nExpressionN+1. If the bits in nExpressionN and nExpressionN+1 are both 1, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

The following table shows the result of a bitwise AND operation on corresponding nExpressionN and nExpressionN+1 bits:

nExpressionN bit | nExpressionN+1 bit | Resulting bit
0 | 0 | 0
0 | 1 | 0
1 | 1 | 1
1 | 0 | 0

Example

x = 3  && 0011 binary
y = 6  && 0110 binary

? BITAND(x,y) && Returns 2, 0010 binary

See Also

BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITCLEAR( ) Function

Clears a specified bit (sets it to 0) in a numeric value and returns the resulting value.

BITCLEAR(nExpression1, nExpression2)

Return Values

Numeric

Parameters

nExpression1
Specifies the numeric value in which a bit is cleared. If nExpression1 is not an integer, it is converted to an integer before its bit is set.
nExpression2
Specifies the bit position in nExpression1 that is cleared. nExpression2 can range from 0 to 31; 0 is the rightmost bit.

Example

x = 7  && 0111 binary
y = 1  && 2nd bit position (0 = 1st bit position)
? BITCLEAR(x,y) && Returns 5, 0101 binary

See Also

BITAND( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITLSHIFT( ) Function

Returns the result of shifting the bits of a numeric value to the left a specified number of positions.

BITLSHIFT(nExpression1, nExpression2)

Return Values

Numeric

Parameters

nExpression1
Specifies the numeric value whose bits are shifted to the left. If nExpression1 is not an integer, it is converted to an integer before its bits are shifted.
nExpression2
Specifies the number of bit positions to shift. If nExpression2 is not an integer, it is converted to an integer.

Example

x = 5  && 0101 binary
y = 1  && Shift bits 1 position left

? BITLSHIFT(x,y) && Returns 10, 1010 binary

See Also

BITAND( ) | BITCLEAR( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITNOT( ) Function

Returns the result of a bitwise NOT operation performed on a numeric value.

BITNOT(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric value on which the bitwise NOT operation is performed. If nExpression is not an integer, it is converted to an integer before its bits are shifted.

Remarks

BITNOT( ) returns the bitwise complement of nExpression. The numeric value returned by BITNOT( ) represents nExpression with each bit of value 0 switched to 1 and each bit of value 1 switched to 0.

The following table shows the result of a bitwise NOT operation on nExpression:

nExpression bit | Resulting bit
0 | 1
1 | 0

Example

x = 5  && 0101 binary
? BITNOT(x) && Returns -6

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITOR( ) Function

Returns the result of a bitwise inclusive OR operation performed on two numeric values.

BITOR(nExpression1, nExpression2, …, nExpressionN )

Return Values

Numeric

Parameters

nExpression1, nExpression2, nExpressionN
Specifies the numeric values on which the bitwise inclusive OR operation is performed. If nExpression1 and nExpression2 are not integers, they are converted to integers before the bitwise inclusive OR operation is performed.
Note A maximum of 26 parameters can be passed.

Remarks

BITAND( ) compares each bit in nExpressionN to the corresponding bit in nExpressionN+1. If the bits in nExpressionN and nExpressionN+1 are both 1, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

The following table shows the result of an inclusive OR operation on corresponding nExpressionN and nExpressionN+1 bits:

nExpressionN bit | nExpressionN+1 bit | Resulting bit
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

Example

x = 5  && 0101 binary
y = 6  && 0110 binary

? BITOR(x,y) && Returns 7, 0111 binary

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITRSHIFT( ) Function

Returns the result of shifting the bits of a numeric value to the right a specified number of positions.

BITRSHIFT(nExpression1, nExpression2)

Return Values

Numeric

Parameters

nExpression1
Specifies the numeric value whose bits are shifted to the right. If nExpression1 is not an integer, it is converted to an integer before its bits are shifted.
nExpression2
Specifies the number of bit positions to shift. If nExpression2 is not an integer, it is converted to an integer.

Example

x = 5  && 0101 binary
y = 1  && Shift bits 1 position right

? BITRSHIFT(x,y) && Returns 2, 0010 binary

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITSET( ) | BITTEST( ) | BITXOR( )


BITSET( ) Function

Sets the bit to 1 in a numeric value and returns the resulting value.

BITSET(nExpression1, nExpression2)

Return Values

Numeric

Parameters

nExpression1
Specifies the numeric value in which a bit is set. If nExpression1 is not an integer, it is converted to an integer before its bit is set.
nExpression2
Specifies the bit position in nExpression1 that is set to 1. nExpression2 can range from 0 to 31; 0 is the rightmost bit.

Example

x = 5  && 0101 binary
y = 1  && 2nd bit position (0 = 1st bit position)
? BITSET(x,y) && Returns 7, 0111 binary

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITTEST( ) | BITXOR( )


BITTEST( ) Function

Returns True (.T.) if a specified bit in a numeric value is set to 1; otherwise, returns False (.F.).

BITTEST(nExpression1, nExpression2)

Return Values

Logical

Parameters

nExpression1
Specifies the numeric value in which a bit is checked. If nExpression1 is not an integer, it is converted to an integer before its bit is checked.
nExpression2
Specifies the bit position in nExpression1 that is checked. nExpression2 can range from 0 to 31; 0 is the rightmost bit.

Example

The following example uses BITTEST( ) to determine whether a series of integers are even. If an integer is even, the function IsEven returns True (.T.); otherwise, it returns False (.F.).

CLEAR
? '2 even? '
?? IsEven(2)  && Even, .T. returned
? '3 even? '
?? IsEven(3)  && Not even, .F. returned
? '0 even? '
?? IsEven(0)  && Even, .T. returned
? '-13 even? '
?? IsEven(-13)  && Not even, .F. returned

Function IsEven
   PARAMETER nInteger
   RETURN NOT BITTEST(nInteger, 0)

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITXOR( )


BITXOR( ) Function

Returns the result of a bitwise exclusive OR operation performed on two numeric values.

BITXOR(nExpression1, nExpression2, …, nExpressionN )

Return Values

Numeric

Parameters

nExpression1, nExpression2, nExpressionN
Specifies the numeric values on which the bitwise exclusive OR operation is performed. If nExpression1 and nExpression2 are not integers, they are converted to integers before the bitwise exclusive OR operation is performed.
Note A maximum of 26 parameters can be passed.

Remarks

BITAND( ) compares each bit in nExpressionN to the corresponding bit in nExpressionN+1. If the bits in nExpressionN and nExpressionN+1 are both 1, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

The following table shows the result of an exclusive OR operation on corresponding nExpressionN and nExpressionN+1 bits:

nExpressionN bit | nExpressionN+1 bit | Result bit
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

Example

x = 5  && 0101 binary
y = 6  && 0110 binary

? BITXOR(x,y) && Returns 3, 0011 binary

See Also

BITAND( ) | BITCLEAR( ) | BITLSHIFT( ) | BITNOT( ) | BITOR( ) | BITRSHIFT( ) | BITSET( ) | BITTEST( )


BOF( ) Function

Determines whether the record pointer is positioned at the beginning of a table.

BOF([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea
Specifies the work area number for a table open in another work area.
cTableAlias
Specifies the table alias for a table open in another work area.

If the table you want to test for a beginning-of-file condition is open in a work area other than the currently selected work area, use these optional arguments to specify the work area number or table alias for the table. If a table isn't open in the work area you specify, BOF( ) returns false (.F.).

Remarks

Use BOF( ) to test for a beginning-of-file condition for a table. BOF( ) returns true (.T.) if you have tried to move the record pointer to a position before the first record in the table.

Example

The following example opens the customer table and lists the company name one page at a time, starting with the last record in the table. The listing continues until the beginning of the file is reached or until you choose Cancel.

CLOSE DATABASES
CLEAR
OPEN DATABASE (HOME() + "samples\data\testdata")
USE customer
GO BOTTOM
local recCtr, btnValue
recCtr = 0
btnValue = 1
DO WHILE btnValue = 1 AND NOT BOF()
 ? "Company : " + company
 recCtr = recCtr + 1
 if (recCtr % 20) = 0 then
  btnValue =MESSAGEBOX ("Click OK to continue, Cancel to quit.",33)
  clear
 endif
 Skip -1    && Move up one record
ENDDO
=MESSAGEBOX("Listing complete.",48)

See Also

EOF( ) | FEOF( ) Function | _FEOF( ) API Library Routine


CANDIDATE( ) Function

Returns true (.T.) if an index tag is a candidate index tag; otherwise, returns false (.F.).

CANDIDATE([nIndexNumber] [, nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nIndexNumber
Specifies the number of the index tag for which CANDIDATE( ) returns the candidate status. CANDIDATE( ) returns the candidate status in the following order as nIndexNumber increases from 1 to the total number of structural compound and independent compound index tags:
  1. Candidate status for each tag in the structural compound index (if one is present) is returned first. The candidate status is returned for the tags in the order in which the tags are created in the structural index.
  2. Candidate status for each tag in any open independent compound indexes is returned last. The candidate status is returned for the tags in the order in which the tags are created in the independent compound indexes.

If you omit nIndexNumber, CANDIDATE( ) checks the master controlling index tag to see if it is a candidate index tag. If there is no master controlling index tag, CANDIDATE( ) returns false (.F.).

nWorkArea
Specifies the work area of the index tag specified with nIndexNumber.
cTableAlias
Specifies the work area of the index tag specified with nIndexNumber.

If you omit nWorkArea and cTableAlias, CANDIDATE( ) checks the index tag in the currently selected work area to see if it is a candidate index tag.

Remarks

A candidate index tag is an index tag that can become the primary index tag because it does not contain null or duplicate values.

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which the candidate status of each index tag in the customer structural index is checked. The name of each structural index tag is displayed with its candidate status.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? TAG(nCount)  && Display tag name
   ? CANDIDATE(nCount)  && Display candidate status
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

ALTER TABLE - SQL | CREATE TABLE - SQL | INDEX | PRIMARY( )


CAPSLOCK( ) Function

Returns the current mode of the CAPS LOCK key or sets the CAPS LOCK key mode on or off.

CAPSLOCK([lExpression])

Return Values

Logical

Parameters

lExpression
Include to turn the CAPS LOCK key on or off. CAPSLOCK(.T.) turns CAPS LOCK on and CAPSLOCK(.F.) turns CAPS LOCK off. A logical value is returned corresponding to the CAPS LOCK setting before CAPSLOCK(.T.) or CAPSLOCK(.F.) is issued.

Remarks

Issuing CAPSLOCK( ) with no argument returns true (.T.) if CAPS LOCK is on, or false (.F.) if CAPS LOCK is off.

Example

The following code stores the state of CAPSLOCK( ) to a system variable. The = command executes the CAPSLOCK( ) function to set CAPS LOCK on. Then the = command executes the CAPSLOCK( ) function to set CAPS LOCK to its previous state.

glOldLock = CAPSLOCK( )     && Save original setting
= CAPSLOCK(.T.)     && Turn CAPS LOCK on

*** Perform any number of statements ***

= CAPSLOCK(glOldLock)  && Return to original setting

*** or, toggle CapsLock to the opposite value and back ***

= CAPSLOCK(!CAPSLOCK( ))
WAIT WINDOW
= CAPSLOCK(!CAPSLOCK( ))
WAIT WINDOW
= CAPSLOCK(glOldLock)  && Return to original setting

See Also

INSMODE( ) | NUMLOCK( ) | = Command


CDOW( ) Function

Returns the day of the week from a given Date or DateTime expression.

CDOW(dExpression | tExpression)

Return Values

Character

Parameters

dExpression
Specifies the date from which CDOW( ) returns the day.
tExpression
Specifies the datetime from which CDOW( ) returns the day.

Remarks

CDOW( ) returns the name of the day of the week as a string in proper noun format.

Example

STORE {^1998-02-16} TO gdDate
CLEAR
? CDOW(gdDate)  && Displays Monday

See Also

DAY( ) | DOW( ) | SET FDOW | SET FWEEK | SYS( ) Functions Overview | DATETIME( )


CDX( ) Function

Returns the names of the open compound index (.cdx) file that has the specified index position number.

CDX(nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nIndexNumber
The following apply to a table with a structural compound index and one or more compound indexes:
nIndexNumber | Description
1 | Returns the name of the structural index file (which is always the same as the name of the table).
2 | Returns the first compound index file name specified in the INDEX clause of USE or in SET INDEX.
3 | Returns the second compound index file name, if any, and so on.
Greater than the number of open .cdx files | Returns the empty string.

The following apply to a table with no structural compound index and one or more compound indexes:

nIndexNumber | Description
1 | Returns the first compound index file name specified in the INDEX clause of USE or in SET INDEX.
2 | Returns the second compound index file name, if any, and so on.
Greater than the number of open .cdx files | Returns the empty string.
nWorkArea
Specifies the work area number of a table whose open compound index file names you want CDX( ) to return.
cTableAlias
Specifies the alias of a table whose open compound index file names you want CDX( ) to return.

If you omit nWorkArea and cTableAlias, names of compound index files are returned for the table in the currently selected work area.

Remarks

The CDX( ) function is identical to the MDX( ) function.

A .cdx (compound) index consists of one physical file containing many index tags. Each index tag is an index order reference for the associated table.

There are two types of .cdx files: standard compound index (.cdx) and structural .cdx. A standard compound index (.cdx) may have a different name from its associated table and can reside in a different directory from its associated table. A table can have multiple compound index files. You open a compound index with the INDEX clause of USE or with SET INDEX.

A structural .cdx must have the same name as its associated table and reside in the same directory. A table can have only one structural index file. Structural .cdx files are automatically opened and updated when the associated table is opened with USE.

CDX( ) ignores any .idx (Microsoft FoxBASE+ and FoxPro 1.0 compatible index) files specified in USE or SET INDEX.

Use TAG( ) to return individual tag names contained in a .cdx, and NDX( ) to return the name of open .idx files.

When SET FULLPATH is ON, CDX( ) returns the path and name of the .cdx. When SET FULLPATH is OFF, CDX( ) returns the drive and name of the .cdx.

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which the name of each structural index is displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

CLEAR
FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? CDX(nCount)     && Display structural index names
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

INDEX | MDX( ) | NDX( ) | SET FULLPATH | SET INDEX | SYS(14) - Index Expression | SYS(21) - Controlling Index Number | SYS(22) - Controlling Tag or Index Name | SYS(2021) - Filtered Index Expression | TAG( ) | USE


CEILING( ) Function

Returns the next highest integer that is greater than or equal to the specified numeric expression.

CEILING(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the number whose next highest integer CEILING( ) returns.

Remarks

CEILING rounds a number with a fractional portion to the next highest integer.

Example

STORE 10.1 TO num1
STORE -10.9 TO num2
? CEILING(num1)  && Displays 11
? CEILING(num2)  && Displays -10
? CEILING(10.0)  && Displays 10
? CEILING(-10.0) && Displays -10

See Also

FLOOR( ) | ROUND( ) | Creating Numeric Expressions | Integer Field Type


CHR( ) Function

Returns the character associated with the specified numeric ANSI code.

CHR(nANSICode)

Return Values

Character

Parameters

nANSICode
Specifies a number between 0 and 255 whose equivalent ANSI character CHR( ) returns.

Use ASC( ) to return the ANSI value for a specified character.

Remarks

CHR( ) returns a single character corresponding to the numeric position of the character in the character table of the current code page. CHR( ) can be used to send printer control codes to a printer.

Example

The following example displays the numbers 65 through 75 and uses CHR( ) to display their corresponding character values A through K.

CLEAR
FOR nCOUNT = 65 TO 75
   ? nCount && Display numeric value
   ?? ' ' + CHR(nCount) && Display character
ENDFOR

See Also

ASC( ) | INKEY( ) | SET ANSI Command


CHRSAW( ) Function

Determines whether or not a character is present in the keyboard buffer.

CHRSAW([nSeconds])

Return Values

Logical

Parameters

nSeconds
Specifies the time in seconds that CHRSAW( ) waits before checking the keyboard buffer. The keyboard buffer is checked immediately if you omit nSeconds.

Including nSeconds lets you use CHRSAW( ) for a variety of timed activities. For example, your program can close an application if a key hasn't been pressed for a specific number of seconds.

Remarks

CHRSAW( ) returns True (.T.) if a character is present in the keyboard buffer, and False (.F.) if not. CHRSAW( ) doesn't affect the keyboard buffer contents.

Example

In the following example, the system displays a window containing input fields created with @ ... GET commands, and waits 5 seconds for keyboard input. If a key isn't pressed in this time period, CHRSAW( ) returns False (.F.) and the program terminates.

SET TALK OFF
DEFINE WINDOW wEnter FROM 7,10 to 13,70 PANEL
ACTIVATE WINDOW wEnter
@ 1,3 SAY 'Customer: '   GET gcCustomer  DEFAULT SPACE(40)
@ 3,3 SAY 'Address:  '   GET gcAddress  DEFAULT SPACE(40)
WAIT WINDOW 'Waiting for input' NOWAIT
IF NOT CHRSAW(5)
   DEACTIVATE WINDOW wEnter
   CLEAR GETS
ELSE
   READ
   DEACTIVATE WINDOW wEnter
ENDIF
RELEASE WINDOW wEnter
WAIT
CLEAR

See Also

INKEY( ) | KEYBOARD | READKEY( )


CHRTRAN( ) Function

Replaces each character in a character expression that matches a character in a second character expression with the corresponding character in a third character expression.

CHRTRAN(cSearchedExpression, cSearchExpression, cReplacementExpression)

Return Values

Character

Parameters

cSearchedExpression
Specifies the expression in which CHRTRAN( ) replaces characters.
cSearchExpression
Specifies the expression containing the characters CHRTRAN( ) looks for in cSearchedExpression.
cReplacementExpression
Specifies the expression containing the replacement characters.

If a character in cSearchExpression is found in cSearchedExpression, the character in cSearchedExpression is replaced by a character from cReplacementExpression that's in the same position in cReplacementExpression as the respective character in cSearchExpression.

If cReplacementExpression has fewer characters than cSearchExpression, the additional characters in cSearchExpression are deleted from cSearchedExpression. If cReplacementExpression has more characters than cSearchExpression, the additional characters in cReplacementExpression are ignored.

Remarks

CHRTRAN( ) translates the character expression cSearchedExpression using the translation expressions cSearchExpression and cReplacementExpression and returns the resulting character string.

Example

? CHRTRAN('ABCDEF', 'ACE', 'XYZ')  && Displays XBYDZF
? CHRTRAN('ABCD', 'ABC', 'YZ')  && Displays YZD
? CHRTRAN('ABCDEF', 'ACE', 'XYZQRST')  && Displays XBYDZF

See Also

CHRTRANC( ) | SYS(15) - Character Translation | Creating Character Expressions | STRTRAN( )


CHRTRANC( ) Function

Replaces each character in a character expression that matches a character in a second character expression with the corresponding character in a third character expression.

CHRTRANC(cSearched, cSearchFor, cReplacement)

Return Values

Character

Parameters

cSearched
Specifies the expression in which CHRTRANC( ) replaces characters.
cSearchFor
Specifies the expression containing the characters CHRTRANC( ) looks for in cSearched.
cReplacement
Specifies the expression containing the replacement characters.

If a character in cSearchFor is found in cSearched, the character in cSearched is replaced by a character from cReplacement that's in the same position in cReplacement as the respective character in cSearchFor.

If cReplacement has fewer characters than cSearchFor, the additional characters in cSearchFor are deleted from cSearched. If cReplacement has more characters than cSearchFor, the additional characters in cReplacement are ignored.

Remarks

CHRTRANC( ) is designed to facilitate working with expressions that contain double-byte characters. Use CHRTRANC( ) to replace single-byte characters with double-byte characters or double-byte characters with single-byte characters. If the expressions contains only single-byte characters, CHRTRANC( ) is equivalent to CHRTRAN( ) .

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

CHRTRAN( ) | STRCONV( ) | Creating Character Expressions


CMONTH( ) Function

Returns the name of the month from a given date or DateTime expression.

CMONTH(dExpression | tExpression)

Return Values

Character

Parameters

dExpression
Specifies the date expression from which CMONTH( ) returns the name of the month.
tExpression
Specifies the DateTime expression from which CMONTH( ) returns the name of the month.

Remarks

CMONTH( ) returns the name of the month as a string in proper noun format.

Example

? CMONTH(DATE( ))
STORE {^1998-02-16} TO gdDueDate
? 'Your payment was due in ', CMONTH(gdDueDate)
STORE gdDueDate+60 TO gdFinalDate
? 'You must pay by ', CMONTH(gdFinalDate)

See Also

DMY( ) | MDY( ) | MONTH( ) | DATETIME( )


CNTBAR( ) Function

Returns the number of menu items on a user-defined menu or the Visual FoxPro system menu.

CNTBAR(cMenuName)

Return Values

Numeric

Parameters

cMenuName
Specifies the name of the menu for which CNTBAR( ) returns the number of menu items. For a list of the Visual FoxPro system menu names, see the System Menu Names topic.

Remarks

If a user-defined menu is created with the PROMPT option in DEFINE POPUP, Visual FoxPro evaluates the number of menu items when you issue ACTIVATE POPUP. For such a menu, CNTBAR( ) returns a meaningful value only after you activate the menu. However, if the menu items in the menu are created with DEFINE BAR, CNTBAR( ) can determine the number of menu items before you issue ACTIVATE POPUP.

Example

In the following program example, named CNTBAR.prg, a menu title is added to the system menu. The menu popEnv is created with four menu items. The program places a mark character by each item when the item is selected. CNTBAR( ) is used within a loop to initially display marks next to the appropriate menu items.

*** You must name this program CNTBAR.PRG ***
CLEAR
SET TALK OFF
DEFINE PAD padEnv OF _MSYSMENU PROMPT 'E\<nvironment';
   KEY ALT+R, 'ALT+R'
ON PAD padEnv OF _MSYSMENU ACTIVATE POPUP popEnv
DEFINE POPUP popEnv MARGIN RELATIVE COLOR SCHEME 4
DEFINE BAR 1 OF popEnv PROMPT '\<Status Bar'
DEFINE BAR 2 OF popEnv PROMPT '\<Clock'
DEFINE BAR 3 OF popEnv PROMPT '\<Extended Video'
DEFINE BAR 4 OF popEnv PROMPT 'St\<icky'
ON SELECTION POPUP popEnv DO enviropop IN cntbar.prg
FOR i = 1 TO CNTBAR('popEnv')
   DO CASE
      CASE PRMBAR('popEnv', i) = 'Status Bar'
         IF _WINDOWS or _MAC
            SET MARK OF BAR i OF popEnv TO SET('STATUS BAR') = 'ON'
         ELSE
            SET MARK OF BAR i OF popEnv TO SET('STATUS') = 'ON'
         ENDIF
      CASE PRMBAR('popEnv', i) = 'Clock'
         SET MARK OF BAR i OF popEnv TO  SET('CLOCK') = 'ON'
      CASE PRMBAR('popEnv', i) = 'Extended Video'
         SET MARK OF BAR i OF popEnv TO  SROW( ) > 25
      CASE PRMBAR('popEnv', i) = 'Sticky'
         SET MARK OF BAR i OF popEnv TO  SET('STICKY') = 'ON'
   ENDCASE
ENDFOR
PROCEDURE enviropop
DO CASE
   CASE PROMPT() = 'Status'
      IF mrkbar('popEnv', BAR( ))
         DO CASE
            CASE _WINDOWS OR _MAC
               SET STATUS BAR OFF
            CASE _DOS
               SET STATUS OFF
            OTHERWISE
         ENDCASE
         SET MARK OF BAR BAR( ) OF popEnv TO .F.
      ELSE
         DO CASE
            CASE _WINDOWS OR _MAC
               SET STATUS BAR ON
            CASE _DOS
               SET STATUS ON
            OTHERWISE
         ENDCASE
         SET MARK OF BAR BAR( ) OF popEnv TO .T.
      ENDIF
CASE PROMPT( ) = 'Clock'
   IF mrkbar('popEnv', BAR( ))
      SET CLOCK OFF
      SET MARK OF BAR BAR( ) OF popEnv TO .F.
   ELSE
      DO CASE
         CASE _WINDOWS OR _MAC
            SET STATUS BAR ON
            SET CLOCK STATUS
         CASE _DOS
            SET CLOCK ON
         OTHERWISE
      ENDCASE
      SET MARK OF BAR BAR( ) OF popEnv TO .T.
   ENDIF
CASE PROMPT( ) = 'Extended Video'
   IF MRKBAR('popEnv', BAR( ))
      SET DISPLAY TO VGA25
      SET MARK OF BAR BAR( ) OF popEnv TO .F.
   ELSE
      SET DISPLAY TO VGA50
      SET MARK OF BAR BAR( ) OF popEnv TO .T.
   ENDIF
CASE PROMPT( ) = 'Sticky'
   IF MRKBAR('popEnv', BAR( ))
      DO CASE
         CASE _WINDOWS OR _MAC
            WAIT WINDOW 'STICKY is always on in this Visual FoxPro version'
         CASE _DOS
            SET STICKY OFF
         OTHERWISE
      ENDCASE
      SET MARK OF BAR BAR( ) OF popEnv TO .F.
   ELSE
      DO CASE
         CASE _WINDOWS OR _MAC
            WAIT WINDOW 'STICKY is always ON in Visual FoxPro'
         CASE _DOS
            SET STICKY ON
         OTHERWISE
      ENDCASE
       SET MARK OF BAR BAR( ) OF popEnv TO .T.
   ENDIF
ENDCASE

See Also

ACTIVATE POPUP | CNTPAD( ) | CREATE MENU | DEFINE BAR | DEFINE POPUP | GETBAR( ) | MRKBAR( ) | ON BAR | ON SELECTION BAR | PRMBAR( )


CNTPAD( ) Function

Returns the number of menu titles on a user-defined menu bar or the Visual FoxPro system menu bar.

CNTPAD(cMenuBarName)

Return Values

Numeric

Parameters

cMenuBarName
Specifies the name of the menu bar for which CNTPAD( ) returns the number of menu titles.

Example

The following command uses CNTPAD( ) to display the number of menu titles in the Visual FoxPro system menu bar.

? CNTPAD('_MSYSMENU')

See Also

ACTIVATE MENU | CNTBAR( ) | CREATE MENU | DEFINE PAD | DEFINE MENU | GETPAD( ) | MRKPAD( ) | ON PAD | ON SELECTION PAD | PRMPAD( )


COL( ) Function

Included for backward compatibility. Use the CurrentX, CurrentY Properties.


COMARRAY( ) Function

Specifies how arrays are passed to COM objects.

COMARRAY(oObject [, nNewValue])

Return Values

Numeric

Parameters

oObject
An object reference to the COM object.
nNewValue
Specifies how an array is passed to the COM object specified with oObject. The following table lists the settings for nNewValue and how the array is passed to the COM object.
nNewValue | Description
0 | The array is a zero-based array, and it is passed by value.
1 (Default) | The array is a one-based array, and it is passed by value. Compatible with earlier versions of Visual FoxPro.
10 | The array is a zero-based array, and it is passed by reference.
11 | The array is a one-based array, and it is passed by reference.
100 | The array is a fixed size array and cannot be redimensioned.
1000 | Byte arrays are not converted to strings.

Issue COMARRAY( ) without the nNewValue argument to return the current setting.

Remarks

Earlier versions of Visual FoxPro can only pass arrays to COM objects by value. Also, the array passed to the COM object is assumed be a one-based array, meaning that the first element, row, and column in the array is referenced with 1.

However, some COM objects require that arrays passed to them be passed by reference, or the array passed is zero-based (the first element, row, and column in the array are referenced with 0), or both. COMARRAY( ) lets you specify how the array is passed to the COM object, and assumes you know how the array should be passed to the COM object.

Note that COMARRAY( ) is only used when arrays are passed to COM objects using the following syntax:

oComObject.Method(@MyArray)

When a byte array (VT_UI1) is used to communicate with a COM server, Visual FoxPro converts the byte array into a string. The additive nValue of 1000 retains the original proper type of the array and does not convert the result to a string.

If a client is passing a byte array by reference to a Visual FoxPro COM Server, the Visual FoxPro COM Server must also set the nValue additive to 1000. This can be done by putting the following call in the Init event of the Visual FoxPro COM Server:

COMARRAY(THIS,1000)

If the @ token is omitted, only the first element of the array is passed to the COM object, and COMARRAY( ) has no effect.

The additive nValue of 100 as used in the following example enables you to prevent redimensioning of an array (to run this example, first build the class definition into a DLL named "t1.dll"). You should check for possible errors after calling the server, in case the server attempts to redimension the array.

LOCAL loSvr, laTest
loSvr = NEWOBJECT("t1.arrayhandler")
DIMENSION laTest[10]
laTest=3
? COMARRAY(loSvr,11 + 100)
* The COM server will return an error on the next line of code
* because arrays passed to loSvr will not allow re-dimensioning.
loSvr.RedimensionArray(@laTest,4)
? ALEN(laTest)

DEFINE CLASS ARRAYHANDLER AS CUSTOM OLEPUBLIC
    PROCEDURE RedimensionArray(aArray, nRows)
        DIME aArray[nRows]
    ENDPROC
ENDDEFINE

See Also

COMCLASSINFO( ) | CREATEOBJECT( ) | GETOBJECT( )


COMCLASSINFO( ) Function

Returns registry information about a COM object such as a Visual FoxPro automation server.

COMCLASSINFO(oObject [, nInfoType])

Return Values

Character

Parameters

oObject
An object reference to a COM or OLE object.
nInfoType
Specifies the type of information to return. The following table lists the values for nInfoType and the information returned.
nInfoType | Information returned
1 (Default) | The object's programmatic identifier (ProgID).A ProgID is a registry entry that can be associated with a CLSID.
2 | The object's VersionIndependentProgID.The VersionIndependentProgID associates a ProgID with a CLSID. It is used to determine the latest version of an object application, refers to the application's class, and does not change from version to version.
3 | The object's friendly name.
4 | The object's class identifier (CLSID). A CLSID is a globally unique identifier that identifies a COM class object.
5 Type of object passed:
Return value Description
1 Visual FoxPro object
2 ActiveX Control
3 COM Component
4 OLEBound object (General field)

Remarks

COMCLASSINFO( ) returns the empty string if registry information isn't available for the object you specify. Visual FoxPro automation servers are COM objects, both .exe executable files and .dll dynamic link libraries you can create in the Project Manager.

If you create an instance of an ActiveX control by using CREATEOBJECT( ) as in the following code, nInfoType returns 3 (COM Component) rather than 2.

X=CREATEOBJECT("mscomctlib.treectrl.2")

To return 2 (ActiveX control) you must use the object as such, as in the following code:

ox.addobject("oc","olecontrol","mscomctlib.treectrl.2")

See Also

COMARRAY( ) | CREATE PROJECT | CREATEOBJECT( ) | GETOBJECT( )


COMPOBJ( ) Function

Compares the properties of two objects and returns True (.T.) if their properties and property values are identical.

COMPOBJ(oExpression1, oExpression2)

Parameters

oExpression1, oExpression2
Specifies the objects to compare. oExpression1 and oExpression2 can be any expressions that evaluate to objects, such as object references, object variables, or object array elements.

Return Values

Logical

Remarks

COMPOBJ( ) returns False (.F.) if an object has a property that the other object doesn't have, or if the objects have identical properties but the values of one or more properties differ.

Example

In the following example, two ListBoxes named lstMyList1 and lstMyList2 and a ComboBox named cmbMyCombo are created. The Name property of each ListBox is displayed.

COMPOBJ( ) is used to compare the properties of the first ListBox with the properties of the ComboBox. Because many of the properties are different, .F. is displayed. COMPOBJ( ) is then used to compare the properties of the first ListBox with the properties of the second ListBox. Because the Names properties are different, .F. is displayed. The second ListBox lstMyList2 is replaced with the first ListBox lstMyList1, and COMPOBJ( ) is used to compare the properties. Because their properties are identical, .T. is displayed.

lstMyList1 = CREATEOBJ('ListBox')  && Creates a ListBox
lstMyList2 = CREATEOBJ('ListBox')  && Creates a second ListBox
cmbMyCombo = CREATEOBJ('ComboBox')  && Creates a ComboBox
lstMyList1.Name = 'list1'
lstMyList2.Name = 'list2'

CLEAR
? lstMyList1.Name  && Displays List1 Name property
? lstMyList2.Name  && Displays List2 Name property

? COMPOBJ(lstMyList1, cmbMyCombo)     && Displays .F.
? COMPOBJ(lstMyList1, lstMyList2)     && Displays .F., different Names
lstMyList2.Name = lstMyList1.Name
? COMPOBJ(lstMyList1, lstMyList2)     && Displays .T., same properties

See Also

CREATEOBJECT( ) | DEFINE CLASS | GETOBJECT( ) | SET CLASSLIB


COMPROP( ) Function

Sets or returns the behavior setting of a COM object property.

COMPROP(oCOMObject, cProperty [, eValue])

Parameters

oComObject
Specifies a reference to a COM object. cProperty is not case sensitive.

You must use the complete name of the COM object. If you do not provide eValue, COMPROP( ) returns the value of cProperty.

cProperty
Specifies the name of the COM property to set. The following table lists possible values of cProperty.
cProperty | Description
UTF8 | Determines whether UNICODE strings returned from a COM object are converted to ANSI. Conversion is performed by default.
PUTREF | Determines if initial object assignment is PROPERTY_PUT (default) or PUTREF.
eValue
Specifies a value representing behavior to apply to the cProperty. The following table lists values for eValue.
eValue | Description
0 | Apply default behavior.
1 Apply nondefault behavior as described in the table for cProperty.

For example, setting an eValue of 1 for UTF8 prevents the display of multi-byte characters as question marks. Setting an eValue of 1 for PUTREF causes Visual FoxPro to attempt object assignment as a PUTREF first and, only if that fails, attempt assignment as a PROPERTY_PUT. Object assignments to properties of some ActiveX controls or COM objects requires PUTREF, and Visual FoxPro defaults to PROPERTY_PUT.

Return Values

COMPROP( ) returns the value of cProperty.

Examples

The following example returns data from methods of an ADO recordset as UNICODE instead of allowing conversion to ANSI:

LOCAL oConn AS adodb.Connection, oRS AS adodb.Recordset
LOCAL lcStr AS STRING
oConn=CREATEOBJECT("ADODB.Connection")
oConn.Open("DSN=Nwind;")  && DSN to SQL Server
oRS=oConn.Execute("select * from customers")
COMPROP(oRS,'UTF8',1)
DO WHILE NOT oRS.Eof
   lcStr = oRS.Fields(4).Value
   oRS.MoveNext
ENDDO
oRS.Close()
oRS.ActiveConnection=NULL
oRS=NULL
oConn.Close()
oConn=NULL

In the following example, an ActiveX control is made to use PUTREF rather than PROPERTY_PUT:

=COMPROP(oForm.OLECONTROL1, 'PUTREF',1)

See Also

DBGETPROP( ) Function | COMARRAY( ) Function


COMRETURNERROR( ) Function

Populates the COM exception structure with information that Automation clients can use to determine the source of Automation errors.

COMRETURNERROR(cExceptionSource, cExceptionText)

Parameters

cExceptionSource
Specifies the text for the source of the exception.
cExceptionText
Specifies the text for the description of the exception.

Remarks

COMRETURNERROR( ) allows Visual FoxPro Automation servers to populate the COM exception structure so that Automation clients can determine the cause of an error on the Automation server.

Executing COMRETURNERROR( ) places the specified text in the COM exception structure, aborts executing the current method, and returns control to the client. The Automation server remains in memory and the client can call more Automation server methods.

Visual FoxPro clients can use AERROR( ) to view the text placed on the COM exception structure.

Note (For advanced users) COMReturnErrorInfo fills in a COM exception information structure. This is used only for IDispatch (late binding calls). If you call the server via early binding and the client passes a COM exception structure to the server, there is no error mechanism to return the error info unless the client does a QueryInterface on the ISupportsErrorInfo interface.

See Also

AERROR( ) | ON ERROR | COMCLASSINFO( ) | Creating Automation Servers | GETINTERFACE( ) | Error Messages A-Z | Error Messages by Number


COS( ) Function

Returns the cosine of a numeric expression.

COS(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies a numeric expression whose cosine COS( ) returns. nExpression can be any value.

Remarks

COS( ) returns the cosine of nExpression in radians. Use DTOR( ) to convert an angle from degrees to radians. The number of decimal places that COS( ) returns can be specified with SET DECIMALS. The value COS( ) returns ranges between –1 and 1.

Example

CLEAR
? COS(0)  && Displays 1.00
? COS(PI( ))  && Displays -1.00
? COS(DTOR(180))  && Displays -1.00
STORE PI( ) * 3 TO gnAngle
? COS(gnAngle)  && Displays -1.00

See Also

ACOS( ) Function | DTOR( ) Function | RTOD( ) Function | SET DECIMALS Command | SIN( ) Function


CPCONVERT( ) Function

Converts character or memo fields or character expressions to another code page.

CPCONVERT(nCurrentCodePage, nNewCodePage, cExpression)

Parameters

nCurrentCodePage
Specifies the code page that cExpression is being converted from.
nNewCodePage
Specifies the code page to which cExpression is converted.
cExpression
Specifies the character expression that's converted.

Remarks

Note that CPCONVERT( ) isn't required for normal cross-platform functioning of the product. It is used strictly to access the underlying translation facilities of Visual FoxPro.

For example, if the variable gcCharExpr contains a character that looks like ä on the Macintosh (in code page 10000) then CPCONVERT( ) will return a character that looks like ä in Microsoft Windows (code page 1252):

CPCONVERT(10000, 1252, gcCharExpr)

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro and Developing International Applications.

See Also

CPCURRENT( ) Function | CPDBF( ) Function | MODIFY COMMAND Command | MODIFY FILE Command | SET NOCPTRANS Command


CPCURRENT( ) Function

Returns the code page setting (if any) in your Visual FoxPro configuration file, or returns the current operating system code page.

CPCURRENT([1 | 2])

Remarks

CPCURRENT( ) returns one of the following:

  • In Visual FoxPro, the current operating system code page if the CODEPAGE configuration item isn't included in your configuration file. In previous versions of FoxPro, 0 is returned if the CODEPAGE configuration item isn't included in your configuration file.
  • The code page number specified in the CODEPAGE configuration item. For example, CPCURRENT( ) returns 852 if the following line is included in your configuration file:
    CODEPAGE = 852
  • The current operating system code page if you have included the following line in your configuration file:
    CODEPAGE = AUTO

In Visual FoxPro, CPCURRENT(1) returns the current operating system code page, regardless of your configuration CODEPAGE setting.

CPCURRENT(2) always returns the underlying operating system code page, regardless of your configuration CODEPAGE setting. For example, if you're running Windows, CPCURRENT(2) returns the MS-DOS code page.

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro and Developing International Applications.

See Also

CPCONVERT( ) Function | CPDBF( ) Function | MODIFY COMMAND Command | MODIFY FILE Command | SET NOCPTRANS Command


CPDBF( ) Function

Returns the code page with which an open table has been marked.

CPDBF([nWorkArea | cTableAlias])

Parameters

nWorkArea
Specifies the work area number.
cTableAlias
Specifies the table alias.

Include nWorkArea or cTableAlias to specify a table open in a work area other than the current work area. CPDBF( ) returns 0 if a table isn't open in the work area you specify. If a table doesn't have the alias you specify with cTableAlias, Visual FoxPro generates an error message.

Remarks

DISPLAY STRUCTURE also displays the code page with which an open table has been marked.

For additional information on code pages and Visual FoxPro's international support, see Code Pages Supported by Visual FoxPro and Developing International Applications.

See Also

CPCONVERT( ) Function | CPCURRENT( ) Function | MODIFY COMMAND Command | MODIFY FILE Command | SET NOCPTRANS Command


CREATEBINARY( ) Function

Converts character type data created in Visual FoxPro to a binary type character string you can pass to an ActiveX control or automation object.

CREATEBINARY(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression for which a binary type character string is returned.

Remarks

Visual FoxPro character strings can contain binary data. However, an ActiveX control or automation object character string (OLE VT_BSTR type data) cannot contain binary data. An ActiveX control or automation object passes binary data to applications such as Visual FoxPro as an array of VT_UI1 type data.

Visual FoxPro automatically converts binary data passed from an ActiveX control or automation object as an array of VT_UI1 type data to a Visual FoxPro character string. Visual FoxPro internally marks this character string as binary data passed from an ActiveX control or automation object. When the character string is passed back to an ActiveX control or automation object, Visual FoxPro automatically converts the character string to an array of VT_UI1 type data the ActiveX control or automation object expects.

Use CREATEBINARY( ) to convert character type data created in Visual FoxPro to a binary type character string you can pass to an ActiveX control or automation object. The minimum number of characters to which CREATEBINARY( ) can be abbreviated is 7.

For more information about ActiveX controls and automation objects, see Adding OLE.

See Also

OLE Bound Control | OLE Container Control | ActiveX Controls Overview


CREATEOBJECT( ) Function

Creates an object from a class definition or an Automation-enabled application.

CREATEOBJECT(ClassName [, eParameter1, eParameter2, ...])

Return Values

Object

Parameters

ClassName
Specifies the class or OLE object from which the new object is created. Visual FoxPro searches for the class or OLE object in the following order:
  1. Visual FoxPro base classes.
  2. Classes in the current program.
  3. Classes in .vcx class libraries opened with SET CLASSLIB.
  4. Classes in procedure files opened with SET PROCEDURE.
  5. Classes in the Visual FoxPro program execution chain.
  6. The OLE registry if SET OLEOBJECT is ON.

OLE objects are created using the following syntax for ClassName:

ApplicationName.Class

For example, to create a Microsoft Excel worksheet (which supports Automation), you can use the following syntax:

x = CREATEOBJECT('Excel.Sheet')

When this code is run, Microsoft Excel is started (if not already running), and a new worksheet is created.

A class library can have an alias. To specify an object in a class library with an alias, include the class library alias followed by a period and the object name.

Note that ClassName cannot be the Visual FoxPro OLE Container control base class.

eParameter1, eParameter2, ...
These optional parameters are used to pass values to the Init event procedure for the class. The Init event is executed when you issue CREATEOBJECT( ) and allows you to initialize the object.

Remarks

Use CREATEOBJECT( ) to create an object from a class definition or an application that supports Automation, and assign a reference to the object to a system variable or array element.

Before you can create an object from a user-defined class, the user-defined class must first be created with DEFINE CLASS, or it must be available in a .vcx visual class library opened with SET CLASSLIB.

Use = or STORE to assign a reference to the object to a system variable or array element. If an object assigned to a system variable or array element is released, the system variable or array element contains the null value. Use RELEASE to remove the system variable or array element from memory.

Example

The following example uses DEFINE CLASS and CREATEOBJECT( ) to create two custom classes named FormChild and FormGrandChild from the Visual FoxPro Form base class. ACLASS( ) is used to create an array named gaNewarray containing the class names, which are then displayed.

CLEAR

* Verify current class library setting
cCurClassLib=SET("CLASSLIB")
IF LEN(ALLTRIM(cCurClassLib))=0
   cCurClassLib="None"
ENDIF

WAIT WINDOW "Current class library is: " + cCurClassLib + CHR(13);
   + "Press any key to continue..."

frmMyForm = CREATEOBJECT("FormGrandChild")

* Create an array
FOR nCount = 1 TO ACLASS(gaNewarray, frmMyForm)
   ? gaNewarray(nCount)  && Display the names of the classes
ENDFOR

RELEASE frmMyForm

* Create FormChild from FORM baseclass
DEFINE CLASS FormChild AS FORM
ENDDEFINE

* Create FormGrandChild from user-defined FormChild class
DEFINE CLASS FormGrandChild AS FormChild
ENDDEFINE

See Also

_BROWSER | COMCLASSINFO( ) | CREATEOBJECTEX( ) | DEFINE CLASS | GETOBJECT( ) | NEWOBJECT( ) | RELEASE | SET CLASSLIB | SET OLEOBJECT


CREATEOBJECTEX( ) Function

Creates an instance of a registered COM object (such as a Visual FoxPro Automation server) on a remote computer.

CREATEOBJECTEX(cCLSID | cPROGID, cComputerName [, cIID])

Return Values

Object

Parameters

cCLSID | cPROGID
Specifies the CLSID (Class Identifier) or PROGID (Programmatic Identifier) for the COM object to instantiate. If you include a CLSID, the COM object must be registered on the remote server you specify with cComputerName. If you include a PROGID, the COM object must be registered on both the your local computer and the remote computer you specify with cComputerName. Attempting to use a PROGID without first registering the server on your local computer will generate the OLE error Code 0x800401f3, "Invalid Class String."

For Visual FoxPro automation servers created on your local machine, you can use the server object CLSID and PROGID properties to determine the local CLSID and PROGID values.

cComputerName
Specifies the remote computer on which the COM object is instantiated.

If cComputerName is the empty string, the COM object is instantiated on the local computer or a redirected machine as specified in the registry.

cComputerName supports Universal Naming Convention (UNC) names such as "\\myserver" and "myserver," and Domain System Names (DNS) names.

cIID
Specifies the Interface ID GUID of cCLSID | cPROGID when you create an early bound instance of the class. If you pass an empty string as cIID Visual FoxPro attempts to access the default interface (IID) of cCLSID | cPROGID.

Example

      x = CREATEOBJECTEX("excel.application","",;
      "{000208D5-0000-0000-C000-000000000046}")
Note The following is a valid function call for an excel application object. It will return the excel.application default interface.
      x = CREATEOBJECTEX("excel.application","","")

Remarks

CREATEOBJECTEX( ) returns an object reference to the COM object if it is successfully instantiated. CREATEOBJECTEX( ) cannot be used to instantiate Visual FoxPro classes such as forms – use CREATEOBJECT( ) to instantiate Visual FoxPro classes. Note that you can only abbreviate CREATEOBJECTEX( ) to a minimum of 13 characters, distinguishing it from the CREATEOBJECT( ) function.

When you call certain COM classes with CREATEOBJECT( ) they return "No such interface supported" because they do not support an IDispatch interface. Using the cIID parameter you can now access these classes in your applications.

If you pass an empty string ("") as cIID Visual FoxPro attempts to to get the default interface (IID) of the specified CLSID or PROGID.

Because it supports early binding through cIID, CREATEOBJECTEX( ) can help improve performance by avoiding much of the overhead of IDispatch calls.

CREATEOBJECTEX( ) supports creation of new early-bound objects. However, it is also possible that your Visual FoxPro component is passed an object that you want to call via early-binding. You can use the GETINTERFACE( ) support on existing COM objects.

For additional information about using Visual FoxPro to create Automation servers, see Adding OLE .

See Also

CLSID Property | CREATEOBJECT( ) Function | ProgID Property | Server Object | GETINTERFACE( ) Function


CREATEOFFLINE( ) Function

Takes an existing view offline.

CREATEOFFLINE(ViewName [, cPath])

Return Values

Logical

Parameters

ViewName
Specifies the name of the existing view to take offline. The database containing the existing view must be open before you can take the existing view offline.
cPath
Specifies the directory in which the offline view is placed and the name of the offline view.

Remarks

CREATEOFFLINE( ) returns a logical true (.T.) if the existing view is successfully taken offline; otherwise false (.F.) is returned.

An offline view is opened with USE. When an offline view is open, you can append records or make changes to records in the offline view. However, you cannot use the CREATE TRIGGER, INSERT, PACK or ZAP commands in an offline view. After making changes to the offline view, you can update the data on the server with your changes by opening the offline view with USE and including the ONLINE clause.

You cannot refresh the contents of an offline view with data from the server until the offline view has been opened with USE and the ONLINE clause.

Use DROPOFFLINE( ) to take the offline view back online.

See Also

DROPOFFLINE( ) | USE | CREATE TRIGGER | INSERT | PACK | ZAP


CTOBIN( ) Function

Converts a binary character representation to an integer value.

CTOBIN(cExpression)

Return Values

Numeric

Parameters

cExpression
Specifies the binary character representation to convert.

Remarks

Use CTOBIN( ) to convert a binary character representation created with BINTOC( ) back to its integer value.

See Also

BINTOC( ) Function | CREATEBINARY( ) Function | Create Small Indexes Using BINTOC( )


CTOD( ) Function

Converts a character expression to a date expression.

CTOD(cExpression)

Parameters

cExpression
Specifies a character expression.

Return Values

Date data type. CTOD( ) returns a Date value.

Remarks

Note CTOD( ) can create ambiguous Date values and generates a compilation error when SET STRICTDATE is set to 2. To create unambiguous Date values, use the DATE( ) function.

Example

The following example uses CTOD( ) to convert Character data to a Date and then performs simple date related actions.

SET CENTURY ON               && Shows the century value.
cDate="01/01/2003"
?CTOD(cDate)               && Returns 01/01/2003 as Date.
?GOMONTH(CTOD(cDate),12)   && Returns 01/01/2004.
?CTOD(cDate)+100            && Returns 04/11/2003.

See Also

DATE( ) | SET STRICTDATE | TTOD( )


CTOT( ) Function

Returns a DateTime value from a character expression.

CTOT(cCharacterExpression)

Parameters

cCharacterExpression
Specifies the character expression from which a DateTime value is returned.

Return Values

DateTime data type. CTOT( ) returns a DateTime value from a character expression.

Remarks

Note CTOT( ) can create ambiguous DateTime values and generates a compilation error when SET STRICTDATE is set to 2. To create nonambiguous Date values, use the DATETIME( ) function instead.

Visual FoxPro supports the native SQL Datatypes Datetime and Smalldatetime, which are returned in 24 hour format in SQL XML.

Note The CTOT( ) function does not address the 19 different ways that T-SQL Convert( ) function returns datetime and smalldatetime values.

To convert date formats from Access, SQL Server, Visual Studio .NET, and XML, you must call the appropriate SET DATE setting to interpret DateTime strings properly. However, if an uppercase T is in the XML date string, Visual FoxPro overrides the current date setting by internally calling SET DATE YMD and restores the current date setting when exiting CTOT( ).

Note CTOT( ) resolves these dates to the limits of precision of the Visual FoxPro DateTime data type. Therefore, precision can be lost when using CTOT( ) with certain formats. The Visual FoxPro DateTime data type does not support milliseconds or time zones.

CTOT( ) respects the setting of the SET CENTURY command. For more information, see SET CENTURY Command.

Examples

The following examples show how CTOT( ) handles DateTime values from different sources. In all examples, CTOT( ) converts the DateTime values correctly without needing to call SET DATE YMD.

  • Access 2000 XML date format
    * 2000-10-24T13:30:00 (24-hour format is exported from Access,
* whether original was in 12- or 24-hour format)
? CTOT("2000-10-24T13:30:00")
  • SQL Server 2000 XML date format
    ? CTOT("2000-10-24T20:47:58.170")   && datetime (24-hour format)
? CTOT("2000-10-24T21:11:00")         && Small DT (24-hour format)
? CTOT("2000-10-03T02:02:02")
  • Visual Studio .NET XML
    ? CTOT("2002-10-05T04:04:04.0000000-07:00")
  • Simple Object Access Protocol (SOAP)
    ? CTOT("2001-09-14T07:00:00Z")

See Also

DATETIME( ) | SET STRICTDATE


CURDIR( ) Function

Returns the current directory.

CURDIR([cExpression])

Return Values

Character

Parameters

cExpression
Specifies the drive or volume for which CURDIR( ) returns the current directory or folder. If you omit cExpression, the current default drive or volume is assumed. The empty string is returned if the drive or volume you specify in cExpression doesn't exist. Note that this argument is only included for earlier versions of Visual FoxPro and FoxPro running under Window 3.1 or MS-DOS.

Remarks

CURDIR( ) returns, as a character string, the current MS-DOS directory on a specified drive.

Example

The following example stores the current directory to a variable, sets the default to the directory Visual FoxPro was started in, displays the new directory, returns the default to the original directory, and displays the original directory.

CLEAR
? 'Current directory: ', CURDIR( )
gcOldDir = SET('DEFAULT') + SYS(2003)
SET DEFAULT TO (HOME( ))
? 'Visual FoxPro directory: ', CURDIR( )
SET DEFAULT TO (gcOldDir)
? 'Current directory: ', CURDIR( )

See Also

FULLPATH( ) | HOME( ) | SYS(2003) - Current Directory


CURSORGETPROP( ) Function

Returns the current property settings for a Visual FoxPro table or a cursor.

To set a specific property for a Visual FoxPro table or a cursor, use CURSORSETPROP( ). For additional information about each of the properties and their settings, see CURSORSETPROP( ).

CURSORGETPROP(cProperty [, nWorkArea | cTableAlias])

Parameters

cProperty
Specifies the property setting to return.

The following table includes a list of properties whose settings can be returned, the data type of the return value, and a description of the return value.

cProperty | Type | Description
ADORecordset | O | Contains an object reference to the ActiveX Data Object (ADO) Recordset associated with the cursor. Not valid for cursors that are not based on ADO Recordsets. Read-only.
AllowSimultaneousFetch L Applies when using remote views, a shared connection, and to cursors created using ODBC.

AllowSimultaneousFetch contains True (.T.) when similarly configured cursors sharing the connection are permitted to fetch rows simultaneously.

Otherwise, AllowSimultaneousFetch contains False (.F.) when fetching rows simultaneously is not permitted.
AutoIncError L Contains True (.T.) when attempts to insert or update a value in a field that uses automatically incrementing field values generate an error message.

Contains False (.F.) when attempts to insert or update a value in a field that uses automatically incrementing field values does not generate an error message and the specified value to be inserted or updated is disregarded.

Applies to cursors and sessions.

Read/write.
BatchUpdateCount* N Contains the number of update statements sent to the remote data source for buffered tables. The default value is 1. Adjusting this value can greatly increase update performance.

Read/write.
Buffering N 1 – Row and table buffering is off. (Default)

2 – Pessimistic row buffering is on.

3 – Optimistic row buffering is on.

4 – Pessimistic table buffering is on.

5 – Optimistic table buffering is on.

Read/write.
CompareMemo L Contains True (.T.) if WHERE clause for updates includes memo fields of type Memo, General, or Picture. (Default).

Otherwise, contains False (.F.).

For views only.

Read/write.
ConnectHandle N The connection handle. This property is valid only when the data source contains a remote table.

Read-only.
ConnectName C The connection name used when the cursor is created. This property is valid only when the data source contains a remote table.

Read-only.

Database C The name of the database that contains the table or view. If a table is a free table, Database contains an empty string.

Read-only.
FetchAsNeeded L If True (.T.), data is fetched only when needed, such as when record pointer moves to a row that has not been fetched.

If False (.F.), additional data is fetched during idle time. (Default)

Note FetchAsNeeded does not apply when progressive fetching is disabled (FetchSize is -1).

Read/write.
FetchMemo* L Contains True (.T.) if memo fields are fetched with the view results. Otherwise, contains False (.F.). (Default).

Read/write.
FetchSize* N Contains the number of rows fetched at a time from the remote tables. The default is 100 rows. Setting FetchSize to –1 retrieves the complete result set, limited by the MaxRecords setting.
Note Progressive fetching holds the connection until all rows are retrieved. Use caution coding with FetchSize if ShareConnection is True (.T.).

Read/write.
KeyFieldList C A comma delimited list of primary fields for the cursor.

Read/write.
MaxRecords* N The maximum number of rows fetched when result sets are returned. The default value is – 1 (all rows are returned). A value of 0 specifies that the view is executed but no results are fetched.

Read/write.
ParameterList C A semi-colon delimited list of view parameters and parameter types. For views only.

Read/write.
Prepared L Contains True (.T.) if SQL statements are prepared for subsequent REQUERY() function calls. Otherwise, contains False (.F.). (Default).

REQUERY() is used to retrieve data again for a SQL view. See SQLPREPARE( ) for additional information about preparing SQL statements. For views only.

Read/write.
SendUpdates L Contains true (.T.) if a SQL update query is sent to update tables when an update is made using the view; otherwise, contains false (.F.) (default).

Read/write.
SourceName C Contains the long name for a SQL view or a table in a database, or the file path and table name for a free table.

Read-only.
SourceType N 1 – The data source is a local SQL view.

101 (1 + 100) - Cursor is created by the CursorFill method.

201 (1 + 200) - Cursor is attached to a CursorAdapter object using the CursorAttach method.

2 – The data source is a remote SQL view.

102 (2 + 100) - Cursor is created by CursorFill.

202 (2 + 200) - Cursor is attached to a CursorAdapter object using CursorAttach.

3 – The data source is a table.

103 (3 + 100) - Cursor is created by CursorFill.

203 (3 + 200) - Cursor is attached to a CursorAdapter object using CursorAttach.

4 - The cursor is based on ADO Recordset and attached to a CursorAdapter object.

104 (4 + 100) - Cursor is created by CursorFill.

204 (4 + 200) - Cursor is attached to a CursorAdapter object using CursorAttach.

Read-only.
SQL C The SQL statement executed when the cursor is created.

Read-only.
Tables C A comma delimited list of the names of tables.

Read/write.
UpdatableFieldList C A comma delimited list of fields in the view. This list can include fields from local and remote tables.

Read/write.
UpdateNameList C A comma delimited list of remote field names and the local field names assigned to the cursor. Use this option to specify valid Visual FoxPro names for fields in the cursor that have invalid Visual FoxPro field names.

Read/write.
UpdateType N 1 – Specifies that old data is updated with the new data. (Default).

2 – Specifies that updates occur by deleting the old data and inserting the new data.

Read/write.
UseMemoSize* N The minimum size, in bytes, for result columns to return in memo fields. For example, if the width of a column result is greater than the value of UseMemoSize, the column result is stored in a memo field. UseMemoSize may vary from 1 to 255; the default value is 255.

Read/write.
WhereType N The WHERE clause for updates to tables. WhereType can specify the following values:

1 or DB_KEY (from FOXPRO.H). The WHERE clause used to update tables consists of only the primary fields specified with the KeyFieldList property.

2 or DB_KEYANDUPDATABLE (from FOXPRO.H). The WHERE clause used to update tables consists of the primary fields specified with the KeyFieldList property and any updatable fields.

3 or DB_KEYANDMODIFIED (from FOXPRO.H) (default). The WHERE clause used to update tables consists of the primary fields specified with the KeyFieldList property and any other fields that are modified.

4 or DB_KEYANDTIMESTAMP (from FOXPRO.H). The WHERE clause used to update tables consists of the primary fields specified with the KeyFieldList property and a comparison of the time stamps.

Read/write.

* The value returned by this property is significant only for remote views; if you get this property for local views, the CURSORGETPROP( ) function returns the default value.

The following table includes a list of properties whose settings can be returned, the data type of the return value, and a description of the return value.

nWorkArea
Specifies the work area of the table or cursor from which the property setting is returned. If you specify 0 for nWorkArea, CURSORGETPROP( ) returns the environment setting.
cTableAlias
Specifies the alias of the table or cursor from which the property setting is returned.

Return Values

Character, Numeric, or Logical data type

Remarks

The current property settings are returned for the table or cursor open in the currently selected work area if CURSORGETPROP( ) is issued without the optional cTableAlias or nWorkArea arguments.

Example

When a cursor is opened, the default value for the AutoIncError property is read from the session default value, which is the current default data session setting. The following example shows how you can retrieve the default AutoIncError value for each session by specifying 0 (default session) as the last parameter:

CURSORGETPROP("AutoIncError", 0)

The default session is used when opening a new private data session or cursor. The following example shows how you can retrieve the cursor or table AutoIncError setting for each table by using the nWorkArea or cTableAlias parameter as the last parameter:

CURSORGETPROP("AutoIncError", nWorkArea | cTableAlias)

The following example opens a "Customer" table in the "Testdata" database and uses CURSORGETPROP( ) to display the buffering mode for the table and the name of the database in which the table is contained:

CLOSE DATABASES
CLEAR

OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

? CURSORGETPROP("Buffering") && Displays buffering mode
? CURSORGETPROP("Database")  && Displays database name

See Also

CURSORSETPROP( ) | SQLGETPROP( ) | SQLSETPROP( )


CURSORSETPROP( ) Function

Specifies property settings for a Visual FoxPro table or a cursor.

CURSORSETPROP( cProperty [, eExpression] [, cTableAlias | nWorkArea ] )

Parameters

cProperty
Specifies the table or cursor property to set. Buffering is the only property you can specify for a Visual FoxPro table.
eExpression
Specifies the value for the property you specify with cProperty. If you omit eExpression, the property is set to its default value.

The following table lists the properties you can specify for cProperty and a description of the values eExpression can assume.

Property | eExpression values
AllowSimultaneousFetch Applies when using remote views, a shared connection, and to cursors created using ODBC.

.T. - Permit similarly configured cursors sharing the connection to fetch rows simultaneously.

.F. - Do not permit similarly configured cursors sharing the connection to fetch rows simultaneously.
AutoIncError .T. - Generate an error message when attempting to insert or update values in a field that uses automatically incrementing field values.

.F. - Does not generate an error message but does not use the value specified when attempting to insert or update the value in a field that uses automatically incrementing field values, which uses the appropriate incremented value.

Applies to cursors and sessions.
BatchUpdateCount* | Specifies the number of update statements to send to the remote data source for buffered tables. The default value is 1. Adjusting this value can greatly increase update performance when using automatic updating.
Buffering 1 – Sets row and table buffering off. Record locking and data writing are identical to earlier FoxPro versions. (Default)

2 – Sets pessimistic row buffering on.

3 – Sets optimistic row buffering on.

4 – Sets pessimistic table buffering on.

5 – Sets optimistic table buffering on. SET MULTILOCKS must be ON for all Buffering modes except 1 (off).
CompareMemo .T. - Include memo fields of type Memo, General, or Picture in the WHERE clause for updates.

.F. – Do not include memo fields in the WHERE clause for updates.

Applies when automatic updating is used.
FetchAsNeeded .T. – Fetch records only when needed, such as when record pointer moves to a row that has not been fetched.

.F. – Fetch additional data during idle time.

Note FetchAsNeeded does not apply when progressive fetching is disabled (FetchSize is -1).
FetchMemo* .T. – Fetch memo fields with the view results.

.F. – Do not fetch memo fields with the view results.
FetchSize* Specifies the number of rows progressively fetched from the remote table result set. The default value is 100 rows. Setting FetchSize to –1 retrieves the complete result set, limited by the MaxRecords setting.
Note Progressive fetching holds the connection until all rows are retrieved. Use caution coding with FetchSize if ShareConnection is True (.T.).
KeyFieldList | Specifies a comma-delimited list of primary fields for the cursor. No default. You must include a list of field names for updates to work when using automatic updating.
MaxRecords* | Specifies the maximum number of rows fetched when returning result sets. The default value is – 1, and all rows are returned. A value of 0 specifies that the view is executed but no results are fetched.
ParameterList | Specifies a semi-colon delimited list of view parameters and parameter types. For views only.
Prepared .T. - Prepare SQL statements for subsequent REQUERY( ) function calls.

.F. - Do not prepare SQL statements for subsequent REQUERY( ) calls. (Default).

REQUERY( ) is used to retrieve data again for a SQL view. For additional information about preparing SQL statements, see SQLPREPARE( ) Function.
SendUpdates .T. – Specifies that a SQL update query is sent to update tables when an update is made using the view.

.F. – Specifies that a SQL update query is not sent to update tables.
Tables | Specifies a comma-delimited list of the names of remote tables. No default. You must include a list of table names for updates to work when using automatic updating.
UpdatableFieldList | Specifies a comma-delimited list of fields in the view. This list can include fields from local and remote tables. You must include a list of fields for updates to work when using automatic updating.
UpdateNameList | Specifies a comma-delimited list of remote field names and the local field names assigned to the cursor. Use this option to specify valid Visual FoxPro names for fields in the cursor that have invalid Visual FoxPro field names.
UpdateType 1 – Update old data with new data. (Default)

2 – Update by deleting old data and inserting new data.
UseMemoSize* | Specifies the minimum size in bytes for result columns to return in memo fields. For example, if the width of a column result is greater than the value of UseMemoSize, the column result is stored in a memo field. UseMemoSize can vary from 1 to 255 bytes. The default value is 255 bytes.
WhereType The WHERE clause for updates to remote tables. WhereType can assume the following values:

1 or DB_KEY (from FOXPRO.H). The WHERE clause used to update remote tables consists of only the primary fields specified with the KeyFieldList property.

2 or DB_KEYANDUPDATABLE (from FOXPRO.H). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and any updatable fields.

3 or DB_KEYANDMODIFIED (from FOXPRO.H). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and any other fields that are modified. (Default)

4 or DB_KEYANDTIMESTAMP (from FOXPRO.H). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and a comparison of the time stamps.

* This property is primarily used for remote views; setting it has no effect on local views. However, you can preset this property for local views that will be upsized.

cTableAlias
Specifies the alias of the table or cursor for which the property is set.
nWorkArea
Specifies the work area of the table or cursor for which the property is set. If you specify 0 for nWorkArea, CURSORSETPROP( ) sets the environment setting used for all subsequent tables or cursors.
Note Buffering is not applied to tables that are opened implicitly, for example, using SQL INSERT/UPDATE/DELETE commands.

Return Values

Logical data type. CURSORSETPROP( ) returns True (.T.) if Visual FoxPro successfully sets the property you specify. Visual FoxPro generates an error if the property you specify cannot be set.

Remarks

The setting of the Buffering property for CURSORSETPROP( ) determines how Visual FoxPro performs record locking and update buffering. For additional information about record locking and update buffering, see Buffering Data.

The setting of the WhereType property for CURSORSETPROP( ) determines how updates are performed on remote tables. For additional information about remote table updates, see Creating Databases.

You can use CURSORSETPROP( ) to override the FetchSize property in the SQLSETPROP( ) function for a cursor. This property is inherited from the cursor's connection handle by default.

Use CURSORGETPROP( ) to return the current property settings for a Visual FoxPro table or a cursor created for a table.

If CURSORSETPROP( ) is issued without the optional cTableAlias or nWorkArea arguments, the property setting is specified for the open table or cursor in the currently selected work area.

Example

When a cursor is opened, the default value for the AutoIncError property is read from the session default value, which is the current default data session setting. The following example shows how you can set the default AutoIncError value for each session by specifying 0 (default session) as the last parameter:

CURSORSETPROP("AutoIncError", .T., 0)

The default session is used when opening a new private data session or cursor. The following example shows how you can set the cursor or table AutoIncError setting for each table by using the cTableAlias or nWorkArea parameter as the last parameter:

CURSORSETPROP("AutoIncError", .F. , cTableAlias | nWorkArea )

The following example demonstrates how you can enable optimistic table buffering with CURSORSETPROP( ). MULTILOCKS is set to ON, a requirement for table buffering. The "Customer" table in the "testdata" database is opened, and CURSORSETPROP( ) is used to set the buffering mode to optimistic table buffering (5). A message box is displayed showing the result of the operation.

CLOSE DATABASES
CLEAR

SET MULTILOCKS ON
OPEN DATABASE (HOME(2) + 'data\testdata')
USE Customer     && Open Customer table.

* Set buffering mode and store logical result
lSuccess=CURSORSETPROP("Buffering", 5, "Customer")
IF lSuccess = .T.
   =MESSAGEBOX("Operation successful!",0,"Operation Status")
ELSE
   =MESSAGEBOX("Operation NOT successful!",0,"Operation Status")
ENDIF

See Also

CURSORGETPROP( ) | SET MULTILOCKS | SQLGETPROP( ) | SQLSETPROP( )


CURSORTOXML( ) Function

Converts a Visual FoxPro cursor to XML.

CURSORTOXML(nWorkArea | cTableAlias, cOutput [, nOutputFormat
[, nFlags [, nRecords [, cSchemaName [, cSchemaLocation [, cNameSpace ]]]]]])

Parameters

nWorkArea
Specifies the work area of the table from which to create the XML string.

If you specify 0 or no value, Visual FoxPro uses the current work area.

cTableAlias
Specifies the alias of the table from which to create the XML string.
cOutput
Specifies the path and file name or memory variable name to which results are sent.

If nFlags is set to 0 (default) for memory variable output, XML is returned to the memory variable. If the memory variable does not exist, it is created.

If nFlags is set to 512 for file output, and the file does not exist, it is created. If the file already exists, it is overwritten. The SAFETY setting is observed.

nOutputFormat
Specifies the output format of the XML string. The following table lists the values for nOutputFormat.
nOuputFormat | Description
1 – ELEMENTS | Element-centric XML (Default)
2 – ATTRIBUTES | Attribute-centric XML
3 – RAW | Generic, attribute-centric XML
nFlags
Specifies the formatting of the XML that is produced and its destination. The following table lists the values for nFlags.
nFlags | Bit | Output description
0 0000 Produce XML in UTF-8 format. (Default)

This setting creates a memory variable if one does not exist when specified by cOutput and returns XML to the memory variable.

The XML Declaration does not contain an Encoding= attribute, that is, no encoding attribute set to UTF-8.
1 | 0001 | Produce unformatted XML as a continuous string.
2 | 0010 | Enclose empty elements with open and closing elements, for example, <cc04><cc04/>.
4 | 0100 | Preserve white space in fields.
8 | 1000 | Wrap Memo fields in CDATA sections.
16 10000 Output encoding. Output is set to the cursor code page.

To ensure accurate character translation, the Visual FoxPro default code page must match the code page of the cursor. You can accomplish this by setting character and memo fields in the cursor to NOCPTRAN (character binary/memo binary).

When setting this value with tables using any of the code pages, the encoding attribute in the XML is set to an empty string (""). To change to the correct encoding attribute, use the STRTRAN( ) function. For example, for code page 936, provide the following to the resulting XML string:

strxml=STRTRAN(strxml, 'encoding=""', 'encoding="gb2312"'
32 | 100000 | Output encoding
512 1000000000 Output to the file specified by cOutput.

If a file does not exist, it is created. If the file already exists, it is overwritten. The SAFETY setting is observed.
4096 1000000000000 Disables base64 encoding.

CURSORTOXML( ) exports Memo (Binary) fields as xsd:base64binary unless you use nFlags set to 4096. In Visual FoxPro, base64 encoding is meant for encoding only binary data.

The following table describes how the encoding attribute is written when output encoding defaults to the cursor or table code page.

Note Encoding flags are set by combining bits 4 and 5 (0010000).
Encoding flag | Bits 4 and 5 | Description
+0 | 00 | Windows-1252 (Default)
+16 | 01 | Set output encoding attribute to the cursor code page.
+32 | 10 | Set output encoding attribute to UTF-8 with no character translation.
+48 | 11 | Set output encoding attribute to UTF-8 and translate character data to UTF-8.

The following table lists common Windows-compatible code pages.

Code page | Platform | Encoding attribute in XML Declaration | Comments
437 | MS-DOS, US | ibm437
850 | MS-DOS, International | ibm850
865 | MS-DOS, Nordic | Empty string ("")
866 | MS-DOS, Russian | cp866
932 | Windows, Japanese | shift-jis
936 | Traditional Chinese | gb2312
949 Windows, Korean iso-2022-kr or:

ks_c_5601-1987
950 | Windows, Chinese (Taiwan) | big5
1250 | Windows, East European | Windows-1250 | note case
1251 | Windows, Russian | Windows-1251
1252 | Windows, U.S., West European | Windows-1252
1253 | Windows, Greek | Windows-1253
1254 | Windows, Turkish | Windows-1254
1255 | Windows, Hebrew | Windows-1255
1256 | Windows, Arabic | Windows-1256
Note Visual FoxPro uses Windows-1252 as the default encoding. You can specify that encoding attribute be set to match the code page, such as Big5 (code page 950), when using double-byte character sets (DBCS) for DBCS languages that Visual FoxPro supports code pages for. When using Windows-1252 and DBCS, no additional character translation is required to display correctly in Internet Explorer.
However, to make XML more compliant for Web browsers that can interpret UTF-8, you can optionally set the encoding attribute to UTF-8 instead of Windows-1252. The result set undergoes translation to UTF-8 characters only when you set nFlags to 48 to specify the encoding attribute as UTF-8 and translate character data to UTF-8 format. This is required only when the data actually contains double-byte characters. However, you do not have to use character translation, for example, if you are outputting only latin (sgl byte) characters.
nRecords
Specifies the number of records to output to XML and has a default value is 0.

If nRecords is 0, all records are output. If nRecords is greater than the number of records remaining in the table, all remaining records are output.

cSchemaName
Specifies the name and location of the schema information for the data in cFileName.

The following table lists the values for cSchemaName.

cSchemaName | Description
"" Specifies that no schema is produced.
"1" | Specifies that inline schema is produced.
<cSchemaName> | Specifies the name and path of the external file to contain the schema (scoped to the root element of the XML)

If cSchemaLocation is not provided or is blank, and cSchemaName contains a file name, the contents of cSchemaName are written to the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute in the XML.

For example, the following code shows how Visual FoxPro generates a generic XML file named myxmlfile.xml from the labels.dbf file in the "Labels" alias and the schema file named mySchema in the same folder.

CURSORTOXML("LABELS", "myXMLFile.xml", 1, 512, 0,  "mySchema.xsd")

If you specify an empty string ("") instead of "mySchema.xsd", no schema is produced. In the following code, specifying "1" produces an inline schema:

CURSORTOXML("LABELS", "myXMLFile.xml", 1, 512, 0, "1")

If cSchemaName includes a URI, the schema is written to the current directory and must be uploaded to the server to be accessed by the browser or parser. External schema always are written to the same location as the XML file.

cSchemaLocation
Specifies an optional location where the application reading the XML data should look for the schema file. Use this parameter only when you are deploying your schema to a location other than the location of the XML data.

The contents of cSchemaLocation are written to the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute of the XML data produced. The cschemaLocation parameter can be an HTTP address or other URI. You need to copy the schema file to the location you have specified in cSchemaLocation.

The following example produces XML data:

   CURSORTOXML("LABELS", "myXMLFile.xml", 1, 512, 0, ;
       "mySchema.xsd", "http://www.microsoft.com/mySchema.xsd")

containing the following attribute:

   xsi:noNamespaceSchemaLocation=" http://www.microsoft.com/mySchema.xsd"

Specifying cSchemaLocation when cSchemaName is blank causes the same attributes to be written to the XML data. This makes it possible for you to point to an existing schema without recreating the schema each time CURSORTOXML( ) is called.

cNamespace
Specifies the namespace of the XML or schema to be produced and has an empty string ("") as the default value.

Specifying a value for cNameSpace sets the targetNamespace attribute to the same value and adds the elementFormDefault="qualified" attribute to the schema.

If you do not specify a cNamespace value, and the schema is external, no namespace declaration is written to the schema. If do not specify a cNamespace value, and the schema is inline, the targetNamespace in the schema is set to an empty string ("").

Return Values

Numeric data type. CURSORTOXML( ) returns the number of bytes written to the file or a memory variable.

Remarks

CURSORTOXML( ) output adheres to the cursor index order, SET FIELDS TO, and current filter settings. This function does not preserve the cursor location. After the call, the cursor record pointer reports EOF if all records are output or points to the last record output to XML if not all records were output.

The resulting XML from CURSORTOXML( ) contains the same scale as the exported table if the table contains Double data type values. For example, if a Double column is created with a scale of 6 using the following code:

CREATE TABLE test (col1 b(6))

The resulting XML contains six digits to the right of the decimal point.

When you use the CURSORTOXML( ) function to export a table or cursor to XML, the root node is always called "VFPData", regardless of the output format.

For Date types only, you can export "EMPTY" Date and DateTime types using CURSORTOXML( ). However, the XML schema validation might fail because "EMPTY" is not valid for these types in XML Schema Definition (XSD) schema. This is an issue only if schema is required, and the resulting XML is validated against an XML parser that can interpret XSD schemas. As a workaround, you might need to change the data to a nonempty representation by calling the appropriate SELECT statement and use CURSORTOXML( ) on the created cursor. For example, you can change the empty Date or DateTime values to .NULL.:

SELECT orderid, EVL(shippeddate,.NULL.) as ShippedDate FROM orders

You can also change the empty Date or DateTime to an appropriate representation for "empty":

SELECT orderid, IIF(EMPTY(shippeddate),{^1899-12-30 00:00:00},tc11);
   as ShippedDate FROM orders

See Also

XML Functions | XMLUpdateGram( ) Function | XMLTOCURSOR( ) Function


CURVAL( ) Function

Returns field values directly from disk for a table or a remote data source.

CURVAL(cExpression [, cTableAlias | nWorkArea])

Return Values

Character, Currency, Date, DateTime, Double, Float, Logical, Numeric, or Memo

Parameters

cExpression
Specifies an expression whose value CURVAL( ) returns from a table or a remote data source. cExpression is typically a field or an expression consisting of a set of fields from the table or remote data source.
cTableAlias
Specifies the alias of the table from which the field values are returned from disk for a table or a remote data source.
nWorkArea
Specifies the work area of the table from which the field values are returned from disk for a table or a remote data source.

Remarks

The field values returned by CURVAL( ) and OLDVAL( ) can be compared to determine if another user on a network changed the field values while the fields were being edited. CURVAL( ) and OLDVAL( ) can only return different values when optimistic row or table buffering is enabled. Optimistic row or table buffering is enabled with CURSORSETPROP( ).

Note If you are working with a view in a multiuser environment, the values returned by CURVAL( ) might not be up to date unless you call the REFRESH( ) function first. Data returned by a view is buffered, and the CURVAL( ) function reads values from the buffer. However, if other users have changed data in the underlying tables for the view, the buffered data is not updated until the REFRESH( ) function is called.

CURVAL( ) returns field values for the current record, and the return value data type is determined by the expression you specify with cExpression.

The value is returned for the table or cursor open in the currently selected work area if CURVAL( ) is issued without the optional cTableAlias or nWorkArea arguments.

Example

This example creates a free table named mytable, and a value of "One" is inserted into the cDigit field. Optimistic table buffering is enabled with SET MULTILOCKS ON and CURSORSETPROP( ).

A value of "Two" is then inserted into the cDigit field, and CURVAL( ) and OLDVAL( ) are used to display the original cDigit values. TABLEUPDATE( ) is used to commit the changes to the table, and CURVAL( ) and OLDVAL( ) are used to display the new cDigit values. Note that because this is a single user example, CURVAL( ) and OLDVAL( ) return the identical values.

CLOSE DATABASES
CLEAR

CREATE TABLE mytable FREE (cDigit C(10))
* Store original value
INSERT INTO mytable (cDigit) VALUES ("One")
SET MULTILOCKS ON        && Allow optimistic table buffering
= CURSORSETPROP("Buffering",5)   && Optimistic table buffering on
REPLACE cDigit WITH "Two"    && New value

? "Current value: " + CURVAL("cDigit", "mytable")
? "Old value: " + OLDVAL("cDigit", "mytable")
= TABLEUPDATE(.T.)       && Commit changes made to table
? "Table changes committed"
? "New current value: " + CURVAL("cDigit", "mytable")
? "New old value: " + OLDVAL("cDigit", "mytable")

See Also

GETFLDSTATE( ) | OLDVAL( ) | TABLEREVERT( ) | TABLEUPDATE( ) | CURSORSETPROP( )


DATE( ) Function

Returns the current system date, which is controlled by the operating system, or creates a year 2000-compliant Date value.

DATE([nYear, nMonth, nDay])

Return Values

Date

Parameters

nYear
Specifies the year returned in the year 2000-compliant Date value. nYear can be a value from 100 to 9999.
nMonth
Specifies the month returned in the year 2000-compliant Date value. nMonth can be a value from 1 to 12.
nDay
Specifies the day returned in the year 2000-compliant Date value. nDay can be a value from 1 to 31.

Remarks

DATE( ) returns the current system date if it is issued without the optional arguments. Include the optional arguments to return a year 2000-compliant Date value in the format set in the Regional tab of the Visual FoxPro Options dialog box. Any NULL parameter is replaced with the current system value.

No Microsoft Visual FoxPro commands or functions can directly change the system date.

Example

The following example displays the current system date with and without the century, and then displays a year 2000-compliant date.

CLEAR
SET CENTURY OFF
? DATE( )  && Displays today's date without the century
SET CENTURY ON
? DATE( )  && Displays today's date with the century
? DATE(1998, 02, 16)  && Displays a year 2000-compliant Date value

See Also

CTOD( ) | DATETIME( ) | DTOC( ) | SET CENTURY | SET DATE | SET MARK TO | SYS( ) Functions Overview


DATETIME( ) Function

Returns the current date and time as a DateTime value, or creates a year 2000-compliant DateTime value.

DATETIME([nYear, nMonth, nDay [, nHours [, nMinutes [, nSeconds]]]])

Return Values

DateTime

Parameters

nYear
Specifies the year returned in the year 2000-compliant DateTime value. nYear can be a value from 100 to 9999.
nMonth
Specifies the month returned in the year 2000-compliant DateTime value. nMonth can be a value from 1 to 12.
nDay
Specifies the day returned in the year 2000-compliant DateTime value. nDay can be a value from 1 to 31.
nHours
Specifies the hours returned in the year 2000-compliant DateTime value. nHours can be a value from 0 (midnight) to 23 (11 P.M). Defaults to 0 if omitted.
nMinutes
Specifies the minutes returned in the year 2000-compliant DateTime value. nMinutes can be a value from 0 to 59. Defaults to 0 if omitted.
nSeconds
Specifies the seconds returned in the year 2000-compliant DateTime value. nSeconds can be a value from 0 to 59. Defaults to 0 if omitted.

Remarks

DATETIME( ) returns the current system DateTime if it is issued without the optional arguments. Any NULL date parameters are replaced with current system values. A NULL time parameter is replaced with 12:00:00.

Include the optional arguments to return a year 2000-compliant DateTime value in the format specified in the Regional tab of the Visual FoxPro Options dialog box.

Example

This first example stores the Datetime for the New Year to a variable named tNewyear, and stores the current Datetime to a variable named tToday. The number of seconds between the current Datetime and the New Year is then displayed.

The second example uses DATETIME( ) to create a year 2000-compliant DateTime value.

tNewyear = DATETIME(YEAR(DATE( ) ) + 1, 1, 1)  && Next New Year
tToday = DATETIME( )
nSecondstonewyear = tNewyear - tToday
CLEAR
? "There are " + ALLTRIM (STR(nSecondstonewyear)) ;
   + " seconds to the next New Year."

CLEAR
SET CENTURY ON
SET DATE TO AMERICAN
? DATETIME(1998, 02, 16, 12, 34, 56) && Displays 02/16/1998 12:34:56 PM

See Also

CTOT( ) | DATE( ) | DTOT( ) | HOUR( ) | SEC( ) | SECONDS( ) | SET SECONDS | SET SYSFORMATS | TIME( ) | TTOC( ) | TTOD( )


DAY( ) Function

Returns the numeric day of the month for a given Date or DateTime expression.

DAY(dExpression | tExpression)

Return Values

Numeric

Parameters

dExpression
Specifies a date from which DAY( ) returns a day of the month. dExpression can be a date literal, a Date-type variable, an array element, or a date field.
tExpression
Specifies a date or time from which DAY( ) returns a day of the month. dExpression can be a DateTime literal, a DateTime-type variable, an array element, or a DateTime field.

Remarks

DAY( ) returns a number from 1 through 31.

Example

STORE {^1998-03-05} TO gdBDate

CLEAR
? CDOW(gdBDate)  && Displays Thursday
? DAY(gdBDate) && Displays 5
? 'That date is ', CMONTH(gdBDate), STR(DAY(gdBDate),2)

See Also

CDOW( ) | DOW( ) | SET FDOW | SET FWEEK | SYS( ) Functions Overview


DBC( ) Function

Returns the name and path of the current database.

DBC( )

Return Values

Character

Remarks

DBC( ) returns the empty string if there is no current database.

Use SET DATABASE to specify the current database.

Example

The following example opens the testdata database and uses DBC( ) to display information about the database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')  && Opens the DBC.

CLEAR
? DBC( )  && Displays the path and name of the database

See Also

ADD TABLE | CLOSE DATABASES | CREATE DATABASE | DISPLAY TABLES | OPEN DATABASE | REMOVE TABLE | SET DATABASE


DBF( ) Function

Returns the name of a table open in a specified work area or a table name from a table alias.

DBF([cTableAlias | nWorkArea])

Return Values

Character

Parameters

cTableAlias
Specifies the table alias.
nWorkArea
Specifies the work area number.

If you omit cTableAlias and nWorkArea, DBF( ) returns the name of the table open in the current work area. DBF( ) returns an empty string if a table isn't open in the work area you specify. If a table doesn't have the alias you specify with cTableAlias, Visual FoxPro generates an error message.

For information on creating an alias for a table, see USE.

Remarks

When SET FULLPATH is ON, DBF( ) returns the path to the table with the table name. When SET FULLPATH is OFF, DBF( ) returns the drive on which the table resides with the table name.

Example

The following example returns the name of a table from its work area and its alias, and returns the empty string after all tables have been closed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer IN 2 ALIAS mycust
CLEAR
? DBF(2)  && Displays customer.dbf with its path
? DBF('mycust')  && Displays customer.dbf with its path
CLOSE DATABASES
? DBF( )      && Displays the empty string

See Also

CDX( ) | FIELD( ) | NDX( ) | SET FULLPATH | USE


DBGETPROP( ) Function

Retrieves the value of a property for the current database or for fields, named connections, tables, or views in the current database.

DBGETPROP(cName, cType, cProperty)

Parameters

cName
Specifies the name of the current open database or the field, named connection, table, or view in the current open database for which DBGETPROP( ) returns information.

To return information about a field in a table or a view, preface the name of the field with the name of the table or view containing the field. For example, to return information about the custid field in the customer table, specify the following for cName:

customer.custid
cType
Specifies whether cName is the current database, or a field, named connection, table, or view in the current database. The following table lists the values you can specify for cType:
cType | Description
CONNECTION | cName is a named connection in the current database.
DATABASE | cName is the current database.
FIELD | cName is a field in the current database.
TABLE | cName is a table in the current database.
VIEW | cName is a view in the current database.
cProperty
Specifies the name of the property for which DBGETPROP( ) returns information.

The following tables list the values you can specify for cProperty, the return value types, and descriptions of each property. Each description includes the read and write privileges for each property. If a property is read-only, its value cannot be changed with DBSETPROP( ). For more information about changing property values, see DBSETPROP( ).

Connection properties

cProperty Type Description
Asynchronous L The connection mode. (Default) False (.F.) specifies a synchronous connection. True (.T.) specifies an asynchronous connection.

Read/write.
BatchMode L The batch-processing mode. (Default) True (.T.) specifies the connection that operates in batch mode.

Read/write.
Comment C The text of the connection comment.

Read/write.
ConnectString C The login connection string.

Read/write.
ConnectTimeout N The connection timeout interval in seconds. The default is 0 (wait indefinitely).

Read/write.
Database C The name of the server database specified with the DATABASE clause in the CREATE CONNECTION command or in the Connection Designer.

Read/write.
DataSource C The name of the data source as defined in the Odbc.ini file.

Read/write.
DispLogin N Contains a numeric value that determines when the ODBC Login dialog box is displayed. DispLogin may assume the following values:

1 or DB_PROMPTCOMPLETE (from Foxpro.h). 1 is the default.

2 or DB_PROMPTALWAYS (from Foxpro.h).

3 or DB_PROMPTNEVER (from Foxpro.h).

If 1 or DB_PROMPTCOMPLETE is specified, Microsoft Visual FoxPro displays the ODBC Login dialog box only if any required information is missing.

If 2 or DB_PROMPTALWAYS is specified, the ODBC Login dialog box is always displayed, allowing you to change settings before connecting.

If 3 or DB_PROMPTNEVER is specified, the ODBC Login dialog box is not displayed and Visual FoxPro generates an error if the required login information is not available.

Read/write.
DispWarnings L Contains a logical value that determines if non-trappable warnings from the remote table, ODBC, or Visual FoxPro are displayed. (Default) True (.T.) specifies that non-trappable errors are displayed.

Read/write.
IdleTimeout N The idle timeout interval in seconds. Active connections are deactivated after the specified time interval. The default value is 0 (wait indefinitely).

Read/write.
PacketSize N The size of the network packet used by the connection. Adjusting this value can improve performance. The default value is 4096 bytes (4K).

Read/write
PassWord C The connection password.

Read/write.
QueryTimeout N The query timeout interval in seconds. The default value is 0 (wait indefinitely).

Read/write.
Transactions N Contains a numeric value that determines how the connection manages transactions on the remote table. Transactions may assume the following values:

1 or DB_TRANSAUTO (from Foxpro.h). 1 is the default. Transaction processing for the remote table is handled automatically.

2 or DB_TRANSMANUAL (from Foxpro.h). Transaction processing is handled manually through SQLCOMMIT( ) and SQLROLLBACK( ).

Read/write.
UserId C The user identification.

Read/write.
WaitTime N The amount of time in milliseconds that elapses before Visual FoxPro checks whether the SQL statement has completed executing. The default is 100 milliseconds.

Read/write.

Database properties

cProperty | Type | Description
Comment C The text of the database comment.

Read/write.
DBCEventFileName | C | Relative path and filename of external program file containing DBC Events code.
DBCEvents L Enabled state of DBC Events.
Set to .T. to enable.
Version N The database version number.

Read-only.

Field properties for tables

cProperty Type Description
Caption C The field caption. If an equal sign (=) precedes the value of this property, Visual FoxPro evaluates the value as an expression. Otherwise, it is treated as a string literal.

Read/write.
Comment C The text of the field comment.

Read/write.
DefaultValue C The field default value.

Read-only.
DisplayClass C Name of the class used for field mapping.

Read/write.
DisplayClassLibrary C Path to the class library specified with the DisplayClass property.

Read/write.
Format C The field display format. See the Format Property for a list of format settings.

Read/write.
InputMask C The field input format. See the InputMask Property for a list of input mask settings.

Read/write.
RuleExpression C The field rule expression.

Read-only.
RuleText C The field rule error text.

Read-only.

Field properties for views

cProperty Type Description
Caption C The field caption. If an equal sign (=) precedes the value of this property, Visual FoxPro evaluates the value as an expression. Otherwise, it is treated as a string literal.

Read/write.
Comment C The text of the field comment.

Read/write.
DataType C The data type for a field in a view. Initially set to the data type for the field in the data source.

To specify a different data type for a field with DBSETPROP( ), use the syntax for creating fields in CREATE TABLE – SQL.

For example, to change the data type of an integer field named iCost in a table named Mytable to numeric type with width 4 and 2 decimal places, use

DBSETPROP('mytable.icost', 'field', ; 'DataType', 'N(4,2)')

You can also include the NOCPTRANS clause to prevent translation of character and memo fields to a different code page.

Read/write for remote views.
DisplayClass C Name of the class used for field mapping.

Read/write.
DisplayClassLibrary C Path to the class library specified with the DisplayClass property.

Read/write.
DefaultValue C The field default value.

Read/write.
KeyField L Contains true (.T.) if the field is specified in an index key expression; otherwise, contains false (.F.).

Read/write.
RuleExpression C The field rule expression.

Read/write.
RuleText C The field rule error text.

Read/write.
Updatable L Contains true (.T.) if the field can be updated; otherwise, contains false (.F.).

Read/write.
UpdateName C The name of the field used when data in the field is updated to the remote table. By default, the remote table field name.

Read/write.

Table properties

cProperty Type Description
Comment C The text of the table comment.

Read/write.
DeleteTrigger C The Delete trigger expression.

Read-only.
InsertTrigger C The Insert trigger expression.

Read-only.
Path C The relative path with respect to the DBC to the table including the name of the file.

Read-only.
PrimaryKey C The tag name of the primary key.

Read-only.
RuleExpression C The row rule expression.

Read-only.
RuleText C The row rule error text.

Read-only.
UpdateTrigger C The Update trigger expression.

Read-only.

View properties

cProperty Type Description
AllowSimultaneousFetch L Applies when using remote views, a shared connection, and to cursors created using ODBC.

AllowSimultaneousFetch contains True (.T.) when similarly configured cursors sharing the connection are permitted to fetch rows simultaneously.

Otherwise, AllowSimultaneousFetch contains False (.F.) when fetching rows simultaneously is not permitted.
BatchUpdateCount N The number of update statements sent to the back end for views. 1 is the default. Adjusting this value can greatly increase update performance.

Read/write.
Comment C The text of the view comment.

Read/write.
CompareMemo L Contains true (.T.) (default) if memo fields (of type Memo, General, or Picture, or, for remote views, type Timestamp) are included in the WHERE clause for updates; otherwise, contains false (.F.).

Read/write.
ConnectName C The named connection used when the view is opened.

Read-only.
FetchAsNeeded L If True (.T.), data is fetched only when needed, such as when record pointer moves to a row that has not been fetched.

If False (.F.), additional data is fetched during idle time. (Default)

Note FetchAsNeeded does not apply when progressive fetching is disabled (FetchSize is -1).

Read/write.
FetchMemo L Contains true (.T.) (default) if memo and general fields are fetched with the view results; otherwise, contains false (.F.).

Read/write.
FetchSize N Contains the number of records fetched at a time from the remote tables. The default is 100 records. Setting FetchSize to –1 retrieves the complete result set, limited by the MaxRecords setting.
Note Progressive fetching holds the connection until all rows are retrieved. Use caution coding with FetchSize if ShareConnection is True (.T.).

Read/write.
MaxRecords N The maximum number of records fetched when result sets are returned. The default is – 1 (all rows are returned). A value of 0 specifies that the view is executed but no results are fetched.

Read/write.
Offline L Contains true (.T.) if the view is an offline view.

Read-only.
ParameterList C The WHERE clause parameters. The format for the parameters is ''ParameterName1, 'Type1'; ParameterName2, 'Type2'; ...'' where Type is a one of the following characters specifying the parameter type:

C – Character
D – Date
T – DateTime
N – Numeric
F – Floating
B – Double
I – Integer
Y – Currency
L - Logical

For example, ''MyParam1, 'C' '' specifies a single character type parameter named MyParam1.

For more information about creating parameterized views, see Creating Views .

Read/write.
Prepared L Contains true (.T.) if SQL statements are prepared for subsequent REQUERY( ) function calls. REQUERY( ) is used to retrieve data again for a SQL view. See SQLPREPARE( ) for additional information about preparing SQL statements.The default is false (.F.).

Read/write.
RuleExpression C The row rule expression.

Read/write.
RuleText C The rule text expression displayed when an error occurs when data is edited in a Browse or Edit window.

Read/write.
SendUpdates L Contains true (.T.) if a SQL update query is sent to update remote tables; otherwise, contains false (.F.) (default).

Read/write.
ShareConnection L Contains true (.T.) if the view can share its connection handle with other connections; otherwise, contains false (.F.).

Read/write.
SourceType N The view source. SourceType may assume the following values:
1 - The view uses local tables.

2 - The view uses remote tables.

Read-only.
SQL C The SQL statement executed when the view is opened.

Read-only.
Tables C A comma-delimited list of the names of the tables.

Read/write.
UpdateType N The update type. Valid values are:
1 or DB_UPDATE (from Foxpro.h). The old data is updated with the new data (default).

2 or DB_DELETEINSERT (from Foxpro.h). The old data is deleted and the new data is inserted.

Read/write.
UseMemoSize N The minimum size (in bytes) for which result columns are returned in memo fields. For example, if the width of a column result is greater than the value of UseMemoSize, the column result is stored in a memo field. UseMemoSize may vary from 1 to 255; the default value is 255.

Read/write.
WhereType N The WHERE clause for updates to remote tables. WhereType may assume the following values:
1 or DB_KEY (from Foxpro.h). The WHERE clause used to update remote tables consists of only the primary fields specified with the KeyFieldList property.

2 or DB_KEYANDUPDATABLE (from Foxpro.h). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and any updatable fields.

3 or DB_KEYANDMODIFIED (from Foxpro.h) (default). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and any other fields that are modified.

4 or DB_KEYANDTIMESTAMP (from Foxpro.h). The WHERE clause used to update remote tables consists of the primary fields specified with the KeyFieldList property and a comparison of the time stamps.

For more information about the WhereType property, see Creating Views.

Read/write.

Return Values

Character, Numeric, or Logical data type. DBGETPROP( ) returns the value for the specified property.

Remarks

A database must be opened before you can get its properties or those of its connections, tables, views, or fields. You do not need to execute the USE command to open a table or view before getting its properties.

For more details about the properties you can get for connections, databases, fields, tables, and views, refer to the topics listed in the following table.

For details about | Refer to this topic | In this section
Database properties | Viewing and Setting Database Properties | Working with Tables
Connections | Accessing Remote Data | Creating Views
Views |  | Creating Views
Triggers | Trigger Usage | Working with Tables
Captions | Controlling Display of a Field | Working with Tables
Default values | Creating Default Field Values | Working with Tables
 | Creating Default Values for View Fields | Creating Views
Comments | "Adding Comments to Fields" under Choosing Data Types | Working with Tables
 | Viewing and Setting Database Properties | Creating Databases
Primary key | Controlling Duplicate Values | Working with Tables
Rules | Enforcing Business Rules | Working with Tables
 | Setting or Changing Field-Level or Table Rules | Working with Tables
 | Creating Rules on View Fields and Rows | Creating Views

Example

The following example displays the name of the primary key field for the customer table. It then displays the field comments for the cust_id field in the customer table. If there are no comments for the field, a message is displayed indicating there are no field comments. To add comments, see the example for DBSETPROP( ).

CLOSE DATABASES
CLEAR

OPEN DATABASE (HOME(2) + 'Data\testdata')

* Displays the primary key field
cResults = DBGETPROP("customer", "Table", "PrimaryKey")
=MESSAGEBOX(cResults)   && Displays    'cust_id'

* Displays comments for the field 'cust_id'
cResults = DBGETPROP("customer.cust_id", "Field", "Comment")
IF LEN(ALLTRIM(cResults)) = 0
   =MESSAGEBOX("No Comment for this field." + CHR(13) + ;
     CHR (13) + "Use DBSETPROP( ) to add comments.")
ELSE
   =MESSAGEBOX("Cust_id field comments: " + cRESULTS)
ENDIF

See Also

ADD TABLE | CREATE CONNECTION | CREATE DATABASE | CREATE SQL VIEW | CURSORGETPROP( ) | CURSORSETPROP( ) | DBSETPROP( ) | DISPLAY DATABASE | LIST DATABASE | RENAME CONNECTION | SQLCOMMIT( ) | SQLROLLBACK( )


DBSETPROP( ) Function

Sets a property for the current database or for fields, named connections, tables, or views in the current database.

DBSETPROP(cName, cType, cProperty, ePropertyValue)

Parameters

cName
Specifies the name of the current open database or the field, named connection, table, or view in the current open database for which DBGETPROP( ) returns information.

To set a property for a field in a table or a view, preface the name of the field with the name of the table or view containing the field. For example, to set a property for the custid field in the customer table, specify the following for cName:

customer.custid
cType
Specifies whether cName is the current database or for a field, named connection, table, or view in the current database.

The following table lists the values you can specify for cType:

cType | Description
CONNECTION | cName is a named connection in the current database.
DATABASE | cName is the current database.
FIELD | cName is a field in the current database.
TABLE | cName is a table in the current database.
VIEW | cName is a view in the current database.
cProperty
Specifies the name of the property to set. If a property is read-only, its value cannot be changed with DBSETPROP( ). If you attempt to set a property that is read-only, Visual FoxPro generates an error message.

For more information on properties you can specify with cProperty, including their data types, see DBGETPROP( ).

ePropertyValue
Specifies the value to which cProperty is set. ePropertyValue must be the same data type as the property's data type.
Caution Visual FoxPro does not verify that the value you specify is valid for the property. Thus, it is possible to set a property to an invalid value with DBSETPROP( ). For example, DBSETPROP( ) can be used to set a field rule expression to an expression that is not valid for the field, and Visual FoxPro will not generate an error. To avoid an error when setting the Tables property of a view, precede ePropertyValue with the database designation in the following syntax:
         <databaseName>!ePropertyValue

Return Values

Logical data type. DBSETPROP( ) returns True (.T.) if Visual FoxPro successfully sets the property you specify. Visual FoxPro generates an error if the property you specify cannot be set.

Remarks

To determine the current property values, see and use DBGETPROP( ) Function. For more details about the property settings you can retrieve for connections, databases, fields, tables, and views, refer to the topics listed in the following table.

For details about | Refer to this topic | In this section
Database properties | Viewing and Setting Database Properties | Creating Databases
Connections | Accessing Remote Data | Creating Views
Views |  | Creating Views
Triggers | Trigger Usage | Working with Tables
Captions | Controlling Display of a Field | Working with Tables
Default values | Creating Default Field Values | Working with Tables
 | Creating Default Values for View Fields | Creating Views
Comments | "Adding Comments to Fields" under Choosing Data Types | Working with Tables
 | Viewing and Setting Database Properties | Creating Databases
Primary key | Controlling Duplicate Values | Working with Tables
Rules | Enforcing Business Rules | Working with Tables
 | Setting or Changing Field-Level or Table Rules | Working with Tables
 | Creating Rules on View Fields and Rows | Creating Views

Example

The following example uses DBSETPROP( ) to specify a comment for the cust_id field in the customer table. DBGETPROP( ) is used to display the comment.

CLOSE DATABASES
CLEAR

OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

= DBSETPROP("customer.cust_id", "Field", "Comment", ;
  "Property has been set by DBSETPROP.")  && New field comments

cRESULTS = DBGETPROP("customer.cust_id", "Field", "Comment")
WAIT WINDOW "Cust_id field comments: "+ cRESULTS  && Display comments

See Also

ADD TABLE | CREATE DATABASE | CURSORGETPROP( ) | CURSORSETPROP( ) | DBGETPROP( ) | DISPLAY DATABASE | LIST DATABASE | OPEN DATABASE | SQLCOMMIT( ) | SQLROLLBACK( )


DBUSED( ) Function

Returns true (.T.) if the specified database is open.

DBUSED(cDatabaseName)

Return Values

Logical

Parameters

cDatabaseName
Specifies the name of the database for which DBUSED( ) returns a logical value indicating whether or not the database is open.

Remarks

DBUSED( ) returns true (.T.) if the specified database is open; otherwise, it returns false (.F.).

Example

The following example opens the TESTDATA database, and then uses DBUSED( ) to determine if the TESTDATA database and a database named TEST are open.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')

CLEAR
? 'Testdata database open? '
?? DBUSED('testdata')     && Displays .T.
? 'Test database open? '
?? DBUSED('test')     && Displays .F.

See Also

CLOSE DATABASES | CREATE DATABASE | OPEN DATABASE


DDE Functions

Exchange data between Visual FoxPro and other Microsoft Windows-based applications.

Remarks

Visual FoxPro can act as both a server and a client to send and receive data to and from other Microsoft Windows-based applications.

The following naming conventions are used in applications that support DDE (dynamic data exchange).

Name | Description
Service Name | A name that the server responds to when a client tries to access the server. A server can support many service names.
Topic Name | A name that specifies a logical set of data. For file-based applications, topic names are usually file names. In other applications, topic names are application-specific. To access the server, the client must specify a topic name in addition to the server's service name.
Item Name | A name that specifies a unit of data that the server can pass to the client requesting the data.

To request data from another application, create a Visual FoxPro program that establishes Visual FoxPro as a client. The following is a brief outline for creating a simple Visual FoxPro program that requests data from another application:

  • Establish a link to the server application with DDEInitiate( ).
  • If the link is successfully established, use DDERequest( ) to request data from the server application. DDERequest( ) can be issued repeatedly to request additional data.
  • After the data has been received, issue DDETerminate( ) to terminate the link to the server application to free up system resources.

The functions above establish a cold link. A cold link exists when the client initiates all the communications between the applications. For a discussion of other types of links, see DDEAdvise( ).

The following is a brief outline for a program that establishes Visual FoxPro as a server:

  • Use DDESetService( ) to create a service and specify the type of service.
  • Use DDESetTopic( ) to create a service topic and specify the procedure to execute when the topic is specified in a client request.
  • Create the procedure specified in DDESetTopic( ) to accept the parameters passed to the procedure.
  • Within the procedure, process the request and, if appropriate, return the requested data to the client.

Note that these DDE functions differ from previous Visual FoxPro function conventions in the following ways:

  • The first four characters of these functions are not unique.
  • The function names exceed 10 characters and cannot be abbreviated.
    DDE Function | Description
    DDEAbortTrans( ) | Ends an asynchronous DDE transaction.
    DDEAdvise( ) | Creates a notify link or an automatic link used in DDE.
    DDEEnabled( ) | Enables or disables DDE processing or returns the status of DDE processing.
    DDEExecute( ) | Using DDE, sends a command to another application.
    DDEInitiate( ) | Establishes a DDE channel between Visual FoxPro and another Microsoft Windows-based application.
    DDELastError( ) | Returns an error number for the last DDE function.
    DDEPoke( ) | Sends data between client and server applications in a DDE conversation.
    DDERequest( ) | Requests data from a server application in a dynamic DDE conversation.
    DDESetOption( ) | Changes or returns DDE settings.
    DDESetService( ) | Creates, releases, or modifies service names and settings in Visual FoxPro.
    DDESetTopic( ) | In a DDE conversation, creates or releases a topic name from a service name.
    DDETerminate( ) | Closes a DDE channel established with DDEInitiate( ).

See Also

DDEAbortTrans( ) | DDEAdvise( ) | DDEEnabled( ) | DDEExecute( ) | DDEInitiate( ) | DDELastError( ) | DDEPoke( ) | DDERequest( ) | DDESetOption( ) | DDESetService( ) | DDESetTopic( ) | DDETerminate( )


DDEAbortTrans( ) Function

Ends an asynchronous dynamic data exchange (DDE) transaction.

DDEAbortTrans(nTransactionNumber)

Return Values

Logical

Parameters

nTransactionNumber
Specifies the transaction number returned by DDEExecute( ), DDEPoke( ), or DDERequest( ) when the transaction is sent to the server application.

Remarks

An asynchronous transaction allows Visual FoxPro program execution to continue without waiting for the server application to respond to a data request.

DDEExecute( ), DDEPoke( ), and DDERequest( ) wait for the period specified by DDESetOption( ) for a server application to respond, unless you specify a user-defined function to execute when the server application responds. Specifying a user-defined function to execute in these functions creates an asynchronous transaction.

If DDEAbortTrans( ) is called before the server has processed the request, the user-defined function will not be called for the transaction.

DDEAbortTrans( ) returns true (.T.) if the asynchronous transaction is successfully ended and returns false (.F.) if the asynchronous transaction cannot be ended. Use DDELastError( ) to determine why the transaction could not be ended.

See Also

DDEExecute( ) | DDELastError( ) | DDEPoke( ) | DDERequest( )


DDEAdvise( ) Function

Creates a notify link or an automatic link used in a dynamic data exchange (DDE).

DDEAdvise(nChannelNumber, cItemName, cUDFName, nLinkType)

Return Values

Logical

Parameters

nChannelNumber
Specifies the channel number.
cItemName
Specifies the item name. For example, Microsoft Excel uses row and column notation to refer to cells in a worksheet. The item name R1C1 designates the cell in the first row and first column of the worksheet.
cUDFName
Specifies the user-defined function that is executed when a notify link or an automatic link is established and the item cItemName is modified. When the user-defined function is executed, it is passed the following six parameters in the order given below:
Parameter | Contents
Channel Number | The channel number of the server application.
Action | ADVISE or TERMINATE.
Item | The item name; for example, R1C1 for a Microsoft Excel worksheet cell.
Data | The new data (automatic link) or the empty string (notify link).
Format | The data format; for example, CF_TEXT.
Advise Status | The link type (0 = manual, 1 = notify, 2 = automatic).

The user-defined function should have six parameters in its LPARAMETER or PARAMETER statement to accept the values passed from the server application. If a notify link is established, the user-defined function is executed and the empty string is passed in the Data parameter. You can issue DDERequest( ) later to retrieve the data. If an automatic link is established, the user-defined function is executed and the data is passed in the Data parameter.

The Action parameter contains ADVISE when the link is being updated by the server. The user-defined function is called, and the Action parameter contains TERMINATE when the link is closed by the client or server.

Any value returned by the user-defined function is ignored.

nLinkType
Specifies the link type in the following way:
nLinkType | Link type
0 | Manual
1 | Notify
2 | Automatic

You can turn off notification from the server application by specifying 0 for nLinkType. If the item changes, the user-defined function is not executed.

Remarks

DDEAdvise( ) is used to create a notify link or an automatic link to an item name in a server application. When a notify link is created with DDEAdvise( ), the server application notifies Visual FoxPro that the item name has been modified. If an automatic link is created, the server application notifies Visual FoxPro that the item name has been modified and passes the new data to Visual FoxPro.

Before you can create a link, you must establish a channel to the server application with DDEInitiate( ).

You can also use DDEAdvise( ) to turn off notification from the server.

DDEAdvise( ) returns a true value (.T.) if it executes successfully; otherwise, it returns false (.F.).

Example

The following example demonstrates how you can establish a DDE channel to a Microsoft Excel worksheet named Sheet1. DDEAdvise( ) is used to establish two links to data in two worksheet cells (R1C1 and R1C2). The user-defined function NEWDATA is executed when data in either of the cells changes. The user-defined function tests the item and advise parameters to determine which item changed and what kind of link has been established.

PUBLIC mchannum
mchannum = DDEInitiate('Excel', 'Sheet1')
IF mchannum != -1
   = DDEAdvise(mchannum, 'R1C1', 'newdata', 1)     && Notify link
   = DDEAdvise(mchannum, 'R1C2', 'newdata', 2)     && Automatic link
   WAIT WINDOW 'Enter data in first two cells in Excel.'
ENDIF
PROCEDURE newdata
PARAMETERS channel, action, item, data, format, advise
IF action = 'ADVISE'
   DO CASE
      CASE item = 'R1C1'   && Notify link
         newvalue = DDERequest(channel, item)
         ? 'R1C1 notify link: ' + newvalue
      CASE item = 'R1C2'   && Automatic link
         newvalue = data
         ? 'R1C2 automatic link: ' + newvalue
   ENDCASE
ELSE
   IF action != "TERMINATE"
      = DDETerminate(mchannum)
 ENDIF
ENDIF

See Also

DDEInitiate( ) | DDELastError( ) | DDESetOption( ) | DDETerminate( )


DDEEnabled( ) Function

Enables or disables dynamic data exchange (DDE) processing or returns the status of DDE processing.

DDEEnabled([lExpression1 | nChannelNumber [, lExpression2]])

Return Values

Logical

Parameters

lExpression1
Specify true (.T.) or false (.F.) to globally enable or disable DDE processing. DDEEnabled( ) returns true (.T.) if DDE processing is successfully enabled or disabled; otherwise false (.F.) is returned.
nChannelNumber
Specifies the channel number for the channel whose DDE processing status DDEEnabled( ) returns. DDEEnabled( ) returns true (.T.) if DDE processing is enabled for the specified channel and returns false (.F.) if DDE processing is disabled.
lExpression2
To enable DDE processing for a specific channel, include the channel number (nChannelNumber) and specify true (.T.) for lExpression2. To disable DDE processing for a specific channel, include the channel number (nChannelNumber) and specify false (.F.) for lExpression2.

Remarks

Using DDEEnabled( ), you can globally enable or disable processing. You can also enable or disable DDE processing for specific channels.

DDEEnabled( ) can be used to protect critical code or disable links for short periods. When DDE processing is disabled, client requests are queued until DDE processing is enabled.

If DDEEnabled( ) is issued without any of its optional arguments, the global DDE processing status is returned. DDEEnabled( ) returns true (.T.) if DDE processing has been globally enabled and false (.F.) if DDE processing has been globally disabled.

See Also

DDEAbortTrans( ) | DDEAdvise( ) | DDEExecute( ) | DDEInitiate( ) | DDELastError( ) | DDEPoke( ) | DDERequest( ) | DDESetOption( ) | DDESetService( ) | DDESetTopic( ) | DDETerminate( )


DDEExecute( ) Function

Sends a command to another application, using dynamic data exchange (DDE).

DDEExecute(nChannelNumber, cCommand [, cUDFName])

Return Values

Logical

Parameters

nChannelNumber
Specifies the channel number.
cCommand
Specifies the command you want to send to the other application. The format of the command is determined by the application you are sending it to. Consult the application's documentation for the correct syntax.
cUDFName
Allows asynchronous command execution requests. If you omit cUDFName, a client application waits for the period specified with DDESetOption( ). If you specify a user-defined function with cUDFName, client program execution continues immediately after the command execution request is made.

When the server application finishes executing the command, the user-defined function you specify with cUDFName is executed. The user-defined function is passed six parameters in the order shown in the following table.

Parameter | Contents
Channel Number | The channel number of the server application.
Action | XACTCOMPLETE (successful execution).XACTFAIL (failed command execution).
Item | The item name; for example, R1C1 for a Microsoft Excel worksheet cell.
Data | The new data (REQUEST) or data passed (POKE or EXECUTED).
Format | The data format; for example, CF_TEXT.
Transaction Number | The transaction number returned by DDEExecute( ).

Use DDEAbortTrans( ) to cancel an uncompleted transaction. If the transaction fails, you can use DDELastError( ) to determine why it failed.

When you include cUDFName, DDEExecute( ) does not return a logical value. Instead, a transaction number is returned; if an error occurs, –1 is returned.

Remarks

The command sent with DDEExecute( ) must be understood by the application. Before you can execute the command, you must establish a channel to the server application with DDEInitiate( ).

For example, Microsoft Excel has an extensive set of macro commands, including DDE commands that let you request data from Visual FoxPro from within Microsoft Excel. If you establish a channel to Microsoft Excel, you can then use DDEExecute( ) to send macro commands to Excel from within Visual FoxPro.

If the receiving application successfully executes the command, DDEExecute( ) returns true (.T.). If the receiving application cannot successfully execute the command or if the channel number you include is not valid, DDEExecute( ) returns false (.F.). If the optional asynchronous user-defined function cUDFName is included, a transaction number is returned. If an error occurs, DDEExecute( ) returns –1.

Example

The following example uses DDEInitiate( ) to establish a DDE channel between Visual FoxPro and the Microsoft Excel worksheet Sheet1. DDEExecute( ) is used to execute a Microsoft Excel command that maximizes the Microsoft Excel window.

gnChanNum = DDEInitiate('Excel', 'Sheet1')
IF gnChanNum != -1
   glExecute = DDEExecute(gnChanNum, '[App.Maximize]')
   IF glExecute != .F.
      WAIT WINDOW 'EXCEL window has been zoomed out.'
   ENDIF
   = DDETerminate(gnChanNum)   && Close the channel
ENDIF

See Also

DDEAbortTrans( ) | DDEInitiate( ) | DDELastError( ) | DDESetOption( ) | DDETerminate( )


DDEInitiate( ) Function

Establishes a dynamic data exchange (DDE) channel between Visual FoxPro and another Microsoft Windows-based application.

DDEInitiate(cServiceName, cTopicName)

Return Values

Numeric

Parameters

cServiceName
Specifies the service name of the server application, which, in most cases, is the name of the executable file without its extension. The default service name for Visual FoxPro is Visual FoxPro. If you are establishing a channel to Microsoft Excel, cServiceName is Excel.
cTopicName
Specifies the topic name. The topic is application-specific and must be understood by the application. For example, one topic supplied by most DDE servers is the System topic. See the application documentation for the service and topic names supported by the application.

Remarks

DDEInitiate( ) establishes a DDE channel between Visual FoxPro and a DDE server application. Once a channel is established, Visual FoxPro can request data from the server by referring to the channel in subsequent DDE functions. Visual FoxPro acts as the client, requesting data from the server application through the channel.

If the channel is successfully established, DDEInitiate( ) returns the channel number. Channel numbers are non-negative, and the number of channels you can establish is limited only by your system resources.

DDEInitiate( ) returns –1 if the channel cannot be established. If the server application is not open, Visual FoxPro asks if you would like to open it. If you choose Yes, Visual FoxPro attempts to open the application. (You can use DDELastError( ) to determine why a channel cannot be established.)

To avoid being asked whether you want to open the application, set the DDESetOption( ) SAFETY option. You can also use RUN with the /N option to start the application.

A channel can be closed with DDETerminate( ).

Example

The following example uses DDEInitiate( ) to establish a DDE channel between Visual FoxPro and a Microsoft Excel worksheet named Sheet1. 'Excel' is the service name, and 'Sheet1' is the topic name. The channel number is stored to the memory variable mchannum for use in subsequent DDE functions.

mchannum = DDEInitiate('Excel', 'Sheet1')
IF mchannum != -1
   * Process client actions
   = DDETerminate(mchannum)  && Close the channel
ENDIF

See Also

DDEAdvise( ) | DDEEnabled( ) | DDEExecute( ) | DDELastError( ) | DDEPoke( ) | DDERequest( ) | DDESetOption( ) | DDETerminate( ) | RUN | !


DDELastError( ) Function

Returns an error number for the last dynamic data exchange (DDE) function.

DDELastError( )

Return Values

Numeric

Remarks

You can use DDELastError( ) to help determine the cause of an error when a DDE function does not execute successfully.

DDELastError( ) returns 0 if the last DDE function executed successfully. It returns a nonzero value if the last DDE function was unsuccessful. The following table lists the error numbers and their descriptions.

Error number | Description
1 | Service busy
2 | Topic busy
3 | Channel busy
4 | No such service
5 | No such topic
6 | Bad channel
7 | Insufficient memory
8 | Acknowledge timeout
9 | Request timeout
10 | No DDEInitiate( )
11 | Client attempted server transaction
12 | Execute timeout
13 | Bad parameter
14 | Low memory
15 | Memory error
16 | Connect failure
17 | Request failure
18 | Poke timeout
19 | Could not display message
20 | Multiple synchronous transactions
21 | Server died
22 | Internal DDE error
23 | Advise timeout
24 | Invalid transaction identifier
25 | Unknown

See Also

DDEAbortTrans( ) | DDEAdvise( ) | DDEEnabled( ) | DDEExecute( ) | DDEInitiate( ) | DDEPoke( ) | DDERequest( ) | DDESetOption( ) | DDESetService( ) | DDESetTopic( ) | DDETerminate( )


DDEPoke( ) Function

Sends data between client and server applications in a dynamic data exchange (DDE) conversation.

DDEPoke(nChannelNumber, cItemName, cDataSent
   [, cDataFormat [, cUDFName]])

Return Values

Logical

Parameters

nChannelNumber
Specifies the channel number of the application data is sent to. If the channel number is a server channel, DDEPoke( ) sends the data in response to a request or a previously established notify or automatic link.
cItemName
Specifies the item name to which data is sent. The item name is application-specific and must be understood by the application. For example, Microsoft Excel supports R1C1 as a valid item name that refers to the first cell in a worksheet.
cDataSent
Specifies the data sent to the item name specified with cItemName.
cDataFormat
Specifies the format used to send the data. The default format is CF_TEXT. In this format, fields are delimited with tabs and records are delimited with a carriage return and a linefeed.
cUDFName
Allows asynchronous data transfer. If cUDFName is omitted, a client waits for the period specified with DDESetOption( ). If you specify the name of a user-defined function with cUDFName, client program execution continues immediately after the request is made.

When the data is available from the server application, the user-defined function specified with cUDFName is executed. The user-defined function is passed six parameters in this order:

Parameter | Contents
Channel Number | The channel number of the server application.
Action | XACTCOMPLETE (successful transaction).XACTFAIL (failed transaction).
Item | The item name; for example, R1C1 for a Microsoft Excel worksheet cell.
Data | The new data (REQUEST) or data passed (POKE or EXECUTED).
Format | The data format; for example, CF_TEXT.
Transaction Number | The transaction number returned by DDEPoke( ).

Use DDEAbortTrans( ) to cancel an uncompleted transaction. If the transaction fails, you can use DDELastError( ) to determine why it failed.

When you include cUDFName, DDEPoke( ) returns a transaction number if successful or –1 if an error occurs.

Remarks

DDEPoke( ) sends data as a character string to the item name in the application specified by the channel number.

If the data is successfully sent, DDEPoke( ) returns true (.T.). If the data cannot be sent, DDEPoke( ) returns false (.F.). If the asynchronous user-defined function cUDFName is included, DDEPoke( ) returns a transaction number; if an error occurs, DDEPoke( ) returns –1.

See Also

DDEAbortTrans( ) | DDEInitiate( ) | DDELastError( ) | DDESetOption( ) | DDETerminate( )


DDERequest( ) Function

Requests data from a server application in a dynamic data exchange (DDE) conversation.

DDERequest(nChannelNumber, cItemName [, cDataFormat [, cUDFName]])

Return Values

Character

Parameters

nChannelNumber
Specifies the channel number of the server application.
cItemName
Specifies the item name. The item name is application-specific and must be understood by the application. For example, Microsoft Excel uses row and column notation to refer to cells in a worksheet. The item name R1C1 designates the cell in the first row and first column of the worksheet.
cDataFormat
Specifies a format for the data requested. The default format is CF_TEXT. In this format, fields are delimited with tabs and records are delimited with a carriage return and a line feed.
cUDFName
Allows an asynchronous data transfer. If you omit cUDFName, Visual FoxPro waits for the data from the server for the period specified with DDESetOption( ). If you specify the name of a user-defined function with cUDFName, Visual FoxPro continues program execution immediately after the request is made.

When the data is available from the server application, the user-defined function specified with cUDFName is executed. The user-defined function is passed six parameters in this order:

Parameter | Contents
Channel Number | The channel number of the server application.
Action | XACTCOMPLETE (successful transaction).XACTFAIL (failed transaction).
Item | The item name; for example, R1C1 for a Microsoft Excel worksheet cell.
Data | The new data (REQUEST) or data passed (POKE or EXECUTED).
Format | The data format; for example, CF_TEXT.
Transaction Number | The transaction number returned by DDERequest( ).

Use DDEAbortTrans( ) to cancel an uncompleted transaction. If the transaction fails, you can use DDELastError( ) to determine why it failed.

When you include cUDFName, DDERequest( ) returns a transaction number equal to or greater than 0 if successful, or –1 if an error occurs.

Remarks

Before you can request data using DDERequest( ), you must establish a channel to the server application with DDEInitiate( ).

If the request for data is successful, DDERequest( ) returns the data as a character string. If the request fails, DDERequest( ) returns an empty string and DDELastError( ) returns a nonzero value. If you include the asynchronous user-defined function cUDFName, DDERequest( ) returns a transaction number if successful, or –1 if an error occurs.

Example

The following example uses DDEInitiate( ) to establish a DDE channel between Visual FoxPro and a Microsoft Excel worksheet named Sheet1. 'Excel' is the service name, and 'Sheet1' is the topic name. The channel number is stored to the memory variable mchannum for use in subsequent DDE functions.

DDERequest( ) requests the item name R1C1, the data in the first row and column of the Sheet1 spreadsheet.

mchannum = DDEInitiate('Excel', 'Sheet1')
IF mchannum != -1
   mrequest = DDERequest(mchannum, 'R1C1')
   IF !EMPTY(mrequest) AND DDELastError( ) = 0      && Successful
      WAIT WINDOW 'R1C1 contents: ' + mrequest
   ENDIF
   = DDETerminate(mchannum)            && Close the channel
ENDIF

See Also

DDEAbortTrans( ) | DDEInitiate( ) | DDELastError( ) | DDESetOption( ) | DDETerminate( )


DDESetOption( ) Function

Changes or returns dynamic data exchange (DDE) settings.

DDESetOption(cOption [, nTimeoutValue | lExpression])

Return Values

Logical or Numeric

Parameters

cOption
Specifies the setting options.
cOption | Setting | Default | Description
TIMEOUT | nTimeoutValue (number of milliseconds) | 2000 | The number of milliseconds DDE functions wait for the server application to respond; the current TIMEOUT value is returned if you omit nTimeoutValue.
SAFETY | lExpression(true (.T.) or false (.F.)) | .T. | Specifies whether a dialog is displayed when you use DDEInitiate( ) to establish a channel to a server application and the application does not respond; the current SAFETY setting is returned if you omit lExpression.
nTimeoutValue
Specifies the timeout value.
lExpression
Enables or disables dialog display.

Remarks

Use DDESetOption( ) to change or return DDE settings. Two options, TIMEOUT and SAFETY, are available.

See Also

DDEAdvise( ) | DDEEnabled( ) | DDEExecute( ) | DDEInitiate( ) | DDEPoke( ) | DDERequest( ) | DDESetService( ) | DDETerminate( )


DDESetService( ) Function

Creates, releases, or modifies DDE service names and settings.

DDESetService(cServiceName, cOption [, cDataFormat | lExpression])

Return Values

Logical

Parameters

cServiceName
Specifies the service name to create, release, modify, or return information about.
cOption
Specifies to create, release, or modify a service name or to return information about a service name. The following table lists the options you can specify with cOption, the default values for the options and a description of each option.
Option | Default value | Description
DEFINE – Creates a new service name.
RELEASE – Releases an existing service name.
ADVISE | .F. | Enables or disables client notification of changes to item names.
EXECUTE | .F. | Enables or disables command execution.
POKE | .F. | Enables or disables client pokes to the service.
REQUEST | .T. | Enables or disables requests to the service name.
FORMATS | CF_TEXT | Specifies supported data formats.
DEFINE
Creates a new service name. For example, the following command creates the service name myservice:
glNewService = DDESetService('myservice', 'DEFINE')
RELEASE
Releases an existing service name to free up system resources. When a service name is released, all of the service's topic names are also released.

The following command releases the service name created in the previous example:

glRelease = DDESetService('myservice', 'RELEASE')

To release the default Visual FoxPro service, issue this command:

glRelFox = DDESetService('FoxPro', 'RELEASE')
ADVISE
Specifies whether a client is notified when data changes in an item name or specifies to return the current advise status for a service name. Refer to DDEAdvise( ) for additional information about advising clients.

To enable client notification, specify true (.T.) for lExpression. Specifying false (.F.) for lExpression disables client notification.

To return the current client notification status for the service name, omit lExpression. DDESetService( ) returns true if client notification is enabled for the service name; it returns false if client notification is disabled.

EXECUTE
Allows you to enable or disable command execution requests to a service name or to determine the current execute status for a service name.

To enable client requests to execute a command, specify true (.T.) for lExpression. Specifying false (.F.) for lExpression disables client requests to execute a command. .F. is the default value.

To return the current command execution status for the service name, omit lExpression. DDESetService( ) returns true if client command execution requests are enabled for the service name; otherwise, it returns false.

The following commands enable command execution and disable data requests from client applications for the service name myservice. The current command execution status for myservice is then displayed:

glExecute = DDESetService('myservice', 'EXECUTE', .T.)
glRequest = DDESetService('myservice', 'REQUEST', .F.)
? DDESetService('myservice', 'EXECUTE')
POKE
Allows you to enable or disable poke requests to the service name. You can also determine the current poke status for a service name. Refer to DDEPoke( ) for additional information about poking data to a server or a client.

To enable client poke requests, specify true (.T.) for lExpression. Specifying false (.F.) for lExpression disables client poke requests. .F. is the default value.

To return the current poke status for the service name, omit lExpression. DDESetService( ) returns true if poke requests are enabled for a service name; it returns false if poke requests are disabled.

REQUEST
Use REQUEST to enable or disable client requests to a service name or to return the current request status for the service name.

To enable client requests to the service name, specify true (.T.) for lExpression. Specifying false (.F.) disables client requests to the service name. True (.T.) is the default value.

To return the current request status for a service name, omit lExpression. DDESetService( ) returns true if client requests are enabled for the service name; it returns false if client requests are disabled.

The following commands disable requests from client applications to the service name myservice and display the current request status for myservice:

glRequest = DDESetService('myservice', 'REQUEST', .F.)
? DDESetService('myservice', 'REQUEST')
FORMATS [cDataFormat]
Specifies the data formats supported by the service name. Server requests for formats not specified with cDataFormat are rejected. When specifying data formats, include a list of the supported formats separated by commas. For example:
=DDESetService('myservice', 'FORMATS', 'CF_TEXT, CF_SYLK')

If you omit cDataFormat, only the CF_TEXT format is supported.

lExpression
Specifies the state of the REQUEST, EXECUTE, POKE, or ADVISE options. Specify true (.T.) for lExpression to enable the option or false (.F.) to disable it.

Remarks

Visual FoxPro can act as a dynamic data exchange (DDE) server to send data to client Microsoft Windows-based applications. DDESetService( ) is used to create, release, or modify service names and settings in Visual FoxPro. Each service name can have a set of topic names created with DDESetTopic( ). Client applications request data from DDE topic names.

DDESetService( ) returns true (.T.) if the service name is successfully created, released, or modified. If the service name cannot be created, released, or modified, DDESetService( ) returns false (.F.).

DDESetService( ) can also be used to return information about a service name. Visual FoxPro has the default service name FoxPro. The Visual FoxPro service name has one topic name called System. The following table lists all the item names supported by the System topic.

Item name | Item
Topics | A list of available topic names
Formats | A list of supported formats
Status | Busy or Ready
SysItems | A list of item names

You can use DDESetTopic( ) to modify the FoxPro service name or to release it. For information about manipulating Visual FoxPro service names, see the DDESetTopic( ) options.

See Also

DDEEnabled( ) | DDELastError( ) | DDEPoke( ) | DDESetTopic( )


DDESetTopic( ) Function

Creates or releases a topic name from a service name in a dynamic data exchange (DDE) conversation.

DDESetTopic(cServiceName, cTopicName [, cUDFName])

Return Values

Logical

Parameters

cServiceName
Specifies the service name. Additional service names can be created with DDESetService( ).
cTopicName
Specifies the topic name to create or release. If you include cUDFName, DDESetTopic( ) creates the topic name cTopicName. If you omit cUDFName, the topic name cTopicName is released. If cTopicName is an empty string, the user-defined function specified with cUDFName is executed for any topic name that is not explicitly declared.
cUDFName
Specifies the name of the user-defined function executed when a client application makes a request to the topic name. If you omit cUDFName, the topic name cTopicName is released from the service name.

When the user-defined function is executed, it is passed the following six parameters in the order given below:

Parameter | Contents
Channel Number | The client channel number.
Action | ADVISE, EXECUTE, INITIATE, POKE, REQUEST, or TERMINATE.
Item | The item name; for example, R1C1 for a Microsoft Excel worksheet cell.
Data | Data from the client.
Format | The data format; for example, CF_TEXT.
Advise Status | The link type (0 = manual, 2 = notify or automatic).

The values of the Item, Data, and Advise Status parameters depend on the Action parameter. The following table lists the Action parameter values and the values contained in the Item, Data, and Advise Status parameters. A dash (–) indicates that the parameter value is the empty string.

Action value Item value Data value Advise status
INITIATE – Topic name –
TERMINATE – – –
POKE Item name New data –
REQUEST Item name – –
EXECUTE – New command –
ADVISE Item name – Link type

If the user-defined function successfully handles the client request, the user-defined function should return true (.T.). If the request cannot be handled or an error occurs, the user-defined function should return false (.F.). If false is returned when the Action parameter value is INITIATE, the client topic name request is rejected. If false is returned when the value is POKE, REQUEST, or EXECUTE, the request is ignored. If false is returned when the value is ADVISE, the client request for a notify or automatic link is rejected.

Remarks

After a topic name is created, any client requests to the topic name cause Visual FoxPro to execute the user-defined function specified with cUDFName. The user-defined function is passed a set of parameters whose values are determined by the client request. The user-defined function return value is passed to the client with DDEPoke( ). The return value is a logical value indicating whether the topic name can provide the service requested by the client.

DDESetTopic( ) returns true (.T.) if it successfully creates or releases the topic name. It returns false (.F.) if the topic name cannot be created or released. Use DDELastError( ) to determine why a topic name cannot be created or released.

Example

The following example creates a basic sample server called myserver that supports Visual FoxPro command execution from a client application. The client application makes requests to myserver through the DO topic, and macro substitution is used to execute the client's command.

*** Set Visual FoxPro up as a DDE server ***
= DDESetService('myserver', 'DEFINE')
= DDESetService('myserver', 'EXECUTE', .T.)
= DDESetTopic('myserver', 'DO', 'DOTOPIC')
WAIT WINDOW 'Server portion service setup ... ' NOWAIT
*** Use Visual FoxPro as a DDE client ***
gnChannel = DDEInitiate('myserver','DO')
=DDEExecute(gnChannel, 'WAIT WINDOW "Command Executed ... "')
=DDETerminate(gnChannel)
PROCEDURE dotopic
PARAMETERS gnChannel, gcAction, gcItem, gData, gcFormat, gnAdvise
glResult = .F.
*** It's necessary to return .T. from an   ***
*** INITIATE action or no connection is made ***
IF gcAction = 'INITIATE'
   glResult = .T.
ENDIF
IF gcAction = 'EXECUTE'
   &gData
   glResult = .T.
ENDIF
IF gcAction = 'TERMINATE'
   WAIT WINDOW 'Goodbye ... ' NOWAIT
   glResult = .T.
ENDIF
RETURN glResult

After running this example program, you have set up Visual FoxPro service, which other applications can access. If you have Microsoft Excel, you can run the following Excel macro:

gnMyChan = INITIATE("myserver","DO")
=EXECUTE(MyChan,"WAIT WINDOW 'Hi, this is EXCEL speaking'")
=RETURN( )

See Also

DDEEnabled( ) | DDELastError( ) | DDEPoke( ) | DDESetService( )


DDETerminate( ) Function

Closes a dynamic data exchange (DDE) channel established with DDEInitiate( ).

DDETerminate(nChannelNumber | cServiceName)

Return Values

Logical

Parameters

nChannelNumber
Specifies the channel number to close.
cServiceName
Specifies the service name to close.

Remarks

If the channel is successfully closed, DDETerminate( ) returns true (.T.). If the channel cannot be closed, DDETerminate( ) returns false (.F.).

Be sure to close channels as soon as they are no longer needed to conserve system resources.

All channels are automatically closed if you exit Visual FoxPro by choosing Exit from the File menu or by issuing QUIT in the Command window or from within a program.

See Also

DDEAbortTrans( ) | DDEAdvise( ) | DDEExecute( ) | DDEInitiate( ) | DDELastError( ) | DDEPoke( ) | DDERequest( ) | DDESetOption( )


DEFAULTEXT( ) Function

Returns a file name with a new extension if one does not already exist.

DEFAULTEXT(cFileName, cDefault)

Return Values

Character

Parameters

cFileName
Specifies the filename (with or without a path or extension) to be returned.
cDefault
Specifies the default extension without a period.

See Also

ADDBS( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


DELETED( ) Function

Returns a logical value that indicates whether the current record is marked for deletion.

DELETED([cTableAlias | nWorkArea])

Return Values

Logical

Parameters

cTableAlias | nWorkArea
You can check the status of the current record in a table open in another work area by specifying the work area number with nWorkArea or the table alias with cTableAlias. If a table isn't open in the work area you specify, DELETED( ) returns false.

If you omit cTableAlias and nWorkArea, the deleted status is returned for the current record in the current work area.

Remarks

If the record is marked for deletion, DELETED( ) returns true (.T.); otherwise, DELETED( ) returns false (.F.).

Records can be marked for deletion with DELETE and DELETE – SQL, and they can be unmarked with RECALL.

Rushmore Query Optimization optimizes queries that test the deleted status of records if the table is indexed on DELETED( ).

For information on using Rushmore to optimize queries, see SET OPTIMIZE and Using Rushmore Query Optimization to Speed Data Access.

Example

The following example opens the customer table in the testdata database. DELETE – SQL is used to mark all records for deletion where the country field contains USA. DELETED( ) is used to display all the records marked for deletion. RECALL ALL is used to unmark all the records marked for deletion.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

DELETE FROM customer WHERE country = 'USA'  && Mark for deletion
CLEAR
LIST FIELDS company, country FOR DELETED( ) && List marked records
RECALL ALL  && Unmark all records marked for deletion

See Also

DELETE | DELETE – SQL | PACK | RECALL | SET DELETED


DESCENDING( ) Function

Returns a logical value that indicates whether an index tag was created with the DESCENDING keyword or whether the DESCENDING keyword was included in USE, SET INDEX, or SET ORDER.

DESCENDING([CDXFileName[, nIndexNumber [, nWorkArea | cTableAlias]]])

Return Values

Logical

Parameters

CDXFileName
Specifies the name of a compound index file with CDXFileName. The compound index file you specify can be the structural compound index file automatically opened with the table or an independent compound index file.
nIndexNumber
Specifies which index tag or index file DESCENDING( ) tests. nIndexNumber is typically an integer that starts at 1 and is increased by 1 to return additional values for each index tag.

If nIndexNumber is 1, a value for the master single-entry .idx index file or master index tag (if one is present) is returned.

As nIndexNumber increases, values for each tag in the structural compound index (if one is present) are returned. The values are returned for the tags in the order in which the tags were created in the structural compound index.

After values for all the tags in the structural compound index are returned, values for each tag in any open independent compound indexes are then returned. The values are returned from the tags in the order in which the tags are created in the independent compound indexes.

The empty string is returned if nIndexNumber is greater than the total number of open, single-entry .idx files and structural compound and independent compound index tags.

nWorkArea | cTableAlias
Returns values for index files or tags open in a work area other than the current work area. nWorkArea specifies the work area number and cTableAlias specifies the table alias.

If no table has the alias you specify, Visual FoxPro generates an error message.

Remarks

You can order records in a table in descending order in two ways:

  • You can include the DESCENDING keyword in the INDEX command to create a descending order index tag in a compound .cdx.
  • You can include the DESCENDING keyword in USE, SET INDEX or SET ORDER to specify a descending order for the master index tag or the master single-entry index (.idx) file.

DESCENDING( ) can determine if an index tag was created in descending order. DESCENDING( ) returns true (.T.) if the index tag you specify was created with the DESCENDING keyword.

DESCENDING( ) can also determine if the master index tag or master index file is in descending order. DESCENDING( ) returns true (.T.) if the DESCENDING keyword was included in USE, SET INDEX, or SET ORDER for the master index tag or a single-entry index (.idx) file you specify.

If you don't include any of the optional arguments, DESCENDING( ) returns a value for the master index tag or master index file. If you don't include any of the optional arguments and a master index tag or .idx file isn't in effect (for example, you've issued SET ORDER TO to place the table in physical record order), DESCENDING( ) returns false (.F.).

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which the descending status of each index tag in the customer structural index is checked. The name of each structural index tag is displayed with its descending status.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
CLEAR

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? TAG(nCount) + ' Descending? ' && Display tag name
   ?? DESCENDING(nCount)  && Display descending status
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

INDEX | SET INDEX | SET ORDER | USE


DIFFERENCE( ) Function

Returns an integer, 0 through 4, which represents the relative phonetic difference between two character expressions.

DIFFERENCE(cExpression1, cExpression2)

Return Values

Numeric

Parameters

cExpression1, cExpression2
Specifies the character expressions that DIFFERENCE( ) compares.

Remarks

DIFFERENCE( ) is useful for searching tables when the exact spelling of an entry isn't known.

The more alike the two expressions are spelled, the higher the number DIFFERENCE( ) returns. If the character expressions are spelled very similarly, DIFFERENCE( ) returns 4. For two character expressions with little in common phonetically, DIFFERENCE( ) returns 0.

Example

STORE 'Smith' TO gcName1
STORE 'Smythe'  TO gcName2
STORE 'Smittie' TO gcName3
STORE '' TO gcName4
CLEAR
? DIFFERENCE(gcName1, gcName2)  && Displays 4
? DIFFERENCE(gcName1, gcName3)  && Displays 4
? DIFFERENCE(gcName1, gcName4)  && Displays 1

See Also

SOUNDEX( )


DIRECTORY( ) Function

Locates the specified directory.

DIRECTORY(cDirectoryName [, nFlags])

Parameters

cDirectoryName
Specifies the name of the directory to locate. If you do not include an absolute path for the directory you specify, Visual FoxPro searches for the directory relative to the Visual FoxPro default directory.
nFlags
Specifies the kind of value DIRECTORY( ) returns when the directory exists but might be marked with the Hidden or System attribute. The following table lists the values for nFlags.
nFlags | Description
0 | DIRECTORY( ) returns False (.F.) if the directory exists but is marked with a Hidden or System attribute. (Default)
1 | DIRECTORY( ) returns True (.T.) if the directory exists, regardless of its attributes. Setting nFlags to 1 allows you to check for hidden or system files.

Return Values

Logical data type. DIRECTORY( ) returns True (.T.) if the specified directory is found on the disk; otherwise, it returns False (.F.).

Remarks

The SET DEFAULT command specifies the Visual FoxPro default directory.

You can use the ADIR( ) function to determine specific attributes for the directory.

You can use the CD and CHDIR commands to switch to hidden files and directories.

See Also

Functions | SET DEFAULT | ADIR( ) Function | CD | CHDIR Command | FILE( ) | GETDIR( ) | GETFILE( ) |


DISKSPACE( ) Function

Returns the number of bytes available on the default or specified disk drive or volume.

DISKSPACE([cVolumeName [, nType]])

Return Values

Numeric

Parameters

cVolumeName
Specifies the name of the disk drive or volume for which the available space is returned. If you omit cVolumeName, the available space is returned for the default disk drive or volume.
nType
Specifies the type of disk space to retrieve according to following table.
Value | Description
1 | Total amount of space on the volume
2 | (Default) Total amount of free space on the volume.
3 | Total amount of free space available to the user associated with the calling thread.

Remarks

This function is useful for determining whether sufficient space is available to back up files or to execute commands such as SORT that require additional disk space for temporary work files.

The default disk drive or volume is specified with SET DEFAULT.

DISKSPACE( ) returns –1 if there is an error reading the disk drive or volume. On some networks, the value returned by DISKSPACE( ) may not be accurate for large network drives.

Example

The following example uses DISKSPACE( ) to determine whether sufficient disk space is available to perform a sort.

*** Check DISKSPACE before sort ***
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

*** Get size of table header ***
gnTableHead = HEADER( )

*** Calculate size of table ***
gnFileSize = gnTableHead + (RECSIZE( ) * RECCOUNT( ) + 1)
IF DISKSPACE( ) > (gnFileSize * 3)
   WAIT WINDOW 'Sufficient diskspace to sort.'
ELSE
   WAIT WINDOW 'Insufficient diskspace. Sort cannot be done.'
ENDIF

See Also

HEADER( ) | RECSIZE( ) | SET DEFAULT


DisplayPath( ) Function

Truncates long path expressions to a specified length for display.

DisplayPath(cFilename, nMaxLength)

Returns

Character data type. DisplayPath( ) returns a string and displays the path in title (proper) case.

Parameters

cFileName
Specifies the name of the file at the end of the target path. If you specify no path, Visual FoxPro uses the value of CURDIR( ).
Note This function does not check the validity of cFileName and will report the truncated path expression even if no such file exists.
nMaxLength
Specifies the maximum length of the truncated result. nMaxLength must be greater than or equal to 10.

Remarks

DisplayPath( ) returns a string suitable only for display purposes, so you cannot use the result to reference a file. The length of the resulting string is equal to or less than nMaxLength. However, the result does not break directory names. If inclusion of a directory name would exceed nMaxLength, the result is an ellipsis (...). If the filename exceeds nMaxLength, the result is the filename plus extension.

See Also

JUSTPATH( ) Function | ADIR( ) Function


DMY( ) Function

Returns a character expression in day-month-year format (for example, 31 May 1998) from a Date or DateTime expression. The month name isn't abbreviated.

DMY(dExpression | tExpression)

Return Values

Character

Parameters

dExpression
Specifies the Date expression from which DMY( ) returns a character string in day-month-year format.
tExpression
Specifies the DateTime expression from which DMY( ) returns a character string in day-month-year format.

Remarks

If SET CENTURY is OFF, DMY( ) returns a character string in a dd-Month-yy format (for example, 16 February 98). If SET CENTURY is ON, the format is dd-Month-yyyy (for example, 16 February 1998).

Example

CLEAR
SET CENTURY OFF
? DMY(DATE( ))
SET CENTURY ON
? DMY(DATE( ))

See Also

MDY( ) | SET CENTURY | SET DATE


DODEFAULT( ) Function

Executes the parent class event or method of the same name from within a subclass.

For example, if you place DODEFAULT( ) in the Click event of a subclass, Visual FoxPro executes the Click event of the parent class. The scope resolution operator (::), unlike DODEFAULT( ), executes a parent class event or method of a different name.

Note You can place DODEFAULT( ) only within an event or method.
DODEFAULT( [ eParameter1 [, eParameter2] ...] )

Parameters

eParameter1 [, eParameter2] ...
Specifies parameters that are passed to the parent class event or method.

Return Values

Character, Numeric, Currency, Date, DateTime, Logical, or Memo

Remarks

The value that DODEFAULT( ) returns is determined by the return value of the event or method.

In versions prior to Visual FoxPro 8.0, you could not call DODEFAULT( ) in a method that did not exist in the parent class without Visual FoxPro generating an error, "Property name is not found (Error 1734)", returning True (.T.), and disregarding DODEFAULT( ) and any passed parameters. However, Visual FoxPro now disregards this and does not generate an error, but the following results still occur:

  • Visual FoxPro disregards any parameters that are passed because no code is executed.
  • Visual FoxPro always returns True (.T.), which is the default behavior for any procedure without an explicit RETURN statement.

This behavior affects the following scenarios:

  • Custom methods that are defined in a class. For example, the line, x.Test(), generated an error prior to Visual FoxPro 8.0 but no longer does:
    CLEAR
x=CREATEOBJECT("s1")
x.ReadMethod("Init")
x.Test()

DEFINE CLASS s1 AS Session
   PROCEDURE Test
      DODEFAULT()
   ENDPROC
   PROCEDURE ReadMethod(cMethod)
      DODEFAULT(cMethod)
   ENDPROC
   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:", nError, cMethod, nLine
   ENDPROC
ENDDEFINE
  • Native methods that are marked with the HIDDEN key word in the parent class. For example:
    CLEAR
x=CREATEOBJECT("s2")
x.Test()

DEFINE CLASS s2 AS s1
   PROCEDURE Test
      THIS.ReadMethod("Init")
   ENDPROC
   PROCEDURE ReadMethod(cMethod)
      DODEFAULT(cMethod)
   ENDPROC
ENDDEFINE

DEFINE CLASS s1 AS Session
   HIDDEN PROCEDURE ReadMethod(cMethod)
      DODEFAULT(cMethod)
   ENDPROC
   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:", nError, cMethod, nLine
   ENDPROC
ENDDEFINE

Starting in Visual FoxPro 7.0, calling a native method in a base class that contains DODEFAULT( ) does not cause an error. For example:

CLEAR
x=CREATEOBJECT("s1")
x.ReadMethod("Init")

DEFINE CLASS s1 AS Session
   PROCEDURE ReadMethod(cMethod)
      DODEFAULT(cMethod)
   ENDPROC
   PROCEDURE Error(nError, cMethod, nLine)
      ? "Error:", nError, cMethod, nLine
   ENDPROC
ENDDEFINE

See Also

:: Scope Resolution Operator | ParentClass Property


DOW( ) Function

Returns a numeric day-of-the-week value from a Date or DateTime expression.

DOW(dExpression | tExpression [, nFirstDayOfWeek])

Return Values

Numeric

Parameters

dExpression
Specifies the Date expression from which DOW( ) returns the day number.
tExpression
Specifies the DateTime expression from which DOW( ) returns the day number.
nFirstDayOfWeek
Specifies the first day of the week. nFirstDayOfWeek may be one of the following values.
nFirstDayOfWeek | Description
0 | DOW( ) uses whatever day is currently selected in the Week Starts On list box, which appears on the Regional Tab in the Options dialog box.
1 | Sunday. This is the default when nFirstDayOfWeek is omitted, and is the first day of the week used in earlier FoxPro versions.
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday

Example

STORE DATE( ) TO gdDayNum
CLEAR
? DOW(gdDayNum)
? CDOW(gdDayNum)

See Also

CDOW( ) | DAY( ) | SET FDOW | SET FWEEK | SYS( ) Functions Overview | WEEK( )


DRIVETYPE( ) Function

Returns the type of the specified drive.

DRIVETYPE(cDrive)

Return Values

Numeric

Parameters

cDrive
The drive designator. The colon in drive names (for example, "C:") is optional.

Remarks

The following table explains the number DRIVETYPE( ) returns and the corresponding drive type description.

Number | Drive Type
1 | No type
2 | Floppy disk
3 | Hard disk
4 | Removable drive or network drive
5 | CD-ROM
6 | RAM disk1

1 Because there are many different types of RAM disks, you might get inconsistent return results.

See Also

SYS(5) - Default Drive or Volume | JUSTDRIVE( ) Function


DROPOFFLINE( ) Function

Discards all changes made to an offline view and takes the offline view back online.

DROPOFFLINE(cViewName)

Return Values

Logical

Parameters

cViewName
Specifies the name of the offline view to take back online.

Remarks

DROPOFFLINE( ) returns a logical true (.T.) if the offline view is successfully taken back online; otherwise it returns false (.F.).

See Also

CREATEOFFLINE( ) | DROP VIEW | USE


DTOC( ) Function

Returns a Character-type date from a Date or DateTime expression.

DTOC(dExpression | tExpression [, 1])

Return Values

Character

Parameters

dExpression
Specifies a Date-type variable, array element, or field for which DTOC( ) returns a Character-type date.
tExpression
Specifies a DateTime-type variable, array element, or field for which DTOC( ) returns a Character-type date.
1
Returns the date in a format suitable for indexing. This is particularly useful for maintaining the table records in chronological sequence.

For example, to order table records in entry sequence, you could issue this command:

INDEX ON DTOC(gdInvDate, 1) + gnInvTime TAG Timeindx

gdInvDate and gnInvTime are fields containing the date and time when the data was entered in the record.

Remarks

DTOC( ) returns a character string corresponding to a Date or DateTime expression. The date format is determined by SET CENTURY and SET DATE.

Example

SET STRICTDATE TO 1
STORE CTOD('10/31/98') TO gdThisDate
CLEAR
? DTOC(gdThisDate)
STORE DTOC({^1998-10-31}+90) TO gcExpireDate
? 'Your 90-day warranty expires ', gcExpireDate
? DTOC({^1998-10-31},1)

See Also

CTOD( ) | SET CENTURY | SET DATE | SYS( ) Functions Overview | TTOC( )


DTOR( ) Function

Converts degrees to radians.

DTOR(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression whose value you want to convert to radians. An angle expressed in a degree:minute:second format should be converted to its decimal equivalent.

Remarks

DTOR( ) converts the value of a numeric expression given in degrees to an equivalent value in radians. DTOR( ) is useful for working with the Microsoft Visual FoxPro trigonometric functions: ACOS( ), ASIN( ), COS( ), SIN( ), TAN( ).

Use RTOD( ) to convert radians to degrees.

Example

CLEAR
? DTOR(0)  && Displays 0.00
? DTOR(45) && Displays 0.79
? DTOR(90) && Displays 1.57
? DTOR(180)  && Displays 3.14
? COS(DTOR(90))  && Displays 0.00

See Also

ACOS( ) | ASIN( ) | COS( ) | RTOD( ) | SIN( ) | TAN( )


DTOS( ) Function

Returns a character-string date in a yyyymmdd format from a specified Date or DateTime expression.

DTOS(dExpression | tExpression)

Return Values

Character

Parameters

dExpression
Specifies the Date expression DTOS( ) converts to an eight-digit character string.
tExpression
Specifies the DateTime expression DTOS( ) converts to an eight-digit character string.

Remarks

This function is useful for indexing tables on a Date or DateTime field. It is equivalent to DTOC( ) when its optional 1 argument is included.

The character string returned by DTOS( ) isn't affected by SET DATE or SET CENTURY.

Example

CLEAR
? DTOS(DATE( ))

See Also

DATE( ) | DATETIME( ) | CTOD( ) | DTOC( )


DTOT( ) Function

Returns a DateTime value from a Date expression.

DTOT(dDateExpression)

Return Values

DateTime

Parameters

dDateExpression
Specifies the Date expression from which a DateTime value is returned.

Remarks

The format of the DateTime value DTOT( ) returns depends on the current SET DATE and SET MARK settings. If a century isn't supplied, the twentieth century is assumed.

DTOT( ) adds a default time of midnight (12:00:00 A.M.) to the date to produce a valid DateTime value.

Example

? DTOT({^1998-02-16}) && Displays 02/16/1998 12:00:00am

See Also

CTOT( ) | DATE( ) | SEC( ) | SECONDS( ) | SET SECONDS | TIME( )


EDITSOURCE( ) Function

Opens the Visual FoxPro editor and, optionally positions the cursor.

EditSource(cShortCutID | [ cFilename [, nLineNo] [, cClassName]
[, cMethodName|cProcName]])

Parameters

cShortCutID
Specifies the valid shortcut ID
cFileName
Specifies the name of the file to open. If the file is already open, Visual FoxPro activates it.
nLineNo
Specifies the line at which to position the cursor. If you use 0, the cursor is positioned at the last location saved in the resource file. If you provide an invalid or non-existent nlineno, the cursor is positioned at the beginning of the current file. A negative nlineno value will generate an error.
cClassName
Specifies the name of a class or data environment to be edited. If you open a class file (.vcx) without naming a class, the Class Designer opens instead of the editor.
cMethodName
Specifies the name of a method to be edited. Use a valid object-referenced method in the form cObject.nMethodName.
cProcName
Specifies the name of a procedure to be edited in a class type file (.vcx, .scx, .frx, .lbx).

Return Values

Logical. Returns true (.T.) if the target file opens successfully, otherwise returns error codes according to the following table:

Value | Description
0 | Successful file opening.
132, 705 | File in use. Cannot be opened.
200 | File not opened due to invalid object reference. Verify the presence of cMethodName in the object referenced by the cClassName parameter.
901, 925 | File opened but invalid object reference in cMethodName. Check the reference in the cMethodName parameter. Use a reference such as MyForm.MyList.CLICK. Forms and classes return 925; reports return 901.

Remarks

You can pass cShortCutID without any additional information and have the editor open at that location. The cShortCutID is the unique ID value for a shortcut record stored in the Foxtask system table (_VFP.FoxTask). The Task List application uses this table to ensure that it can get the latest line position of the shortcut. Visual FoxPro maintains, internally, current shortcut information, but only writes line position updates to Foxtask when a file is saved.

The file extension determines which Visual FoxPro editor opens, according to the following table:

Extension | Editor | Default Settings
PRG | Text Editor | MODIFY COMMAND
MPR | Text Editor | MODIFY COMMAND
QPR | Text Editor | MODIFY COMMAND
TXT | Text Editor | MODIFY FILE
SCX | Code Snippet | MODIFY FORM
VCX | Code Snippet | MODIFY CLASS
FRX | Code Snippet | MODIFY REPORT
LBX | Code Snippet | MODIFY LABEL
MNX | Menu Snippet | MODIFY MENU
DBC | Stored Procedures | MODIFY PROCEDURE
<other> | Text Editor | MODIFY FILE

Program (.prg), database (.dbc stored procedures) and text files support only the nLineNo parameter.

Menu file (.mnx) are opened as text files without reference to objects or to line numbers.

See Also

MODIFY Command | APROCINFO( ) Function


EMPTY( ) Function

Determines whether an expression evaluates to empty.

EMPTY(eExpression)

Return Values

Logical

Parameters

eExpression
Specifies the expression that EMPTY( ) evaluates.

The expression you include can be a character, numeric, date, or logical expression, or the name of a memo or general field in an open table. EMPTY( ) returns true (.T.) when expressions evaluate to the following:

Expression type | Evaluates to
Character | The empty string, spaces, tabs, carriage returns, linefeeds, or any combination of these.
Numeric | 0
Currency | 0
Float | 0
Integer | 0
Double | 0
Date | Empty (e.g. CTOD(''))
DateTime | Empty (e.g. CTOT(''))
Logical | False (.F.)
Memo | Empty (no contents)
General | Empty (no OLE object)
Picture | Empty (no picture)

EMPTY( ) cannot be used to determine if a variable object reference is empty. For example, a variable can contain an object reference for a form. If the form is closed by clicking Close from the form's pop-up menu or by issuing CLEAR WINDOWS, the variable contains the null value.

The following program example demonstrates how to use TYPE( ) and ISNULL( ) to determine if a variable object reference is valid.

goMyForm = CREATEOBJECT('Form')
WAIT WINDOW IIF(TYPE('goMyForm') = 'O' AND !ISNULL(goMyForm), ;
   'goMyForm has valid object reference',;
   'goMyForm does not have valid object reference')

Remarks

EMPTY( ) returns true (.T.) if the expression eExpression evaluates to empty; otherwise, EMPTY( ) returns false (.F.).

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which EMPTY( ) s used to determine if TAG( ) returns the empty string. The name of each structural index tag is displayed with its candidate status.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer     && Open customer table

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for empty string
   ? TAG(nCount)  && Display tag name
   ? CANDIDATE(nCount)  && Display candidate status
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

LEN( ) | TYPE( ) Function | ISNULL( ) Function


EOF( ) Function

Determines whether the record pointer is positioned past the last record in the current or specified table.

EOF([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea
Specifies the work area number of the table.
cTableAlias
Specifies the alias of the table.

EOF( ) returns false (.F.) if a table isn't open in the work area you specify.

If you do not specify a work area or alias, the table that is open in the currently selected work area is tested for the end of the table condition.

Remarks

EOF( ) returns true (.T.) if the record pointer reaches the end of the table file (EOF). The end of the table is reached when the record pointer passes the last record in the table. For example, when a FIND, LOCATE, or SEEK is unsuccessful, Visual FoxPro moves the record pointer past the last record, and EOF( ) returns true (.T.). EOF( ) returns false (.F.) if the record pointer isn't at the end of the table.

Example

The following example opens the customer table and lists the company name one page at a time until the end of the file is reached or you until you choose Cancel.

CLOSE DATABASES
CLEAR
OPEN DATABASE (HOME() + "samples\data\testdata")
USE customer
GO TOP
local recCtr, btnValue
recCtr = 0
btnValue = 1
DO WHILE btnValue = 1 AND NOT EOF()
  ? "Company : " + company
  recCtr = recCtr + 1
  if (recCtr % 20) = 0 then
    btnValue =MESSAGEBOX ("Click OK to continue, ;
     Cancel to quit.",33)
    clear
  endif
  Skip 1    && Move down one record
ENDDO
=MESSAGEBOX("Listing complete.",48)

See Also

BOF( ) | GO | GOTO | SKIP


ERROR( ) Function

Returns the error number for the error that triggered an ON ERROR routine.

ERROR( )

Return Values

Numeric

Remarks

ERROR( ) returns the number of the most recent error. An ON ERROR routine must be active for ERROR( ) to return a value other than 0.

When an error is trapped during program execution, the error type can be returned by ERROR( ) in an ON ERROR routine. The corresponding error message can be returned by MESSAGE( ).

The value ERROR( ) returns is reset by RETURN or RETRY.

Example

The following example demonstrates a simple error-handling routine that displays a message when an error occurs.

CLEAR
ON ERROR DO errhand WITH ERROR( ), MESSAGE( )

*** The next line generates an error - there is no BRWSE command

BRWSE
ON ERROR
RETURN

*** Error handler ***

PROCEDURE errhand
PARAMETER errnum,message
? Message
? 'Error number: '+ ALLTRIM(STR(Errnum))
RETURN

See Also

AERROR( ) Function | ERROR | MESSAGE( ) | Error Messages A-Z | Error Messages by Number | ON ERROR | RETRY | RETURN


EVALUATE( ) Function

Evaluates a character expression and returns the result.

EVALUATE(cExpression)

Return Values

Character, Numeric, Currency, Date, DateTime, Logical, or Memo

Parameters

cExpression
Specifies the expression to evaluate. cExpression can be a literal character string, or a valid Visual FoxPro expression, variable, array element, or field of any data type, enclosed in quotation marks. cExpression cannot exceed 255 characters.

Whenever possible, use EVALUATE( ) or a name expression to replace macro substitution using &. EVALUATE and name expressions execute faster than macro substitution.

Remarks

EVALUATE( ) is similar to TYPE( ) but returns the result of an expression instead of the expression type. An expression containing EVALUATE( ) cannot be optimized by Rushmore Query Optimization.

Including the EVALUATE( ) function in the WHERE clause of a SQL query can return incorrect data.

Example

The following example uses the EVALUATE() function to evaluate a math expression stored in a character variable.

cMathFunc="INT(4.33)"
nResult=EVALUATE(cMathFunc)
?nResult

See Also

TYPE( ) | _Evaluate( ) API Library Routine | Using Rushmore Query Optimization to Speed Data Access


EVL( ) Function

Returns a non-empty value from two expressions.

You can use the EVL( ) function to return an appropriate substitute value instead of an empty value, such as False (.F.) or 0, from two expressions. You can also use this functionality to remove empty values from calculations or operations where empty values are not supported or relevant.

Note The Visual FoxPro Logical value, False (.F.), and the Numeric value of 0 also evaluate to empty.
EVL( eExpression1, eExpression2 )

Parameters

eExpression1, eExpression2
Specifies two expressions. eExpression1 and eExpression2 can be any data type except the following:
  • General fields: If eExpression1 or eExpression2 represents a General field, EVL( ) returns an error, "Operation is invalid for a General field. (Error 1912)"
  • Object references

Return Values

Character, Date, DateTime, Numeric, Currency, Logical, Object reference. EVL( ) returns eExpression1 if it does not evaluate to an empty value; otherwise, it returns eExpresssion2.

Example

The following examples create the memory variables, glEmptyDate, which contains an empty Date value, and glEmptyNum, which contains an empty Numeric value, 0.

When performing EVL( ) with glEmptyDate, EVL( ) returns an empty string ("") when evaluating glEmptyDate and an empty string, and "None" when evaluating glEmptyDate and "None".

STORE {  /  /  } TO glEmptyDate
? EVL(glEmptyDate,"")
? EVL(glEmptyDate, "None")

When performing EVL( ) with glEmptyNum, EVL( ) returns an empty string when evaluating glEmptyNum and an empty string, and "Empty" when evaluating glEmptyNum and "Empty".

STORE 0 TO glEmptyNum
? EVL(glEmptyNum,"")
? EVL(glEmptyNum, "Empty")

See Also

Functions | EMPTY( ) Function


EVENTHANDLER( ) Function

Binds a COM server event to implemented interface methods on a Visual FoxPro object.

For information about binding events from native Visual FoxPro objects, see Event Binding for Visual FoxPro Objects.

EVENTHANDLER(oCOMObject, oVFPObject [, lUnbind])

Parameters

oCOMObject
Specifies the object reference to the object whose events are to be bound. oCOMObject must be a valid COM object.
oVFPObject
Specifies the object reference to the Visual FoxPro object that contains user-defined method code, which maps to corresponding COM object events. The class must implement the events interface for the particular COM object being passed in the first parameter. For example, you must implement the RecordsetEvents interface to bind to an ADO Recordset object.
lUnbind
Visual FoxPro automatically releases the COM object when it goes out of scope. By passing this parameter with a value of .T., you can release the event binding while both objects remain in scope.

Return Values

Logical data type. EVENTHANDLER( ) returns True (.T.) if successful and False (.F.) if unsuccessful.

Remarks

You can bind a single COM object to several Visual FoxPro objects, or you can bind several COM objects to the same Visual FoxPro object.

Event handling is automatically unbound when either the Visual FoxPro or the COM object is released. You can explicitly call the EVENTHANDLER( ) function and pass the lUnbind parameter to unbind objects without releasing object references.

Example

LOCAL oEvents
LOCAL oRS AS adodb.recordset
LOCAL oConn AS adodb.Connection

oEvents = NEWOBJECT("myclass")
oConn = NEWOBJECT("adodb.connection")

oConn.Provider="MSDASQL"
* Make sure to set the SourceDB property
* below to your TESTDATA location.
oConn.ConnectionString="DSN=Visual FoxPro Database;" + ;
"SourceType=DBC; SourceDB=D:\VFP\DATA\TESTDATA.DBC"
oConn.Open
oRS = oConn.Execute("select * from customer")
? EVENTHANDLER(oRS, oEvents)
?
? PADR(oRS.Fields(0).Value,20)
? EVENTHANDLER (oRS, oEvents, .T.)
oRS.MoveNext
? PADR(oRS.Fields(0).Value,20)
oRS.MoveNext
CLEAR all
RETURN

DEFINE CLASS myclass AS session
IMPLEMENTS RecordsetEvents IN "adodb.recordset"

PROCEDURE Recordsetevents_WillChangeField(cFields AS Number @, Fields AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_FieldChangeComplete(cFields AS Number @, Fields AS VARIANT @, pError AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_WillChangeRecord(adReason AS VARIANT @, cRecords AS Number @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_RecordChangeComplete(adReason AS VARIANT @, cRecords AS Number @, pError AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_WillChangeRecordset(adReason AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())
   ?adreason,adstatus,precordset.recordcount

PROCEDURE Recordsetevents_RecordsetChangeComplete(adReason AS VARIANT @, pError AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_WillMove(adReason AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_MoveComplete(adReason AS VARIANT @, pError AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_EndOfRecordset(fMoreData AS LOGICAL @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_FetchProgress(Progress AS Number @, MaxProgress AS Number @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

PROCEDURE Recordsetevents_FetchComplete(pError AS VARIANT @, adStatus AS VARIANT @, pRecordset AS VARIANT @) AS VARIANT
   ? " "+program() + ' ' + TRANSFORM(DATETIME())

ENDDEFINE

See Also

DEFINE CLASS Command


EXECSCRIPT( ) Function

Enables you to run multiple lines of code from variables, tables, and other text at runtime.

ExecScript(cExpression [, eParameter1, eParameter2, ...])

Parameters

cExpression
Represents the text, a variable, type string, or memo to be executed as code.
eParameter1, eParameter2, ...
Optional. Specify parameters passed to a script that has a parameter statement in first line.

Return Values

The return value is the value returned by the script in cExpression. If the script returns no value, Visual FoxPro returns .T.

Remarks

ExecScript( ), unlike macro expansion, provides the same effect as selecting several lines of code in the command window then pressing the Enter key.

Example

This example creates a form and then shows the value of the AutoCenter property of the new Form object. Note the use of CHR(13), which is used to separate the two code lines.

?EXECSCRIPT("oForm=CREATEOBJECT('Form')"+CHR(13)+"?oForm.AutoCenter")

See Also

COMPILE Command | Handling Run-Time Errors | ON ERROR Command


EXP( ) Function

Returns the value of ex where x is a specified numeric expression.

EXP(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the exponent, x, in the exponential expression ex.

Remarks

The value of e, the base of natural logarithms, is approximately 2.71828. The number of decimal places returned by EXP( ) is specified with SET DECIMALS.

Example

? EXP(0)  && Displays 1.00
? EXP(1)  && Displays 2.72

See Also

LOG( ) | SET DECIMALS | LOG( ) Function


FCHSIZE( ) Function

Changes the size of a file opened with a low-level file function.

FCHSIZE(nFileHandle, nNewFileSize)

Return Values

Numeric

Parameters

nFileHandle
Specifies the file handle of the file whose size you wish to change. The file handle is returned by FOPEN( ) when you open the file or by FCREATE( ) when you create the file. If a file is opened with FOPEN( ), it must be opened with write or read/write privileges to be able to change its size.
nNewFileSize
Specifies the new file size in bytes. If nNewFileSize is less than the original file size, the file is truncated. If nNewFileSize is greater than the original file size, the file size is increased.

Remarks

Use FCHSIZE( ) to increase the file's size or truncate the file after a specified byte.

When a file's size is increased, Microsoft Visual FoxPro allocates sectors for the file on the drive where the file is opened. Since FCHSIZE( ) does not initialize the new file space, the space can contain previous data. Be sure to manage the new file space.

The final size of the file in bytes is returned. Visual FoxPro returns –1 if FCHSIZE( ) is unable to change the file size if, for example, an invalid file handle is specified because of insufficient disk space, or if the file is read-only.

Tip This function can be used to truncate a file to length 0.

See Also

FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FCLOSE( ) Function

Flushes and closes a file or communication port opened with a low-level file function.

FCLOSE(nFileHandle)

Return Values

Logical

Parameters

nFileHandle
Specifies the file handle of the low-level file to close. The numeric file handle is returned when you create the file with FCREATE( ) or open the file with FOPEN( ).

Remarks

If the file is successfully closed, FCLOSE( ) returns true (.T.) and releases the file handle. If the file cannot be closed, FCLOSE( ) returns false (.F.).

CLOSE ALL also closes low-level files.

See Also

CLOSE ALL | FCHSIZE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FCOUNT( ) Function

Returns the number of fields in a table.

FCOUNT([nWorkArea | cTableAlias])

Return Values

Numeric

Parameters

nWorkArea
Specifies the work area of the table for which FCOUNT( ) returns the number of fields.

FCOUNT( ) returns 0 if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FCOUNT( ) returns the number of fields.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

If you omit the optional arguments, FCOUNT( ) returns the number of fields in the table open in the currently selected work area.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
SELECT 0
USE employee  && Opens employee table

CLEAR
? FCOUNT('CUSTOMER')     && Displays 13, # of fields in Customer
? FCOUNT('EMPLOYEE')  && Displays 22, # of fields in Employee

See Also

DBF( ) | FIELD( ) | FSIZE( )


FCREATE( ) Function

Creates and opens a low-level file.

FCREATE(cFileName [, nFileAttribute])

Return Values

Numeric

Parameters

cFileName
Specifies the name of the file to create. You can include a drive designator and path with the file name. If a drive designator or path isn't included, the file is created in the default directory.
Note Visual FoxPro does not recognize a path name properly if a disk or directory name contains an exclamation point (!).
nFileAttribute
Specifies the attributes of the file created. The following table lists the file attributes you can specify.
nFileAttribute | File attributes
0 | (Default) Read/write
1 | Read-only
2 | Hidden
3 | Read-only/Hidden
4 | System
5 | Read-only/System
6 | System/Hidden
7 | Read-only/Hidden/System

Note that a file created with nFileAttribute other than 0 cannot be written to with FPUTS( ) or FWRITE( ) until the file is closed and opened again.

Use DISPLAY STATUS or LIST STATUS to display or print information about files created and opened with FCREATE( ). DISPLAY STATUS and LIST STATUS give the following information about each file opened or created with a low-level file function:

  • The drive, directory, and file name
  • The file handle number
  • The file pointer position
  • The read/write attributes

Remarks

If a file with the name you specify already exists, it is overwritten without warning.

FCREATE( ) assigns a file handle number to the file, which you can use to identify the file in other Visual FoxPro low-level file functions. FCREATE( ) returns the file handle number when a file is created, or returns –1 if the file cannot be created.

Tip Assign the file handle number to a memory variable so you can access the file by the variable in other low-level file functions.

You cannot open a communication port with FCREATE( ). Use FOPEN( ) to open a communication port.

Example

IF FILE('errors.txt')  && Does file exist?
   gnErrFile = FOPEN('errors.txt',12)     && If so, open read/write
ELSE
   gnErrFile = FCREATE('errors.txt')  && If not create it
ENDIF
IF gnErrFile < 0     && Check for error opening file
   WAIT 'Cannot open or create output file' WINDOW NOWAIT
ELSE  && If no error, write to file
   =FWRITE(gnErrFile , 'Error information to be written here')
ENDIF
=FCLOSE(gnErrFile )     && Close file
IF gnErrFile > 0
MODIFY FILE errors.txt NOWAIT  && Open file in edit window
ENDIF

See Also

CLOSE ALL | FCHSIZE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FDATE( ) Function

Returns the last modification Date or DateTime for a file.

FDATE(cFileName [, nType])

Return Values

Date

Parameters

cFileName
Specifies the name of the file whose last modification date FDATE( ) returns. cFileName can include a path with the file name. If a path is not included with the file name, Visual FoxPro searches for the file in the default directory and in any directories or folders specified with SET PATH.
nType
Specifies that FDATE( ) returns the last modification date or DateTime of the file specified with cFileName. If nType is 0, the last modification date is returned. Including 0 is identical to omitting nType. If nType is 1, the last modification DateTime is returned.

Remarks

The Date or DateTime value that FDATE( ) returns is assigned to the file by the operating system.

Use LUPDATE( ) to determine the last modification date for an open table.

Example

The following example uses FDATE( ) to display the last modification DateTime for FoxUser.dbf, the Visual FoxPro resource file.

? FDATE('FOXUSER.DBF', 1)  && Displays the last modification DateTime

See Also

FTIME( ) | LUPDATE( ) | DATE( ) Function


FEOF( ) Function

Determines whether the file pointer is positioned at the end of a file.

FEOF(nFileHandle)

Return Values

Logical

Parameters

nFileHandle
Specifies the file handle number of the file to check for the end-of-file condition. FEOF( ) always returns true (.T.) if you specify a file handle number of a communication port opened with FOPEN( ).

Remarks

This low-level file function returns true (.T.) if the file pointer is positioned at the end of a file opened with a low-level file function. FEOF( ) returns false (.F.) if the file pointer isn't at the end of the file.

Example

*** Open the file test.txt ***

gnFileHandle = FOPEN('test.txt')

*** Move the file pointer to BOF ***

gnPosition = FSEEK(gnFileHandle, 0)

*** If file pointer is at BOF and EOF, the file is empty ***
*** Otherwise the file must have something in it ***

IF FEOF(gnFileHandle)
   WAIT WINDOW 'This file is empty!' NOWAIT
ELSE
   WAIT WINDOW 'This file has something in it!' NOWAIT
ENDIF
= FCLOSE(gnFileHandle)

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FERROR( ) Function

Returns a number corresponding to the most recent low-level file function error.

FERROR( )

Return Values

Numeric

Remarks

FERROR( ) returns 0 if a low-level file function executes successfully. A positive value is returned if a function doesn't execute successfully. The following table lists each error number returned by FERROR( ) and the cause of the error.

Error number | Error cause
2 | File not found
4 | Too many files open (out of file handles)
5 | Access denied
6 | Invalid file handle given
8 | Out of memory
25 | Seek error (can't seek before the start of a file)
29 | Disk full
31 | Error opening file

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FFLUSH( ) Function

Flushes to disk a file opened with a low-level function.

FFLUSH(nFileHandle)

Return Values

Logical

Parameters

nFileHandle
Specifies the file handle of the file to flush to disk.

Remarks

FFLUSH( ) also releases the memory used by the file's buffer.

FLUSH is different from the FFLUSH( ) function. FLUSH doesn't operate on low-level files but rather on tables and indexes.

Example

The following example opens and writes to a file named Input.dat. After writing the first two strings, the program flushes the buffers to ensure that the strings are written to disk. It then writes the next two strings, flushes the buffers again and closes the file.

IF FILE('input.dat')
   gnTestFile = FOPEN('input.dat',2)
ELSE
   gnTestFile = FCREATE('input.dat')
ENDIF
gnIOBytes = FWRITE(gnTestFile,'Test output')
gnIOBytes = FWRITE(gnTestFile,' for low-level file I/O')
glFlushOk = FFLUSH(gnTestFile)
gnIOBytes = FWRITE(gnTestFile,'Test output2')
gnIOBytes = FWRITE(gnTestFile,' for low-level file I/O')
glFlushOk = FFLUSH(gnTestFile)
glCloseOk = FCLOSE(gnTestFile)
MODIFY FILE input.dat NOWAIT NOEDIT

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FGETS( ) Function

Returns a series of bytes from a file or a communication port opened with a low-level file function until it encounters a carriage return.

FGETS(nFileHandle [, nBytes])

Return Values

Character

Parameters

nFileHandle
Specifies the numeric file handle of the file or communication port from which FGETS( ) returns data.
nBytes
Specifies the number of bytes FGETS( ) returns. FGETS( ) returns nBytes bytes unless a carriage return is encountered first. FGETS( ) returns data between the starting file-pointer position and the carriage return if a carriage return is encountered within nBytes bytes.

FGETS( ) returns a maximum of 8192 bytes. If you omit nBytes, FGETS( )returns 254 bytes by default.

Remarks

You can read a file line by line by issuing a series of FGETS( ).

FGETS( ) returns a series of bytes as a character string. Data is returned starting from the current file's pointer position and continuing until a carriage return is encountered. The file pointer is then positioned on the byte immediately following the carriage return. The carriage return is not returned as part of the string, and line feeds are discarded.

Example

*** TEST.TXT must exist ***
STORE FOPEN('test.txt') TO gnFileHandle    && Open the file
STORE FSEEK(gnFileHandle, 0, 2) TO gnEnd    && Move pointer to EOF
STORE FSEEK(gnFileHandle, 0) TO gnTop     && Move pointer to BOF
IF gnEnd <= 0  && Is file empty?
   WAIT WINDOW 'This file is empty!' NOWAIT
ELSE  && If not
   gcString = FGETS(gnFileHandle, gnEnd)  && Store contents
   ? gcString
ENDIF
= FCLOSE(gnFileHandle)  && Close the file

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FILETOSTR( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FIELD( ) Function

Returns the name of a field, referenced by number, in a table.

FIELD(nFieldNumber | cFieldName [, nWorkArea | cTableAlias [, nFlags]])

Parameters

nFieldNumber
Specifies the field number. If nFieldNumber is 1, the name of the first field in the table is returned; if nFieldNumber is 2, the name of the second field is returned, and so on. The empty string is returned if nFieldNumber is greater than the number of fields. Field names are returned in upper case.
cFieldName
Specifies the name of a field. This is used primarily to retrieve the actual field caption as stored in a database container (DBC) when used with the nFlags parameter.

If the field caption is an expression (=), the expression is evaluated. Otherwise, the actual string literal is returned. If the expression cannot be evaluated at run time, an error is raised, and the actual field name is returned.

nWorkArea
Specifies the work area of the table for which FIELD( ) returns field names.

FIELD( ) returns the empty string if a table is not open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FIELD( ) returns field names.

Visual FoxPro generates an error message if you specify a table alias that does not exist.

nFlags
Specifies whether the actual field name or field caption is returned.
nFlags | Value description
0 Return actual field name.

FIELD( ) preserves the case of the returned field name, as long as the table is stored in a DBC.
1 | Return field caption. If the field caption is an expression, return its evaluated value.

Return Values

Character data type. If you omit the optional arguments, FIELD( ) returns the names of the fields in the table open in the currently selected work area.

Remarks

You can use the SELECT( ) function to determine the current work area for nWorkArea. You can use the ALIAS( ) function to determine the alias of the table in the current work area for cTableAlias. For more information, see SELECT( ) Function and ALIAS( ) Function.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

CLEAR
FOR gnCount = 1 TO FCOUNT( )  && Loop for number of fields
   ? FIELD(gnCount)  && Display each field
NEXT
?
? 'Number of fields: ' + ALLTRIM(STR(gnCount -1))

See Also

DISPLAY STRUCTURE | FCOUNT( ) | FSIZE( )


FILE( ) Function

Locates the specified file.

FILE(cFileName [, nFlags])

Parameters

cFileName
Specifies the name of the file to locate. cFileName must include the file extension. You can include a path with the file name to search for a file in a directory or on a drive other than the current directory or drive.

Visual FoxPro searches in the default directory for the file. If it cannot find the file in the default directory, Visual FoxPro searches along the Visual FoxPro path, which is established with SET PATH.

nFlags
Specifies the kind of value FILE( ) returns when the file exists but might be marked with the Hidden or System attribute. The following table lists the values for nFlags.
nFlags | Description
0 | FILE( ) returns False (.F.) if the file exists but is marked with a Hidden or System attribute. (Default)
1 | FILE( ) returns True (.T.) if the file exists, regardless of its file attributes. Setting nFlags to 1 allows you to check for hidden or system files.

Return Values

Logical data type. FILE( ) returns True (.T.) if the specified file is found on disk; otherwise, it returns False (.F.).

Remarks

You can use the ADIR( ) function to retrieve specific attributes for the file.

You can use the CD and CHDIR commands to switch to hidden files and directories.

Example

The following example displays a message indicating if the Visual FoxPro resource file exists in the Visual FoxPro startup directory.

SET PATH TO HOME( )
CLEAR
IF FILE('foxuser.dbf')
   WAIT WINDOW 'Visual FoxPro resource file present'
ELSE
   WAIT WINDOW 'Visual FoxPro resource file not present'
ENDIF

See Also

Functions | ADIR( ) Function | CD | CHDIR Command | FULLPATH( ) | GETFILE( ) | LOCFILE( )


FILETOSTR( ) Function

Returns the contents of a file as a character string.

FILETOSTR(cFileName)

Return Values

Character

Parameters

cFileName
Specifies the name of the file whose contents are returned as a character string. If the file is in a directory other than the current default directory, include a path with the file name.

Remarks

Note that the size of the character string FILETOSTR( ) returns can be very large. The amount of available memory or disk space determines if you can store the character string to a memory variable, array element, or memo field. Also, character fields in Visual FoxPro are limited to 254 characters. See Visual FoxPro System Capacities for more information about limitations on character type data.

Example

The following code loads REDIST.TXT into a character string, then counts the number of merge modules mentioned in the text. REDIST.TXT ships with Microsoft Visual FoxPro and lists, which Visual FoxPro files, may be redistributed with your applications.

CD HOME()
cRedist=FILETOSTR("REDIST.TXT")
?OCCURS(".MSM",cRedist)

See Also

FGETS( ) | FREAD( ) | STRTOFILE( ) | Visual FoxPro System Capacities


FILTER( ) Function

Returns the table filter expression specified in SET FILTER.

FILTER([nWorkArea | cTableAlias])

Return Values

Character

Parameters

nWorkArea
Specifies the work area of the table for which FILTER( ) returns the filter expression.

FILTER( ) returns the empty string if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FILTER( ) returns the filter expression.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

If you omit the optional arguments, FILTER( ) returns the filter expression for the table open in the currently selected work area. For more information about creating a filter, see SET FILTER.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
SET TALK ON
SET FILTER TO SUBSTR(cust_id,1) = 'B'

CLEAR
? FILTER( )  && Display filter expression
STORE FILTER('customer') TO gcOldFilter    && Save filter expression
SET FILTER TO country = 'USA'
? FILTER( )  && Display filter expression
SET FILTER TO &gcOldFilter    && Restore filter expression
? FILTER( )  && Display filter expression

LIST FIELDS cust_id, contact  && Demonstrate filter condition

See Also

SET FILTER | Filter Property


FKLABEL( ) Function

Returns the name of the function key (F1, F2, F3 ...) from the key's corresponding function key number.

FKLABEL(nFunctionKeyNumber)

Return Values

Character

Parameters

nFunctionKeyNumber
Specifies the function key number. The value of nFunctionKeyNumber should be from 0 through the number of function keys minus 1. FKLABEL( ) returns the empty string if nFunctionKeyNumber is greater than the number of function keys minus 1. The number of function keys can be determined with FKMAX( ).

Remarks

Function keys can be programmed with SET FUNCTION.

The value returned by FKLABEL( ) is affected by SET COMPATIBLE. When COMPATIBLE is set to FOXPLUS (the default), FKLABEL( ) returns the function keys. When COMPATIBLE is set to DB4, FKLABEL( ) returns the function key and function key combinations (F1, CTRL+F1, SHIFT+F1, F2, CTRL+F2, SHIFT+F2, ...).

Example

CLEAR
SET COMPATIBLE OFF
? 'COMPATIBLE OFF'
?
FOR nCount = 1 TO FKMAX( )  && Loop for # of function keys
   ? FKLABEL(nCount)  && Display programmable function keys
ENDFOR
SET COMPATIBLE ON

?
? 'COMPATIBLE ON'
?
FOR nCount = 1 TO FKMAX( )  && Loop for # of function keys
   ? FKLABEL(nCount)  && Display programmable function keys
ENDFOR

See Also

FKMAX( ) | SET COMPATIBLE | SET FUNCTION


FKMAX( ) Function

Returns the number of programmable function keys or function key combinations on your keyboard.

FKMAX( )

Return Values

Numeric

Remarks

The value returned by FKMAX( ) is affected by SET COMPATIBLE. When SET COMPATIBLE is set to FOXPLUS (the default), FKMAX( ) returns the number of function keys. When SET COMPATIBLE is set to DB4, FKMAX( ) returns the number of function key and function key combinations (F1, CTRL+F1, SHIFT+F1, F2, CTRL+F2, SHIFT+F2, ...).

Example

CLEAR
SET COMPATIBLE OFF
? 'COMPATIBLE OFF'
?
FOR nCount = 1 TO FKMAX( )  && Loop for # of function keys
   ? FKLABEL(nCount)  && Display programmable function keys
ENDFOR
SET COMPATIBLE ON

?
? 'COMPATIBLE ON'
?
FOR nCount = 1 TO FKMAX( )  && Loop for # of function keys
   ? FKLABEL(nCount)  && Display programmable function keys
ENDFOR

See Also

FKLABEL( ) | SET COMPATIBLE | SET FUNCTION


FLDLIST( ) Function

Included for compatibility with dBASE.


FLOCK( ) Function

Attempts to lock the current or specified table.

FLOCK([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea
Specifies the work area of the table that FLOCK( ) attempts to lock.

FLOCK( ) returns false (.F.) if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table that FLOCK( ) attempts to lock.

Microsoft Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

FLOCK( ) returns true (.T.) if the table is successfully locked and returns false (.F.) if the table or a record in the table is already locked by another user.

If you omit the optional arguments, FLOCK( ) attempts to lock the table open in the currently selected work area.

Note If FLOCK( ) fails to lock a table, it returns false (.F.) and does not generate an error. As a result, you can't use FLOCK( ) to trigger an ON ERROR routine.

When a table is locked, the table is available for both read and write access by the user who placed the lock. Other users on the network have read-only access to the table. For information on how to lock a table and prevent access to it by other users, see SET EXCLUSIVE and USE.

A table remains locked until it is unlocked by the user who placed the lock. The table can be unlocked by issuing UNLOCK, closing the table, or quitting Visual FoxPro. Tables can be closed with USE, CLEAR ALL, or CLOSE DATABASES.

By default, FLOCK( ) attempts to lock a table once. Use SET REPROCESS to automatically retry a table lock when the first attempt fails. SET REPROCESS determines the number of lock attempts, or the length of time during which lock attempts are made when the initial lock attempt is unsuccessful. For more information, see SET REPROCESS.

You can establish relations between two or more tables with SET RELATION. Placing a file lock on a table that is related to one or more tables doesn't place a file lock on the related tables. You must explicitly place and remove locks on the related tables.

For additional information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE products  && Opens products table
SET REPROCESS TO 3 SECONDS
SELECT * FROM products INTO TABLE newprods

IF FLOCK( )
   *** New product initialization ***
   REPLACE ALL in_stock  WITH 0.00
   REPLACE ALL on_order WITH 0.00
   WAIT 'Initialization Complete' WINDOW NOWAIT
ELSE
   *** File is locked, warn user ***
   WAIT WINDOW 'Unable to open products file; try again later!' NOWAIT
ENDIF

BROWSE FIELDS in_stock, on_order && Displays newprods table
USE
ERASE newprods.dbf

See Also

LOCK( ) | RLOCK( ) | SET REPROCESS | SET RELATION | UNLOCK | USE | SET EXCLUSIVE | ISFLOCKED( ) Function | ISRLOCKED( ) Function


FLOOR( ) Function

Returns the nearest integer that is less than or equal to the specified numeric expression.

FLOOR(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression for which FLOOR( ) returns the nearest integer that is less than or equal to the numeric expression.

Example

STORE  10.9 TO gnNumber1
STORE -10.1 TO gnNumber2

CLEAR
? FLOOR(gnNumber1)  && Displays 10
? FLOOR(gnNumber2)  && Displays -11
? FLOOR(10.0)  && Displays 10
? FLOOR(-10.0)  && Displays -10

See Also

CEILING( ) | INT( ) | ROUND( )


FONTMETRIC( ) Function

Returns font attributes for the current installed operating system fonts.

FONTMETRIC(nAttribute [, cFontName, nFontSize [, cFontStyle]])

Return Values

Numeric

Parameters

nAttribute
Determines the font attribute FONTMETRIC( ) returns. If you omit cFontName, nFontSize, and cFontStyle, FONTMETRIC( ) returns the attribute for the current font in the active output window.

The following table lists values for nAttribute and the corresponding font attributes returned.

NAttribute | Attribute
1 | Character height in pixels
2 | Character ascent (units above baseline) in pixels
3 | Character descent (units below baseline) in pixels
4 | Leading (space between lines) in pixels
5 | Extra leading in pixels
6 | Average character width in pixels
7 | Maximum character width in pixels
8 | Font weight.
9 | Italic (0 = no, nonzero = yes)
10 | Underlined (0 = no, nonzero = yes)
11 | Strikeout (0 = no, nonzero = yes)
12 | First character defined in font
13 | Last character defined in font
14 | Default character (substituted for characters not in font)
15 | Word-break character
16 | Pitch and family
17 | Character set
18 | Overhang (extra added width)
19 | Horizontal aspect for font device
20 | Vertical aspect for font device

For more information about the numeric values returned by FONTMETRIC( ), see the TEXTMETRIC function in the Microsoft Windows Programmer's Reference.

cFontName
Specifies the name of an installed font.
nFontSize
Specifies the point size of the font specified with cFontName.
cFontStyle
Specifies a font style code for the font specified with cFontName. If you omit cFontStyle, FONTMETRIC( ) returns the attribute for the Normal font style.

cFontStyle can be a character or a combination of characters listed in the following font style table. For example, the combination BI specifies the Bold Italic font style.

Character | Font style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
– Strikeout
T | Transparent
U | Underline

Remarks

FONTMETRIC( ) returns font attributes for the current font for the active output window. WFONT( ) can be used to determine the current window font.

See Also

AFONT( ) | Fonts Overview | GETFONT( ) | SYSMETRIC( ) | TXTWIDTH( ) | WFONT( )


FOPEN( ) Function

Opens a file for use with low-level file functions.

FOPEN(cFileName [, nAttribute])

Return Values

Numeric

Parameters

cFileName
Specifies the name of the file to open. cFileName can include a path to open files in directories, folders, drives, or volumes not in the current Microsoft Visual FoxPro search path. If a path isn't included, Visual FoxPro searches for the file in the following locations:
  • Default directory
  • Path established with SET PATH
    Note Visual FoxPro will not recognize a path name properly if a disk or directory name contains an exclamation point (!).
nAttribute
Specifies read/write privileges or a buffering scheme for the file you open. The following table lists each number you can include in nAttribute, and the read/write file privileges and buffering scheme it establishes.
nAttribute | Read/Write privileges | Buffered/unbuffered
0 | (Default) Read-only | Buffered
1 | Write-only | Buffered
2 | Read and Write | Buffered
10 | Read-only | Unbuffered
11 | Write-only | Unbuffered
12 | Read and Write | Unbuffered

If nAttribute isn't included, or if nAttribute evaluates to 0, the file is opened as read-only and is buffered.

Note Visual FoxPro will not recognize a path name properly if a disk or directory name contains an exclamation point (!).

Remarks

If FOPEN( ) successfully opens the file, the file handle number of the file is returned. FOPEN( ) returns –1 if the file cannot be opened.

Tip Assign the file handle number to a memory variable so you can access the file by the memory variable in other low-level file functions.

The following information about files opened with FOPEN( ) can be displayed or sent to a printer with DISPLAY STATUS or LIST STATUS.

  • Drive and directory or volume and folder, and file name
  • File handle number
  • File pointer position
  • Read/write attributes

Example

IF FILE('errors.txt')  && Does file exist?
   gnErrFile = FOPEN('errors.txt',12)  && If so, open read/write
ELSE
   gnErrFile = FCREATE('errors.txt')  && If not, create it
ENDIF
IF gnErrFile < 0  && Check for error opening file
   WAIT 'Cannot open or create output file' WINDOW NOWAIT
ELSE  && If no error, write to file
   =FWRITE(gnErrFile, 'Error information to be written here')
ENDIF
=FCLOSE(gnErrFile)  && Close file
MODIFY FILE errors.txt NOWAIT  && Open file in edit window

See Also

CLOSE ALL | FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FOR( ) Function

Returns the index filter expression, in uppercase, of an open single-entry index (.idx) file or an index tag.

FOR([nIndexNumber [, nWorkArea | cTableAlias]])

Return Values

Character

Parameters

If you don't include any of the optional arguments, FOR( ) returns the index filter expression for the master index file or index tag. If a master index file or index tag isn't in effect (for example, you've issued SET ORDER TO to place the table in physical record order), FOR( ) returns the empty string.

nIndexNumber
Specifies the index file or tag for which the filter expression is returned. FOR( ) returns filter expressions in the following order as nIndexNumber increases from 1 to the total number of open single-entry files and structural compound and independent compound index tags:
  1. Filter expressions from single-entry index files (if any are open) are returned first. The order the single-entry index files are included in USE or SET INDEX determines the order in which the filter expressions are returned.
  2. Filter expressions for each tag in the structural compound index (if one is present) are returned next. The filter expressions are returned from the tags in the order the tags are created in the structural index.
  3. Filter expressions for each tag in any open independent compound indexes are returned last. The filter expressions are returned from the tags in the order in which the tags are created in the independent compound indexes.

    The empty string is returned if an index or index tag is created without a FOR clause or if nIndexNumber is greater than the total number of open single-entry files and structural compound and independent compound index tags.

nWorkArea
Specifies the work area of the table for which FOR( ) returns the index filter expressions.

FOR( ) returns the empty string if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FOR( ) returns the index filter expressions.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

You can create filtered indexes in Visual FoxPro. If you include the optional FOR lExpression clause in INDEX, the index file acts as a filter on the table. Only records that match the filter expression lExpression are available for display and access. Index keys are created in the index file for just those records matching the filter expression.

USE and SET INDEX both support an index file name list that makes it possible for you to open multiple index files for a table. Any combination of single-entry index file names, structural compound, or independent compound index file names can be included in the index file name list. FOR( ) is similar to SYS(2021) and is provided for compatibility with dBASE IV.

See Also

INDEX


FORCEEXT( ) Function

Returns a string with the old file name extension replaced by a new extension.

FORCEEXT(cFileName, cExtension)

Return Values

Character

Parameters

cFileName
Specifies the file name (with or without a path or extension), which will get a new extension.
cExtension
Specifies the new extension (without a period) for cFileName.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


FORCEPATH( ) Function

Returns a file name with a new path name substituted for the old one.

FORCEPATH(cFileName, cPath)

Return Values

Character

Parameters

cFileName
Specifies the file name (with or without a path or extension), which will get a new path.
cPath
Specifies the new path for cFileName.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


FOUND( ) Function

Returns true (.T.) if CONTINUE, FIND, INDEXSEEK( ), LOCATE, or SEEK is successful.

FOUND([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea
Specifies the work area of the table for which FOUND( ) returns a value indicating the success of the last CONTINUE, FIND, INDEXSEEK( ), LOCATE, or SEEK.

FOUND( ) returns false (.F.) if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FOUND( ) returns a value indicating the success of the last CONTINUE, FIND, INDEXSEEK( ), LOCATE, or SEEK.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

FOUND( ) returns a logical value that indicates whether the most recently executed CONTINUE, FIND, INDEXSEEK( ), LOCATE, or SEEK was successful, or if the record pointer was moved in a related table. FOUND( ) returns true (.T.) if the search is successful; otherwise FOUND( ) returns false (.F.).

If you omit the optional arguments, FOUND( ) returns a value indicating the success of the last CONTINUE, FIND, INDEXSEEK( ), LOCATE, or SEEK for the table open in the currently selected work area.

Tip This function can be used to determine if a child table has a record that matches the parent record.

Examples

In the following example, all customers from Germany are counted.

SET TALK OFF
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

STORE 0 TO gnCount
LOCATE FOR UPPER(country) = 'GERMANY'
DO WHILE FOUND( )
   gnCount = gnCount + 1
   CONTINUE
ENDDO
WAIT WINDOW 'Total customers from Germany: ' ;
   + LTRIM(STR(gnCount)) NOWAIT

See Also

CONTINUE | EOF( ) | FIND | INDEXSEEK( ) | LOCATE | SEEK


FPUTS( ) Function

Writes a character string, carriage return, and line feed to a file opened with a low-level file function.

FPUTS(nFileHandle, cExpression [, nCharactersWritten])

Return Values

Numeric

Parameters

nFileHandle
Specifies the file handle number for the file to which FPUTS( ) writes data.
cExpression
Specifies the character expression that FPUTS( ) writes to the file.
nCharactersWritten
Specifies the number of characters in cExpression to write to the file.

FPUTS( ) writes the entire character expression cExpression to the file if you omit nCharactersWritten. If you include nCharactersWritten, nCharactersWritten characters are written to the file. If nCharactersWritten is less than the number of characters in cExpression, only nCharactersWritten characters are written to the file. All of cExpression is written to the file if nCharactersWritten is equal to or greater than the number of characters in cExpression.

Remarks

FPUTS( ) returns the number of bytes written to the file. Zero is returned if FPUTS( ) cannot write to the file for any reason.

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FREAD( ) | FSEEK( ) | FWRITE( )


FREAD( ) Function

Returns a specified number of bytes from a file opened with a low-level function.

FREAD(nFileHandle, nBytes)

Parameters

nFileHandle
Specifies the file handle number for the file from which FREAD( ) returns data. You can obtain nFileHandle from the return value of successful FOPEN( ) or FCREATE( ) statements.
nBytes
Specifies the number of bytes returned by FREAD( ) with a limit of 65,535 bytes. FREAD( ) returns data starting from the current file pointer position and continues until it returns nBytes bytes or until it encounters the end of the file.

Return Values

Character data type

Example

The following example uses FREAD( ) to display the contents of a file. If the file is empty, a message is displayed. Before using this example, you must create a sample text file called Test.txt.

Local gnFileHandle,nSize,cString
gnFileHandle = FOPEN("test.txt")
* Seek to end of file to determine number of bytes in the file.
nSize =  FSEEK(gnFileHandle, 0, 2)     && Move pointer to EOF
IF nSize <= 0
 * If file is empty, display an error message.
 WAIT WINDOW "This file is empty!" NOWAIT
ELSE
 * If file is not empty, store the file's contents in memory
 * and display the text in the main Visual FoxPro window.
 = FSEEK(gnFileHandle, 0, 0)      && Move pointer to BOF
 cString = FREAD(gnFileHandle, nSize)
 ? cString
ENDIF
= FCLOSE(gnFileHandle)         && Close the file

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FILETOSTR( ) | FOPEN( ) | FPUTS( ) | FSEEK( ) | FWRITE( )


FSEEK( ) Function

Moves the file pointer in a file opened with a low-level file function.

FSEEK(nFileHandle, nBytesMoved [, nRelativePosition])

Return Values

Numeric

Parameters

nFileHandle
Specifies the file handle for the file in which FSEEK( ) moves the file pointer. A file handle number is returned by FCREATE( ) or FOPEN( ) when the file is created or opened.
nBytesMoved
Specifies the number of bytes to move the file pointer. The file pointer is moved toward the end of the file if nBytesMoved is positive. The file pointer is moved toward the beginning of the file if nBytesMoved is negative.
nRelativePosition
Moves the file pointer to a relative position in the file. By default, the file pointer is moved relative to the beginning of the file. You can also move the file pointer relative to the current file pointer or the end of the file by including nRelativePosition. The following table lists values for nRelativePosition and from where the file pointer is moved.
nRelativePosition | Moves the file pointer relative to
0 | (Default) The beginning of the file.
1 | The current file pointer position.
2 | The end of the file.

Remarks

After moving the file pointer, FSEEK( ) returns the number of bytes the file pointer is positioned from the beginning of the file. The file pointer can also be moved with FREAD( ) and FWRITE( ).

Example

The following user-defined function uses FSEEK( ) to return the size of a file. If you don't pass parameters to the user-defined function, it returns –2. If the file cannot be found, the user-defined function returns –1.

FUNCTION fsize2
PARAMETERS gcFileName  && File to be checked
PRIVATE pnHandle,pnSize
IF PARAMETERS( ) = 0
   RETURN -2  && Return -2 if no parameter passed
ELSE
   IF !FILE(gcFileName)
      RETURN -1  && Return -1 if file does not exist
   ENDIF
ENDIF
pnHandle = FOPEN(gcFileName)   && Open file
pnSize = FSEEK(pnHandle,0,2)   && Determine file size, assign to pnSize
=FCLOSE(pnHandle)  && Close file
RETURN pnSize  && Return value

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FWRITE( )


FSIZE( ) Function

Returns the size in bytes of a specified field or file.

FSIZE(cFieldName [, nWorkArea | cTableAlias] | cFileName)

Return Values

Numeric

Parameters

cFieldName
Specifies the name of the field.
nWorkArea
Specifies the work area of the table for which FSIZE( ) returns a field size.

FSIZE( ) returns 0 if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which FSIZE( ) returns a field size.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

cFileName
Specifies a file for which FSIZE( ) returns the size in bytes.

Remarks

The current setting of SET COMPATIBLE determines if FSIZE( ) returns the size of a field or a file. If SET COMPATIBLE is set to OFF or FOXPLUS (the default), FSIZE( ) returns the size of a field. If SET COMPATIBLE is set to ON or DB4, FSIZE( ) returns the size of a file.

The following table shows the default size (in bytes) for each fixed-length field type.

Field type | Default field size(in bytes)
Currency | 8
Date | 8
DateTime | 8
Double | 8
Integer | 4
Logical | 1
Memo | 4
General | 4

The size of a field can be displayed with DISPLAY STRUCTURE and LIST STRUCTURE.

If you omit the optional nWorkArea and cTableAlias arguments, FSIZE( ) returns the field size for a field in the current table and work area.

Example

The following example uses FSIZE( ) to return the size of two fields in the customer table.

SET COMPATIBLE OFF
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Open Customer table

CLEAR
? FSIZE('contact')  && Displays 30
? FSIZE('cust_id')  && Displays 6

See Also

DISPLAY STRUCTURE | FCOUNT( ) | LIST


FTIME( ) Function

Returns the last modification time for a file.

FTIME(cFileName)

Return Values

Character

Parameters

cFileName
Specifies the name of the file whose last modification time FTIME( ) returns. cFileName can include a path with the file name. If a path is not included with the file name, Visual FoxPro searches for the file in the default directory and in any directories or folders specified with SET PATH.

Remarks

The time that FTIME( ) returns is assigned to the file by the operating system.

Example

The following example uses FTIME( ) to display the last modification time for FoxUser.dbf, the Visual FoxPro resource file.

? FTIME('FOXUSER.DBF')  && Displays the last modification time

See Also

FDATE( ) | LUPDATE( ) | SET PATH Command


FULLPATH( ) Function

Returns the path to a specified file or the path relative to another file.

FULLPATH(cFileName1 [, nMSDOSPath | cFileName2])

Return Values

Character

Parameters

cFileName1
Specifies the file for which Visual FoxPro searches. Be sure to include the file name extension.

If the file is located in the Visual FoxPro path, the path is returned with the file name. The Visual FoxPro path can be specified with SET PATH.

nMSDOSPath
Specifies that the MS-DOS path is searched instead of the Visual FoxPro path. nMSDOSPath can have any numeric value. If the file can't be located in the MS-DOS path, a path and the file name are returned as if the file had been found in the current default directory.
cFileName2
Specifies a second file name to search for. Be sure to include the file name extension. FULLPATH( ) returns the path for the first file relative to the second file.

See Also

DBF( ) | FILE( ) | LOCFILE( ) | SYS(2014) - Minimum Path


FV( ) Function

Returns the future value of a financial investment.

FV(nPayment, nInterestRate, nPeriods)

Return Values

Numeric

Parameters

nPayment
Specifies the constant periodic payment (which can be negative or positive).
nInterestRate
Specifies the periodic interest rate. If the interest rate is annual but the payments are made monthly, divide the annual interest rate by 12.
nPeriods
Specifies the number of periods over which payments are made. FV( ) assumes that the periodic payments are made at the end of each period.

Remarks

FV( ) computes the future value of a series of constant periodic payments earning fixed compound interest. The future value is the total of all payments and the interest.

Example

STORE 500 TO gnPayment  && Monthly payment
STORE .075/12 TO gnInterest     && 7.5% annual interest rate
STORE 48 TO gnPeriods  && Four years (48 months)

CLEAR
? FV(gnPayment, gnInterest, gnPeriods)    && Displays 27887.93

See Also

CALCULATE | PV( ) | STORE Command


FWRITE( ) Function

Writes a character string to a file opened with a low-level file function.

FWRITE(nFileHandle, cExpression [, nCharactersWritten])

Return Values

Numeric

Parameters

nFileHandle
Specifies the file handle number for the file to which FWRITE( ) writes.
cExpression
Specifies the character expression that FWRITE( ) writes to the file specified with nFileHandle.
nCharactersWritten
FWRITE( ) writes the entire character expression to the file unless you include nCharactersWritten. When you include nCharactersWritten, nCharactersWritten characters are written to the file. If nCharactersWritten is less than the number of characters in cExpression, only nCharactersWritten characters are written to the file. All of the characters in cExpression are written to the file if nCharactersWritten is equal to or greater than the number of characters in cExpression.

Remarks

Unlike FPUTS( ), FWRITE( ) doesn't place a carriage return and a line feed at the end of the character string.

FWRITE( ) returns the number of bytes written to the file. If FWRITE( ) can't write to the file for any reason, 0 is returned.

See Also

FCHSIZE( ) | FCLOSE( ) | FCREATE( ) | FEOF( ) | FFLUSH( ) | FGETS( ) | FOPEN( ) | FPUTS( ) | FREAD( ) | FSEEK( ) | STRTOFILE( )


GETBAR( ) Function

Returns the number of an item on a menu defined with DEFINE POPUP or the Visual FoxPro system menu.

GETBAR(MenuItemName, nMenuPosition)

Return Values

Numeric

Parameters

MenuItemName
Specifies the menu item.
nMenuPosition
Specifies a position on the menu. nMenuPosition can range from 1 through the number of items within the menu. 1 corresponds to the first item on the menu, 2 to the second item, and so on.

Remarks

Use GETBAR( ) to determine which item occupies a specific position on a menu. This function is useful when items on a menu are added, removed, or rearranged. Use DEFINE BAR to add an item to a menu or RELEASE BAR to remove an item. The position of items in a menu can be changed if MOVER is included when the menu is created with DEFINE POPUP.

Example

The following example creates a menu named popDemo. The MOVER keyword is included so the items in the menu can be rearranged. For information about rearranging menu items, see the MOVER clause in DEFINE POPUP.

The menu is activated, and a series of GETBAR( ) functions are used in PRMBAR( ) to return captions of each item. After you rearrange the items, press CTRL+Z to display the new item order.

CLEAR
ON KEY LABEL CTRL+Z DO showorder
WAIT WINDOW "Press CTRL+Z to refresh." NOWAIT

DEFINE POPUP popDemo MOVER FROM 2,2
DEFINE BAR 1 OF popDemo PROMPT 'One'
DEFINE BAR 2 OF popDemo PROMPT 'Two'
DEFINE BAR 3 OF popDemo PROMPT 'Three'
DEFINE BAR 4 OF popDemo PROMPT 'Four'

DO showorder
ACTIVATE POPUP popDemo

PROCEDURE showorder
CLEAR
@ 3,12 SAY  '1 ' + PRMBAR('popDemo', GETBAR('popDemo',1))
@ 4,12 SAY  '2 ' + PRMBAR('popDemo', GETBAR('popDemo',2))
@ 5,12 SAY  '3 ' + PRMBAR('popDemo', GETBAR('popDemo',3))
@ 6,12 SAY  '4 ' + PRMBAR('popDemo', GETBAR('popDemo',4))
RETURN

See Also

DEFINE BAR | DEFINE POPUP | RELEASE BAR


GETCOLOR( ) Function

Displays the Windows Color dialog box and returns the color number of the chosen color.

GETCOLOR([nDefaultColorNumber])

Return Values

Numeric

Parameters

nDefaultColorNumber
Specifies the color that is initially selected when the Color dialog box is displayed. If nDefaultColorNumber doesn't correspond to a color in the Color dialog box, the first color in the Color dialog box is selected. If you omit nDefaultColorNumber, black is selected.

Remarks

GETCOLOR( ) returns – 1 if you exit the Color dialog box by pressing ESC, choosing the Cancel button, or choosing Close from the Control menu.

Example

The following example displays the Windows Color dialog box with the color red selected. A number corresponding to the color you choose is displayed when you exit the dialog box.

CLEAR
? GETCOLOR(255)

See Also

GETPICT( ) | RGB( ) | GETCP( ) Function


GETCP( ) Function

Prompts for a code page by displaying the Code Page dialog box, and then returns the number of the code page chosen.

GETCP([nCodePage] [, cText] [, cDialogTitle])

Return Values

Numeric

Parameters

nCodePage
Specifies the number of the code page that is initially selected when the Code Page dialog box is displayed. If nCodePage is 0 or if you omit nCodePage, a code page isn't selected when the Code Page dialog box is displayed.
cText
Specifies the text displayed in the Code Page dialog box. If you omit cText, Visual FoxPro displays the following text: "Please select a code page for cross-platform data sharing."
cDialogTitle
Specifies the title that appears in the Code Page dialog box title bar. If you omit cDialogTitle, the title "Code Page" is displayed.

Remarks

GETCP( ) returns 0 if you exit the Code Page dialog box by pressing ESC, choosing the Cancel button, or choosing Close from the Control menu.

The code pages listed in the Code Page dialog box are determined by FOXPRO.INT, the Visual FoxPro International code page support file.

You can include GETCP( ) in commands such as MODIFY COMMAND, APPEND FROM, and COPY TO that support the AS nCodePage clause. The Code Page dialog box is displayed, making it possible for you to specify the code page of the file opened, appended, or created. Because no code page 0 exists, you must trap for 0 in case the user chooses ESC, the Cancel button, or Close from the Control menu.

Example

The following example displays the Code Page dialog box with code page 1252 (Windows ANSI) selected. "Select a Code Page" is displayed as the caption in the Code Page dialog box, and "Code Page Selection" is displayed in the Code Page dialog box title bar.

? GETCP(1252, "Select a Code Page", "Code Page Selection")

See Also

APPEND FROM | COPY TO | EXPORT | IMPORT | MODIFY COMMAND | MODIFY FILE | MODIFY QUERY


GETCURSORADAPTER( ) Function

Returns an object reference to a CursorAdapter object at run time by referencing the cursor name.

GETCURSORADAPTER( [ cAlias ] )

Parameters

cAlias
Specifies the alias of the cursor. If you do not supply an alias, Visual FoxPro uses the alias for the cursor in the current work area.

Return Values

An object reference to a CursorAdapter object.

See Also

CursorAdapter Object Properties, Methods, and Events

Applies To: CursorAdapter Class


GETDIR( ) Function

Displays the Select Directory dialog box from which you can choose a directory.

GETDIR([cDirectory [, cText [, cCaption [, nFlags [, lRootOnly]]]]])

Return Values

Character

Parameters

cDirectory
Specifies the directory that is initially displayed in the dialog box. When cDirectory is not specified, the dialog box opens with the Visual FoxPro default directory displayed.
cText
Specifies the text for the directory list in the dialog box.
cCaption
Specifies the caption to display in the dialog title bar. The Windows default is "Select Directory".
nFlags
Specify the options for the dialog box. nFlags can include zero or an additive combination of the values. The following table includes some of more common flags. For more information, see SHBrowseForFolder in MSDN.
nFlag | Value | Description
1 | BIF_RETURNONLYFSDIRS | Return only file system directories (physical locations). If a user selects folders that are not part of the file system, the OK button is grayed.
2 | BIF_DONTGOBELOWDOMAIN | Do not include network folders below the domain level in the tree view control (For example, My Computer and My Networks).
8 | BIF_RETURNFSANCESTORS | Return only file system ancestors. If a user selects anything other than a file system ancestor, the OK button is grayed.
16 | BIF_EDITBOX | The browse dialog includes an edit control in which the user can type the name of an item. Available on Windows 98 and above, or with Internet Explorer 4.0 or higher (assuming shell integration option selected). Requires version 4.71 of shell32.dll.
32 | BIF_VALIDATE | Validates the editbox contents. If the editbox is used, it is necessary to validate the user-specified content. If the user types an invalid name into the edit box, the Cancel button becomes the only selection available. This flag is ignored if BIF_EDITBOX is not specified.
64 | BIF_NEWDIALOGSTYLE | Use the new user-interface. Setting this flag provides the user with a larger, resizable dialog box. Additional functionality includes: drag and drop capability within the dialog box, reordering, context menus, new folders, delete, and other context menu commands. Support in Windows 2000 and above. Requires version 5.00 of shell32.dll.
16384 | BIF_BROWSEINCLUDEFILES | The browse dialog will display files as well as folders. Available on Windows 98 and above, or with Internet Explorer 4.0 or higher (assuming shell integration option selected). Requires version 4.71 of shell32.dll.
lRootOnly
Specifies that only cDirectory and its subfolders display. This parameter prevents navigation above the root folder. If you do not specify cDirectory, the default directory (SET DEFAULT value) is used.

Remarks

GETDIR( ) returns as a character string the name of the directory you choose.

If you do not choose a directory (you click Cancel, press ESC, or choose Close from the window menu), GETDIR( ) returns the empty string.

Beginning with Visual FoxPro 7, GETDIR( ) supports two different dialog boxes. If you provide fewer than three parameters, GETDIR( ) returns the dialog box from earlier versions. If you provide more than two parameters, Visual FoxPro uses the SHBrowseForFolder routine from the Win32 API to provide the dialog.

See Also

DIRECTORY | DIRECTORY( ) | GETEXPR | GETFILE( )


GETENV( ) Function

Returns the contents of the specified MS-DOS environment variable.

GETENV(cVariableName)

Return Values

Character

Parameters

cVariableName
Specifies the name of the MS-DOS environment variable. The empty string is returned if the MS-DOS environment variable you specify doesn't exist.

You can locate the Windows directory with the WINDIR environmental variable, which Windows sets when it starts.

Remarks

Two environment variables are always available: COMSPEC and PATH. You can create your own environment variables with the MS-DOS SET command.

For additional information on creating environment variables, see your MS-DOS manual.

Example

CLEAR
? GETENV('PATH')  && Displays the MS-DOS path

See Also

DISKSPACE( ) | OS( ) | VERSION( )


GETFILE( ) Function

Displays the Open dialog box and returns the name of the file you chose.

GETFILE([cFileExtensions] [, cText] [, cOpenButtonCaption]
   [, nButtonType] [, cTitleBarCaption])

Return Values

Character data type

Parameters

cFileExtensions
Specifies the file extensions of the files displayed in the scrollable list when the All Files menu item is not chosen. The cFileExtensions parameter cannot exceed 254 characters in length. If passing a value as a literal, enclose it in quotation marks. Do not include a period (.) in front of file extensions.

cFileExtensions can take a variety of forms:

  • If cFileExtensions contains a single extension (for example, "PRG"), only files with that extension are displayed.
  • If cFileExtensions is the empty string, all files in the current directory are displayed.
  • cFileExtensions can also contain wildcards (* and ?). All files with extensions that meet the wildcard criteria are displayed. For example, if cFileExtensions is "?X?", all files with the extension .fxp, .exe, and .txt are displayed.
  • In Visual FoxPro, cFileExtensions can contain a file description followed by a file extension or a list of file extensions separated with commas. The file description appears in the Files of Type list box. Separate the file description from the file extension or list of file extensions with a colon (:). Separate multiple file descriptions and their file extensions with a semicolon (;).

    For example, if cFileExtensions is "Text:TXT" the file description "Text" appears in the Files of Type list box and all files with a .txt extension are displayed.

    If cFileExtensions is "Tables:DBF; Files:TXT,BAK" the file descriptions "Tables" and "Files" appear in the Files of Type list box. When "Tables" is chosen from the Files of Type list box, all files with a .dbf extension are displayed. When "Files" is chosen from the Files of Type list box, all files with .txt and .bak extensions are displayed.

  • If cFileExtensions contains just a semicolon (";"), all files without extensions are displayed.
cText
Specifies the text for the directory list in the Open dialog box.
cOpenButtonCaption
Specifies a caption for the OK button.
nButtonType
Specifies the number and type of buttons that appear in the Open dialog box. The following buttons appear in the dialog box when nButtonType is 0, 1, or 2.
nButtonType | Buttons
0 (or omitted) | OKCancel
1 | OKNewCancel
2 | OKNoneCancel

"Untitled" is returned with the path specified in the Open dialog box if nButtonType is 1 and the user chooses the New button. The empty string is returned if nButtonType is 2 and the user chooses the None button.

cTitleBarCaption
Specifies the title bar caption.

Remarks

GETFILE( ) returns the empty string if you exit the Open dialog box by pressing ESC, choosing Cancel, or choosing Close from the Control menu.

Example

CLOSE DATABASES
SELECT 0

gcTable=GETFILE('DBF', 'Browse or Create a .DBF:',
   'Browse', 1, 'Browse or Create')
DO CASE
   CASE 'Untitled' $ gcTable
      CREATE (gcTable)
   CASE EMPTY(gcTable)
      RETURN
   OTHERWISE
      USE (gcTable)
      BROWSE
ENDCASE

See Also

FULLPATH( ) | GETEXPR | GETPICT( ) | LOCFILE( ) | PUTFILE( )


GETFLDSTATE( ) Function

Returns a numeric value indicating if a field in a table or cursor has been modified or had a record appended, or if the deleted status of the current record has been changed.

GETFLDSTATE(cFieldName | nFieldNumber [, cTableAlias | nWorkArea])

Return Values

Numeric, Character, or .NULL.

Parameters

cFieldName | nFieldNumber
Specifies the name of the field or the number of the field for which the modification status is returned. The field number nFieldNumber corresponds to the position of the field in the table or cursor structure. DISPLAY STRUCTURE or FIELD( ) can be used to determine a field's number.

You can specify –1 for nFieldNumber to return a character string consisting of deletion and modification status values for all fields in the table or cursor. For example, if a table has five fields and only the first field has been changed, GETFLDSTATE( ) returns the following:

121111

The 1 in the first position indicates the deletion status has not been changed.

You can also include 0 for nFieldNumber to determine if the deletion status of the current record has changed since the table or cursor was opened.

Note Using GETFLDSTATE( ) only determines if the deletion status of the current record has changed. For example, if you mark a record for deletion and then recall it, GETFLDSTATE( ) indicates the deletion status has changed even though the record's deletion status has returned to its original state. Use DELETED( ) to determine the current deletion status of a record.
cTableAlias
Specifies the alias of the table or cursor for which the field modification or record deletion status is returned.
nWorkArea
Specifies the work area of the table or cursor for which the field modification or record deletion status is returned.

If you do not specify an alias or work area, GETFLDSTATE( ) returns a value for a field in the currently selected table or cursor.

Remarks

The following table lists the character return values and the corresponding modification or deletion status.

Return value | Modification or deletion status
1 | Field has not been modified or deletion status has not changed.
2 | Field has been modified or deletion status has changed.
3 | Field in an appended record has not been modified or deletion status has not changed for the appended record.
4 | Field in an appended record has been modified or deletion status has changed for the appended record.
.NULL. | At EOF( )

Row or table buffering must first be enabled with CURSORSETPROP( ) for GETFLDSTATE( ) to operate on local tables.

The modification or deletion status is returned for the table or cursor open in the currently selected work area if GETFLDSTATE( ) is issued without the optional cTableAlias or nWorkArea arguments.

Any change in a field will cause GETFLDSTATE() to return a value showing that the field has been modified, whether the change is explicit or implicit. An example of an explicit modification would be including the field in a REPLACE or INSERT INTO command. An implicit modification occurs in a field that has a default value when any command is issued that adds a new record.

Example 1

The following example demonstrates how you can use GETFLDSTATE( ) to determine if the contents of a field have changed. MULTILOCKS is set to ON, a requirement for table buffering. The customer table in the testdata database is opened, and CURSORSETPROP( ) is then used to set the buffering mode to optimistic table buffering (5).

GETFLDSTATE( ) is issued to display a value (1) corresponding to the unmodified state of the cust_id field before it is modified. The cust_id field is modified with REPLACE, and GETFLDSTATE( ) is issued again to display a value (2) corresponding to the modified state of the cust_id field. TABLEREVERT( ) is used to return the table to its original state, and GETFLDSTATE( ) is issued again to display a value (1) corresponding to the original state of the cust_id field.

CLOSE DATABASES
CLEAR

SET MULTILOCKS ON         && Allow table buffering
OPEN DATABASE (HOME(2) + 'data\testdata')
USE Customer             && Open customer table
=CURSORSETPROP("Buffering",5,"customer")  && Enable table buffering

* Get field state on original cust_id field and display state
nState=GETFLDSTATE("cust_id")
DO DisplayState WITH nState("Original")

* Change field contents and display state
REPLACE cust_id    WITH "***"
nState=GETFLDSTATE("cust_id")
DO DisplayState WITH nState("After Replace")

* Discard table changes and display state
= TABLEREVERT(.T.)        && Discard all table changes
nState=GETFLDSTATE("cust_id")
DO DisplayState WITH nState("After Revert")

PROCEDURE DisplayState
PARAMETER nState,cOperation
DO CASE
   CASE nState=1
      =MESSAGEBOX("Field has not been modified",0,cOperation)
   OTHERWISE
      =MESSAGEBOX("Field has been modified",0,cOperation)
ENDCASE

Example 2

The following example shows the difference in behavior between fields with and without default values.

SET MULTILOCKS ON
CREATE DATABASE example
CREATE TABLE customer (cust_id C(6),state C(2) DEFAULT "FL")
CLOSE TABLES
USE customer
=CURSORSETPROP("Buffering",5,"customer")

APPEND BLANK
?GETFLDSTATE("cust_id")     && Returns 3, field in an appended record has
                            && not been modified.

?GETFLDSTATE("state")    && Returns 4, field in an appended record has
                         && been modified.

See Also

CURVAL( ) | DELETED( ) | FIELD( ) | OLDVAL( ) | CURSORSETPROP( ) | SETFLDSTATE( )


GETFONT( ) Function

Displays the Font dialog box and returns the name of the font you choose.

GETFONT(cFontName [, nFontSize [, cFontStyle [, nFontCharSet])

Return Values

Character data type

Parameters

cFontName
Specifies the name of the font initially selected in the Font dialog box. If the font you specify hasn't been installed, the default font is initially selected.
nFontSize
Specifies the font size initially selected in the Font dialog box. If the font size you specify isn't supported, the default font size is initially selected. The font size defaults to 10 point if nFontSize is less than or equal to zero or you omit nFontSize.
cFontStyle
Specifies the font style initially selected in the Font dialog box. If the font style you specify isn't supported, the default font style is initially selected. cFontStyle is one or two characters that specify the font style. The following table lists the characters that you can specify for cFontStyle and the corresponding font style.
Character | Font style
B | Bold
I | Italic
BI | Bold Italic
nFontCharSet
Specifies the language script value. The following table describes some available values for nFontCharSet.
nFontCharSet | Language Script
1 | Western
2 | Symbol
77 | Mac
128 | Japanese
161 | Greek
162 | Turkish
163 | Vietnamese
177 | Hebrew
178 | Arabic
186 | Baltic
204 | Cyrillic
238 | Central European
255 | OEM/DOS

Remarks

GETFONT( ) returns the name, size, and style of the font you choose. Your choice is returned as a character string with the font name, size, and style separated by commas. If you pass nFontCharSet value, the selected font script is included in the returned string.

GETFONT( ) returns the empty string if you exit the Font dialog box by choosing Cancel, choosing Close from the Control menu, or pressing ESC.

If you omit any of the GETFONT( ) options (cFontName, nFontSize, or cFontStyle), include a comma as a placeholder for the option. For example, the following command omits the cFontName and nFontSize options and initially selects the Bold font style in the Font dialog:

cMyFont = GETFONT("Arial",12,'B')
Note Visual FoxPro commands and functions can be abbreviated to four characters. In the case of GETFONT( ) and GETFILE( ), which both begin with the same four letters, precedence is given to GETFILE( ). Issuing GETF( ) displays the Open dialog box.

See Also

FONTMETRIC( ) | SYSMETRIC( ) | TXTWIDTH( ) | WFONT( )


GETINTERFACE( ) Function

Provides access to COM object properties, methods, and events through early binding.

GETINTERFACE(oObject [, cIID | cInterface[, cTypelib | cProgID]])

Returns

COM Object Interface reference

Parameters

oObject
Specifies the target COM object.
cIID
Specifies the GUID of the target interface of oObject. cIID can be an interface such as "IContextState" or it can be a GUID, such as "{94631BEC-EE81-479A-AE64-A6CFC37B4799}". If it's "IDispatch", then GetInterface() returns an IDispatch (late-bound) reference to the object. If cIID is not specified, then GetInterface() will return the early binding interface for the object.
cInterface
Specifies the interface name.
cTypelib
Specifies the name of the type library containing the oObject class.
cProgID
Specifies the name of the program to be used to lookup the type library.

Remarks

GetInterface( ) applies only to COM objects. If you use native Visual FoxPro objects, GetInterface( ) generates an error. GetInterface( ) returns an early-bound Object reference.

When a DLL is built on a Windows 9x platform (Windows95, Windows98, and Windows ME), Visual FoxPro does not include the type library inside the DLL. When you use GETINTERFACE( ) and refer to a DLL built on one of these platforms, you must use the Type Library name instead of the DLL name as in the following code:

oX = GETINTERFACE(x, "Imyclass", "myclass1.TLB")

You can use the following code for a DLL built on Windows XP, Windows 2000 or Windows NT:

oX = GETINTERFACE(x, "Imyclass", "myclass1.DLL")

Example

The following code snippet is an example of a method you can use in your Visual FoxPro COM server to handle transactions in a COM+ Application. This sample requires that the COM server containing this code be added to a COM+ Application before it can be called by a client.

LOCAL oMTX, oContext, oContextState
LOCAL lTxnState, lGetTxnState, lDone, lGetDone
lGetDone = .F.     && initialize setting
lGetTxnState = 0  && initialize setting

oMTX = CREATEOBJECT("MTXAS.APPSERVER.1")
oContext = oMTX.GetObjectContext()
oContextState = GetInterface(oContext,"IContextState")

* Handle activation setting (Doneness)
* Values: .T. - Deactivate, .F. - Leave activated
lDone = .T.
oContextState.SetDeactivateOnReturn(lDone)
oContextState.GetDeactivateOnReturn(@lGetDone)

* Handle transaction setting (Consistency)
* Values: 0 - commit, 1 - abort
lTxnState = 1
oContextState.SetMyTransactionVote(lTxnState)
oContextState.GetMyTransactionVote(@lGetTxnState)

See Also

CREATEOBJECTEX( ) | Early (vtable) and Late (IDispatch) Binding | GETOBJECT( ) | SYS(2333) - ActiveX Dual Interface Support | Viewing Type Library Information


GETNEXTMODIFIED( ) Function

Returns the record number for the next modified record in a buffered table or cursor.

GETNEXTMODIFIED(nRecordNumber [, cTableAlias | nWorkArea] [, lNoFire])

Return Values

Numeric

Parameters

nRecordNumber
Specifies the record number after which GETNEXTMODIFIED( ) searches for the next modified record. Specify 0 for nRecordNumber to determine the first record in the table or cursor that has been modified.
cTableAlias
Specifies the alias of the table or cursor for which GETNEXTMODIFIED( ) returns the number of the next modified record.
nWorkArea
Specifies the work area of the table or cursor for which GETNEXTMODIFIED( ) returns the number of the next modified record.

If you do not specify an alias or work area, GETNEXTMODIFIED( ) returns the record number for the next modified record in the currently selected table or cursor.

lNoFire
Specifies that all firing of rules are suppressed.

Remarks

GETNEXTMODIFIED( ) returns 0 if there are no modified records after the record you specify. Because of this, if you modify only one record, to verify its modification you must first use the GO TOP command to position the cursor before the changed record. A record is considered modified if the contents of any of its fields are changed in any way (even if the original field contents are restored) or the record's deletion status is changed.

GETNEXTMODIFIED( ) can operate only on tables and cursors for which table buffering is enabled. Table buffering is enabled with CURSORSETPROP( ).

Since triggers are unaffected by GETNEXTMODIFIED( ), lNoFire suppresses only field and record rules, and the "Uniqueness of index ID is violated" error. lNoFire prevents the flushing of temporary data, such as data stored in controls or updates made to the current record, to the underlying cursor.

Example

The following example demonstrates how you can use GETNEXTMODIFIED( ) to determine which records in a table have been changed. MULTILOCKS is set to ON, a requirement for table buffering. The customer table in the testdata database is opened, and CURSORSETPROP( ) is then used to set the buffering mode to optimistic table buffering (5).

SKIP is issued to move the record pointer to the second record, and the cust_id field is modified with REPLACE. GETNEXTMODIFIED(0) is used to display the record number of the next modified record (2, the second record), starting from the beginning of the table. TABLEREVERT( ) is used to return the table to its original state, and GETNEXTMODIFIED(0) is used again to display the record number of the next modified record (0, indicating that no records have been modified).

CLOSE DATABASES
CLEAR

OPEN DATABASE SYS (HOME(2) + 'data\testdata')
SET MULTILOCKS ON  && Allow table buffering
USE Customer     && Open customer table
=CURSORSETPROP("Buffering", 5, "customer")  && Enable table buffering

SKIP  && Move record pointer to the second record

* Change field contents
REPLACE cust_id WITH "***"

* Call MESSAGEBOX function with results of GETNEXTMODIFIED
=MESSAGEBOX("Record " + ALLTRIM(STR(GETNEXTMODIFIED(0))) + ;
   " has changed.",0,"Results")

* Revert table and display results with MESSAGEBOX
=TABLEREVERT(.T.)  && Discard all table changes
nChange=GETNEXTMODIFIED(0)
IF nChange=0
   =MESSAGEBOX("Record(s) have been reverted.",0,"Results")
ELSE
   =MESSAGEBOX("Record " + ALLTRIM(STR(GETNEXTMODIFIED(0))) + ;
    " has changed.",0,"Results")
ENDIF

See Also

CURSORSETPROP( ) | CURVAL( ) | GETFLDSTATE( ) | OLDVAL( )


GETOBJECT( ) Function

Activates an Automation object and creates a reference to the object.

GETOBJECT(cFileName | Moniker [, cClassName])

Returns

Object reference

Parameters

cFileName
Specifies the full path and name of the file to activate. The application does not need to be specified, because the OLE dynamic link libraries determine the application to start based on the file name you provide.

For example, the following code launches Microsoft Excel, opens a file named BUDGET.XLS, and creates a reference through an object variable named MBUDVAR:

MBUDVAR = GETOBJECT('C:\EXCEL\WORK\BUDGET.XLS')
Moniker
The identifier of a COM object that implements the IMoniker interface. A moniker can be any of the following types: file, item, generic composite, anti-, pointer, and URL. For details about COM monikers, search for "IMoniker" on the Microsoft Developer Network.
cClassName
Specifies the class name of the object to retrieve. Some applications can store more than one object type in the same file, making it possible for you to use the class name to specify the object to activate. For example, if a word processing application stores its documents, macro definitions, and ToolBar objects in the same file, you can create a reference to the document file with the following command:
MDOCFILE = GETOBJECT('C:\WRDPROC\MYDOC.DOC','WrdProc.Document')

With some server applications, each time you issue GETOBJECT( ), an additional instance of the application is started, using additional memory. If the application is already running, you can prevent additional instances of the application from starting by omitting FileName and including ClassName, as in this example:

oleApp = GETOBJECT(, "Excel.Application")

Remarks

Use GETOBJECT( ) to activate an Automation object from a file and to assign a reference to the object through a memory variable or array element.

If you specify an invalid file or class name, an OLE error is displayed, and the GETOBJECT( ) function returns an empty string.

Example

For example, on a network that has implemented Active Directory Services, you can query the network for information on a particular user.

   *  Replace "DomainName" with the domain name, and "UserLoginID"
   *  with the login ID of the user you are looking up.
   oUser = GetObject("WinNT://DomainName/UserLoginID,user")
   ? oUser.FullName

See Also

COMCLASSINFO( ) | CREATEOBJECT( ) | DEFINE CLASS | SET OLEOBJECT | GETINTERFACE( )


GETPAD( ) Function

Returns the menu title for a given position on the menu bar.

GETPAD(cMenuBarName, nMenuBarPosition)

Return Values

Character

Parameters

cMenuBarName
Specifies the menu bar name.
nMenuBarPosition
Specifies a position on the menu bar. nMenuPosition can range from 1 (the leftmost menu title on the menu bar) through the number of menu titles on the menu bar.

Remarks

Menu names on a titles bar can be added, removed, or rearranged. Use DEFINE PAD to add a menu name to a title bar or RELEASE PAD to remove a menu title.

Example

The following program uses GETPAD( ) to test if the Edit menu name is on the Visual FoxPro system menu bar. If it is, GETPAD( ) returns the menu name. (To restore the Edit menu bar to its default state, issue the command SET SYSMENU TO DEFAULT.)

FOR gnCount = 1 TO CNTPAD('_msysmenu')      && Number of pads
   IF PRMPAD('_msysmenu', GETPAD('_msysmenu', gnCount)) = 'Edit'
      RELEASE PAD (GETPAD('_msysmenu', gnCount)) OF _msysmenu
      EXIT
   ENDIF
ENDFOR

See Also

DEFINE MENU | DEFINE PAD | RELEASE PAD


GETPEM( ) Function

Returns the current value for a property or program code for an event or method at design time.

GETPEM(oObjectName | cClassName, cProperty | cEvent | cMethod)

Return Values

Character, Currency, Date, DateTime, Numeric, or Logical

Parameters

oObjectName
Specifies the object for which a property value or event or method program code is returned. oObjectName can be any expression that evaluates to an object, such as an object reference, an object memory variable, or an object array element.
cClassName
Specifies the class for which a property value or event or method program code is returned.
cProperty
Specifies the property whose value is returned.
cEvent
Specifies the event for which program code is returned.
cMethod
Specifies the method for which program code is returned.

Remarks

In Visual FoxPro 6.0 and later, using GETPEM( ) to return method code is supported only during an interactive Visual FoxPro session. You can, however, obtain method code from an object by using its Class property, as in the following code:

LOCAL oObject, lcCode
oObject = NEWOBJECT("_form", HOME()+"ffc\_base.vcx")
lcCode = GETPEM(oObject.class, "Release")

See Also

CREATE FORM | PEMSTATUS( ) | SYS(1269) – Property Information | SYS(1270) – Object Location | SYS(1271) - Object's .SCX File | SYS(1272) – Object Hierarchy


GETPICT( ) Function

Displays the Open Picture dialog box and returns the name of the picture file you chose.

Note You can preview images in Windows 2000 and later by clicking the View Menu icon and then Thumbnails. Visual FoxPro uses the Thumbnails view as the default setting to provide mini-previews of images. Therefore, the Open Picture dialog box no longer includes a frame for displaying an image. The Preview check box appears in the Open Picture dialog box only when running Visual FoxPro on operating systems earlier than Windows 2000.
GETPICT([cFileExtensions] [, cFileNameCaption] [, cOpenButtonCaption])

Return Values

Character data type. Returns the name of the picture file you chose.

Parameters

cFileExtensions
Specifies the file extensions of the picture files displayed in the scrollable list when the All Files menu item isn't chosen.

cFileExtensions can take the following forms:

  • If cFileExtensions contains a single extension (for example, .bmp), only files with that extension are displayed.
  • cFileExtensions can also contain wildcards (* and ?). All files with extensions that meet the wildcard criteria are displayed. For example, if cFileExtensions is ?X?, all files with the extension .fxp, .exe, and .txt are displayed.
  • If cFileExtensions contains an empty string (""), all available graphics files (for example, files with the extensions .bmp and .dib ) are displayed.
CFileNameCaption
Specifies the caption displayed to the left of the File Name text box. cFileNameCaption replaces "File Name" that appears when cFileNameCaption is omitted.
cOpenButtonCaption
Specifies a caption for the OK button.

Remarks

The GETPICT( ) function returns the empty string if you exit the Open Picture dialog box by pressing ESC, choosing the Cancel button, or clicking the Close button. The Open Picture dialog box displayed by typing GETPICT( ) in the Command window makes it possible for you to quickly locate all the graphic files supported in Visual FoxPro. In versions earlier than Visual FoxPro 8.0, check the Preview check box in the Picture Open dialog box to display the currently selected graphics file.

The following table lists the graphic file formats that Visual FoxPro supports.

Graphic format | File extension
Animated Cursor | .ani
Bitmap | .bmp
Cursor | .cur
Device Independent Bitmap | .dib
Exchangeable Image File | .exif
Graphics Interchange Format | .gif, .gfa
Joint Photographic Electronic Group, JPEG File Interchange Format | .jpg, .jpeg, .jpe, .jfif
Icon | .ico
Portable Networks Graphics | .png
Tag Image File Format | .tif, .tiff
Windows Enhanced Metafile | .emf
Note In Visual FoxPro, cursor, animated cursor, and icon files can be used as graphics files. For example, you can specify an animated cursor file for the Picture property for the Image control (however, the Image control displays the static representation of the cursor).

Use the CLEAR RESOURCES command to clear all cached graphic files, including .gif and .jpg files.

See Also

GETFILE( ) | GETEXPR | LOCFILE( ) | PUTFILE( )


GETPRINTER( ) Function

Displays the Print dialog box and returns the name of the printer you select.

GETPRINTER( )

Return Values

Character

Remarks

GETPRINTER( ) returns an empty string if you exit the Print dialog box by pressing ESC, choosing the Cancel button, or clicking the Close button.

The display in the print dialog box may differ in different versions of Windows. For local printers in all versions of Windows, and for network printers in Windows 98, the display consists of the printer name. For network printers Windows NT 4.0 or later displays the network path.

Example

CLEAR
cPrinter = GETPRINTER( ) && Displays the Windows Printer Dialog
*** Displays the name of the printer chosen ***
WAIT WINDOW IIF(EMPTY(cPrinter), 'No printer chosen', cPrinter)

See Also

APRINTERS( ) | SET PRINTER | SYS(102) - Printer Setting | SYS(1037) - Page Setup Dialog Box


GETWORDCOUNT( ) Function

Counts the words in a string.

GetWordCount(cString[, cDelimiters])

Parameters

cString
Specifies the string whose words will be counted.
cDelimiters
Optional. Specifies one or more optional characters used to separate words in cString. The default delimiters are space, tab, carriage return, and line feed. Note that GetWordCount( ) uses each of the characters in cDelimiters as individual delimiters, not the entire string as a single delimiter.

Return Value

Numeric

Remarks

GetWordCount( ) by default assumes that words are delimited by spaces or tabs. If you specify another character as delimiter, this function ignores spaces and tabs and uses only the specified character.

If you use "AAA aaa, BBB bbb, CCC ccc." as the target string for GetWordCount( ), you can get all the following results.

cString = "AAA aaa, BBB bbb, CCC ccc."
? GetWordCount(cString)               && 6 - character groups, delimited by " "
? GetWordCount(cString, ",")               && 3 - character groups, delimited by ","
? GetWordCount(cString, ".")               && 1 - character group, delimited by "."

See Also

GETWORDNUM( ) Function


GETWORDNUM( ) Function

Returns a specified word from a string.

GETWORDNUM(cString, nIndex[, cDelimiters])

Parameters

cString
Specifies the string to be evaluated
nIndex
Specifies the index position of the word to be returned. For example, if nIndex is 3, GetWordNum( ) returns the third word (if cString contains three or more words).
cDelimiters
Optional. Specifies one or more optional characters used to separate words in cString. The default delimiters are space, tab, carriage return, and line feed. Note that GetWordNum( ) uses each of the characters in cDelimiters as individual delimiters, not the entire string as a single delimiter.

Return Value

Character

Remarks

Returns the word at the position specified by nIndex in the target string, cString. If cString contains fewer than nIndex words, GetWordNum( ) returns an empty string.

See Also

GETWORDCOUNT( ) Function


GOMONTH( ) Function

Returns the date that is a specified number of months before or after a given Date or DateTime expression.

GOMONTH(dExpression | tExpression, nNumberOfMonths)

Return Values

Date

Parameters

dExpression
Specifies a date expression for which GOMONTH( ) returns the date.
tExpression
Specifies a datetime expression for which GOMONTH( ) returns the date.
nNumberOfMonths
Specifies the number of months from the date or datetime. If nNumberOfMonths is positive, GOMONTH( ) returns a date that is nNumberOfMonths months after the date or datetime. If nNumberOfMonths is negative, GOMONTH( ) returns a date that is nNumberOfMonths months before the date or datetime.

Remarks

GOMONTH( ) does not support dates earlier than 1752.

Example

SET CENTURY ON
STORE GOMONTH({^1998-02-16}, 5) TO gdDeadLine

CLEAR
? gdDeadLine  && Displays 07/16/1998
? GOMONTH({^1998-12-31}, 2)  && Displays 02/28/1999
? GOMONTH({^1998-12-31}, -2)  && Displays 10/31/1998

See Also

CMONTH( ) | BuildDateTime Property | DATETIME( ) Function


HEADER( ) Function

Returns the number of bytes in the header of the current or specified table file.

HEADER([nWorkArea | cTableAlias])

Return Values

Numeric

Parameters

nWorkArea | cTableAlias
Returns the header size for a table open in another work area. nWorkArea specifies the work area number and cTableAlias specifies the table alias. If you omit the work area and alias, HEADER( ) returns the size of the header for the table open in the current work area.

HEADER( ) returns 0 if a table isn't open in the work area you specify. If a table doesn't have the alias you specify, Visual FoxPro displays an error message.

Remarks

A table header contains information about the table itself, such as the field names and sizes and the presence of a memo file or structural index.

See Also

FSIZE( ) | RECSIZE( ) | HeaderHeight Property | Working with Table Aliases


HOME( ) Function

Returns the names of the Visual FoxPro and Visual Studio directories.

HOME([nLocation])

Parameters

nLocation
Specifies that HOME( ) returns the name of a specific Visual FoxPro or Visual Studio directory. Omitting nLocation is identical to HOME(0).

The following table lists the values for nLocation and the directory that HOME( ) returns. The directories listed below assume that you chose the default installation directory when you installed Visual FoxPro or Visual Studio.

nLocation | Directory
0 or omitted | The directory from which Visual FoxPro was started
1 | The directory in which Visual FoxPro is installed
2 | The directory containing the Visual FoxPro samples. This directory is identical to the samples directory in the _SAMPLES system variable.
3 | Visual Studio Common directory
4 | Visual FoxPro Graphics directory
5 | Visual Studio MSDN directory
6 | Visual Studio Tools directory
7 | Visual FoxPro subdirectory in the user's Visual FoxPro Application Data directory
8 | Visual FoxPro Projects subdirectory in the user's Visual FoxPro My Documents directory. This directory is the default location for new projects and files created by Visual FoxPro.

Return Values

Character data type. HOME( ) returns the names of specific Visual FoxPro and Visual Studio directories.

Example

CLEAR
? 'Visual FoxPro startup directory:           ', HOME( )
? 'Visual FoxPro installation directory:      ', HOME(1)
? 'Visual FoxPro samples directory:           ', HOME(2)
? 'Visual Studio common directory:            ', HOME(3)
? 'Visual FoxPro graphics directory:          ', HOME(4)
? 'MSDN samples directory:                    ', HOME(5)
? 'Visual Studio tools directory:             ', HOME(6)
? 'Visual FoxPro user app data subdirectory:  ', HOME(7)
? 'Visual FoxPro user documents subdirectory: ', HOME(8)

See Also

_SAMPLES System Variable | SYS( ) Functions Overview | SYS(2004) - Visual FoxPro Start Directory


HOUR( ) Function

Returns the hour portion from a DateTime expression.

HOUR(tExpression)

Parameters

tExpression
Specifies a DateTime expression from which HOUR( ) returns the hour.

Return Values

Numeric

Remarks

HOUR( ) returns a numeric value based on a 24 hour format, and is not affected by the current setting of SET HOURS. For example, if SET HOURS is 12 or 24, the following command returns 13:

? HOUR({^1998-02-16 1:00p})

Example

The following example displays the hour portion of the current time and the hour portion of a specific time.

CLEAR
? HOUR(DATETIME( ))
? HOUR({^1998-02-16 10:42a})  && Displays 10

See Also

CTOT( ) | DATE( ) | DATETIME( ) | DTOT( ) | MINUTE( ) | SEC( ) | SECONDS( ) | SET SECONDS | TIME( )


ID( ) Function - Network Machine Information

ID( ) returns network machine information when using Visual FoxPro in a network environment. The same functionality is available by using SYS(0).

ID( )

Return Values

Character

Remarks

Computer information must first be assigned by the network software and the network shell must be loaded.

If computer information has not been assigned or the network shell hasn't been loaded, ID( ) returns a character string consisting of 15 spaces, a number sign (#) followed by another space, and then 0. Consult your network documentation for further information on defining machine information.

ID( ) returns 1 when using Visual FoxPro in a stand-alone environment.

When the computer is connected to a network, ID( ) returns the computer name, a space, a number sign (#) followed by another space, and then the id of the current user (or the security context in which Visual FoxPro is running). For example:

? ID( )

returns the following format:

MACHINEID # userid

See Also

SYS(0) | IDXCOLLATE( ) Function


IDXCOLLATE( ) Function

Returns the collating sequence for an index or index tag.

IDXCOLLATE([cCDXFileName,] nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

cCDXFileName
Specifies the name of the compound index file. The compound index file you specify can be the structural compound index file automatically opened with the table or an independent compound index file.
nIndexNumber
Specifies the index or index tag for which IDXCOLLATE( ) returns the collating sequence. IDXCOLLATE( ) returns the collating sequence for indexes and index tags in the following order as nIndexNumber increases from 1 to the total number of open index files and index tags:
  1. Collating sequences for single-entry .idx index files (if any are open) are returned first. The order in which the single-entry index files are included in USE or SET INDEX determines how the collating sequences are returned.
  2. Collation sequences for tags in the structural compound index (if one is present) are returned next. The collating sequences are returned for the tags in the order in which the tags are created in the structural compound index.
  3. Collating sequences for tags in any open independent compound indexes are returned last. The collation sequences are returned for the tags in the order in which the tags are created in the independent compound indexes.

The empty string is returned if nIndexNumber is greater than the total number of open single-entry .idx files and structural compound and independent compound index tags.

nWorkArea
Specifies the work area of the table for which IDXCOLLATE( ) returns index file and index tag collating sequences.

IDXCOLLATE( ) returns the empty string if a table isn't open in the work area you specify.

cTableAlias
Specifies the alias of the table for which IDXCOLLATE( ) returns index file and index tag collation sequences.

Visual FoxPro generates an error message if you specify a table alias that doesn't exist.

Remarks

IDXCOLLATE( ) can be used to return the collating sequence for each tag in multiple-entry compound index files, allowing you to completely delete an index file and rebuild it correctly, using a series of SET COLLATE and INDEX commands.

Note that IDXCOLLATE( ) is not required for the proper functioning of REINDEX, because the collation sequence information is present in existing indexes and index tags.

For additional information about Visual FoxPro's international support, see Developing International Applications.

Example

The following example opens the Customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which IDXCOLLATE( ) is used to display the collation sequence of each index tag in the Customer structural index. The name of each structural index tag is displayed with its collation sequence.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open Customer table.
CLEAR

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index.
   ? TAG(nCount) + ' '  && Display tag name.
   ?? IDXCOLLATE(nCount)  && Display collation sequence.
   ELSE
      EXIT  && Exit the loop when no more tags are found.
   ENDIF
ENDFOR

See Also

SET COLLATE | Developing International Applications | INDEX Command | CREATE TABLE - SQL Command | CREATE CURSOR - SQL Command | ALTER TABLE - SQL Command | INDEX Command


IIF( ) Function

Returns one of two values depending on the value of a logical expression.

IIF(lExpression, eExpression1, eExpression2)

Return Values

Character, Numeric, Currency, Date, or DateTime

Parameters

lExpression
Specifies the logical expression that IIF( ) evaluates.
eExpression1, eExpression2
If lExpression evaluates to True (.T.), eExpression1 is returned and eExpression2 is not evaluated. If lExpression evaluates to False (.F.) or null (.NULL.), eExpression2 is returned and eExpression1 is not evaluated.

Remarks

This function, also known as Immediate IF, evaluates a logical expression and then returns one of two expressions. If the logical expression evaluates to True (.T.), IIF( ) returns the first expression. If the logical expression evaluates to False (.F.) or null (.NULL.), IIF( ) returns the second expression.

Tip This function can be used in place of IF ... ENDIF for simple conditional expressions, and is especially useful in report and label expressions that conditionally specify field contents. The IIF( ) function also executes faster than an equivalent IF ... ENDIF.

Example

The following example uses IIF( ) to check if the notes field in the employee table is empty. If it is empty, "No description" is displayed; otherwise, the contents of the memo field are displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee  && Open Employee table
CLEAR

SCAN
   ? IIF(EMPTY(notes), 'No notes', notes)    && Empty memo field?
ENDSCAN

See Also

IF ... ENDIF | #IF ... #ENDIF Preprocessor Directive | IF Statements


IMESTATUS( ) Function

Turns the IME (Input Method Editor) window on or off or returns the current IME status.

IMESTATUS([nExpression])

Return Values

Numeric

Parameters

nExpression
Turns the IME window on or off. The following table lists the values for nExpression and the corresponding state of the IME window.
nExpression | IME window action
0 | Turns the IME window off.
1 | Turns the IME window on.

If nExpression is omitted, IMESTATUS( ) returns the current IME status. The following table lists the values returned for the IME status. Use VERSION(3) to determine the current locale.

The following table lists the values returned for the IME status in the Japanese locale.

Return value | IME status
0 | No IME installed
1 | IME on
2 | IME off
3 | IME disabled
4 | Hiragana mode (double-byte)
5 | Katakana mode (double-byte)
6 | Katakana mode (single-byte)
7 | Alphanumeric mode (double-byte)
8 | Alphanumeric mode (single-byte)

The following table lists the values returned for the IME status in the Korean locale.

Return value | IME status
0 | No IME installed
1 | Hangul mode (single-btye)
2 | English mode (single-btye)
11 | English mode (double-btye)
15 | Hangul mode (double-btye)
23 | Hanja conversion mode (Hangul + single-btye mode)
31 | Hanja conversion mode (Hangul + double-btye mode)

Remarks

For more information, see Developing International Applications.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

Entering International Data | SET BROWSEIME | IMEMode Property | ISLEADBYTE( ) Function | STRCONV( ) Function


INDBC( ) Function

Returns true (.T.) if the specified database object is in the current database; otherwise returns false (.F.).

INDBC(cDatabaseObjectName, cType)

Return Values

Logical

Parameters

cDatabaseObjectName
Specifies the name of a named connection, field, index, table, or SQL view for which INDBC( ) returns a logical value indicating whether or not the object is in the current database.
cType
Specifies the database object type of cDatabaseObjectName. The following table lists the values for cType and the corresponding database object type.
cType | Database object type
CONNECTION | Named connection
FIELD | Field
INDEX | Index
TABLE | Table
VIEW | SQL View

The CONNECTION, FIELD, INDEX, TABLE, and VIEW settings cannot be abbreviated.

Remarks

A database must be open and current when INDBC( ) is issued; otherwise Visual FoxPro generates an error message.

Example

In the following example, a temporary database named mydbc is created, and a temporary table named mytable is added to the database. INDBC( ) is used to determine if the new table is in the database. The database and table are closed and erased.

CLOSE DATABASES
CREATE DATABASE mydbc  && Creates a new database
CREATE TABLE mytable (field1 C(10)) && Automatically added to database

? 'MyTable in the database? '
?? INDBC('mytable', 'TABLE')  && Returns .T.

CLOSE DATABASES
DELETE DATABASE mydbc DELETETABLES

See Also

ADBOBJECTS( ) | CREATE DATABASE | DELETE DATABASE | OPEN DATABASE | SET DATABASE


INDEXSEEK( ) Function

Without moving the record pointer, searches an indexed table for the first occurrence of a record whose index key matches a specified expression.

INDEXSEEK(eExpression [, lMovePointer [, nWorkArea | cTableAlias
   [, nIndexNumber | cIDXIndexFileName | cTagName]]])

Return Values

Logical

Parameters

eExpression
Specifies the index key expression for which you want INDEXSEEK( ) to search.
lMovePointer
Specifies if the record pointer is moved to the matching record. If lMovePointer is true (.T.) and a matching record exists, the record pointer is moved to the matching record. If lMovePointer is true (.T.) and a matching record doesn't exist, the record pointer isn't moved. If lMovePointer is false (.F.) or is omitted, the record pointer isn't moved even if a matching record exists.
nWorkArea
Specifies the work area number of the table that is searched for the index key.
cTableAlias
Specifies the alias of the table that is searched. If you omit nWorkArea and cTableAlias, the table in the currently selected work area is searched.
nIndexNumber
Specifies the number of the index file or tag that is used to search for the index key. nIndexNumber refers to the index files as they are listed in USE or SET INDEX. Open .IDX files are numbered first in the order in which they appear in USE or SET INDEX. Tags in the structural .cdx file (if one exists) are then numbered in the order in which they were created. Finally, tags in any open independent .cdx files are numbered in the order in which they were created. For more information about index numbering, see SET ORDER.
cIDXIndexFileName
Specifies an .idx file that is used to search for the index key.
cTagName
Specifies a tag of a .cdx file that is used to search for the index key. The tag name can be from a structural .cdx file or any open independent .cdx file.
Note The .idx file takes precedence if duplicate .idx file and tag names exist.

Remarks

INDEXSEEK( ) returns true (.T.) if a match is found; otherwise false (.F.) is returned. You can use INDEXSEEK( ) only with a table with an index order set, and you can search only for an index key. The match must be exact unless SET EXACT is set to OFF.

INDEXSEEK( ) provides a fast way to search for records without moving the record pointer. Because the record pointer isn't moved, rules and triggers aren't executed. If INDEXSEEK( ) returns true (.T.) indicating that a matching record is found, you can execute INDEXSEEK( ) again with the second parameter lMovePointer set to true (.T.) to move to the matching record.

INDEXSEEK( ) returns false (.F.) when you are attempting to find a value in the most recently created record (created with INSERT INTO or APPEND BLANK) until the record pointer is moved. You can execute a GO BOTTOM command to cause INDEXSEEK( ) to find the most recently created record.

See Also

INDEX | KEYMATCH( ) | LOCATE | SEEK | SEEK( )


INKEY( ) Function

Returns a number corresponding to the first mouse click or key press in the type-ahead buffer.

INKEY([nSeconds] [, cHideCursor])

Return Values

Numeric

Parameters

nSeconds
Specifies how many seconds INKEY( ) waits for a keystroke. If nSeconds isn't included, INKEY( ) immediately returns a value for a keystroke. INKEY( ) waits indefinitely for a keystroke if nSeconds is 0.
cHideCursor
Shows or hides the cursor, or checks for a mouse click. To show the cursor, include S in cHideCursor. To hide the cursor, include H in cHideCursor. If both S and H are included in cHideCursor, the last character in cHideCursor takes precedence.

By default, INKEY( ) doesn't detect a mouse click. To check for a mouse click, include M in cHideCursor. If M is included in cHideCursor, INKEY( ) returns the value 151 for a single mouse click. Refer to the second example in the following table to see how you can check for a double click.

To check for a mouse click and show the cursor, include both M and S. To check for a mouse click and hide the cursor, include H and M.

When a keyboard macro is assigned to a key or key combination, you can include E in cHideCursor to expand the keyboard macro. When E is included, INKEY( ) returns a value corresponding to the first keystroke assigned to the keyboard macro. You can return successive values for each keystroke in a macro by repeatedly executing INKEY( ) with E included. If you omit E, INKEY( ) returns the value for the key or key combination that triggers the keyboard macro.

Any characters other than H, M, S, and E in cHideCursor are ignored.

The following table lists INKEY( ) function return values for keys alone and in combination with the SHIFT, CTRL, and ALT keys. A dash (–) indicates that the key combination returns no value.

Key | Alone | SHIFT | CTRL | ALT
F1 | 28 | 84 | 94 | 104
F2 | –1 | 85 | 95 | 105
F3 | –2 | 86 | 96 | 106
F4 | –3 | 87 | 97 | 107
F5 | –4 | 88 | 98 | 108
F6 | –5 | 89 | 99 | 109
F7 | –6 | 90 | 100 | 110
F8 | –7 | 91 | 101 | 111
F9 | –8 | 92 | 102 | 112
F10 | –9 | 93 | 103 | 113
F11 | 133 | 135 | 137 | 139
F12 | 134 | 136 | 138 | 140
1 49 33 – 120
2 50 64 – 121
3 51 35 – 122
4 52 36 – 123
5 53 37 – 124
6 54 94 – 125
7 55 38 – 126
8 56 42 – 127
9 57 40 – 128
0 48 41 – 19
a | 97 | 65 | 1 | 30
b | 98 | 66 | 2 | 48
c | 99 | 67 | 3 | 46
d | 100 | 68 | 4 | 32
e | 101 | 69 | 5 | 18
f | 102 | 70 | 6 | 33
g | 103 | 71 | 7 | 34
h | 104 | 72 | 127 | 35
I | 105 | 73 | 9 | 23
j | 106 | 74 | 10 | 36
k | 107 | 75 | 11 | 37
l | 108 | 76 | 12 | 38
m | 109 | 77 | 13 | 50
n | 110 | 78 | 14 | 49
o | 111 | 79 | 15 | 24
p | 112 | 80 | 16 | 25
q | 113 | 81 | 17 | 16
r | 114 | 82 | 18 | 19
s | 115 | 83 | 19 | 31
t | 116 | 84 | 20 | 20
u | 117 | 85 | 21 | 22
v | 118 | 86 | 22 | 47
w | 119 | 87 | 23 | 17
x | 120 | 88 | 24 | 45
y | 121 | 89 | 25 | 21
z | 122 | 90 | 26 | 44
INS | 22 | 22 | 146 | 162
HOME | 1 | 55 | 29 | 151
DEL | 7 | 7 | 147 | 163
END | 6 | 49 | 23 | 159
PAGE UP | 18 | 57 | 31 | 153
PAGE DOWN | 3 | 51 | 30 | 161
UP ARROW | 5 | 56 | 141 | 152
DOWN ARROW | 24 | 50 | 145 | 160
RIGHT ARROW | 4 | 54 | 2 | 157
LEFT ARROW | 19 | 52 | 26 | 155
ESC | 27 | –/27 | –*/27 | –*/1
ENTER | 13 | 13 | 10 | –/166
BACKSPACE | 127 | 127 | 127 | 14
TAB 9 15 148/* *
SPACEBAR | 32 | 32 | 32/– | 57

* Keystroke reserved by Windows.

Remarks

INKEY( ) returns 0 if a key isn't pressed. If there are several keys in the type-ahead buffer, INKEY( ) returns the value of the first key entered in the buffer.

See Also

_DBLCLICK | KEYBOARD | KeyPress Event | LASTKEY( ) | ON KEY | READKEY( ) | SET TYPEAHEAD


INLIST( ) Function

Determines whether an expression matches another expression in a set of expressions.

INLIST(eExpression1, eExpression2 [, eExpression3 ...])

Return Values

Logical or null value

Parameters

eExpression1
Specifies the expression INLIST( ) searches for in the set of expressions.
eExpression2 [, eExpression3 ...]
Specifies the set of expressions to search. You must include at least one expression (eExpression2), and can include up to 24 expressions (eExpression2, eExpression3, and so on).

All the expressions in the set of expressions must be of the same data type.

Remarks

INLIST( ) returns true (.T.) if it finds the expression in the set of expressions; otherwise INLIST( ) returns false (.F.). The null value is returned if eExpression1 is the null value. The null value is also returned if eExpression1 is not the null value, eExpression1 does not match another expression, and at least one of the other expressions is the null value.

Example

In this example, INLIST( ) determines the quarter of the year for the current month. The current month is stored to the variable gcMonth. Each CASE statement uses INLIST( ) to determine whether the contents of gcMonth can be found in a list of month names. The name of the quarter returned is stored to the variable gcReporTitle.

SET TALK ON
STORE CMONTH(DATE( )) TO gcMonth
DO CASE
   CASE INLIST(gcMonth,'January','February','March')
      STORE 'First Quarter' TO gcReporTitle
   CASE INLIST(gcMonth,'April','May','June')
      STORE 'Second Quarter' TO gcReporTitle
   CASE INLIST(gcMonth,'July','August','September')
      STORE 'Third Quarter' TO gcReporTitle
   OTHERWISE
      STORE 'Fourth Quarter' TO gcReporTitle
ENDCASE
WAIT WINDOW gcReporTitle

See Also

BETWEEN( ) | CASE Statements | DO CASE ... ENDCASE Command | AT( ) | ATLINE( ) | RAT( ) | RATLINE( ) | $ Operator | OCCURS( )


INPUTBOX( ) Function

Displays a modal dialog used by a parameterized view for input of a single string.

INPUTBOX(cInputPrompt [, cDialogCaption [, cDefaultValue [, nTimeout [,cTimeoutValue]]]])

Parameters

cInputPrompt
Specifies the Prompt displayed above the text entry box.
cDialogCaption
Specifies the text to display in the title bar of the dialog box.
cDefaultValue
Specifies a default value to display in the text entry box.
nTimeout
Specifies a timeout value in 1/1000 seconds.
cTimeoutValue
Specifies value to return if a timeout occurs.

Remarks

The dialog box displays an edit box and OK and Cancel buttons. The OK button always returns the contents of the text box. The Cancel button always returns an empty string. A timeout will return the specified text in cTimeoutValue or an empty string if cTimeoutValue is not passed.

Example

Y = "Nothing at all"
Y = INPUTBOX("TypeHere","Input ",Y,5000)
         && Displays dialog box for 5 seconds,
         && then displays anything typed or "Nothing at all"

See Also

Input and Output | INPUT Command | MESSAGEBOX Function


INSMODE( ) Function

Returns the current insert mode, or sets the insert mode on or off.

INSMODE([lExpression])

Return Values

Logical

Parameters

lExpression
Turns the insert mode on or off. INSMODE(.T.) turns the insert mode on and INSMODE(.F.) turns it off. A logical value corresponding to the insert mode setting before INSMODE(.T.) or INSMODE(.F.) was issued is returned.

Remarks

If you omit the optional argument and the insert mode is on (characters are inserted before the cursor), INSMODE( ) returns true (.T.). If the insert mode is off (characters are overwritten at the insertion point), INSMODE( ) returns false (.F.).

Example

The example below uses INSMODE( ) to set the insert mode on, and then toggles the insert mode to the opposite state.

SET TALK ON
=INSMODE(.T.)  && Set insert mode on
? INSMODE( )
= INSMODE(!INSMODE( ))  && Toggle insert mode to opposite state
? INSMODE( )

See Also

CAPSLOCK( ) | NUMLOCK( ) | SET TALK Command


INT( ) Function

Evaluates a numeric expression and returns the integer portion of the expression.

INT(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression for which INT( ) returns the integer portion.

Example

CLEAR
? INT(12.5)  && Displays 12
? INT(6.25 * 2)  && Displays 12
? INT(-12.5)  && Displays -12
STORE -12.5 TO gnNumber
? INT(gnNumber)  && Displays -12

See Also

CEILING( ) | FLOOR( ) | ROUND( )


ISALPHA( ) Function

Determines whether the leftmost character in a character expression is alphabetic.

ISALPHA(cExpression)

Return Values

Logical

Parameters

cExpression
Specifies the character expression that ISALPHA( ) evaluates. Any characters after the first character in cExpression are ignored.

Remarks

ISALPHA( ) returns true (.T.) if the leftmost character in the specified character expression is an alphabetic character; otherwise ISALPHA( ) returns false (.F.).

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
CLEAR

DISPLAY contact
? ISALPHA(contact)  && Displays .T.
DISPLAY maxordamt
? ISALPHA(cust_id)  && Displays .F.

See Also

ISLOWER( ) | ISUPPER( ) | LOWER( ) | UPPER( )


ISBLANK( ) Function

Determines whether an expression is blank.

ISBLANK(eExpression)

Return Values

Logical

Parameters

eExpression
Specifies the expression that ISBLANK( ) evaluates. eExpression can be a field in a table, a variable or array element, or an expression.

For a field, ISBLANK( ) returns true (.T.) if the field contains the following values.

Type | Contents
Character | Empty string, spaces, or no value (newly appended blank record or cleared with BLANK)
Numeric | No value (newly appended blank record or cleared with BLANK)
Float | No value (newly appended blank record or cleared with BLANK)
Date | Blank date ({ / / }) or no value (newly appended blank record or cleared with BLANK)
DateTime | Blank datetime ({ / / : : }) or no value (newly appended blank record or cleared with BLANK)
Logical | No value (newly appended blank record or cleared with BLANK)
Memo | Empty (no memo contents)
General | Empty (no OLE object)
Picture | Empty (no picture)

Remarks

ISBLANK( ) returns true (.T.) if the expression eExpression is blank; otherwise, ISBLANK( ) returns false (.F.).

APPEND BLANK and BLANK are used to create a blank record. BLANK can also be used to clear data from fields in a record. ISBLANK( ) can determine if a field is blank.

Note that Currency, Integer and Double type expressions are never blank, and ISBLANK( ) always returns false (.F.) for these data types.

ISBLANK( ) differs from EMPTY( ) and ISNULL( ). For example, EMPTY( ) returns true (.T.) if a character expression contains any combination of null values, spaces, tabs, carriage returns, or line feeds; ISBLANK( ) returns true (.T.) if a character expression contains only the empty string or spaces.

Example

In the following example, a table named mytable is created and a blank record is appended. ISBLANK( ) returns true (.T.) because myfield is blank. A value is placed in myfield, and ISBLANK( ) returns false (.F.) because myfield is no longer blank.

CREATE TABLE mytable FREE (myfield C(20))
APPEND BLANK  && Add new blank record
CLEAR

? ISBLANK(myfield)  && Displays .T.
REPLACE myfield WITH 'John Smith'  && Insert a value in the field
? ISBLANK(myfield)  && Displays .F.

See Also

APPEND | BLANK | EMPTY( ) | ISNULL( ) | LEN( )


ISCOLOR( ) Function

Determines whether a computer can display color.

ISCOLOR( )

Return Values

Logical

Remarks

ISCOLOR( ) returns true (.T.) if the computer has color capability (whether or not a color monitor is actually being used). If the computer doesn't provide color support, ISCOLOR( ) returns false (.F.).

See Also

SET DISPLAY | SYS(2006) – Current Graphics Card


ISDIGIT( ) Function

Determines whether the leftmost character of the specified character expression is a digit (0 through 9).

ISDIGIT(cExpression)

Return Values

Logical

Parameters

cExpression
Specifies the character expression that ISDIGIT( ) tests. Any characters after the first character in cExpression are ignored.

Remarks

ISDIGIT( ) returns true (.T.) if the leftmost character of the specified character expression is a digit (0 through 9); otherwise, ISDIGIT( ) returns false (.F.).

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE orders  && Open Orders table
CLEAR

DISPLAY cust_id
? ISDIGIT(cust_id)  && Displays .F.
DISPLAY order_dsc
? ISDIGIT(ALLTRIM(STR(order_dsc)))  && Displays .T.

See Also

ISALPHA( ) | CLEAR Commands | Character Functions | USE


ISEXCLUSIVE( ) Function

Returns true (.T.) if a table or database is opened for exclusive use; otherwise, returns false (.F.).

ISEXCLUSIVE([cTableAlias | nWorkArea | cDatabaseName [, nType]])

Return Values

Logical

Parameters

cTableAlias
Specifies the alias of the table for which the exclusive use status is returned. Visual FoxPro generates an error message if you specify a table alias that doesn't exist.
nWorkArea
Specifies the work area of the table for which the exclusive use status is returned. ISEXCLUSIVE( ) returns false (.F.) if a table isn't open in the work area you specify.
cDatabaseName
Specifies the name of the database for which the exclusive use status is returned.
nType
Specifies whether the exclusive status is returned for a table or a database. The following table lists the values for nType and the corresponding status returned.
nType | Exclusive Status Returned
1 | Table
2 | Database

To determine the exclusive status for a database, you must include nType with a value of 2.

Remarks

ISEXCLUSIVE( ) returns a value for the table open in the currently selected work area if you omit the optional cTableAlias, nWorkArea, or cDatabaseName arguments.

A table is opened for exclusive use by including the EXCLUSIVE keyword in USE, or by setting SET EXCLUSIVE to ON before the table is opened.

A database is opened for exclusive use by including the EXCLUSIVE keyword in OPEN DATABASE.

Example

In the following example, the ISEXCLUSIVE( ) function verifies that the table was opened for exclusive use. The table is not reindexed since the one in the current work are was not opened for exclusive use.

cExclusive = SET('EXCLUSIVE')
SET EXCLUSIVE OFF
SET PATH TO (HOME(2) + 'data\')
OPEN DATA testdata  && Opens the test databsase
USE customer     && Not opened exclusively
USE employee IN 0 EXCLUSIVE    && Opened exclusively in another work area
IF ISEXCLUSIVE( )
 REINDEX  && Can only be done if table opened exclusively
ELSE
  WAIT WINDOW 'The table has to be exclusively opened'
ENDIF
SET EXCLUSIVE &cExclusive

See Also

OPEN DATABASE | SET EXCLUSIVE | USE


ISFLOCKED( ) Function

Returns the table lock status.

ISFLOCKED([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea
Specifies the work area number of the table for which the lock status is returned. If you omit cTableAlias and nWorkArea, the lock status is returned for the table open in the current work area.
cTableAlias
Specifies the alias of the table for which the lock status is returned. An "Alias not found" error message is generated if you specify an alias of a table that isn't open.

Remarks

ISFLOCKED( ) returns a logical true (.T.) if the table is locked; otherwise a logical false (.F.) is returned. ISFLOCKED( ) is similar to SYS(2011), but returns a logical value which does not require localization for international applications.

Note ISFLOCKED() only returns .T. at the workstation that applied the file lock.

See Also

FLOCK( ) | ISRLOCKED( ) | LOCK( ) | RLOCK( ) | SYS(2011) – Current Lock Status


ISLEADBYTE( ) Function

Returns true (.T.) if the first byte of the first character in a character expression is the lead byte of a double-byte character.

ISLEADBYTE(cExpression)

Return Values

Logical

Parameters

cExpression
Specifies the character expression that ISLEADBYTE( ) evaluates. Any bytes after the first byte in the first character in cExpression are ignored.

Remarks

ISLEADBYTE( ) returns true (.T.) if the first byte of the first character in a character expression is the lead byte in a double-byte character. If ISLEADBYTE( ) returns false (.F.), the character being tested is a single-byte character.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

ISALPHA( ) Function | ISDIGIT( ) Function | ISLOWER( ) Function | ISUPPER( ) Function


ISLOWER( ) Function

Determines whether the leftmost character of the specified character expression is a lowercase alphabetic character.

ISLOWER(cExpression)

Return Values

Logical

Parameters

cExpression
Specifies the character expression that ISLOWER( ) tests. ISLOWER( ) ignores any characters after the first character in cExpression.

Remarks

ISLOWER( ) returns true (.T.) if the leftmost character in the specified character expression is a lowercase alphabetic character; otherwise, ISLOWER( ) returns false (.F.).

Example

CLEAR
? ISLOWER('redmond')  && Displays .T.
? ISLOWER('Redmond')  && Displays .F.

See Also

ISALPHA( ) | ISUPPER( ) | LOWER( ) | UPPER( )


ISMOUSE( ) Function

Returns true (.T.) if mouse hardware is present.

ISMOUSE( )

Remarks

ISMOUSE( ) returns true (.T.) if mouse hardware is present; otherwise it returns false (.F.).

Example

The following example displays a true value (.T.) if mouse hardware is present; otherwise, it displays false (.F.).

CLEAR
? 'Mouse hardware present? '
?? ISMOUSE( )

See Also

MCOL( ) | MDOWN( ) | MROW( ) | SYSMETRIC( )


ISNULL( ) Function

Returns true (.T.) if an expression evaluates to a null value; otherwise, ISNULL( ) returns false (.F.).

ISNULL(eExpression)

Return Values

Logical

Parameters

eExpression
Specifies the expression to evaluate.

Remarks

Use ISNULL( ) to determine if the contents of a field, memory variable, or array element contains a null value, or if an expression evaluates to a null value.

Example

In the following example, ISNULL( ) is used to check for a null value.

STORE .NULL. TO mNullvalue  && Store a null value to a memory variable

CLEAR
? mNullvalue  && Display the value of the memory variable
? ISNULL(mNullvalue)  && Returns .T., indicating a null value
? TYPE('mNullvalue')     && Returns L, indicating a logical value
? (mNullvalue = .NULL.)  && Returns .NULL., bad test for null values

See Also

NVL( ) | SET NULL | Handling Null Values


ISREADONLY( ) Function

Determines whether a table or database is opened read-only.

ISREADONLY([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea | cTableAlias
Returns the read-only status for a table open in another work area. nWorkArea specifies the work area number and cTableAlias specifies the table or work area alias. ISREADONLY( ) returns false (.F.) if a table isn't open in the work area you specify.

If you don't specify a work area number or a table or work area alias, the ISREADONLY( ) function returns the read-only status of the table open in the current work area.

ISREADONLY(0) returns the status of the current database. If there is no current open database, ISREADONLY(0) returns an error.

Remarks

ISREADONLY( ) returns true (.T.) if a table is opened read-only; otherwise, ISREADONLY( ) returns false (.F.).

You can open a table read-only by including the NOUPDATE option when opening the table with USE, by checking the Read Only check box when opening the table from the Open dialog box, or by assigning MS-DOS read-only attributes to the table.

You cannot pass a non-current database alias to the ISREADONLY( ) function. To ensure that a database is present, you can use code such as the following:

!EMPTY(DBC())

A cursor created with the SELECT – SQL command is always read-only.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer    NOUPDATE  && Open customer table read-only

CLEAR
? ISREADONLY('customer')  && Returns .T.

See Also

USE | ReadOnly Property | SELECT - SQL Command


ISRLOCKED( ) Function

Returns the record lock status.

ISRLOCKED([nRecordNumber, [nWorkArea | cTableAlias]])

Return Values

Logical

Parameters

nRecordNumber
Specifies the number of the record for which the lock status is returned. If nRecordNumber is omitted, the record lock status is returned for the current record.
nWorkArea
Specifies the work area number of the table for which the record lock status is returned. If you omit cTableAlias and nWorkArea, the record lock status is returned for the table open in the current work area.
cTableAlias
Specifies the alias of the table for which the record lock status is returned.

Remarks

ISRLOCKED( ) returns a logical true (.T.) if the record is locked by the current application; otherwise a logical false (.F.) is returned.

Note ISRLOCKED() only returns .T. at the workstation that applied the record lock.

See Also

FLOCK( ) | ISFLOCKED( ) | LOCK( ) | RLOCK( ) | SYS(2011) - Current Lock Status


ISUPPER( ) Function

Determines whether the first character in a character expression is an uppercase alphabetic character.

ISUPPER(cExpression)

Return Values

Logical

Parameters

cExpression
Specifies the character expression that ISUPPER( ) evaluates. Any characters after the first character in cExpression are ignored.

Remarks

ISUPPER( ) returns true (.T.) if the first character in a character expression is an uppercase alphabetic character; otherwise, ISUPPER( ) returns false (.F.).

Example

? ISUPPER('Redmond')  && Displays .T.
? ISUPPER('redmond')  && Displays .F.

See Also

ISALPHA( ) | ISLOWER( ) | LOWER( ) | UPPER( )


JUSTDRIVE( ) Function

Returns the drive letter from a complete path.

JUSTDRIVE(cPath)

Return Values

Character

Parameters

cPath
Specifies the complete path name for which you want only the drive.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


JUSTEXT( ) Function

Returns the three-letter extension from a complete path.

JUSTEXT(cPath)

Return Values

Character

Parameters

cPath
Specifies the name, which may include the full path, of the file for which you want only the extension. The maximum length of the string passed to cPath is 259 bytes.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTFNAME( ) | JUSTPATH( ) | JUSTSTEM( )


JUSTFNAME( ) Function

Returns the file name portion of a complete path and file name.

JUSTFNAME(cFileName)

Return Values

Character

Parameters

cFileName
Specifies the name, which may include the full path, of the file for which you want only the file name. The maximum length of the string passed to cFileName is 259 bytes.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTPATH( ) | JUSTSTEM( )


JUSTPATH( ) Function

Returns the path portion of a complete path and file name.

JUSTPATH(cFileName)

Return Values

Character

Parameters

cFileName
Specifies the full name (including path) of the file for which you want only the path. The maximum length of the string passed to cFileName is 259 bytes.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTSTEM( )


JUSTSTEM( ) Function

Returns the stem name (the file name before the extension) from a complete path and file name.

JUSTSTEM(cFileName)

Return Values

Character

Parameters

cFileName
Specifies the name (including path) of the file for which you want only the stem. The maximum length of the string passed to cFileName is 259 bytes.

See Also

ADDBS( ) | DEFAULTEXT( ) | FILE( ) | FORCEEXT( ) | FORCEPATH( ) | JUSTDRIVE( ) | JUSTEXT( ) | JUSTFNAME( ) | JUSTPATH( )


KEY( ) Function

Returns the index key expression for an index tag or index file.

KEY([CDXFileName,] nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

CDXFileName
Specifies the name of a compound index file. KEY( ) returns the index key expressions of the .cdx file's index tag. The compound index file you specify can be the structural compound index file automatically opened with the table, or it can be an independent compound index file.
nIndexNumber
Specifies which index key expression to return.

USE and SET INDEX both support an index file list that lets you open multiple indexes for a table. Any combination of single-entry .idx index files, structural compound index files, or independent compound index files can be included in the index file list.

The numeric expression nIndexNumber specifies which index expression to return from the open index files. KEY( ) returns index expressions from open index files in the following order as nIndexNumber increases from 1 to the total number of open single-entry .idx files and structural compound and independent compound index tags:

  1. Index expressions from single-entry .idx index files (if any are open) are returned first. The order in which the single-entry index files are included in USE or SET INDEX determines how the index expressions are returned.
  2. Index expressions for each tag in the structural compound index (if one is present) are returned next. The index expressions are returned from the tags in the order in which the tags are created in the structural compound index.
  3. Index expressions for each tag in any open independent compound indexes are returned last. The index expressions are returned from the tags in the order in which the tags are created in the independent compound indexes.

The empty string is returned if nIndexNumber is greater than the total number of open single-entry .idx files and structural compound and independent compound index tags.

nWorkArea
Specifies the work area number of the table whose index key expressions you want KEY( ) to return.

If a table isn't open in the work area you specify, KEY( ) returns the empty string.

cTableAlias
Specifies the alias of the table whose index key expressions you want KEY( ) to return.

If no table has the alias you specify, Microsoft Visual FoxPro generates an error message.

If you omit nWorkArea and cTableAlias, the index key expressions are returned for the table open in the current work area.

Remarks

An index key expression is specified when an index tag or index file is created with INDEX. The index key expression determines how a table is displayed and accessed when the index tag or index file is opened as the master controlling index tag or file.

For more information on creating index tags, index files, and index key expressions, see INDEX.

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which KEY( ) is used to display the index expression of each index tag in the customer structural index. The name of each structural index tag is displayed with its index expression.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
CLEAR

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? TAG(nCount) + ' '  && Display tag name
   ?? KEY(nCount)  && Display index expression
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

DESCENDING( ) | INDEX | REINDEX | SET INDEX | SYS(14) - Index Expression | USE


KEYMATCH( ) Function

Searches an index tag or index file for an index key.

KEYMATCH(eIndexKey [, nIndexNumber [, nWorkArea | cTableAlias]])

Return Values

Logical

Parameters

eIndexKey
Specifies the index key that KEYMATCH( ) searches for. The index keys in an index file or index tag are determined by the index expression. An index expression is specified when an index file or index tag is created with INDEX. KEY( ) and SYS(14) can be used to return the index expressions for index files and index tags. For more information on creating index files, index expressions, and index keys, see INDEX.

If you don't include any of the optional parameters, KEYMATCH( ) searches the master index file or master index tag for the index key you specify. If a master index file or index tag isn't in effect (for example, you've issued SET ORDER TO without any parameters to place the table in physical record order), Visual FoxPro generates an error message.

nIndexNumber
Specifies which index file or index tag is searched. nIndexNumber is typically an integer that starts at 1 and is increased by 1 to search additional index tags.

If nIndexNumber is 1, the master single-entry .idx index file or master index tag (if one is present) is searched.

As nIndexNumber increases, subsequent tags in the structural compound index (if one is present) are searched. The tags are searched in the order in which the tags were created in the structural compound index.

As nIndexNumber continues to increase and all the tags in the structural compound index have been searched, tags in any open independent compound indexes are then searched. The tags are searched in the order in which the tags were created in the independent compound indexes.

An error message is generated if nIndexNumber is greater than the total number of open single-entry .idx files and structural compound and independent compound index tags.

nWorkArea | cTableAlias
Searches index files or tags open in another work area. nWorkArea specifies the work area number and cTableAlias specifies the table alias. If you omit the work area and alias, KEYMATCH( ) searches index files or tags open for the table in the current work area.

If no table has the alias you specify, Visual FoxPro generates an error message.

Remarks

KEYMATCH( ) searches an index tag or index file for a specific index key and returns true (.T.) if the index key is found; otherwise, KEYMATCH( ) returns false (.F.). KEYMATCH( ) can be used to prevent duplicate index keys.

KEYMATCH( ) returns the record pointer to the record on which it was originally positioned before KEYMATCH( ) was issued.

See Also

INDEX | INDEXSEEK( ) | KEY( ) | SET INDEX | SYS(14) | USE


LASTKEY( ) Function

Returns an integer corresponding to the last key pressed.

LASTKEY( )

Return Values

Numeric

Remarks

The values returned by LASTKEY( ) are the same as the values returned by INKEY( ). See INKEY( ) for a list of keys and their return values.

LASTKEY( ) is updated when you move between controls.

See Also

CHRSAW( ) | INKEY( ) | READKEY( )


LEFT( ) Function

Returns a specified number of characters from a character expression, starting with the leftmost character.

LEFT(cExpression, nExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which LEFT( ) returns characters.
nExpression
Specifies the number of characters returned from the character expression. If nExpression is greater than the length of cExpression, all of the character expression is returned. The empty string is returned if nExpression is negative or 0.

LEFT( ) is identical to SUBSTR( ) with a starting position of 1.

Example

CLEAR
? LEFT('Redmond, WA', 4)  && Displays Redm

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LTRIM( ) | RAT( ) | RATLINE( ) | RIGHT( ) | RTRIM( ) | SUBSTR( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( )


LEFTC( ) Function

Returns a specified number of characters from a character expression, starting with the leftmost character.

LEFTC(cExpression, nExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which LEFTC( ) returns characters.
nExpression
Specifies the number of characters returned from the character expression. If nExpression is greater than the length of cExpression, all of the character expression is returned. The empty string is returned if nExpression is negative or 0.

Remarks

LEFTC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, LEFTC( ) is equivalent to LEFT( ).

LEFTC( ) returns a specified number of characters from a character expression containing any combination of single-byte and double-byte characters.

LEFTC( ) is identical to SUBSTRC( ) with a starting position of 1.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | LTRIM( ) | RAT( ) | RATLINE( ) | RIGHT( ) | RTRIM( ) | SUBSTR( ) | RIGHTC( ) | SUBSTRC( )


LEN( ) Function

Returns the number of characters in a character expression.

LEN(cExpression)

Return Values

Numeric

Parameters

cExpression
Specifies the character expression for which LEN( ) returns the number of characters.

Remarks

Use LEN( ) to determine the length of a character expression.

Example

The following example opens the customer table in the testdata database. LEN( ) is used to display the widths of the cust_id and contact fields.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table

CLEAR
? 'Width of contact field: '
?? LEN(contact)
? 'Width of cust_id field: '
?? LEN(cust_id)

See Also

FSIZE( ) | TXTWIDTH( ) | LENC( ) Function


LENC( ) Function

Returns the number of characters in a character expression or memo field.

LENC(cExpression)

Return Values

Numeric

Parameters

cExpression
Specifies the character expression for which LENC( ) returns the number of characters.

Remarks

LENC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, LENC( ) is equivalent to LEN( ).

LENC( ) returns the number of characters in a character expression or memo field containing any combination of single-byte and double-byte characters.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

LEN( ) | Application Creation with Double-Byte Character Sets | FSIZE( ) | TXTWIDTH( )


LIKE( ) Function

Determines if a character expression matches another character expression.

LIKE(cExpression1, cExpression2)

Return Values

Logical

Parameters

cExpression1
Specifies the character expression that LIKE( ) compares with cExpression2. cExpression1 can contain the wildcards such as * and ?. The question mark (?) matches any single character in cExpression2 and the asterisk (*) matches any number of characters. You can mix any number of wildcards in any combination in cExpression1.
cExpression2
Specifies the character expression LIKE( ) compares with cExpression1. cExpression2 must match cExpression1 letter for letter in order for LIKE( ) to return true (.T.).

Remarks

LIKE( ) returns true (.T.) if cExpression1 matches cExpression2; otherwise, it returns false (.F.).

SET COMPATIBLE determines how LIKE( ) evaluates cExpression1 and cExpression2. If SET COMPATIBLE is set to ON or DB4, cExpression1 and cExpression2 have all trailing blanks removed before they are compared. If SET COMPATIBLE is set to OFF or FOXPLUS, any trailing blanks in cExpression1 and cExpression2 are used in the comparison.

Example

In the following example, all product names in the products table with the first two letters "Ch" are displayed.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE products  && Open Products table

CLEAR
? 'All product names with first two letters Ch:'
?
SCAN FOR LIKE('Ch*', prod_name)
   ? prod_name
ENDSCAN
USE

See Also

$ | AT( ) | ATC( ) | OCCURS( ) | RAT( ) | SET COMPATIBLE | LIKEC( )


LIKEC( ) Function

Determines whether a character expression matches another character expression.

LIKEC(cExpression1, cExpression2)

Return Values

Logical

Parameters

cExpression1
Specifies the character expression that LIKEC( ) compares with cExpression2. cExpression1 can contain wild cards such as * and ?. A question mark (?) matches any single character in cExpression2 and an asterisk (*) matches any number of characters. You can mix any number of wild cards in any combination in cExpression1.
cExpression2
Specifies the character expression LIKEC( ) compares with cExpression1. cExpression2 must match cExpression1 character for character in order for LIKE( ) to return true (.T.).

Remarks

LIKEC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, LIKEC( ) is equivalent to LIKE( ).

LIKEC( ) determines if a character expression matches another character expression. LIKEC( ) returns true (.T.) if cExpression1 matches cExpression2; otherwise, it returns false (.F.).

SET COMPATIBLE determines how LIKEC( ) compares blanks in cExpression1 and cExpression2. If SET COMPATIBLE is set to ON or DB4, all trailing blanks are removed from cExpression1 and cExpression2 before they are compared. If SET COMPATIBLE is set to OFF or FOXPLUS, any trailing blanks in cExpression1 and cExpression2 are used in the comparison.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT_C( ) | ATCC( ) | LIKE( ) | RATC( )


LINENO( ) Function

Returns the line number of a line being executed in a program relative to the first line of the main program.

LINENO([1])

Return Values

Numeric

Parameters

1
Returns the line number relative to the first line of the current program or procedure. If you omit the 1 argument, the line number is returned relative to the first line of the main program.

Remarks

Program lines are counted starting from the top of the program. Comment lines, continuation lines, and blank lines are included in the line number count. If a program is suspended during execution, LINENO( ) returns the number of the program line at which program execution was suspended. LINENO( ) returns 0 if a program is canceled.

By default, line numbers are returned relative to the beginning of the main program. If a procedure is called, line numbering continues from the top of the calling program.

LINENO( ) is useful for debugging programs. You can set a breakpoint to stop program execution at a specific line number by opening the Breakpoints window, setting the Type to 'Break when expression is true' and adding LINENO( ) = nExpression in the Expression textbox.

Example

The following example is part of a simple error-handling routine.

ON ERROR DO bug_proc WITH LINENO( )
BRWS  && Causes an error
ON ERROR

*** Bug_Proc error handler ***

PROCEDURE bug_proc
PARAMETERS gnBadLine
WAIT WINDOW 'Error occurred at line: ' + ALLTRIM(STR(gnBadLine))
RETURN

See Also

ERROR( ) | MESSAGE( ) | PROGRAM( ) | SYS(16) - Executing Program File Name | Error Messages A-Z | Error Messages by Number


LOADPICTURE( ) Function

Creates an object reference for a bitmap, icon, or Windows meta file.

LOADPICTURE([cFileName])

Return Values

Object

Parameters

cFileName
Specifies the bitmap (.bmp), icon (.ico), or Windows metafile (.wmf) file for which an object reference is created. If cFileName is omitted, the null picture is returned. You can include GETPICT( ) as cFileName to display the Open dialog from which you can choose a bitmap (.bmp) file.

Remarks

Many presentation properties of ActiveX controls require an object reference for their settings. For example, the ActiveX Outline control supports the PictureOpen property that requires an object reference for its setting.

See Also

GETPICT( ) | SAVEPICTURE( ) | Picture Property


LOCFILE( ) Function

Locates a file on disk and returns the file name with its path.

LOCFILE(cFileName [, cFileExtensions] [, cFileNameCaption])

Return Values

Character

Parameters

cFileName
Specifies the name of the file to locate. If cFileName includes only a file name, LOCFILE( ) searches the Visual FoxPro default directory or folder first. If the file is not found in the default directory or folder, the Microsoft Visual FoxPro path is then searched. Use SET PATH to specify the Visual FoxPro path.

If cFileName includes a path and a file name, the specified location is searched. If the file cannot be found in the specified location, LOCFILE( ) searches the Visual FoxPro default directory or folder and then the Visual FoxPro path.

If the file is located, LOCFILE( ) returns the file name and path.

cFileExtensions
Specifies file extensions for the file to locate. If the file name you specify with cFileName does not include an extension, Visual FoxPro applies the file extensions listed in cFileExtensions to the file name and searches for the file again.

cFileExtensions also specifies the file name extensions of the files displayed in the Open dialog box when the file you specified cannot be located.

cFileExtensions can take a variety of forms:

  • If cFileExtensions contains a single extension (for example, PRG), only files with that extension are displayed.
  • cFileExtensions can also contain wildcards (* and ?). All files with extensions that meet the wildcard criteria are displayed. For example, if cFileExtensions is ?X?, all files with the extension .fxp, .exe, or .txt are displayed.
  • In Visual FoxPro for Windows, cFileExtensions can contain a file description followed by a file extension or a list of file extensions separated with commas. The file description appears in the Files of Type list box. Separate the file description from the file extension or list of file extensions with a colon (:). Separate multiple file descriptions and their file extensions with a semicolon (;).

    For example, if cFileExtensions is "Text:TXT" the file description "Text" appears in the Files of Type list box and all files with a .txt extension are displayed.

    If cFileExtensions is "Tables:DBF; Files:TXT,BAK" the file descriptions "Tables" and "Files" appear in the Files of Type list box. When "Tables" is chosen from the Files of Type list box, all files with a .dbf extension are displayed. When "Files" is chosen from the Files of Type list box, all files with .txt and .bak extensions are displayed.

cFileNameCaption
Specifies the text you want to use to prompt the user. The text appears to the left of the textbox in which you enter the file name. If omitted, "File name:" is displayed.

For a list of Visual FoxPro file extensions and corresponding creator types, see the File Extensions and File Types online topic.

Remarks

The Open dialog box is displayed if the file cannot be located in the default directory or folder, the Visual FoxPro path, or a specified location. The Open dialog box can be used to locate the file. When a file is chosen from the Open dialog box, the file name is returned with the file's path.

If you exit the Open dialog box by choosing Cancel, pressing ESC, or choosing Close from the Control menu, Visual FoxPro generates an error message and LOCFILE( ) does not return a value.

See Also

FILE( ) | GETFILE( ) | GETPICT( ) | PUTFILE( ) | SET PATH


LOCK( ) Function

Attempts to lock one or more records in a table.

LOCK([nWorkArea | cTableAlias]|
 [cRecordNumberList, nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea | cTableAlias
Attempts a lock on the current record in a table open in a specific work area. nWorkArea specifies the work area number and cTableAlias specifies the table alias. If you do not specify a work area or table alias, LOCK( ) attempts to lock the current record in the table in the current work area.
cRecordNumberList
Specifies a list of one or more record numbers which you must include to attempt to lock multiple records. SET MULTILOCKS must be ON and you must include the work area or alias of the table for which you are attempting to place multiple record locks.

LOCK( ) attempts to lock all of the records you specify. The record numbers specified with cRecordNumberList are separated by commas. For example, to attempt record locks on the first four records in a table, cRecordNumberList must contain 1,2,3,4.

You can also lock multiple records by moving the record pointer to the record you would like to lock, issuing LOCK( ) or RLOCK( ) and then repeating these steps for each additional record.

In Visual FoxPro, you can specify 0 as a record number. Specifying 0 makes it possible for you to attempt to lock the table header.

Note Keep the table header locked for as short a time as possible because other users cannot add records to the table when the table header is locked.

Release the table header lock with UNLOCK RECORD 0, UNLOCK or UNLOCK ALL.

If all the records specified in cRecordNumbers are successfully locked, LOCK( ) returns true (.T.). If even one of the records specified with cRecordNumbers cannot be locked, LOCK( ) returns false (.F.) and none of the records are locked. However, any existing record locks remain in place. Multiple record locking is an additive process. Placing additional record locks does not release locks on other records.

The maximum number of records that can be locked in each work area is approximately 8,000. It is always faster to lock the entire table rather than even a small number of records.

Remarks

LOCK( ) is identical to RLOCK( ).

If the lock or locks are successfully placed, LOCK( ) returns true (.T.). Locked records are available for both read and write access to the user who placed the locks; they are available for read-only access to all other users on the network.

Executing LOCK( ) does not guarantee that the record lock or locks will be successfully placed. A record lock cannot be placed on a record already locked by another user or in a table locked by another user. If the record lock or locks cannot be placed for any reason, LOCK( ) returns false (.F.).

By default, LOCK( ) makes one attempt to lock a record. Use SET REPROCESS to automatically retry a record lock when the first attempt fails. SET REPROCESS determines the number of lock attempts or the length of time during which lock attempts are made when the initial lock attempt is unsuccessful. For more information, see SET REPROCESS.

SET MULTILOCKS determines whether you can lock multiple records in a table. If SET MULTILOCKS is OFF (the default), you can lock only a single record in a table. When SET MULTILOCKS is ON, you can lock multiple records in a table. For more information, see SET MULTILOCKS.

Unlocking Records A table record can be unlocked only by the user who placed the lock. You can release record locks by issuing UNLOCK, closing the table, or exiting Visual FoxPro.

UNLOCK can be used to release record locks in the current work area, a specific work area, or in all work areas. For more information, see UNLOCK.

Switching SET MULTILOCKS from ON to OFF or from OFF to ON implicitly performs UNLOCK ALL — all record locks in all work areas are released.

Tables can be closed with USE, CLEAR ALL, or CLOSE DATABASES.

For more information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Example

The following example locks and unlocks the first four records in the customer and employee tables.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
SET REPROCESS TO 3 AUTOMATIC
STORE '1,2,3,4' TO gcRecList
gcOldExc = SET('EXCLUSIVE')
SET EXCLUSIVE OFF
SELECT 0
USE employee  && Open Employee table
SELECT 0
USE customer  && Open Customer table
? LOCK('1,2,3,4', 'customer')  && Lock 1st 4 records in customer
? RLOCK(gcRecList, 'employee')  && Lock 1st 4 records in employee
UNLOCK IN customer
UNLOCK IN employee
SET EXCLUSIVE &gcOldExc

See Also

CLEAR | CLOSE | FLOCK( ) | RLOCK( ) | SET MULTILOCKS | SET REPROCESS | UNLOCK | USE | ISFLOCKED( ) Function | ISRLOCKED( ) Function


LOG( ) Function

Returns the natural logarithm (base e) of the specified numeric expression.

LOG(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression for which LOG( ) returns the value of x in the equation e^x = nExpression. nExpression must be greater than 0.

Remarks

The base for the natural logarithm is the constant e. The number of decimal places returned in the result is specified with SET DECIMALS.

Example

CLEAR
? LOG(1)  && Displays 0.00
STORE EXP(2) TO gneSquare
? LOG(gneSquare)  && Displays 2.00

See Also

EXP( ) | LOG10( ) | SET DECIMALS


LOG10( ) Function

Returns the common logarithm (base 10) of the specified numeric expression.

LOG10(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression for which LOG10( ) returns the value of x in the equation 10^x = nExpression. nExpression must be greater than 0.

Remarks

The base for the common logarithm is 10. The number of decimal places returned in the result is specified with SET DECIMALS.

Example

CLEAR
? LOG10(10)  && Displays 1.00
STORE 100 TO gnBaseTen
? LOG10(gnBaseTen)  && Displays 2.00
? LOG10(gnBaseTen^2)  && Displays 4.00

See Also

EXP( ) | LOG( ) | SET DECIMALS


LOOKUP( ) Function

Searches a table for the first record with a field matching the specified expression.

LOOKUP(ReturnField, eSearchExpression, SearchedField [, cTagName])

Return Values

Character, Numeric, Currency, Float, Integer, Double, Date, DateTime, or Logical

Parameters

ReturnField
Specifies the field whose contents LOOKUP( ) returns when the search is successful. If the search is unsuccessful, LOOKUP( ) returns an empty character string of the same length and data type as ReturnField.
eSearchExpression
Specifies the search expression. The search expression is usually the contents of a field in the table, or it can correspond to the index expression of the active index or compound index tag.
SearchedField
Specifies the field to search. If the table does not have an active index, LOOKUP( ) performs a sequential search through the field specified with SearchedField.

If an index file or index tag is open whose index key expression is the search field you specify, LOOKUP( ) uses the index file or index tag to perform a faster search.

cTagName
Specifies the name of a compound index tag for LOOKUP( ) to use in the search. A compound index search is the fastest search LOOKUP( ) can perform.

Remarks

If the search is successful, LOOKUP( ) moves the record pointer to the matching record and returns the contents of a specified field in the record.

If the search expression is not found, LOOKUP( ) returns a blank character string the same length and data type as ReturnField. The record pointer is positioned at the end of the file.

If LOOKUP( ) is used to search a parent table, record pointers in all related child tables are moved to the related records.

This function cannot be optimized with Rushmore Query Optimization.

Example

In the following example, LOOKUP( ) uses the index tag company to search for the first occurrence of the string "Ernst Handel." If the search is successful, LOOKUP( ) returns the contents of the contact field and @ ... SAY displays the return value.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer ORDER company  && Open Customer table
CLEAR
@ 2,2 SAY LOOKUP(contact, 'Ernst Handel', company, 'company')

See Also

FIND | INDEX | LOCATE | SEEK | SEEK( )


LOWER( ) Function

Returns a specified character expression in lowercase letters.

LOWER(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression LOWER( ) converts.

Remarks

LOWER( ) converts all uppercase letters (A – Z) in the character expression to lowercase (a – z). All other characters in the character expression remain unchanged.

Example

STORE 'FOX' TO gcName
CLEAR
? LOWER(gcName)  && Displays fox

See Also

ISALPHA( ) | ISLOWER( ) | ISUPPER( ) | PROPER( ) | UPPER( )


LTRIM( ) Function

Returns the specified character expression with leading blanks removed.

LTRIM(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression whose leading blanks LTRIM( ) removes.

Remarks

This function is especially useful for removing the leading blanks that are inserted when you use STR( ) to convert a numeric value to a character string.

Example

STORE 'Redmond' TO gcCity
STORE '   Washington' TO gcState
CLEAR
? gcCity, gcState  && Displays Redmond   Washington
? gcCity, LTRIM(gcState)  && Displays Redmond Washington

See Also

ALLTRIM( ) | LEFT( ) | RIGHT( ) | RTRIM( ) | SUBSTR( ) | TRIM( )


LUPDATE( ) Function

Returns the date on which a table was last updated.

LUPDATE([nWorkArea | cTableAlias])

Return Values

Date

Parameters

nWorkArea | cTableAlias
Returns the last update to a table open in another work area. nWorkArea specifies the work area number and cTableAlias specifies the table alias. LUPDATE( ) returns the date of the last update to the table in the currently selected work area if you omit nWorkArea and cTableAlias.

If no table is open in the work area you specify, LUPDATE( ) returns a blank date. If no table has the alias you specify, Visual FoxPro generates an error message.

Remarks

This function is useful in update procedures.

LUPDATE( ) queries Windows to determine the date a table was last updated. However, the last two digits of the year the table was last updated are stored the table header.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Open Customer table

CLEAR
? LUPDATE( )  && Displays date of last update

See Also

DIR | FDATE( ) | FTIME( )


MAX( ) Function

Evaluates a set of expressions and returns the expression with the maximum value.

MAX(eExpression1, eExpression2 [, eExpression3 ...])

Return Values

Character, Numeric, Currency, Double, Float, Date, or DateTime

Parameters

eExpression1, eExpression2 [, eExpression3 ...]
Specify the expressions from which you want MAX( ) to return the expression with the highest value. All the expressions must be of the same data type.

Example

The following example uses APPEND BLANK to create a table with 10 records containing random values, then uses MIN( ) and MAX( ) to display the maximum and minimum values in the table.

CLOSE DATABASES
CREATE TABLE Random (cValue N(3))
FOR nItem = 1 TO 10  && Append 10 records,
   APPEND BLANK
   REPLACE cValue WITH 1 + 100 * RAND( )  && Insert random values
ENDFOR

CLEAR
LIST  && Display the values
gnMaximum = 1  && Initialize minimum value
gnMinimum = 100  && Initialize maximum value
SCAN
   gnMinimum = MIN(gnMinimum, cValue)
   gnMaximum = MAX(gnMaximum, cValue)
ENDSCAN
? 'The minimum value is: ', gnMinimum  && Display minimum value
? 'The maximum value is: ', gnMaximum  && Display maximum value

See Also

CALCULATE | MIN( ) | SELECT - SQL


MCOL( ) Function

Returns the column position of the mouse pointer in the main Visual FoxPro window or a user-defined window.

MCOL([cWindowName [, nScaleMode]])

Parameters

cWindowName
Specifies the name of the window whose mouse-pointer column position MCOL( ) returns.
nScaleMode
Specifies the unit of measurement for the value MCOL( ) returns. The following table lists the settings for nScaleMode.
nScaleMode | Description
0 | Foxels. A foxel is equivalent to the average height and width of a character based on the current font of the form in which an object is contained. (Default)
3 | Pixels. A pixel is the smallest element that can be displayed on a screen or printer. Pixels are screen-dependent.

Return Values

Numeric. MCOL( ) returns the column position of the mouse pointer in the main Visual FoxPro window or a user-defined window.

If you omit cWindowName, and there is no active user-defined window, MCOL( ) returns the mouse pointer's column position in the main Visual FoxPro window. If you omit cWindowName, and there is an active user-defined window, MCOL( ) returns the mouse pointer's column position in the active user-defined window. MCOL( ) returns –1 if the mouse pointer is positioned outside the user-defined window or, if no mouse driver is loaded, and there is no output window.

Remarks

Using the MCOL( ) function without an optional argument might affect the behavior of code on forms when Form AllowOutput property set to False (.F.). For example, the placement of a shortcut menu that is defined in the RightClick event might not display in the proper location if you use the MCOL( ) function to determine where the menu is displayed. For more information, see

See Also

AMOUSEOBJ( ) | COL( ) | GridHitTest Method | INKEY( ) | ISMOUSE( ) | MROW( ) | ROW( ) | WCOLS( ) | WROWS( )


MDOWN( ) Function

Included for backward compatibility. Use the Click, MouseDown, MouseUp, and RightClick events instead.


MDX( ) Function

Returns the name of the open .cdx compound index file that has the specified index position number.

MDX(nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nIndexNumber
Specifies which compound index file name to return. If the table has a structural compound index file and nIndexNumber is 1, the name of the structural compound index file (which is always the same as the name of the table) is returned. If nIndexNumber is 2, the name of the first compound index file specified with USE or SET INDEX is returned. If nIndexNumber is 3, the second compound index file name is returned, and so on. If nIndexNumber is greater than the number of open compound index files, an empty string is returned.

If the table doesn't have a structural compound index file and nIndexNumber is 1, the name of the first compound index file specified with USE or SET INDEX is returned. If nIndexNumber is 2, the second compound index file name is returned, and so on. If nIndexNumber is greater than the number of open compound index files, an empty string is returned.

nWorkArea
Specifies the work area number for compound index files open in work areas other than the current one. If you omit this optional argument, names of compound index files are returned for the current work area.
cTableAlias
Specifies the table alias for compound index files open in work areas other than the current one. If you omit this optional argument, names of compound index files are returned for the current work area.

Remarks

MDX( ) is identical to CDX( ).

Index files can be opened for a table with the INDEX clause of the USE command or with SET INDEX. A structural compound index file is automatically opened with its table. MDX( ) ignores any .idx index files specified with USE or with SET INDEX.

Use TAG( ) to return tag names from a compound index file; use NDX( ) to return the name of an open .idx index file.

In Visual FoxPro for Windows, when SET FULLPATH is ON, MDX( ) returns the path to the .cdx file with the .cdx file name. When SET FULLPATH is OFF, MDX( ) returns the drive the .cdx file resides on with the .cdx file name.

See Also

CDX( ) | INDEX | NDX( ) | SET INDEX | SET FULLPATH | SYS(14) - Index Expression | TAG( ) | USE


MDY( ) Function

Returns the specified date or datetime expression in month-day-year format with the name of the month spelled out.

MDY(dExpression | tExpression)

Return Values

Character

Parameters

dExpression
Specifies the date expression to return in month-day-year format.
tExpression
Specifies the datetime expression to return in month-day-year format.

Remarks

If SET CENTURY is OFF, the character expression is returned in a month dd, yy format. If SET CENTURY is ON, the format is month dd, yyyy.

Example

The following example creates a user-defined function that returns a date with the corresponding weekday.

SET CENTURY OFF

CLEAR
? Longdate({^1998-02-16})  && Displays Monday, February 16, 98

SET CENTURY ON
? Longdate({^1998-02-16})  && Displays Monday, February 16, 1998

*** LongDate ***

FUNCTION longdate
PARAMETERS gdDate
RETURN CDOW(gdDate) + ', ' + MDY(gdDate)

See Also

DMY( ) | SET CENTURY | SET DATE


MEMLINES( ) Function

Returns the number of lines in a memo field.

MEMLINES(MemoFieldName)

Return Values

Numeric

Parameters

MemoFieldName
Specifies the name of the memo field. If the memo field is in a table that isn't open in the current work area, preface the memo field name with the table alias and a period.

Remarks

The number of lines in a memo field is determined by the current value of SET MEMOWIDTH.

Example

The following example scans three records in the employee table and uses MEMLINES( ) to determine whether or not there is data in the notes memo field and when page breaks should occur. The last_name data for the record appears, along with the notes (if there is data in the memo field) or a message indicating that there are no notes for that record.

CLOSE DATABASES
CLEAR
SET TALK OFF
CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE employee  && Open Employee table

SET MEMOWIDTH TO 65
gnLine = 1
GOTO 2
SCAN NEXT 3
   gnMemoSize = MEMLINES(notes)
   IF gnMemoSize = 0
      STORE .T. TO glNoMemo
      STORE 1 TO gnMemoSize
   ELSE
      STORE .F. TO glNoMemo
   ENDIF
   IF gnLine + gnMemoSize > 65
      EJECT
      gnLine = 1
   ENDIF
   @ gnLine,2 SAY 'Last Name: '+ last_name
   gnLine = gnLine +1
   @ gnLine ,2 SAY 'Notes: '
   ?? IIF(glNoMemo, 'No notes ',notes)
   gnLine = gnLine + gnMemoSize + 2
   IF gnLine > 24
      gnLine = 1
      CLEAR
   ENDIF
ENDSCAN

See Also

_MLINE | ALINES( ) | ATCLINE( ) | ATLINE( ) | COPY MEMO | MLINE( ) | MODIFY MEMO | SCATTER | SET MEMOWIDTH


MEMORY( ) Function

Returns the amount of memory available to run an external program.

MEMORY( )

Return Values

Numeric

Remarks

In Visual FoxPro, MEMORY( ) always returns 640.

MEMORY( ) is similar to SYS(12), with two exceptions:

  • MEMORY( ) returns the amount of available memory in kilobytes; SYS(12) returns the amount of memory in bytes.
  • MEMORY( ) returns a numeric expression. SYS(12) returns its value as a character string.

See Also

SYS(12) - Available Memory in Bytes | SYS(1001) - Visual FoxPro Memory


MENU( ) Function

Returns the name of the active menu bar as an uppercase character string.

MENU( )

Return Values

Character

Remarks

MENU( ) returns an empty string if no menu is active. Use the Menu Designer to create a menu and activate it.

Example

The following example uses MENU( ) to pass the name of a menu bar to a procedure. The current system menu bar is saved to memory with SET SYSMENU SAVE, and all system menu titles are removed with SET SYSMENU TO.

Several system menu titles are created with DEFINE PAD. When you choose a menu title, MENU( ) passes the name of the Microsoft Visual FoxPro system menu bar, _MSYSMENU, to the choice procedure. The choice procedure displays the name of the menu title you chose and the name of the system menu bar. If you choose the Exit menu, the original Visual FoxPro system menu is restored.

*** Save this program as MENUEXAM.PRG in the default VFP directory.***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD padSys OF _MSYSMENU PROMPT '\<System' COLOR SCHEME 3 ;
   KEY ALT+S, ''
DEFINE PAD padEdit OF _MSYSMENU PROMPT '\<Edit' COLOR SCHEME 3 ;
   KEY ALT+E, ''
DEFINE PAD padRecord OF _MSYSMENU PROMPT '\<Record' COLOR SCHEME 3 ;
   KEY ALT+R, ''
DEFINE PAD padWindow OF _MSYSMENU PROMPT '\<Window' COLOR SCHEME 3 ;
   KEY ALT+W, ''
DEFINE PAD padReport OF _MSYSMENU PROMPT 'Re\<ports' COLOR SCHEME 3 KEY ALT+P, ''
DEFINE PAD padExit OF _MSYSMENU PROMPT 'E\<xit' COLOR SCHEME 3 ;
   KEY ALT+X, ''
ON SELECTION MENU _MSYSMENU ;
   DO choice IN menuexam WITH PAD(), MENU()
PROCEDURE choice
PARAMETER gcPad, gcMenu
WAIT WINDOW 'You chose ' + gcPad + ;
   ' from menu ' + gcMenu NOWAIT
IF gcPad = 'PADEXIT'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

ACTIVATE MENU | CREATE MENU | DEFINE MENU


MESSAGE( ) Function

Returns either the current error message as a character string or the contents of the program line that caused the error.

MESSAGE([1])

Return Values

Character

Parameters

1
If MESSAGE( ) is used in an ON ERROR routine, include this argument to return the program source code that caused the error. If the program source code is not available, MESSAGE(1) returns one of the following:
  • The entire program line if the line is macro substituted.
  • A command if the line contains a command without any additional clauses.
  • A command followed by three dots (...) if the line contains a command and additional clauses.

Remarks

Unlike ERROR( ), MESSAGE( ) is not reset by RETURN or RETRY.

Example

The following example displays output from MESSAGE( ) and MESSAGE(1).

ON ERROR DO Errhand

*** The next line should generate an error ***

USE Nodatabase
ON ERROR     && restore system error handler
PROCEDURE Errhand
? 'Line of code with error: ' + MESSAGE(1)
? 'Error number: ' + STR(ERROR( ))
? 'Error message: ' + MESSAGE( )

See Also

ERROR Command | ERROR( ) | ON ERROR | AERROR( ) Function | Error Messages A-Z | Error Messages by Number


MESSAGEBOX( ) Function

Displays a user-defined dialog box.

MESSAGEBOX(eMessageText [, nDialogBoxType ][, cTitleBarText][, nTimeout])

Parameters

eMessageText
Specifies the text that appears in the dialog box.

You can use any valid Visual FoxPro function, object, or data type instead of eMessageText. If the function you use evaluates to a noncharacter value, Visual FoxPro automatically uses the TRANSFORM( ) function to provide the character equivalent. In the following example, a character type date is returned and passed to MESSAGEBOX( ):

MESSAGEBOX(DATE())

To move a portion of the message to the next line in the dialog box, use a carriage return, CHR(13), in eMessageText. The height and width of the dialog box increases as needed to contain cMessageText.

nDialogBoxType
Specifies the buttons and icons that appear in the dialog box, the default button when the dialog box is displayed, and the behavior of the dialog box.

In the following tables, the dialog box button values 0 to 5 specify the buttons that appear in the dialog box. The icon values 16, 32, 48, and 64 specify the icon that appears in the dialog box. The default values 0, 256, and 512 specify which button in the dialog box is the default button. The default button is selected when the dialog box is displayed. Omitting nDialogBoxType is identical to specifying a value of 0 for nDialogBoxType.

Value | Dialog box buttons
0 | OK button only
1 | OK and Cancel buttons
2 | Abort, Retry, and Ignore buttons
3 | Yes, No, and Cancel buttons
4 | Yes and No buttons
5 | Retry and Cancel buttons
Value | Icon
16 | Stop sign
32 | Question mark
48 | Exclamation point
64 | Information (i) icon
Value | Default button
0 | First button
256 | Second button
512 | Third button

nDialogBoxType can be the sum of up to three values, one value from each of the preceding tables. For example, if nDialogBoxType is 290 (2+32+256), the specified dialog box has the following characteristics:

  • Abort, Retry, and Ignore buttons.
  • The message box displays the question mark icon.
  • The second button, Retry, is the default.

Additional information about the constants is available in the FoxPro.h file, located in the Visual FoxPro home directory. Using defined constants such as MB_ABORTRETRYIGNORE + MB_ICONQUESTION + MB_DEFBUTTON2 can be more readable than 2 + 32 + 256.

cTitleBarText
Specifies the text that appears in the title bar of the dialog box. If you omit cTitleBarText, the title "Microsoft Visual FoxPro" appears in the title bar.
nTimeout
Specifies the number of milliseconds Visual FoxPro displays cMessageText without input from the keyboard or the mouse before clearing cMessageText. You can specify any valid timeout value. A value of less than 1 never times out until user enters input and behaves the same as omitting the nTimeout parameter.

Return Values

Numeric data type. MESSAGEBOX( ) returns a value that indicates which button was chosen in the dialog box. The following table lists the values MESSAGEBOX( ) returns for each button.

Return value | Button
1 | OK
2 | Cancel
3 | Abort
4 | Retry
5 | Ignore
6 | Yes
7 | No

In dialog boxes with a Cancel button, pressing ESC to exit the dialog box returns the same value (2) as choosing Cancel.

MESSAGEBOX( ) returns a value of -1 when a timeout occurs.

Remarks

The shortest abbreviation for MESSAGEBOX( ) is MESSAGEB( ).

The MESSAGEBOX( ) function uses smart parameters in that the parameter type determines which parameter is used. The first parameter is required and is always cMessageText. However, the optional second parameter can be nDialogBoxType if the type is Numeric or cTitleBarText if type is Character. The nTimeout parameter is always assumed for the second optional numeric parameter passed. Valid examples include:

   MESSAGEBOX("HELLO","MyTitle",36,1)
   MESSAGEBOX("HELLO",36,"MyTitle",1)
   MESSAGEBOX("HELLO",36,1)
   MESSAGEBOX("HELLO",36,1,"MyTitle")

Example

The following example displays a user-defined dialog box. The message "Record not found. Would you like to search again?" is displayed as the caption in the user-defined dialog box, and "My Application" is displayed in the title bar.

The user-defined dialog box contains Yes and No buttons and the question mark icon, and the second button (No) is the default button. When you choose one of the buttons, your choice is displayed.

cMessageTitle = 'My Application'
cMessageText = 'Record not found. Would you like to search again?'
nDialogType = 4 + 32 + 256
*  4 = Yes and No buttons
*  32 = Question mark icon
*  256 = Second button is default

nAnswer = MESSAGEBOX(cMessageText, nDialogType, cMessageTitle)

DO CASE
   CASE nAnswer = 6
      WAIT WINDOW 'You chose Yes'
   CASE nAnswer = 7
      WAIT WINDOW 'You chose No'
ENDCASE

See Also

WAIT | DO CASE ... ENDCASE Command | InputBox( ) Function | TRANSFORM( ) Function


MIN( ) Function

Evaluates a set of expressions and returns the expression with the minimum value.

MIN(eExpression1, eExpression2 [, eExpression3 ...])

Return Values

Character, Numeric, Currency, Double, Float, Date, or DateTime

Parameters

eExpression1, eExpression2 [, eExpression3 ...]
Specify the set of expressions from which you want MIN( ) to return the expression with the lowest value. All the expressions must be of the same type.

Example

The following example uses APPEND BLANK to create a table with 10 records containing random values, then uses MIN( ) and MAX( ) to display the maximum and minimum values in the table.

CLOSE DATABASES
CREATE TABLE Random (cValue N(3))
FOR nItem = 1 TO 10  && Append 10 records,
   APPEND BLANK
   REPLACE cValue WITH 1 + 100 * RAND( )  && Insert random values
ENDFOR

CLEAR
LIST  && Display the values
gnMaximum = 1  && Initialize minimum value
gnMinimum = 100  && Initialize maximum value
SCAN
   gnMinimum = MIN(gnMinimum, cValue)
   gnMaximum = MAX(gnMaximum, cValue)
ENDSCAN
? 'The minimum value is: ', gnMinimum  && Display minimum value
? 'The maximum value is: ', gnMaximum  && Display maximum value

See Also

CALCULATE | MAX( )


MINUTE( ) Function

Returns the minute portion from a DateTime expression.

MINUTE(tExpression)

Return Values

Numeric

Parameters

tExpression
Specifies the DateTime expression from which the minute portion is returned.

Example

The following example displays the minute portion of the current time and the minute portion of a specific time.

CLEAR
? MINUTE(DATETIME( ))
? MINUTE({^1998-02-16 10:42a})  && Displays 42

See Also

CTOT( ) | DATE( ) | DATETIME( ) | DTOT( ) | HOUR( ) | SEC( ) | SECONDS( ) | SET SECONDS | TIME( )


MLINE( ) Function

Returns a specific line from a memo field as a character string.

MLINE(MemoFieldName, nLineNumber [, nNumberOfCharacters])

Return Values

Character

Parameters

MemoFieldName
Specifies the name of the memo field from which MLINE( ) returns a line. If the memo field is in a table open in a noncurrent work area, preface the memo field name with a period and the table alias.
nLineNumber
Specifies the number of the line to be returned from the memo field. An empty string is returned if nLineNumber is negative, 0, or greater than the number of lines in the memo field.
nNumberOfCharacters
Specifies the number of characters from the beginning of the memo field after which MLINE( ) returns the specified line.

The _MLINE system variable is typically used for nNumberOfCharacters. _MLINE is automatically adjusted each time MLINE( ) is called.

In recursive procedures that return lines from large memo fields, you can obtain the best performance by including _MLINE as nNumberOfCharacters.

Remarks

MLINE( ) trims any trailing spaces from the line specified with nLineNumber.

The length and number of the lines in a memo field are determined by the current value of SET MEMOWIDTH (the default line length is 50 characters). If a carriage return is encountered, no additional characters are returned. The current _WRAP setting determines how the memo field line is displayed.

When searching a memo field for a character string, you can use ATLINE( ) or ATCLINE( ) to return the line number of the line in which the character string is found. Use this line number in MLINE( ) to return the contents of the line from the memo field.

Example

In the following example, two methods are used to return lines from a memo field. Two loops use MLINE( ) to return lines from the memo field. Note the improvement in performance in the second loop when the system variable _MLINE is used in MLINE( ).

CLEAR
SET TALK OFF
SET MEMOWIDTH TO 50
CLOSE DATABASES
CREATE TABLE tmemo (name c(10), notes m)
APPEND BLANK                  && Add a record
WAIT WINDOW 'Filling memo field - takes several seconds' NOWAIT
*** Fill the memo field  ***
FOR gnOuterLoop = 1 TO 5         && loop 5 times
   FOR gnAlphabet = 65 TO 75   && letters A to H
      REPLACE notes WITH REPLICATE(CHR(gnAlphabet), 10) ;
         + CHR(13) ADDITIVE
   NEXT
NEXT

*** Display all lines from the memo field ***

STORE MEMLINES(notes) TO gnNumLines   && Number of lines in memo field
STORE SECONDS( ) TO gnBegin      && Beginning time
FOR gnCount = 1 TO gnNumLines   && Loop for # of lines in memo field
   ? MLINE(notes, gnCount)      && Display each line
NEXT
? STR(SECONDS( ) - gnBegin, 4, 2) + ' seconds'   && Total time

*** Preferable method using _MLINE in MLINE( ) ***
*** Display all lines from the memo field ***

WAIT 'Press a key to see the preferred method' WINDOW
CLEAR
STORE 0 TO _MLINE             && Reset _MLINE to zero
STORE SECONDS( ) TO gnBegin      && Beginning time
FOR count = 1 TO gnNumLines      && Loop for # of lines in memo field
   ? MLINE(notes, 1, _MLINE)      && Display each line
NEXT
? STR(SECONDS( ) - gnBegin, 4, 2) + ' seconds'   && Total time
SET TALK ON
CLOSE DATABASES
ERASE tmemo.dbf
ERASE tmemo.fpt

See Also

ALINES( ) | ATCLINE( ) | ATLINE( ) | COPY MEMO | MEMLINES( ) | _MLINE | MODIFY MEMO | SET MEMOWIDTH | _WRAP


MOD( ) Function

Divides one numeric expression by another numeric expression and returns the remainder.

MOD(nDividend, nDivisor)

Return Values

Numeric

Parameters

nDividend
Specifies the dividend. The number of decimal places in nDividend determines the number of decimal places in the return value.
nDivisor
Specifies the divisor. A positive number is returned if nDivisor is positive, and a negative number is returned if nDivisor is negative.

Remarks

The modulus function MOD( ) and the % operator return identical results.

Example

CLEAR
? MOD(36,10)  && Displays 6
? MOD((4*9), (90/9))  && Displays 6
? MOD(25.250,5.0)  && Displays 0.250
? IIF(MOD(YEAR(DATE( )), 4) = 0, 'Summer Olympics this year';
   , 'No Summer Olympics this year')

See Also

% Operator


MONTH( ) Function

Returns the number of the month for a given Date or DateTime expression.

MONTH(dExpression | tExpression)

Return Values

Numeric

Parameters

dExpression
Specifies the Date expression for which you want MONTH( ) to return the month number.
tExpression
Specifies the DateTime expression for which you want MONTH( ) to return the month number.

Remarks

MONTH( ) returns a number from 1 through 12. January is month 1, and December is month 12.

Example

CLEAR
? DATE( )  && Displays today's date
? MONTH(DATE( ))  && Displays the month number
STORE {^1998-05-03} TO gdBuy
STORE MONTH(gdBuy + 31) TO gdMonth
? gdMonth  && Displays 6

See Also

CMONTH( ) | DAY( ) | QUARTER( ) | YEAR( )


MRKBAR( ) Function

Determines whether a menu item on a user-defined or Microsoft Visual FoxPro system menu is marked.

MRKBAR(cMenuName, nMenuItemNumber | cSystemMenuItemName)

Return Values

Logical

Parameters

cMenuName
Specifies the name of the menu containing the menu item. The menu can be a Visual FoxPro system menu (such as _MFILE, MEDIT, or _MDATA).
nMenuItemNumber
Specifies the number of a menu item in a user-defined menu. A menu item's number is specified when the menu item is created with DEFINE BAR.
cSystemMenuItemName
Specifies the name of a Visual FoxPro system menu item. For example, the following command displays a logical value specifying if the New menu item on the File menu is marked.
? MRKBAR('_MFILE', _MFI_NEW)

Remarks

Use SET MARK OF to mark or unmark a menu item.

If the specified menu item is marked, MRKBAR( ) returns true (.T.); otherwise, MRKBAR( ) returns false (.F.).

For an example of using MRKBAR( ), see CNTBAR( ).

See Also

MRKPAD( ) | SET MARK OF | SET MARK TO


MRKPAD( ) Function

Determines whether a menu title on a user-defined menu bar or on the Visual FoxPro system menu bar is marked.

MRKPAD(cMenuBarName, cMenuTitleName)

Return Values

Logical

Parameters

cMenuBarName
Specifies the name of the menu bar containing the menu title.
cMenuTitleName
Specifies the name of the menu title.

Remarks

Use SET MARK OF to mark or unmark a menu title.

If the specified menu title is marked, MRKPAD( ) returns true (.T.); otherwise, MRKPAD( ) returns false (.F.).

Example

The following program example, named MARKPAD.PRG, uses MRKPAD( ) to toggle the mark character of a menu title when you choose it.

The current system menu bar is first saved to memory with SET SYSMENU SAVE, and all the system menu items are removed with SET SYSMENU TO.

Several system menu items are created with DEFINE PAD. When you choose a menu item, the choice procedure is executed. choice displays the name of the menu item you choose and the name of the menu bar. SET MARK OF is used with MRKPAD( ) to display or remove the menu item's mark character. If you choose the Exit menu, the original Visual FoxPro system menu is restored.

*** Name this program MARKPAD.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
SET MARK OF MENU _MSYSMENU TO CHR(4)
PUBLIC glMarkPad
glMarkPad = .T.
DEFINE PAD padSys OF _MSYSMENU PROMPT '\<System'  COLOR SCHEME 3 ;
   KEY ALT+S, ''
DEFINE PAD padEdit OF _MSYSMENU PROMPT '\<Edit'  COLOR SCHEME 3 ;
   KEY ALT+E, ''
DEFINE PAD padRecord OF _MSYSMENU PROMPT '\<Record'  COLOR SCHEME 3 ;
   KEY ALT+R, ''
DEFINE PAD padWindow OF _MSYSMENU PROMPT '\<Window'  COLOR SCHEME 3 KEY ALT+W, ''
DEFINE PAD padReport OF _MSYSMENU PROMPT 'Re\<ports' COLOR SCHEME 3 ;
   KEY ALT+P, ''
DEFINE PAD padExit OF _MSYSMENU PROMPT 'E\<xit'  COLOR SCHEME 3 ;
   KEY ALT+X, ''
ON SELECTION MENU _MSYSMENU ;
   DO choice IN markpad WITH PAD( ), MENU( )

PROCEDURE choice
PARAMETER gcPad, gcMenu
WAIT WINDOW 'You chose ' + gcPad + ;
   ' from menu ' + gcMenu NOWAIT
SET MARK OF PAD (gcPad) OF _MSYSMENU TO ;
   ! MRKPAD('_MSYSMENU', gcPad)
glMarkPad= ! glMarkPad
IF gcPad = 'PADEXIT'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

MRKBAR( ) | SET MARK OF


MROW( ) Function

Returns the row position of the mouse pointer in the main Visual FoxPro window or in a user-defined window.

MROW([cWindowName [, nScaleMode]])

Return Values

Numeric

Parameters

cWindowName
Specifies the name of a window whose mouse-pointer row position MROW( ) returns.
nScaleMode
Specifies the unit of measurement for the value MROW( ) returns. The settings for nScaleMode are:
nScaleMode | Description
0 | (Default) Foxels. A foxel is equivalent to the average height and width of a character based on the current font of the form in which an object is contained. Foxels are useful in developing cross-platform applications for character-based and graphical platforms.
3 | Pixels. A pixel is the smallest element that can be displayed on a screen or printer. Pixels are screen-dependent.

Remarks

MROW( ) returns the main Visual FoxPro window row position of the mouse pointer if there is no active user-defined window and you omit the optional argument.

MROW( ) returns the mouse-pointer row coordinate relative to the active user-defined window if there is an active user-defined window and you omit the optional argument. MROW( ) returns a value of –1 if the mouse pointer is positioned outside the user-defined window or if no mouse driver is loaded and there is no output window.

Using the MROW( ) function without an optional argument may affect the behavior of code on forms with the AllowOutput property set to False (.F.). For example, the placement of a shortcut menu that is defined in the RightClick event, may not be displayed in the proper location, if you use the MROW( ) function to determine where the menu is displayed.

See Also

AMOUSEOBJ( ) | COL( ) | GridHitTest Method | ISMOUSE( ) | MCOL( ) | ROW( ) | WCOLS( ) | WROWS( )


MTON( ) Function

Returns a Numeric value from a Currency expression.

MTON(mExpression)

Return Values

Numeric

Parameters

mExpression
Specifies a Currency expression whose value MTON( ) returns. mExpression must evaluate to a valid Currency value or Visual FoxPro generates an error.

Currency values are created by placing a dollar sign ($) prefix immediately before a Numeric value.

Remarks

MTON( ) returns a Numeric value with four decimal places.

Example

The following example creates a currency type variable named gyMoney. TYPE( ) displays Y, indicating the variable is a currency type. MTON( ) is used to convert the variable to a numeric type, and TYPE( ) now displays N, indicating the variable is a numeric type after the conversion.

STORE $24.95 TO gyMoney  && Creates a currency type memory variable
CLEAR
? "gyMoney is type: "
?? TYPE('gyMoney')  && Displays Y, currency type value

gyMoney = MTON(gyMoney)     &&  Converts gyMoney to a numeric value
? "gyMoney is now type: "
?? TYPE('gyMoney')  && Displays N, numeric type value

See Also

NTOM( ) | TYPE( ) Function


MWINDOW( ) Function

Returns the name of the window over which the mouse pointer is positioned.

MWINDOW([cWindowName])

Return Values

Character, Logical

Parameters

cWindowName
Specifies a window name. If the mouse pointer is positioned over the specified window, MWINDOW( ) returns true (.T.); otherwise, MWINDOW( ) returns false (.F.).

Remarks

If you omit the optional window name, MWINDOW( ) returns the name of the window over which the mouse pointer is positioned, or an empty string if the mouse pointer is positioned over the main Visual FoxPro window or over any other window that is not part of Visual FoxPro.

See Also

MCOL( ) | MDOWN( ) | MROW( ) | WONTOP( ) | WOUTPUT( )


NDX( ) Function

Returns the name of an open index (.IDX) file for the current or specified table.

NDX(nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nIndexNumber
Specifies which .idx file name to return. USE and SET INDEX both support an index file list that makes it possible for you to open .idx files for a table. The order of the file names in this index file list determines which .idx file name NDX( ) returns. For example, if nIndexNumber is 1, NDX( ) returns the name of the first .idx file in the index file list; if nIndexNumber is 2, NDX( ) returns the second .idx file name, and so on. NDX( ) ignores names of compound index (.cdx) files in the index file list.

NDX( ) returns an empty string if nIndexNumber is greater than the number of .idx files in the index file list.

nWorkArea
Specifies the work area number for .IDX files open in a work area other than the current one. NDX( ) returns an empty string if no table is open in the work area you specify. If you omit nWorkArea, NDX( ) returns the names of .idx files open with the table in the current work area.
cTableAlias
Specifies the table alias for .idx files open in a work area other than the current one. If no table has the alias you include, Visual FoxPro generates an error message. If you omit cTableAlias, NDX( ) returns the names of .idx files open with the table in the current work area.

Remarks

The CDX( ) and MDX( ) functions can be used to return the names of open compound (.cdx) index files.

In Visual FoxPro for Windows, when SET FULLPATH is ON, NDX( ) returns the path to the .idx file with the .idx file name. When SET FULLPATH is OFF, NDX( ) returns the drive the .idx file resides on with the .idx file name.

See Also

CDX( ) | INDEX | MDX( ) | SET FULLPATH | SET INDEX | SYS(14) - Index Expression | TAG( ) | USE


NEWOBJECT( ) Function

Creates a new class or object directly from a visual class library (.vcx) file or program (.prg) file without opening the file.

NEWOBJECT(cClassName [, cModule [, cInApplication
   [, eParameter1, eParameter2, ...]]])

Parameters

cClassName
Specifies the class or object from which the new class or object is created.
cModule
Specifies a .vcx file or Visual FoxPro program (.prg, .mpr, .app, .exe, and so on) containing the class or object specified with cClassName. The default is a .vcx file. If you specify a program file, you must include an extension.
Note A class library can have an alias. To specify a class or object from a class library with an alias, include the class library alias followed by a period and the object name.

If cModule is omitted, or is the empty string or the null value, Visual FoxPro searches for the class or object in the following order:

  • Visual FoxPro base classes
  • Classes in the current program
  • Class libraries opened with SET CLASSLIB
  • Classes in procedure files opened with SET PROCEDURE
  • Classes in the Visual FoxPro program execution chain
  • The OLE registry if SET OLEOBJECT is ON
cInApplication
Specifies the Visual FoxPro application (.exe or .app) containing the .vcx file you specify with cModule. You must include an extension for the application. CInApplication is ignored if cModule is omitted, or if cInApplication is the empty string or the null value.

If you want to use the cInApplication parameter, you must specify the name of .vcx file for cModule. You cannot pass the name of a .prg file or compiled program (.fxp).

eParameter1, eParameter2, ...
Specifies optional parameters that are passed to the Init event procedure for the class or object.

Return Values

Object

Remarks

To assign the object reference returned by NEWOBJECT( ) to a variable or array element, use the equal sign (=) or STORE command. If an object assigned to a variable or array element is released, the variable or array element contains the null value. To remove the variable or array element from memory, use the RELEASE command.

For NEWOBJECT( ), Visual FoxPro performs an internal SET CLASSLIB or SET PROCEDURE for the second or third parameters using the ADDITIVE clause where the parameters are first used to determine the search order. If these parameters already exist in the SET CLASSLIB or SET PROCEDURE list, Visual FoxPro rearranges the order in the list so they come first. Visual FoxPro then locates all the classes, creates the object, and calls the Init events. Finally, Visual FoxPro restores the original SET CLASSLIB or SET PROCEDURE list if the installation did not change list.

OLE objects are created with the following syntax for cClassName:

ApplicationName.Class

For example, to create a Microsoft Excel worksheet, which supports Automation, use the following syntax:

oExcelSheet = NEWOBJECT('Excel.Sheet')

See Also

Class Designer | CREATE CLASS | CREATE CLASSLIB | CREATEOBJECT( ) | DEFINE CLASS | NewObject Method


NORMALIZE( ) Function

Converts a character expression, supplied by a user, into a form that can be compared with Visual FoxPro function return values.

NORMALIZE(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression to normalize.

Remarks

NORMALIZE( ) returns a character string from the character expression cExpression with the following changes:

  • The character expression is converted to uppercase. However, embedded strings are not changed. An example of an embedded string is "Hello" in the character expression "LEFT('Hello',1)".
  • Any abbreviated Visual FoxPro keywords in the character expression are expanded to their full length.
  • Any -> operators separating aliases from field names are converted to periods.
  • The syntax of any Visual FoxPro commands or functions within the character expression is checked, although the expression is not evaluated. If the syntax is incorrect, Visual FoxPro generates a syntax error. NORMALIZE( ) does not check for the existence of any fields, tables, memory variables, user-defined functions, or other references in the character expression.

For example, a user may enter an index expression like the following in the Expression Builder:

UPPE(cust->lname) + UPPE(cust->fname)

While this is a valid Visual FoxPro index key expression, it's difficult to compare this to the return values from a Visual FoxPro function like KEY( ). NORMALIZE( ) returns the following character string for the expression above:

UPPER(CUST.LNAME) + UPPER(CUST.FNAME)

This can be easily compared to the value returned by a function like KEY( ), making it possible for you, in this example, to determine if an index or index tag with the user-supplied index expression already exists.

See Also

EVALUATE( ) | ISUPPER( ) | PROPER( ) | UPPER( )


NTOM( ) Function

Returns a Currency value with four decimal places from a numeric expression.

NTOM(nExpression)

Return Values

Currency

Parameters

nExpression
Specifies a numeric expression whose Currency value NTOM( ) returns. If nExpression has more than four decimal places, it is rounded to four decimal places. If nExpression has less than four decimals places, it is padded with zeros until four decimal places are created.

Example

The following example creates a numeric type variable named gnNumeric. TYPE( ) displays N, indicating the variable is a numeric type. NTOM( ) is used to convert the variable to a currency type, and TYPE( ) now displays Y, indicating the variable is a currency type after the conversion.

STORE 24.95 TO gnNumeric  && Creates a numeric type memory variable
CLEAR
? "gnNumeric is type: "
?? TYPE('gnNumeric')  && Displays N, numeric type value

gnNumeric= NTOM(gnNumeric)     &&  Converts gnNumeric to a currency value
? "gnNumeric is now type: "
?? TYPE('gnNumeric')  && Displays Y, currency type value

See Also

MTON( ) | TYPE( ) Function


NUMLOCK( ) Function

Returns the current mode of the NUM LOCK key or sets the mode of the NUM LOCK key on or off.

NUMLOCK([lExpression])

Return Values

Logical

Parameters

lExpression
Turns the NUM LOCK key on or off. If lExpression is true (.T.), the NUM LOCK key is turned on; if lExpression is false (.F.), the NUM LOCK key is turned off. NUMLOCK( ) returns a logical value corresponding to the NUM LOCK key setting before NUMLOCK(.T.) or NUMLOCK(.F.) is issued.

Remarks

NUMLOCK( ) returns true (.T.) if the NUM LOCK key is on (pressing a key on the numeric keypad returns a number), or false (.F.) if NUM LOCK is off (pressing a key on the numeric keypad moves the cursor).

Example

In the following example, the equal sign (=) is used to execute NUMLOCK( ) without returning a value.

gcOldLock = NUMLOCK( )  && Save original setting
WAIT WINDOW 'Press a key to turn Num Lock on'
= NUMLOCK(.T.)  && Turn Num Lock on
WAIT WINDOW 'Press a key to turn Num Lock off'
= NUMLOCK(!NUMLOCK( ))  && Toggle Num Lock to the opposite value
WAIT WINDOW 'Press a key to restore original Num Lock setting'
= NUMLOCK(gcOldLock)     && Return to original setting

See Also

CAPSLOCK( ) | INSMODE( )


NVL( ) Function

Returns a non-null value from two expressions.

NVL(eExpression1, eExpression2)

Return Values

Character, Date, DateTime, Numeric, Currency, Logical, or the null value

Parameters

eExpression1, eExpression2
NVL( ) returns eExpression2 if eExpression1 evaluates to a null value. NVL( ) returns eExpression1 if eExpression1 is not a null value. eExpression1 and eExpression2 may be any data type. NVL( ) returns .NULL. if both eExpression1 and eExpression2 both evaluate to the null value.

Remarks

Use NVL( ) to remove null values from calculations or operations where null values are not supported or are not relevant.

Example

The following example creates a memory variable named glMyNull that contains the null value. NVL( ) is used to return a non-null value from glMyNull and another expression.

STORE .NULL. TO glMyNull  && A memory variable containing the null value
CLEAR
? NVL(.T., glMyNull)  && Displays .T.
? NVL(glMyNull, glMyNull)  && Displays .NULL.

See Also

ISNULL( ) | SET NULL


OBJNUM( ) Function

Included for backward compatibility. Use the TabIndex property for controls instead.


OBJTOCLIENT( ) Function

Returns a position or dimension of a control or object relative to its form.

OBJTOCLIENT(ObjectName, nPosition)

Return Values

Numeric

Parameters

ObjectName
Specifies the name of the control or object for which the form position is returned.
nPosition
Specifies which form position or dimension of the control or object is returned. The following table lists the values for nPosition and the corresponding position or dimension returned.
nPosition | Position or dimension
1 | Top
2 | Left
3 | Width
4 | Height

Remarks

OBJTOCLIENT( ) returns the position or dimension of a control or object relative to the client area of the form on which it resides. For example, a control or object can be placed on a page in a page frame, and the page frame is placed on a form. The Top, Left, Width, and Height properties return the position or dimension of a control or object relative to the page on which it is placed. However, you can use OBJTOCLIENT( ) to determine the position or dimension of a control or object relative to the form on which the page is placed.

The value returned by OBJTOCLIENT( ) is in pixels.

Example

The following example uses OBJTOCLIENT( ) to display the positions and dimensions of two check boxes relative to the form they're placed on. The Top, Left, Width, and Height properties are also used to display the positions and dimensions of the two check boxes relative to the page frame on which they're placed.

A command button and a page frame are placed on a form. The PageCount property is used to specify the number of pages on the page frame. The Tabs property is set to true (.T.) to specify that the page frame has tabs for each page. Check boxes are placed on each page in different positions.

When a check box is clicked, the Click procedure for the check box is executed. If the check box is checked, the Top, Left, Width, and Height properties are used to display the positions and dimensions of the check box relative to the page frame, and OBJTOCLIENT( ) is used to display the positions and dimensions of the check box relative to the form. If the check box is unchecked, the main Microsoft Visual FoxPro window is cleared.

CLEAR
STORE _DBLCLICK TO gnDblClick  && Save double-click value
STORE 0.05 TO _DBLCLICK  && Make double-click unlikely

frmMyForm = CREATEOBJECT('Form')  && Create a form
frmMyForm.Closable = .f.  && Disable the window pop-up menu

frmMyForm.Move(150,10)  && Move the form

frmMyForm.AddObject('cmbCommand1','cmdMyCmdBtn')  && Add Command button
frmMyForm.AddObject('pgfPageFrame1','pgfMyPageFrame')  && Add PageFrame
frmMyForm.pgfPageFrame1.Page1.AddObject('chkCheckBox1','chkMyCheckBox1')
frmMyForm.pgfPageFrame1.Page2.AddObject('chkCheckBox2','chkMyCheckBox2')

frmMyForm.cmbCommand1.Visible =.T.  && "Quit" Command button visible
frmMyForm.pgfPageFrame1.Visible =.T.  && PageFrame visible
frmMyForm.pgfPageFrame1.Page1.chkCheckBox1.Visible =.T.
frmMyForm.pgfPageFrame1.Page2.chkCheckBox2.Visible =.T.

frmMyForm.SHOW  && Display the form
READ EVENTS  && Start event processing

DEFINE CLASS cmdMyCmdBtn AS CommandButton  && Create Command button
   Caption = '\<Quit'  && Caption on the Command button
   Cancel = .T.  && Default Cancel Command button (Esc)
   Left = 125  && Command button column
   Top = 210  && Command button row
   Height = 25  && Command button height

   PROCEDURE Click
      CLEAR EVENTS  && Stop event processing, close Form
      CLEAR  && Clear main Visual FoxPro window
      STORE gnDblClick TO _DBLCLICK  && Restore double-click value
ENDDEFINE

DEFINE CLASS pgfMyPageFrame AS PageFrame  && Create PageFrame
   Left = 10  && PageFrame  column
   Top = 10  && PageFrame  row
   Height = 175  && PageFrame  height
   Width = 350  && PageFrame  height
   PageCount = 2  && 2 Pages on the PageFrame
   Tabs = .T.  && Tabs visible
ENDDEFINE

DEFINE CLASS chkMyCheckBox1 AS CheckBox  && Create first Check Box
   Top = 0
   Width = 200
   Caption = 'Display Position'

PROCEDURE Click
   DO CASE
      CASE ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Value = 0
         ACTIVATE SCREEN
         CLEAR
      CASE ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Value = 1
         ACTIVATE SCREEN
         CLEAR
         ? 'Positions relative'
         ? 'to PageFrame:'
         ?
         ? 'Top: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Top))
         ? 'Left: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Left))
         ? 'Width: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Width))
         ? 'Height: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1.Height))
         ?
         ? 'Positions relative'
         ? 'to Form:'
         ?
         ? 'Top: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1,1)))
         ? 'Left: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1,2)))
         ? 'Width: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page1.chkCheckBox1,3)))
         ? 'Height: '
         ?? ALLTRIM(STR(OBJTOCLIENT(ThisForm.pgfPageFrame1.Page1.chkCheckBox1,4)))
   ENDCASE
ENDDEFINE

DEFINE CLASS chkMyCheckBox2 AS CheckBox  && Create second Check Box
   Top = 30
   Left = 175
   Width = 200
   Caption = 'Display Position'

PROCEDURE CLICK
   DO CASE
      CASE ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Value = 0
         ACTIVATE SCREEN
         CLEAR
      CASE ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Value = 1
         ACTIVATE SCREEN
         CLEAR
         ? 'Positions relative'
         ? 'to PageFrame:'
         ?
         ? 'Top: '
         ?? ALLTRIM(STR(ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Top))
         ? 'Left: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Left))
         ? 'Width: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Width))
         ? 'Height: '
         ?? ALLTRIM(STR;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2.Height))

         ?
         ? 'Positions relative'
         ? 'to Form:'
         ?
         ? 'Top: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2,1)))
         ? 'Left: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2,2)))
         ? 'Width: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2,3)))
         ? 'Height: '
         ?? ALLTRIM(STR(OBJTOCLIENT;
            (ThisForm.pgfPageFrame1.Page2.chkCheckBox2,4)))
   ENDCASE
ENDDEFINE

See Also

Height Property | Left Property | Top Property | Width Property


OBJVAR( ) Function

Included for backward compatibility. Use the Name property for controls instead.


OCCURS( ) Function

Returns the number of times a character expression occurs within another character expression.

OCCURS(cSearchExpression, cExpressionSearched)

Return Values

Numeric

Parameters

cSearchExpression
Specifies a character expression that OCCURS( ) searches for within cExpressionSearched.
cExpressionSearched
Specifies the character expression OCCURS( ) searches for cSearchExpression.

Remarks

OCCURS( ) returns 0 (zero) if cSearchExpression isn't found within cExpressionSearched.

Example

STORE 'abracadabra' TO gcstring
CLEAR
? OCCURS('a', gcstring)  && Displays 5
? OCCURS('b', gcstring)  && Displays 2
? OCCURS('c', gcstring)  && Displays 1
? OCCURS('e', gcstring)  && Displays 0

See Also

$ Operator | AT( ) | ATLINE( ) | RAT( ) | RATLINE( ) | INLIST( )


OEMTOANSI( ) Function

Included for backward compatibility. Use the GETCP( ) Function instead.


OLDVAL( ) Function

Returns original field values for fields that have been modified but not updated.

OLDVAL(cExpression [, cTableAlias | nWorkArea])

Return Values

Character, Currency, Date, DateTime, Double, Float, Integer, Logical, Numeric, or Memo

Parameters

cExpression
Specifies an expression whose original value OLDVAL( ) returns from a table or a remote data source. cExpression is typically a field or an expression consisting of a set of fields from the table or remote data source.
cTableAlias
Specifies the alias of the table or cursor from which the original field values are returned.
nWorkArea
Specifies the work area of the table or cursor from which the original field values are returned.

Remarks

OLDVAL( ) returns original field values for records in a Visual FoxPro table or cursor that has row or table buffering enabled with CURSORSETPROP( ).

If a table in a database or a cursor has validation rules, OLDVAL( ) does not require that row or table buffering be enabled in order to return original field values.

If the record pointer is moved to a different record when row buffering is enabled, or if TABLEUPDATE( ) is issued to commit changes to the record, or there is some other action that causes an update, such as ending a transaction, the fields are updated and the original field values are no longer available.

The data type of the value OLDVAL( ) returns is determined by the expression you specify with cExpression.

The original field values are returned for the table or cursor open in the currently selected work area if OLDVAL( ) is issued without the optional cTableAlias or nWorkArea arguments.

Example

The following example demonstrates how you can use OLDVAL( ) to return original field value for a field in a buffered table. A table named employees is created and INSERT – SQL is used insert the value "Smith" into the cLastName field.

MULTILOCKS is set to ON, a requirement for table buffering. CURSORSETPROP( ) is used to set the buffering mode to optimistic table buffering (5).

The original value of the cLastName field (Smith) is displayed and then the cLastName field is modified with REPLACE. The new value of the cLastName field (Jones) is displayed. The original value of the cLastName field (Smith) is displayed with OLDVAL( ). TABLEUPDATE( ) is then used to commit changes to the table. The updated value of the cLastName field (Jones) is then displayed.

CLOSE DATABASES
CLEAR

* Create new table and add blank record
CREATE TABLE employee (cLastName C(10))
APPEND BLANK

* Insert initial value
INSERT INTO employee (cLastName) VALUES ("Smith")

* Enable and set table buffering
SET MULTILOCKS ON  && Allow table buffering
=CURSORSETPROP("Buffering", 5, "employee" )  && Enable table buffering

* Display initial value
=MESSAGEBOX("Original cLastName value: "+ cLastName, 0, "Results")

* Change record value and display results
REPLACE cLastName WITH "Jones"
=MESSAGEBOX("Modified cLastName value: "+ cLastName, 0, "Results")

* Store the old value of the field to cTemp variable and display results
cTemp=OLDVAL("cLastName", "employee")
=MESSAGEBOX("Original cLastName value: "+ cTemp, 0, "Results")

* Update table and display final value
=TABLEUPDATE(.T.)
=MESSAGEBOX("Final cLastName value: "+ cLastName, 0, "Results")

* Close and delete example table file
USE
DELETE FILE employee.dbf

See Also

CURVAL( ) | GETFLDSTATE( ) | TABLEREVERT( ) | TABLEUPDATE( ) | CURSORSETPROP( )


ON( ) Function

Returns the command assigned to each of these event-handling commands: ON ERROR, ON ESCAPE, ON KEY LABEL, or ON PAGE.

ON(cONCommand [, KeyLabelName])

Return Values

Character

Parameters

cONCommand
Specifies one of the event-handling commands. Here are the commands and corresponding character expressions to use with ON( ):
Command | cONCommand
ON ERROR | ERROR
ON ESCAPE | ESCAPE
ON KEY LABEL | KEY
ON PAGE | PAGE

For example, to return the command currently assigned to ON ERROR, use the following:

? ON('ERROR')
KeyLabelName
Used in ON KEY LABEL to specify a key or key combination to which the command is assigned. Specify KEY in cONCommand and the key label name of the key or key combination in KeyLabelName. For a complete list of key label names, see ON KEY LABEL.

For example, to return the command currently assigned to the F7 function key with ON KEY LABEL, use the following:

? ON('KEY', 'F7')

Remarks

When an event occurs that is trapped by one of the event-handling commands, the command assigned by the event-handling command executes. ON( ) returns the command you assigned to an event-handling command. ON( ) returns an empty string if a command isn't currently assigned to the event-handling command you specify.

Example

The following example uses ON( ) to display ON ERROR and ON KEY LABEL settings.

ON ERROR DO errorhand
ON KEY LABEL CTRL+F2 WAIT WINDOW 'You pressed ^F2'
ON KEY LABEL ALT+Z DISPLAY MEMORY
CLEAR
? ON('ERROR')  && Displays DO errorhand
? ON('KEY', 'CTRL+F2')  && Displays WAIT WINDOW 'You pressed ^F2'
? ON('KEY', 'ALT+Z')  && Displays DISPLAY MEMORY
ON ERROR
ON KEY LABEL CTRL+F2
ON KEY LABEL ALT+Z

See Also

INKEY( ) | LASTKEY( ) | ON ERROR | ON ESCAPE | ON KEY | ON KEY LABEL | ON PAGE | ON READERROR | READKEY( )


ORDER( ) Function

Returns the name of the controlling index file or tag for the current or specified table.

ORDER([nWorkArea | cTableAlias [, nPath]])

Return Values

Character

Parameters

nWorkArea
Specifies the work area of a table whose controlling index file name or controlling tag name ORDER( ) returns.
cTableAlias
Specifies a table alias whose controlling index file name or controlling tag name ORDER( ) returns.
nPath
Specifies that the drive and directory are returned along with the single-entry or compound index file name. The numeric expression nPath can have any value.

Remarks

A table can have several index files open simultaneously. However, only one single-entry index file (the controlling index file) or tag from a compound index file (the controlling tag) controls the order in which the table is displayed or accessed. Certain commands, such as SEEK, use the controlling index file or controlling tag to search for records. This function returns the name of the controlling index file or controlling tag.

USE and SET INDEX both support opening more than one index with an index file list. A controlling index file or controlling tag can be designated in this index file list. SET ORDER can also be used to designate a controlling index or controlling tag.

By default, ORDER( ) returns the controlling index file name or controlling tag name for the current work area. ORDER( ) returns the empty string if an order has not been set (SET ORDER TO is issued or there is no controlling index file or tag).

Example

The following example displays index tags and files.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer ORDER cust_id && Opens Customer table
? ORDER( )  && Displays CUST_ID
? ORDER('customer', 1)  && Displays CUSTOMER.CDX

See Also

INDEX | SET INDEX | SET ORDER | USE


OS( ) Function

Returns the name and version number of the operating system under which Microsoft Visual FoxPro is running.

OS([nValue])

Return Values

Character

Parameters

nValue
Specifies the item to return, according to the following table.

nValues

Value | Description
1 | Specifies that the name and version number of the operating system is returned.
2 | DBCS Support. If DBCS (Double Byte Character Sets) are supported, "DBCS" is returned. Otherwise, an empty string is returned
3 | Identifies the major version number of the operating system. For example, for Windows 2000, the major version number is 5.
4 | Identifies the minor version number of the operating system. For example, for Windows 2000, the minor version number is 0.
5 | Identifies the build number of the operating system.
6 | Identifies the operating system platform.
7 | Contains a string, such as "Service Pack 3", that indicates the latest Service Pack installed on the system. If no Service Pack has been installed, the string is empty.
8 | Identifies the major version number of the latest Service Pack installed on the system. For example, for Service Pack 3, the major version number is 3. If no Service Pack has been installed, the value is zero.
9 | Identifies the minor version number of the latest Service Pack installed on the system. For example, for Service Pack 3, the minor version number is 0.
10 | A set of bit flags that identify the product suites available on the system. See Product Suite bit flag table below for values.
11 | Indicates additional information about the system. See Product Type settings table below for values.

Product Suite bit flags:

Value | Meaning
1 | Microsoft Small Business Server is installed.
2 | Windows 2000 Advanced Server or Windows Server 2003, Enterprise Edition, is installed.
4 | Microsoft BackOffice components are installed.
16 | Terminal Services is installed.
32 | Microsoft Small Business Server is installed with the restrictive client license in force.
64 | Windows Embedded NT is installed
128 | Windows 2000 or Windows Server 2003, Datacenter Edition, is installed.
256 | Terminal Services is installed.
512 | Windows XP Home Edition is installed.
1024 | Windows Server 2003, Web Edition, is installed.

Product Type settings:

Value | Meaning
1 | The system is running Windows NT 4.0 Workstation, Windows 2000 Professional, Windows XP Home Edition, or Windows XP Professional.
2 | The system is a domain controller.
3 | The system is a server.

Remarks

If you omit the optional argument, this function returns the underlying operating system name and its version number.

Some nValues are not applicable to some operating systems. In such cases, the OS( ) function returns "0" or "", an empty string.

Example

? OS( )
? OS(1)
? OS(2)

See Also

DISKSPACE( ) | GETENV( ) | VERSION( )


PAD( ) Function

Returns as an uppercase character string the menu title most recently chosen from a menu bar, or returns a logical value indicating if a menu title is defined for an active menu bar.

PAD([cMenuTitle [, cMenuBarName]])

Return Values

Character or Logical

Parameters

cMenuTitle
Specifies the name of a menu title in a menu bar. Include this argument to test if the menu title is defined for an active menu bar. A logical true (.T.) is returned if the menu title is defined; otherwise a logical false (.F.) is returned.
cMenuBarName
Specifies the name of the menu bar containing the menu title cMenuTitle. If cMenuBarName is omitted, the menu title is assumed to be in the currently active menu bar.

Remarks

A menu bar must be defined and active for PAD( ) to return a menu title. Menu bars are created and activated with DEFINE MENU and ACTIVATE MENU.

You can also use PAD( ) with the Visual FoxPro system menu bar.

PAD( ) (issued without any of its optional arguments) returns an empty string if a menu bar isn't defined and active or you issue PAD( ) from the Command window.

Example

In this example, PAD( ) is used to pass a menu title to a procedure.

The current Visual FoxPro system menu bar is saved to memory with SET SYSMENU SAVE , and all system menu titles are removed with SET SYSMENU TO.

Several system menu titles are created with DEFINE PAD. When a menu title is chosen, PAD( ) is used to pass the menu title to the procedure named choice. choice displays the menu title chosen and the name of the menu bar. If you choose the Exit menu title, the original Visual FoxPro system menu is restored.

*** Name this program PADEXAM.PRG ***
CLEAR
SET SYSMENU SAVE
SET SYSMENU TO
DEFINE PAD padSys OF _MSYSMENU PROMPT '\<System' COLOR SCHEME 3 ;
   KEY ALT+S, ''
DEFINE PAD padEdit OF _MSYSMENU PROMPT '\<Edit' COLOR SCHEME 3 ;
   KEY ALT+E, ''
DEFINE PAD padRecord OF _MSYSMENU PROMPT '\<Record' COLOR SCHEME 3 ;
   KEY ALT+R, ''
DEFINE PAD padWindow OF _MSYSMENU PROMPT '\<Window' COLOR SCHEME 3 ;
   KEY ALT+W, ''
DEFINE PAD padReport OF _MSYSMENU PROMPT 'Re\<ports' COLOR SCHEME 3 KEY ALT+P, ''
DEFINE PAD padExit OF _MSYSMENU PROMPT 'E\<xit' COLOR SCHEME 3 ;
   KEY ALT+X, ''
ON SELECTION MENU _MSYSMENU ;
   DO choice IN padexam WITH PAD( ), MENU( )
PROCEDURE choice
PARAMETERS gcPad, gcMenu
WAIT WINDOW 'You chose ' + gcPad + ;
   ' from menu ' + gcMenu NOWAIT
IF gcPad = 'PADEXIT'
   SET SYSMENU TO DEFAULT
ENDIF

See Also

ACTIVATE MENU | BAR( ) | DEFINE PAD | DEFINE MENU | MENU( ) | ON PAD | ON SELECTION PAD | PROMPT( )


PADL( ) | PADR( ) | PADC( ) Functions

Returns a string from an expression, padded with spaces or characters to a specified length on the left or right sides, or both.

PADL(eExpression, nResultSize [, cPadCharacter])

-Or-

PADR(eExpression, nResultSize [, cPadCharacter])

-Or-

PADC(eExpression, nResultSize [, cPadCharacter])

Return Values

Character

Parameters

eExpression
Specifies the expression to be padded. This expression can be any expression type except a logical or currency expression or a general or picture field.
nResultSize
Specifies the total number of characters in the expression after it is padded.
cPadCharacter
Specifies the value to use for padding. This value is repeated as necessary to pad the expression to the specified number of characters.

If you omit cPadCharacter, spaces (ASCII character 32) are used for padding.

Remarks

PADL( ) inserts padding on the left, PADR( ) inserts padding on the right, and PADC( ) inserts padding on both sides.

Example

STORE 'TITLE' TO gcString
CLEAR
? PADL(gcString, 40, '=')
? PADR(gcString, 40, '=')
? PADC(gcString, 40, '=')

See Also

ALLTRIM( ) | LEFT( ) | LTRIM( ) | RIGHT( ) | STUFF( ) | TRIM( )


PARAMETERS( ) Function

Returns the number of parameters passed to the most recently called program, procedure, or user-defined function.

PARAMETERS( )

Return Values

Numeric

Remarks

PARAMETERS( ) is useful for determining how many parameters are passed to a program, procedure, or user-defined function.

Note The value returned by PARAMETERS( ) is reset every time a program, procedure, or user-defined function is called or when ON KEY LABEL is executed. Unlike PARAMETERS( ), the PCOUNT( ) function does not get reset, so PCOUNT( ) may be preferable in most programming situations.

Examples

Example 1 calls a procedure and displays in a wait window the number of parameters passed.

Example 2 uses a procedure to display the average of 4 values.

* Example 1
DO testpar WITH 1,2,3

PROCEDURE testpar
PARAMETERS gn1,gn2,gn3
gcMessage = 'PARAMETERS( ) ='+ALLTRIM(STR(PARAMETERS( )))
WAIT WINDOW (gcMessage)
RETURN

* Example 2
SET TALK OFF
gnVal1 = 10
gnVal2 = 20
gnVal3 = 30
gnVal4 = 15
gnMin = getavg(gnVal1, gnVal2, gnVal3, gnVal4)
? 'Average value is '
?? gnMin

* This user-defined function permits up to 9 parameters to be passed.
* It uses the PARAMETERS( ) function to determine how many
* were passed and returns the average value.

FUNCTION getavg
PARAMETERS gnPara1,gnPara2,gnPara3,gnPara4,gnPara5, ;
   gnPara6,gnPara7,gnPara8,gnPara9
IF PARAMETERS( ) = 0
   RETURN 0
ENDIF
gnResult = 0
FOR gnCount = 1 to PARAMETERS( )
   gcCompare = 'gnPara' +(STR(gnCount,1))
   gnResult = gnResult + EVAL(gcCompare)
ENDFOR
gnResult = gnResult / (gnCount - 1)
RETURN gnResult

See Also

DO | FUNCTION | LPARAMETERS | LOCAL | PARAMETERS | PCOUNT( ) Function | PRIVATE | PROCEDURE | PUBLIC | SET UDFPARMS


PAYMENT( ) Function

Returns the amount of each periodic payment on a fixed-interest loan.

PAYMENT(nPrincipal, nInterestRate, nPayments)

Return Values

Numeric

Parameters

nPrincipal
Specifies the beginning principal of the loan.
nInterestRate
Specifies the fixed interest rate per period. If monthly payments are made on the loan but the interest rate is annual, divide the annual interest rate by 12.
nPayments
Specifies the total number of payments to be made on the loan.

Remarks

PAYMENT( ) assumes a constant periodic interest rate and assumes that payments are made at the end of each period.

Example

STORE 100000 to gnPrincipal     && $100,000 beginning principal
STORE .105/12 TO gnInterest  && 10.5% annual interest rate
STORE (20*12) TO gnPayments     && 20 years of monthly payments
CLEAR
? PAYMENT(gnPrincipal, gnInterest, gnPayments)  && Displays 998.38

See Also

CALCULATE Command | FV( ) Function | PV( ) Function


PCOL( ) Function

Returns the current column position of the printer's print head.

PCOL( )

Return Values

Numeric

Remarks

The value PCOL( ) returns is relative to the current setting of the left printer margin. You can set the left margin with SET MARGIN or by storing a value to the system memory variable _PLOFFSET.

PCOL( ) is especially useful for relative addressing of printed text.

You can use the $ operator in place of PCOL( ).

Example

CLEAR
@ PROW( ), PCOL( )+12 SAY 'Contact person'
@ PROW( ), $+12 SAY 'Contact person'

See Also

COL( ) Function | ROW( ) Function | PROW( ) Function


PCOUNT( ) Function

Returns the number of parameters passed to the current program, procedure, or user-defined function.

PCOUNT( )

Return Values

Numeric

Remarks

PCOUNT( ) is useful for determining how many parameters are passed to the current program, procedure, or user-defined function.

Examples

Example 1 calls a procedure and displays in a wait window the number of parameters passed.

Example 2 uses a procedure to display the average of 4 values.

Example 1

DO testpar WITH 1,2,3

PROCEDURE testpar
PARAMETERS gn1,gn2,gn3
gcMessage = 'PCOUNT( ) ='+ALLTRIM(STR(PCOUNT( )))
WAIT WINDOW (gcMessage)
RETURN

Example 2

SET TALK OFF
gnVal1 = 10
gnVal2 = 20
gnVal3 = 30
gnVal4 = 15
gnMin = getavg(gnVal1, gnVal2, gnVal3, gnVal4)
? 'Average value is '
?? gnMin

* This user-defined function permits up to 9 parameters to be passed.
* It uses the PCOUNT( ) function to determine how many
* were passed and returns the average value.

FUNCTION getavg
PARAMETERS gnPara1,gnPara2,gnPara3,gnPara4,gnPara5, ;
   gnPara6,gnPara7,gnPara8,gnPara9
IF PCOUNT( ) = 0
   RETURN 0
ENDIF
gnResult = 0
FOR gnCount = 1 to PARAMETERS( )
   gcCompare = 'gnPara' +(STR(gnCount,1))
   gnResult = gnResult + EVAL(gcCompare)
ENDFOR
gnResult = gnResult / (gnCount - 1)
RETURN gnResult

See Also

DO Command | FUNCTION Command | LPARAMETERS Command | LOCAL Command | PARAMETERS Command | PARAMETERS( ) Function | PRIVATE Command | PROCEDURE Command | PUBLIC Command | SET UDFPARMS Command


PEMSTATUS( ) Function

Returns an attribute for a property, event, method, or object.

PEMSTATUS(oObjectName | cClassName, cProperty | cEvent | cMethod
   | cObject, nAttribute)

Return Values

Character or Logical

Parameters

oObjectName
Specifies the object for which a property, event, method, or object attribute is returned. oObjectName can be any expression that evaluates to an object, such as an object reference, an object memory variable, or an object array element. If oObjectName is a container object such as a form, you can determine attributes for objects within the container object.
cClassName
Specifies the class for which a property, event, or method attribute is returned.
cProperty
Specifies the property for which an attribute is returned.
cEvent
Specifies the event for which an attribute is returned.
cMethod
Specifies the method for which an attribute is returned.
cObject
Specifies the object for which an attribute is returned. For example, you can use the AddObject method to add an object to a container object, and then use PEMSTATUS( ) to return information about the object added to the container object.
nAttribute
A numeric value that specifies which property, event, or method attribute is returned.

The following table lists the values for nAttribute and the corresponding property, event, or method attribute.

nAttribute | Property, event, or method attribute
0 | Changed (properties only). A logical true (.T.) is returned if the property value has changed from its original, default value; otherwise a logical false (.F.) is returned.
1 | Read-only (properties only). A logical true (.T.) is returned if the property is read-only; otherwise a logical false (.F.) is returned.
2 | Protected. A logical true (.T.) is returned if the property, event, or method is a protected; otherwise a logical false (.F.) is returned.
3 | Type. A character string is returned indicating if cProperty, cEvent, cMethod or cObject is a property, event, method or object. Property, Event, Method, or Object is returned.
4 | User-defined. A logical true (.T.) is returned if the property, event, or method is a user-defined property, event, or method; otherwise a logical false (.F.) is returned.
5 | Defined property, event, method, or object. A logical true (.T.) is returned if the property, event, method, or object exists for oObjectName or cClassName, otherwise a logical false (.F.) is returned.
6 | Inherited property, event, method, or object. A logical true (.T.) is returned if the property, event, method, or object for oObjectName or cClassName was inherited from another object or class, otherwise a logical false (.F.) is returned.

Remarks

PEMSTATUS( ) does not detect for changes in specific array elements if the array is passed.

See Also

CREATE FORM Command | GETPEM( ) Function | SYS(1269) – Property Information | SYS(1270) – Object Location | SYS(1271) - Object's .SCX File | SYS(1272) – Object Hierarchy


PI( ) Function

Returns the numeric constant pi.

PI( )

Return Values

Numeric

Remarks

The numeric constant pi (3.141592) is the ratio of the circumference of a circle to its diameter.

The number of decimal places displayed in the value returned by PI( ) is determined by SET DECIMALS.

Example

CLEAR
? PI( ) && Displays 3.14
STORE 2.30 TO gnRadius
STORE PI( ) * gnRadius^2 TO gnArea
? gnArea  && Displays 16.6190

See Also

SET DECIMALS Command | STORE Command | Circle Method


POPUP( ) Function

Returns as a string the name of the active menu, or a logical value indicating if a menu has been defined.

POPUP([cMenuName])

Return Values

Character or Logical

Parameters

cMenuName
Returns a logical value indicating if cMenuName has been defined. POPUP( ) returns true (.T.) if the menu you specify has been defined; otherwise POPUP( ) returns false (.F.).

Remarks

POPUP( ) returns the name of the active menu as a character string if you omit the optional cMenuName argument. A menu must be defined and active for POPUP( ) to return its name. Menus are created and activated with DEFINE POPUP and ACTIVATE POPUP. The menu can also be a Visual FoxPro system menu. POPUP( ) returns an empty string if a menu isn't defined and active or you issue POPUP( ) from the Command window.

See Also

ACTIVATE POPUP | BAR( ) | DEFINE BAR | DEFINE POPUP | ON SELECTION POPUP


PRIMARY( ) Function

Returns true (.T.) if an index tag is a primary index tag; otherwise, returns false (.F.).

PRIMARY([nIndexNumber] [, nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nIndexNumber
Specifies the number of the index tag for which PRIMARY( ) returns the primary status. PRIMARY( ) returns the primary status in the following order as nIndexNumber increases from 1 to the total number of structural compound and independent compound index tags.
  1. Primary status for each tag in the structural compound index (if one is present) are returned first. The primary status is returned for the tags in the order the tags are created in the structural index.
  2. Primary status for each tag in any open, independent compound indexes are returned next. The primary status is returned for the tags in the order in which the tags are created in the independent compound indexes.

    If you omit nIndexNumber, PRIMARY( ) checks the master controlling index tag to see if it's a primary index tag. If there is no master controlling index tag, PRIMARY( ) returns false (.F.).

nWorkArea
Specifies the work area of the index tag specified with nIndexNumber.
cTableAlias
Specifies the work area of the index tag specified with nIndexNumber.

If you omit nWorkArea and cTableAlias, PRIMARY( ) checks the index tag in the currently selected work area to see if it's a primary index tag.

Example

The following example opens the customer table in the database. FOR ... ENDFOR is used to create a loop in which the primary status of each index tag in the customer structural index is checked. The name of each structural index tag is displayed with its primary status.

CLOSE DATABASES
SET PATH TO (HOME(2) + 'Data\')   && Sets path to database
OPEN DATABASE testdata  && Open testdata database
USE Customer     && Open customer table

FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? TAG(nCount)  && Display tag name
   ? PRIMARY(nCount)     && Display primary status
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

ALTER TABLE – SQL | CANDIDATE( ) | CREATE TABLE – SQL | INDEX


PRINTSTATUS( ) Function

Returns true (.T.) if the printer or print device is online; otherwise, false (.F.) is returned.

PRINTSTATUS( )

Return Values

Logical

Remarks

PRINTSTATUS( ) is similar to SYS(13), except SYS(13) returns READY instead of true (.T.) or OFFLINE instead of false (.F.).

In Visual FoxPro, PRINTSTATUS( ) always returns true (.T.) if the printer is connected through the Windows Control Panel.

Example

? PRINTSTATUS( )
*** Program Example ***
STORE PRINTSTATUS( ) TO glReady
IF NOT glReady
   WAIT 'Make sure printer is attached and turned on!' WINDOW
ELSE
   WAIT 'Printer is ready!' WINDOW
ENDIF

See Also

SET DEVICE | SET PRINTER | SYS(13) – Printer Status | PRINTJOB ... ENDPRINTJOB Command


PRMBAR( ) Function

Returns the text of a menu item.

PRMBAR(cMenuName, nMenuItemNumber)

Return Values

Character

Parameters

cMenuName
Specifies the menu name.
nMenuItemNumber
Specifies the number of the menu item whose text PRMBAR( ) returns. For example, if nMenuItemNumber is 1, the text of the first menu item is returned; if nMenuItemNumber is 2, the text of the second menu item is returned, and so on. The expression must be at least 1 and no greater than the number of menu items in the menu.

Remarks

Menus are created with DEFINE POPUP, which creates the menu, and DEFINE BAR, which creates the menu items in the menu. PRMBAR( ) also works with a Visual FoxPro system menu. PRMBAR( ) returns the text that appears on the menu item. The menu doesn't have to be active.

If a menu item was created using the backslash and less-than characters (\<) to create an access key, or a backslash (\) to disable the menu item, PRMBAR( ) returns only the menu item text; it doesn't include these special characters. PRMBAR( ) returns an empty string when a menu item is a separator created with the backslash and dash (\-) characters.

See Also

CNTBAR( ) | GETBAR( ) | DEFINE BAR | DEFINE POPUP | MRKBAR( ) | PRMPAD( )


PRMPAD( ) Function

Returns the text of a menu title.

PRMPAD(MenuBarName, MenuTitleName)

Return Values

Character

Parameters

MenuBarName
Specifies the name of the menu bar containing the menu title.
MenuTitleName
Specifies the menu title.

Remarks

Menu bars are created with DEFINE MENU, which creates the menu bar, and DEFINE PAD, which creates the menu titles in the menu bar. PRMPAD( ) also works with the Visual FoxPro menu system. A menu bar doesn't have to be active for PRMPAD( ) to return the text for a menu title.

If a menu title was created using the backslash and less-than characters (\<) to create an access key, or a backslash (\) to disable the menu title, PRMPAD( ) returns only the text of the menu title; it doesn't include the special characters.

Example

In the following example, a menu bar named mnuExample is created with three menu titles. The access key and disabled option designators aren't returned from the menu titles named titleTwo and titleThree. The menu bar is activated to show the menu titles and is cleared from the screen and from memory when a menu title is chosen.

CLEAR
SET TALK OFF
STORE 'mnuExample' TO gcPopName

DEFINE MENU mnuExample BAR AT LINE 1
DEFINE PAD titleOne OF mnuExample PROMPT 'This will be returned'
DEFINE PAD titleTwo OF mnuExample PROMPT '\<As will this'
DEFINE PAD titleThree OF mnuExample PROMPT '\And this, too'

=messagebox( PRMPAD('mnuExample', 'titleOne') )
=messagebox( PRMPAD('mnuExample', 'titleTwo') )
=messagebox( PRMPAD(gcPopName, 'titleThree') )

ACTIVATE MENU mnuExample
DEACTIVATE MENU mnuExample
RELEASE MENU mnuExample

See Also

CNTBAR( ) | GETBAR( ) | DEFINE BAR | DEFINE POPUP | MRKPAD( ) | PRMBAR( )


PROGRAM( ) Function

Returns the name of the program currently executing, the current program level, or the name of the program executing when an error occurred.

PROGRAM([nLevel])

Return Values

Character or Numeric

Parameters

nLevel
Specifies how many program levels back the program name is to be found. This parameter can range from 0 to the program nesting depth. A program can execute another program, which can execute another program, and so on. Programs may be nested to 128 levels.

If you specify 0 or 1 for nLevel, PROGRAM( ) returns the name of the master program (the highest-level program). If nLevel exceeds the program nesting depth, PROGRAM( ) returns an empty string.

If you specify –1 for nLevel, PROGRAM( ) returns as a numeric value the current program level. PROGRAM(–1) always returns zero when issued from the Command window.

Remarks

PROGRAM( ) helps your program recover from errors. It is similar to SYS(16).

If used without an argument, PROGRAM( ) returns the name of the currently executing program.

Example

ON ERROR DO errhand WITH PROGRAM( )
*** The next line should generate an error ***
USE nodatabase
ON ERROR     && Returns to system default error-handling routine
PROCEDURE errhand
PARAMETERS gcProgram
WAIT 'An error occurred in the program ' + gcProgram WINDOW

See Also

DO | LINENO( ) | MESSAGE( ) | SYS(16) – Executing Program File Name | ASTACKINFO( )


PROMPT( ) Function

Returns the text for a menu title chosen from a menu bar or for a menu item chosen from a menu.

PROMPT( )

Return Values

Character

Remarks

PROMPT( ) returns the text of the menu title last chosen from a menu bar or the menu item last chosen from a menu. The menu bar or menu can be user-defined or a Visual FoxPro system menu bar or menu. If a menu bar or menu isn't active or you press ESC to exit a menu bar or menu, PROMPT( ) returns an empty string.

A menu bar is created with DEFINE MENU, and each menu title in the menu bar is created with DEFINE PAD. A menu is created with DEFINE POPUP, and the menu items in the menu are created with DEFINE BAR.

MENU( ) and POPUP( ) can be used to return the name of the menu bar or menu from which the menu title or menu item is chosen.

See Also

BAR( ) | DEFINE BAR | DEFINE MENU | DEFINE PAD | DEFINE POPUP | POPUP( ) | PRMBAR( )


PROPER( ) Function

Returns from a character expression a string capitalized as appropriate for proper names.

PROPER(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which PROPER( ) returns a capitalized character string.

Example

STORE 'Visual FoxPro' TO gcExpr1

CLEAR
? PROPER(gcExpr1)  && Displays "Visual Foxpro"
STORE 'VISUAL FOXPRO' TO gcExpr2
? PROPER(gcExpr2)  && Displays "Visual Foxpro"

See Also

LOWER( ) | UPPER( ) | Character Expression Creation


PROW( ) Function

Returns the current row number of the printer's print head.

PROW( )

Return Values

Numeric

Remarks

If you issue EJECT, Visual FoxPro resets PROW( ) to 0.

PROW( ) is especially useful for relative addressing of printed text.

Example

In the following example, the two commands return the same result. You can use the $ operator in place of PCOL( ). Both $ and PCOL( ) return the current column position of the printer.

@ PROW( ), PCOL( ) + 12 SAY 'Contact person'
@ PROW( ), $+12 SAY 'Contact person'

See Also

@ ... SAY | COL( ) | PCOL( ) | ROW( )


PRTINFO( ) Function

Returns the current specified printer setting.

PRTINFO(nPrinterSetting [, cPrinterName])

Parameters

nPrinterSetting
Specifies which Visual FoxPro printer setting to return. The following table lists descriptions of the type of printer settings returned.
nPrinterSetting | FOXPRO.H | Setting returned
1 | PRT_ORIENTATION | Paper orientation
2 | PRT_PAPERSIZE | Paper size
3 | PRT_PAPERLENGTH | Paper length in .1 millimeter increments
4 | PRT_PAPERWIDTH | Paper width in .1 millimeter increments
5 | PRT_SCALE | Factor by which printer output is scaled
6 | PRT_COPIES | Number of copies to print
7 | PRT_DEFASOURCE | Default paper source
8 | PRT_PRINTQUAL | A positive value that indicates the horizontal resolution in dots per inch (DPI) or a negative value that indicates the print quality.
9 | PRT_COLOR | A value that indicates if a color printer rends color or monochrome output
10 | PRT_DUPLEX | Duplex mode
11 | PRT_YRESOLUTION | The vertical resolution in dots per inch (DPI). If not available, a value of -1 is returned.
12 | PRT_TTOPTION | A value that indicates how TrueType® fonts are printed
13 | PRT_COLLATE | A value that indicates if output is collated
cPrinterName
Specifies the name of the printer for which information is returned. If cPrinterName is omitted, information is returned for the default printer.

Return Values

Numeric data type. The following tables list values returned when specifying particular values for nPrinterSetting.

If nPrinterSetting is 1, PRTINFO( ) returns the paper orientation as the following:

Return values | Paper orientation
–1 | Information not available
0 | Portrait
1 | Landscape

If nPrinterSetting is 2, PRTINFO( ) returns the paper size as the following:

Return values | Paper size
–1 or value other than listed | Information not available. Use nPrinterSetting = 3 and nPrinterSetting = 4 to return the paper size.
1 | Letter, 8 1/2 x 11 in
2 | Letter Small, 8 1/2 x 11 in
3 | Tabloid, 11 x 17 in
4 | Ledger, 17 x 11 in
5 | Legal, 8 1/2 x 14 in
6 | Statement, 5 1/2 x 8 1/2 in
7 | Executive, 7 1/4 x 10 1/2 in
8 | A3, 297 x 420 mm
9 | A4, 210 x 297 mm
10 | A4, Small 210 x 297 mm
11 | A5, 148 x 210 mm
12 | B4, 250 x 354 mm
13 | B5, 182 x 257 mm
14 | Folio, 8 1/2 x 13 in
15 | Quarto, 215 x 275 mm
16 | 10 x 14 in
17 | 11 x 17 in
18 | Note, 8 1/2 x 11 in
19 | Envelope #9, 3 7/8 x 8 7/8 in
20 | Envelope #10, 4 1/8 x 9 1/2 in
21 | Envelope #11, 4 1/2 x 10 3/8 in
22 | Envelope #12, 4 1/2 x 11 in
23 | Envelope #14, 5 x 11 1/2 in
24 | C size sheet
25 | D size sheet
26 | E size sheet
27 | Envelope DL, 110 x 220 mm
28 | Envelope C5, 162 x 229 mm
29 | Envelope C3, 324 x 458 mm
30 | Envelope C4, 229 x 324 mm
31 | Envelope C6, 114 x 162 mm
32 | Envelope C65, 114 x 229 mm
33 | Envelope B4, 250 x 353 mm
34 | Envelope B5, 176 x 250 mm
35 | Envelope B6, 176 x 125 mm
36 | Envelope, 110 x 230 mm
37 | Envelope Monarch, 3 7/8 x 7.5 in
38 | 6 3/4 Envelope, 3 5/8 x 6 1/2 in
39 | US Std Fanfold, 14 7/8 x 11 in
40 | German Std Fanfold, 8 1/2 x 12 in
41 | German Legal Fanfold, 8 1/2 x 13 in

If nPrinterSetting is 7, PRTINFO( ) returns the default paper source as the following:

Return values | Default paper source
1 | Upper bin
2 | Lower bin
3 | Middle bin
4 | Manual feed
5 | Envelope bin
6 | Manual feed envelope
7 | Automatic feed
8 | Tractor feed
9 | Small format
10 | Large format
11 | Large capacity
14 | Cassette
15 | Default input bin (automatically select)

If nPrinterSetting is 8 and PRTINFO( ) returns a negative value, the return value indicates the print quality as the following:

Return values | Print quality
–1 | Draft
–2 | Low
–3 | Medium
–4 | High

If nPrinterSetting is 9, PRTINFO( ) returns a value indicating if a color printer renders color or monochrome output as the following:

Return values | Color of output
1 | Monochrome
2 | Color

If nPrinterSetting is 10, PRTINFO( ) returns the duplex mode as the following:

Return values | Duplex mode
1 | Simplex printing
2 | Vertical duplex
3 | Horizontal duplex

If nPrinterSetting is 12, PRTINFO( ) returns a value that indicates how TrueType® fonts are printed as the following:

Return values | Printing of TrueType® fonts
1 | Print as bitmapped graphics
2 | Download as soft fonts
3 | Substitute device fonts

If nPrinterSetting is 13, PRTINFO( ) returns a value that indicates if output is collated as the following:

Return values | Collation
0 | No collation
1 | Collated

Remarks

Visual FoxPro printer settings are set in the Page Setup dialog box. Choose Page Setup from the File menu to display the Visual FoxPro Page Setup dialog box.

See Also

GETPRINTER( ) | PRINTSTATUS( ) | SET DEVICE | SET PRINTER | SYS(13) – Printer Status | SYS(1037) – Page Setup Dialog Box


PUTFILE( ) Function

Invokes the Save As dialog box and returns the file name you specify.

PUTFILE([cCustomText] [, cFileName] [, cFileExtensions])

Return Values

Character

Parameters

cCustomText
Specifies custom text to appear in the Save As dialog box.
cFileName
Specifies the default file name displayed in the text box.
cFileExtensions
Specifies file name extensions. Only file names with the specified extension are displayed in the scrollable list of the Save As dialog box when the All Files check box is cleared. The first extension in cFileExtensions is automatically appended to the file name entered if an extension isn't included with the file name. The cFileExtensions parameter cannot exceed 254 characters in length. For a list of Visual FoxPro file extensions and corresponding creator types, see the File Extensions and File Types online topic.

The character expression cFileExtensions can take one of the following forms:

  • cFileExtensions can contain a single extension, such as PRG, and only file names with that extension are displayed.
  • cFileExtensions can contain a list of file name extensions separated by semicolons. For example, if you include PRG;FXP, Visual FoxPro displays all file names with the extensions .prg and .fxp.
  • If file names have the same root name but different extensions (for example, Customer.prg and Customer.fxp), Visual FoxPro displays only the file name with the extension that appears first in cFileExtensions.
  • cFileExtensions can contain a list of file name extensions separated by vertical bars, such as PRG|FXP. In such a case, Visual FoxPro displays all file names with listed extensions, even if the files have the same root name.
  • If cFileExtensions contains only a semicolon (;), Visual FoxPro displays all file names that don't have an extension.
  • If cFileExtensions is an empty string, Visual FoxPro displays the names of all files in the current directory or folder.
  • If cFileExtensions contains MS-DOS wildcards, such as the question mark (?) and asterisk (*), Visual FoxPro displays all file names with extensions that meet the wildcard criteria. For example, if cFileExtensions is ?X?, all file names with the extensions .fxp, .exe, .txt, and so on, are displayed.

Remarks

Use PUTFILE( ) to choose an existing file name or specify a new file name. PUTFILE( ) returns the file name with its path. If you don't enter a file name, PUTFILE( ) returns the default file name (specified with cFileName) and extension (specified by cFileExtensions). If you choose Cancel or press ESC, PUTFILE( ) returns an empty string. You can use the file name that PUTFILE( ) returns to name a file and save it to disk.

Example

The following example creates a delimited data file from any existing table the user chooses. GETFILE( ) is used to find and open a table and PUTFILE( ) is used to return the name of the target file.

gcTableName = GETFILE('DBF', 'Open Table:')
USE (gcTableName)
gcDelimName = ALIAS( ) + '.DLM'
gcDelimFile = PUTFILE('Delimited file:', gcDelimName, 'DLM')
IF EMPTY(gcDelimFile)  && Esc pressed
   CANCEL
ENDIF
COPY TO (gcDelimFile) DELIMITED   && Create delimited file
MODIFY FILE (gcDelimFile) NOEDIT

See Also

FILE( ) | GETEXPR | GETFILE( ) | GETPICT( ) | LOCFILE( )


PV( ) Function

Returns the present value of an investment.

PV(nPayment, nInterestRate, nTotalPayments)

Return Values

Numeric

Parameters

nPayment
Specifies the periodic payment amount. nPayment can evaluate to a positive or negative number. PV( ) assumes that the payments are made at the end of each period.
nInterestRate
Specifies the periodic interest rate. If the interest rate of an investment is annual and the payments are made monthly, divide the annual interest rate by 12.
nTotalPayments
Specifies the total number of payments.

Remarks

PV( ) computes the present value of an investment based on a series of equal periodic payments at a constant periodic interest rate.

Example

STORE 500 to gnPayment  && Periodic payments made monthly
STORE .075/12 TO gnInterest     && 7.5% annual interest rate
STORE 48 TO gnPeriods  && Four years (48 months)
CLEAR
? PV(gnPayment, gnInterest, gnPeriods)  && Displays 20679.19

See Also

CALCULATE | FV( ) | PAYMENT( )


QUARTER( ) Function

Returns the quarter of the year in which a date or datetime expression occurs.

QUARTER(dExpression | tExpression [, nMonth])

Parameters

dExpression
Specifies the Date expression for which you want QUARTER( ) to return a value.
tExpression
Specifies the DateTime expression for which you want QUARTER( ) to return a value.
nMonth
Specifies an optional starting month to the examined quarter. You can use this to specify quarters based on a fiscal rather than a calendar year.

Return Values

Numeric data type. QUARTER( ) returns the quarter of the year in which a date occurs, and the values can be 0, 1, 2, 3, or 4.

Note QUARTER( ) returns 0 if passed an empty Date or DateTime value, for example, QUARTER({//}).

See Also

CMONTH( ) | DATE( ) | DATETIME( ) | DAY( ) | MONTH( ) | YEAR( )


RAISEEVENT() Function

You can use RAISEEVENT() to raise, or trigger, an event from a custom method. Though RAISEEVENT() applies primarily to custom methods, you can use it for raising native events and methods.

RAISEEVENT( oEventSource, cEvent [, eParm1...] )

Parameters

oEventSource
Specifies the event source, which must be a valid Visual FoxPro object.
cEvent
Specifies the name of the event, method, or property you want to raise.
eParm1...
Specifies one or more parameters to pass if the method has parameters.

Return Values

Logical data type. RAISEEVENT() always returns True (.T.).

Remarks

Visual FoxPro does not automatically raise events for custom methods that are bound to objects using BINDEVENT( ) if the methods are called directly. For example, the following code does not raise an event:

oForm.GetMyData(cData)

Instead, to raise an event for a custom method, you need to make the following call:

RAISEEVENT( oForm, "GetMyData", cData )

You can also change this behavior by using BINDEVENT( ) with nFlags set to 2 or 3.

The event you wish to raise must be marked Public, not Hidden or Protected.

If you use RAISEEVENT() on a property, Visual FoxPro sets the property to itself. The following example sets the Caption property for _SCREEN to the current value for Caption:

RAISEEVENT( _SCREEN, "Caption" )

Raising an event fails if you bind to an event, for example, using BINDEVENT( ), that has parameters that are passed by reference.

Visual FoxPro disregards recursive RAISEEVENT() calls to an event from within the same raised event.

Example

Activating a form or using Form1.Show triggers the Activate event for the form. However, calling the Activate event directly using a call such as Form1.Activate does not trigger the Activate event. The following example shows how you can use RAISEEVENT( ) to trigger the Activate event:

RAISEEVENT( Form1, "Activate" )

See Also

Functions | Event Binding for Visual FoxPro Objects | BINDEVENT() Function | UNBINDEVENTS() Function | AEVENTS() Function


RAND( ) Function

Returns a random number between 0 and 1.

RAND([nSeedValue])

Return Values

Numeric

Parameters

nSeedValue
Specifies the seed value that determines the sequence of values RAND( ) returns.

RAND( ) returns the same sequence of random numbers if you use the same seed value for nSeedValue the first time you issue RAND( ) followed by subsequent RAND( ) function calls without nSeedValue.

If nSeedValue is negative the first time you issued RAND( ), a seed value from the system clock is used. To achieve the most random sequence of numbers, issue RAND( ) initially with a negative argument and then issue RAND( ) without an argument.

If you omit nSeedValue, RAND( ) uses a default seed value of 100,001.

Example

The first example below uses RAND( ) to create a table with 10 records containing random values, then uses MIN( ) and MAX( ) to display the maximum and minimum values in the table.

The second example below displays a random number that falls between two values, 1 and 10.

CLOSE DATABASES
CREATE TABLE Random (cValue N(3))
FOR nItem = 1 TO 10  && Append 10 records,
   APPEND BLANK
   REPLACE cValue WITH 1 + 100 * RAND( )  && Insert random values
ENDFOR

CLEAR
LIST  && Display the values
gnMaximum = 1  && Initialize minimum value
gnMinimum = 100  && Initialize maximum value
SCAN
   gnMinimum = MIN(gnMinimum, cValue)
   gnMaximum = MAX(gnMaximum, cValue)
ENDSCAN
? 'The minimum value is: ', gnMinimum  && Display minimum value
? 'The maximum value is: ', gnMaximum  && Display maximum value

CLEAR
gnLower = 1
gnUpper = 10

? INT((gnUpper - gnLower + 1) * RAND( ) + gnLower)

See Also

EXP( ) | PI( ) | MIN( ) | MAX( )


RAT( ) Function

Returns the numeric position of the last (rightmost) occurrence of a character string within another character string.

RAT(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that RAT( ) looks for in cExpressionSearched. The character expression can refer to a memo field of any size.
cExpressionSearched
Specifies the character expression that RAT( ) searches. The character expression can refer to a memo field of any size.
nOccurrence
Specifies which occurrence, starting from the right and moving left, of cSearchExpression RAT( ) searches for in cExpressionSearched. By default, RAT( ) searches for the last occurrence of cSearchExpression (nOccurrence = 1). If nOccurrence is 2, RAT( ) searches for the next to last occurrence, and so on.

Remarks

RAT( ), the reverse of the AT( ) function, searches the character expression in cExpressionSearched starting from the right and moving left, looking for the last occurrence of the string specified in cSearchExpression.

RAT( ) returns an integer indicating the position of the first character in cSearchExpression in cExpressionSearched. RAT( ) returns 0 if cSearchExpression isn't found in cExpressionSearched, or if nOccurrence is greater than the number of times cSearchExpression occurs in cExpressionSearched.

The search performed by RAT( ) is case-sensitive.

Example

STORE 'abracadabra' TO string
STORE 'a' TO find_str
CLEAR
? RAT(find_str,string)  && Displays 11
? RAT(find_str,string,3)  && Displays 6

See Also

AT( ) | AT_C( ) | ATC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RATLINE( ) | RIGHT( ) | SUBSTR( ) | ATCC( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | $ Operator | OCCURS( ) | INLIST( )


RATC( ) Function

Returns the numeric position of the last occurrence of a character expression or memo field within another character expression or memo field.

RATC(cSearchExpression, cExpressionSearched [, nOccurrence])

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that RATC( ) looks for in cExpressionSearched.
cExpressionSearched
Specifies the character expression that RATC( ) searches. The character expressions cSearchExpression and cExpressionSearched can be memo fields of any size.
nOccurrence
Specifies which occurrence, starting from the right and moving left, of cSearchExpression RATC( ) searches for in cExpressionSearched. By default, RATC( ) searches for the last occurrence of cSearchExpression (nOccurrence equals 1). If nOccurrence is 2, RATC( ) searches for the next to last occurrence, and so on.

Remarks

RATC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, RATC( ) is equivalent to RAT( ).

RATC( ) returns the numeric position of the last occurrence of a character expression or memo field within another character expression or memo field. The character expressions or memo fields can contain any combination of single-byte and double-byte characters.

RATC( ) is the reverse of the AT_C( ) function: it searches from right to left.

RATC( ) returns an integer indicating the position of the first character in cSearchExpression in cExpressionSearched. RATC( ) returns 0 if cSearchExpression isn't found in cExpressionSearched, or if nOccurrence is greater than the number of times cSearchExpression occurs in cExpressionSearched.

The search performed by RATC( ) is case-sensitive.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT_C( ) | LEFTC( ) | RAT( ) | RIGHTC( ) | SUBSTRC( )


RATLINE( ) Function

Returns the line number of the last occurrence of a character expression within another character expression or memo field, counting from the last line.

RATLINE(cSearchExpression, cExpressionSearched)

Return Values

Numeric

Parameters

cSearchExpression
Specifies the character expression that RATLINE( ) looks for in cExpressionSearched.
cExpressionSearched
Specifies the character expression that RATLINE( ) searches. The character expressions cSearchExpression and cExpressionSearched can be memo fields of any size.

Use MLINE( ) to return the line containing cSearchExpression.

Tip RATLINE( ) offers a convenient way to search memo fields.

Remarks

RATLINE( ), the reverse of the ATLINE( ) function, searches a character expression cExpressionSearched, starting with the last character in cExpressionSearched, for the occurrence of cSearchExpression.

If the search is successful, RATLINE( ) returns the number of the line where the match occurs. If the search is unsuccessful, RATLINE( ) returns 0.

The search performed by RATLINE( ) is case-sensitive.

Caution The line number that RATLINE( ) returns is determined by the value of SET MEMOWIDTH, even if cExpressionSearched isn't a memo field. For more information, see SET MEMOWIDTH.

Example

In the following example, RATLINE( ) returns the line number for the last line in the notes memo field containing the word "graduated." MLINE( ) uses this value to return the contents of the line.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE employee  && Opens Employee table
STORE 'graduated' TO gcString
STORE MLINE(notes, RATLINE(gcString, notes)) TO gnFileLine
? gnFileLine

See Also

AT( ) | AT_C( ) | ATC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RIGHT( ) | SUBSTR( ) | ATCC( ) | LEFTC( ) | MLINE( ) | RIGHTC( ) | SUBSTRC( ) | $ Operator | OCCURS( ) | INLIST( )


RDLEVEL( ) Function

Included for backward compatibility. Use the Form Designer instead of READ.


READKEY( ) Function

Included for backward compatibility with READ. Use the Form Designer instead of READ.


RECCOUNT( ) Function

Returns the number of records in the current or specified table.

RECCOUNT([nWorkArea | cTableAlias])

Return Values

Numeric

Parameters

nWorkArea
Specifies the work area number for a table open in another work area.

RECCOUNT( ) returns 0 if a table isn't open in the work area you specify.

cTableAlias
Specifies the table alias for a table open in another work area.

Remarks

The value RECCOUNT( ) returns isn't affected by SET DELETED and SET FILTER.

RECCOUNT( ) without the optional arguments nWorkArea or cTableAlias returns the number of records in the table in the currently selected work area.

Example

In the following example, Microsoft Visual FoxPro compares the available disk space with the amount needed to sort customer.

*** Check DISKSPACE before a SORT ***

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

*** Get size of table header ***

gnTableHead = HEADER( )

*** Calculate size of table ***

gnFileSize = gnTableHead + (RECSIZE( ) * RECCOUNT( ) + 1)
IF DISKSPACE( ) > (gnFileSize * 3)
   WAIT WINDOW 'Sufficient diskspace to sort.'
ELSE
   WAIT WINDOW 'Insufficient diskspace. Sort cannot be done.'
ENDIF

See Also

RECNO( ) | RECSIZE( ) | SET DELETED | SET FILTER


RECNO( ) Function

Returns the current record number in the current or specified table.

RECNO([nWorkArea | cTableAlias])

Return Values

Numeric

Parameters

nWorkArea
Specifies the work area number for a table open in another work area. RECNO( ) returns 0 if a table isn't open in the work area you specify.
cTableAlias
Specifies the table alias for a table open in another work area.

Remarks

The current record is the record on which the record pointer is positioned.

RECNO( ) returns negative numbers for records appended in a table buffer.

RECNO( ) returns a value that is one greater than the number of records in the table if the record pointer is positioned beyond the last record in the table. RECNO( ) returns 1 if the record pointer is positioned before the first record in the table or the table has no records. If a table has no records, EOF( ) always returns true (.T.).

RECNO( ) issued without the optional arguments nWorkArea or cTableAlias returns the current record number for the table in the currently selected work area.

If you have issued SEEK unsuccessfully in an indexed table, you can specify 0 for nWorkArea to use "soft seek" logic to return the record number of the closest matching record. RECNO(0) returns 0 if a close match cannot be found. Visual FoxPro generates an error message if you issue GO RECNO(0) when a close match isn't found.

Example

The following example searches the customer table for a company name, and, if the company name isn't found, uses RECNO(0) to return the closest matching company.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE customer  && Opens Customer table
SET ORDER TO company
SEEK 'Ernst'
IF FOUND( )
   DISPLAY company, contact
ELSE
   GOTO RECNO(0)
   CLEAR
   ? 'Closest matching company is ' + company
   ? 'Record number: ' + ALLTRIM(STR(RECNO( )))
ENDIF

See Also

GO|GOTO | RECCOUNT( ) | RECSIZE( ) | SEEK | SKIP


RECSIZE( ) Function

Returns the size (width) of a table record.

RECSIZE([nWorkArea | cTableAlias])

Return Values

Numeric

Parameters

nWorkArea
Specifies the work area number for a table open in another work area. RECSIZE( ) returns 0 if a table isn't open in the work area you specify.
cTableAlias
Specifies the table alias for a table open in another work area.

Remarks

RECSIZE( ) issued without the optional arguments nWorkArea or cTableAlias returns the record size for the table in the currently selected work area.

Example

In the following example, Microsoft Visual FoxPro compares the available disk space with the amount needed to sort customer.

*** Check DISKSPACE before a SORT ***

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table

*** Get size of table header ***

gnTableHead = HEADER( )

*** Calculate size of table ***

gnFileSize = gnTableHead + (RECSIZE( ) * RECCOUNT( ) + 1)
IF DISKSPACE( ) > (gnFileSize * 3)
   WAIT WINDOW 'Sufficient diskspace to sort.'
ELSE
   WAIT WINDOW 'Insufficient diskspace. Sort cannot be done.'
ENDIF

See Also

RECCOUNT( ) | FSIZE( ) | HEADER( )


REFRESH( ) Function

Refreshes data in an updatable SQL view.

REFRESH([nRecords [, nRecordOffset]] [, cTableAlias | nWorkArea])

Return Values

Numeric

Parameters

nRecords
Specifies the number of records to refresh. If nRecords is 1 or you omit nRecords, only the current record is refreshed. If nRecords is 0, no records are refreshed.
nRecordOffset
Specifies the number of records before the current record where the refresh begins. For example, if the current record is record 10 and nRecordOffset is 4, record refresh begins with record 6. If nRecordOffset is 0 or you omit nRecordOffset, the refresh begins with the current record.
cTableAlias
Specifies the alias of the remote SQL view in which records are refreshed.
nWorkArea
Specifies the work area of the table or cursor in which records are refreshed. If you omit nWorkArea and cTableAlias, records are refreshed in the remote SQL view in the currently selected work area.

Remarks

REFRESH( ) returns the number of records refreshed.

The records are refreshed with data from the tables from which the SQL view is created. Records are refreshed in the SQL view open in the currently selected work area.

REFRESH( ) cannot refresh locked or buffered records, and the records must have unique primary keys. If a record in a table does not have a primary key value, the corresponding record in the SQL view is marked for deletion.

Tip Calling the REFRESH( ) function can result in a significant impact on performance, because the function reexecutes the query on which the view is based. Therefore, do not call this function more than necessary.

See Also

CREATE SQL VIEW | CURSORGETPROP( ) | CURSORSETPROP( )


RELATION( ) Function

Returns a specified relational expression for a table open in a specific work area.

RELATION(nRelationNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nRelationNumber
Specifies which relation is returned. For example, if nRelationNumber is 3, RELATION( ) returns the relational expression for the third relation created.
nWorkArea
Specifies the work area for a table open in another work area. If a table isn't open in the work area you specify, RELATION( ) returns the empty string.
cTableAlias
Specifies the table alias for a table open in another work area.

Remarks

RELATION( ) by default returns relational expressions for the table in the currently selected work area. It returns the empty string if no relations exist. For additional information about creating relations between tables, see SET RELATION.

DISPLAY STATUS and LIST STATUS display relational expressions. Issue MODIFY DATABASE to display the Database Designer, allowing you to view and modify relations between tables in the current open database. Issue SET to display the Data Session window, allowing you to view and modify relations between free tables.

Example

In the following example, tables are opened and orders set, and then the relations are displayed using RELATION( ).

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer IN 0 ORDER cust_id  && Opens Customer table
USE employee IN 0 ORDER emp_id  && Opens Customer table
USE orders IN  0 ORDER order_id  && Opens Customer table
SELECT orders
SET RELATION TO emp_id INTO employee
SET RELATION TO cust_id INTO customer ADDITIVE
? RELATION(1)  && Displays CUST_ID
? RELATION(2)  && Displays EMP_ID
? RELATION(3)  && Displays empty string

See Also

DISPLAY STATUS | MODIFY DATABASE | LIST STATUS | SET | SET RELATION | SET RELATION OFF | TARGET( )


REMOVEPROPERTY( ) Function

Removes a property from an object at run time.

REMOVEPROPERTY(oObjectName, cPropertyName)

Parameters

oObjectName
Specifies the name of the object from which to remove the property.
cPropertyName
Specifies the name of the existing property to remove from the object. You can specify only a property name, not an event or method name.

Return Values

Logical data type. REMOVEPROPERTY( ) returns True (.T.) if it successfully removes the property; otherwise, it returns False (.F.).

Remarks

You can use REMOVEPROPERTY( ) to remove properties, but not methods or events. You can use REMOVEPROPERTY( ) with object instances created from Visual FoxPro classes, COM classes, SCATTER...NAME command, _VFP, and _SCREEN.

Properties must be visibly Public, not Hidden or Protected and have been added to an instance of an object, typically using the ADDPROPERTY( ) function, the AddProperty method, or SCATTER...NAME command, so that they can be removed using REMOVEPROPERTY( ).

You cannot remove a property if it is a member of the class definition used to create the instance of the object.

REMOVEPROPERTY( ) function does not remove properties that are specific array elements. To remove an array, provide only the array name.

Examples

Example 1

The following example adds a new property to an object created with the SCATTER command and then removes it.

USE customers
SCATTER NAME oCust
ADDPROPERTY(oCust,"MyProperty")
REMOVEPROPERTY(oCust,"MyProperty")

Example 2

The following example creates a property array for the object, oMyForm, displays its contents, 1 and "Two", and then removes it.

oMyForm = CREATEOBJECT('Form')
ADDPROPERTY(oMyForm, 'MyArray(2)', 1)
oMyForm.MyArray(2) = "Two"
CLEAR
? oMyForm.MyArray(1)
? oMyForm.MyArray(2)
REMOVEPROPERTY(oMyForm, 'MyArray')
RELEASE oMyForm
CLEAR

See Also

Functions | ADDPROPERTY( ) Function | AddProperty Method


REPLICATE( ) Function

Returns a character string that contains a specified character expression repeated a specified number of times.

REPLICATE(cExpression, nTimes)

Return Values

Character

Parameters

cExpression
Specifies the character expression that is replicated.
nTimes
Specifies the number of times the character expression is replicated.

Remarks

In Visual FoxPro, the maximum length of the resulting character string is restricted by the amount of available memory.

Example

CLEAR
? REPLICATE('HELLO ',4) && Displays HELLO HELLO HELLO HELLO

See Also

SPACE( ) | Creating Character Expressions | CLEAR Commands


REQUERY( ) Function

Retrieves data again for a SQL view.

REQUERY([nWorkArea | cTableAlias])

Parameters

nWorkArea
Specifies the work area in which the SQL view is open.
cTableAlias
Specifies the alias of the SQL view. If you omit nWorkArea and cTableAlias, the data for the SQL view open in the currently selected work area is retrieved.

Return Values

Numeric

Remarks

REQUERY( ) returns 1 if the data is successfully retrieved; otherwise, it returns 0.

REQUERY( ) is typically used to refresh a SQL view when data has changed on the data source.

See Also

CREATE SQL VIEW | SELECT - SQL | USE | CREATE QUERY Command


RGB( ) Function

Returns a single color value from a set of red, green, and blue color components.

RGB(nRedValue, nGreenValue, nBlueValue)

Parameters

nRedValue
Specifies the intensity of the red color component. nRedValue can range from 0 to 255. Zero is the minimum color intensity; 255 is the maximum color intensity.
nGreenValue
Specifies the intensity of the green color component. nGreenValue can range from 0 to 255.
nBlueValue
Specifies the intensity of the blue color component. nBlueValue can range from 0 to 255.

Remarks

The value returned by RGB( ) can be used to set color properties such as BackColor and ForeColor.

Example

The following example uses RGB( ) to change the background color of a Form to blue.

goMyForm = CREATEOBJECT('FORM')  && Create a form
goMyForm.Show  && Display the form
WAIT WINDOW 'Press a key to change the form color'
goMyForm.BackColor=RGB(0,0,255)  && Change the form background color
WAIT WINDOW 'Press a key to release the form'
RELEASE goMyForm  && Release the form from memory

See Also

GETCOLOR( ) | RGBSCHEME( ) | BackColor, ForeColor Properties


RGBSCHEME( ) Function

Returns an RGB color pair or an RGB color pair list from a specified color scheme.

RGBSCHEME(nColorSchemeNumber [, nColorPairPosition])

Return Values

Character

Parameters

nColorSchemeNumber
Specifies the number of the color scheme for which you want a complete RGB color listing. RGBSCHEME( ) returns 10 RGB color pairs.
nColorPairPosition
Returns a single RGB color pair from a color scheme. nColorPairPosition specifies the position of the RGB color pair in the color scheme. For example, if nColorPairPosition is 4, the fourth RGB color pair is returned.

Remarks

Use SCHEME( ) to return a traditional color pair or a color pair list from a color scheme. RGB color pairs use numeric values to specify colors. Traditional color pairs use letters to specify colors.

Example

The following displays the third RGB color pair from color scheme number 4.

CLEAR
? RGBSCHEME(4,3)

See Also

RGB( ) | SCHEME( )


RIGHT( ) Function

Returns the specified number of rightmost characters from a character string.

RIGHT(cExpression, nCharacters)

Return Values

Character

Parameters

cExpression
Specifies the character expression whose rightmost characters are returned.
nCharacters
Specifies the number of characters returned from the character expression. RIGHT( ) returns the entire character expression if nCharacters is greater than the length of cExpression. RIGHT( ) returns an empty string if nCharacters is negative or 0.

Remarks

Characters are returned beginning with the last character on the right and continuing for a specified number of characters.

Example

CLEAR
? RIGHT('Redmond, WA', 2)  && Displays WA

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | LEFTC( ) Function | LTRIM( ) | RAT( ) | RATLINE( ) | RTRIM( ) | SUBSTR( ) | RIGHTC( ) | SUBSTRC( ) | TRIM( )


RIGHTC( ) Function

Returns the specified number of rightmost characters from a character string.

RIGHTC(cExpression, nCharacters)

Return Values

Character

Parameters

cExpression
Specifies the character expression whose rightmost characters are returned.
nCharacters
Specifies the number of characters returned from the character expression. RIGHTC( ) returns the entire character expression if nCharacters is greater than the length of cExpression. RIGHTC( ) returns an empty string if nCharacters is negative or 0.

Remarks

RIGHTC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, RIGHTC( ) is equivalent to RIGHT( ).

Characters are returned beginning with the last character on the right and continuing for nCharacters.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | LEFTC( ) Function | RAT( ) | RATLINE( ) | SUBSTR( ) | RIGHT( ) | SUBSTRC( )


RLOCK( ) Function

Attempts to lock a table record or records.

RLOCK([nWorkArea | cTableAlias] | [cRecordNumberList, nWorkArea
 | cTableAlias])

Return Values

Logical

Parameters

nWorkArea | cTableAlias
Specifies the work area number or table alias for a table open in another work area. If you don't specify a work area or alias, RLOCK( ) attempts to lock the current record in the table in the currently selected work area.
cRecordNumberList
Specifies that RLOCK( ) attempts to lock multiple records. The character expression cRecordNumberList specifies one or more record numbers, separated by commas, that RLOCK( ) attempts to lock. For example, to attempt record locks on the first four records in a table, cRecordNumberList should contain 1, 2, 3, 4.

To lock multiple records, you must have SET MULTILOCKS on and you must include the work area number (nWorkArea) or alias (cTableAlias) of the table in which you attempt to lock multiple records.

You can also lock multiple records by moving the record pointer to the record you would like to lock, issuing RLOCK( ) or LOCK( ) and then repeating this process for additional records.

In Visual FoxPro, you can specify 0 as a record number. Specifying 0 lets you attempt to lock the table header.

Caution Keep the table header locked for as short a time as possible because other users cannot add records to the table when the table header is locked.

Release the table header lock with UNLOCK RECORD 0, UNLOCK, or UNLOCK ALL.

If all the records specified in cRecordNumberList are successfully locked, RLOCK( ) returns true (.T.). If one or more of the records specified in cRecordNumberList cannot be locked, RLOCK( ) returns false (.F.) and locks none of the records. In either case, existing record locks remain in place. Multiple record locking is an additive process — placing additional record locks doesn't release existing record locks.

From a performance perspective, it is always faster to lock the entire table than to lock even a small number of records.

Remarks

RLOCK( ) is identical to LOCK( ).

If the lock or locks are successfully placed, RLOCK( ) returns true (.T.). Locked records are available for both read and write access by the user who placed the locks and for read-only access to all other users on the network.

Executing RLOCK( ) doesn't guarantee that the attempted record lock or locks are successfully placed. A record lock cannot be placed on a record already locked by another user or in a table locked by another user. If the record lock or locks cannot be placed for any reason, RLOCK( ) returns false (.F.).

By default, RLOCK( ) makes one attempt to lock a record. Use SET REPROCESS to automatically retry a record lock when the first attempt fails. SET REPROCESS controls the number of lock attempts or the length of time lock attempts are made when the initial lock attempt is unsuccessful. For more information about SET REPROCESS and table locking, see SET REPROCESS.

SET MULTILOCKS determines whether you can lock multiple records in a table. If SET MULTILOCKS is off (the default), you can lock only a single record in a table. If SET MULTILOCKS is on, you can lock multiple records in a table. For more information, see SET MULTILOCKS.

A table record can be unlocked only by the user who placed the lock. Record locks can be released by issuing UNLOCK, closing the table, or exiting Visual FoxPro.

UNLOCK can be used to release record locks in the current work area, a specific work area or in all work areas. For more information, see UNLOCK.

Switching SET MULTILOCKS from ON to OFF or from OFF to ON implicitly performs UNLOCK ALL. All record locks in all work areas are released.

To close tables, use USE, CLEAR ALL, or CLOSE DATABASES.

For more information about record and file locking and sharing tables on a network, see Programming for Shared Access.

Example

The following example locks and unlocks the first four records in the customer and employee tables.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
SET REPROCESS TO 3 AUTOMATIC
STORE '1,2,3,4' TO gcRecList
gcOldExc = SET('EXCLUSIVE')
SET EXCLUSIVE OFF
SELECT 0
USE employee  && Open Employee table
SELECT 0
USE customer  && Open Customer table
? LOCK('1,2,3,4', 'customer')  && Lock 1st 4 records in customer
? RLOCK(gcRecList, 'employee')  && Lock 1st 4 records in employee
UNLOCK IN customer
UNLOCK IN employee
SET EXCLUSIVE &gcOldExc

See Also

CLEAR | CLOSE | FLOCK( ) | LOCK( ) | SET MULTILOCKS | SET RELATION | SET REPROCESS | UNLOCK | USE | ISFLOCKED( ) Function | ISRLOCKED( ) Function


ROUND( ) Function

Returns a numeric expression rounded to a specified number of decimal places.

ROUND(nExpression, nDecimalPlaces)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression whose value is to be rounded.
nDecimalPlaces
Specifies the number of decimal places nExpression is rounded to.

If nDecimalPlaces is negative, ROUND( ) returns a whole number containing zeros equal in number to nDecimalPlaces to the left of the decimal point. For example, if nDecimalPlaces is –2, the first and second digits to the left of the decimal point in the value are 0.

Remarks

The value ROUND( ) returns has the same number of decimal places as nDecimalPlaces. ROUND( ) ignores the number of decimal places specified by SET DECIMALS.

Example

SET DECIMALS TO 4
SET FIXED ON     && Fix decimal display
CLEAR

? ROUND(1234.1962, 3) && Displays 1234.1960
? ROUND(1234.1962, 2) && Displays 1234.2000
? ROUND(1234.1962, 0) && Displays 1234.0000
? ROUND(1234.1962, -1)  && Displays 1230.0000
? ROUND(1234.1962, -2)  && Displays 1200.0000
? ROUND(1234.1962, -3)  && Displays 1000.0000

SET FIXED OFF  && Restore start up defaults
SET DECIMALS TO 2

See Also

CEILING( ) | FLOOR( ) | INT( ) | SET DECIMALS | SET FIXED Command


ROW( ) Function

Included for backward compatibility. Use the CurrentY property.


RTOD( ) Function

Converts radians to its equivalent in degrees.

You can use RTOD( ) when working with the Visual FoxPro trigonometric functions COS( ), SIN( ), and TAN( ).

RTOD(nExpression)

Parameters

nExpression
Specifies a numeric expression representing a radian value.

Return Values

Numeric data type. RTOD( ) returns the number of degrees converted from the number of radians.

Remarks

To convert degrees to radians, use the DTOR( ) function.

Example

CLEAR
? RTOD(ACOS(0))  && Displays 90.00
STORE -1 to gnArcAngle
? RTOD(ACOS(gnArcAngle))  && Displays 180.00
? RTOD(ACOS(SQRT(2)/2)) && Displays 45.00

See Also

COS( ) Function | DTOR( ) Function | SIN( ) Function | TAN( ) Function


RTRIM( ) Function

Returns a character string that results from removing the trailing blanks from a character expression.

RTRIM(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which trailing blanks are trimmed.

Remarks

RTRIM( ) can be used to ensure that blanks are removed from data entered by a user. RTRIM( ) is identical to TRIM( ).

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
CLEAR
? 'The contact for '+ RTRIM(company) + ' is ' + contact

See Also

ALLTRIM( ) Function | LTRIM( ) Function | TRIM( ) Function


SAVEPICTURE( ) Function

Creates a bitmap (.bmp) file from a picture object reference.

SAVEPICTURE(oObjectReference, cFileName)

Return Values

Logical

Parameters

oObjectReference
Specifies a picture object reference from which SAVEPICTURE( ) creates a bitmap file.
cFileName
Specifies the name of the bitmap file that SAVEPICTURE( ) creates. If cFileName includes a path, the file is created in the directory specified in the path. If a file with the same name already exists, it is overwritten without warning, even if SET SAFETY is ON.

Remarks

Picture object references are typically created with LOADPICTURE( ). However, certain properties (such as the PictureOpen property for the OLE Outline control) use a default picture object reference, which can be used to create a bitmap file.

See Also

LOADPICTURE( ) | SET SAFETY Command | _ObjectReference( ) API Library Routine


SCHEME( ) Function

Returns a color pair list or a single color pair from a specified color scheme.

SCHEME(nSchemeNumber [, nColorPairNumber])

Return Values

Character

Parameters

nSchemeNumber
Specifies the number of the color scheme for which you want a complete color-pair list. SCHEME( ) returns ten color pairs.
nColorPairNumber
Specifies the position of one color pair in the color scheme, and SCHEME( ) returns only this color pair. For example, if nColorPairNumber is 4, SCHEME( ) returns the fourth color pair from the color scheme.

Example

The following example returns the third color pair from color scheme number 4:

? SCHEME(4,3)

See Also

ColorScheme Property | GETCOLOR( ) Function


SCOLS( ) Function

Returns the number of columns available in the main Microsoft Visual FoxPro window.

SCOLS( )

Return Values

Numeric

Remarks

The value returned by SCOLS( ) depends on the current display mode. Display modes can be changed with SET DISPLAY.

See Also

COL( ) | ROW( ) | SET DISPLAY | SROWS( ) | WCOLS( ) | WROWS( )


SEC( ) Function

Returns the seconds portion from a DateTime expression.

SEC(tExpression)

Return Values

Numeric

Parameters

tExpression
Specifies the DateTime expression from which SEC( ) returns the second. If tExpression contains only a date and not a time, Visual FoxPro adds the default time of midnight (12:00:00 A.M.) to tExpression.

Example

The following example displays the second portion of the current time and the second portion of a specific time.

CLEAR
? SEC(DATETIME( ))
? SEC({^1998-08-21 10:42:16am})  && Displays 16

See Also

DATETIME( ) | HOUR( ) | MINUTE( ) | SET SECONDS


SECONDS( ) Function

Returns the number of seconds that have elapsed since midnight.

SECONDS( )

Return Values

Numeric

Remarks

SECONDS( ) returns a numeric value in decimal format, with a resolution of 1 millisecond. If you are running Windows NT 4.0 or later, resolution is 10 milliseconds.

Example

CLEAR
? SECONDS( )
? SECONDS( )/(60 * 60)

See Also

SYS(2) - Seconds Since Midnight | TIME( ) | Seconds Property


SEEK( ) Function

Searches an indexed table for the first occurrence of a record whose index key matches a specified expression. Returns a logical value indicating if the search was successful.

SEEK(eExpression [, nWorkArea | cTableAlias
   [, nIndexNumber | cIDXIndexFileName | cTagName]])

Return Values

Logical

Parameters

eExpression
Specifies the index key expression for which you want SEEK( ) to search.
nWorkArea
Specifies the work area number of the table that is searched for the index key.
cTableAlias
Specifies the alias of the table that is searched.

If you omit nWorkArea and cTableAlias, the table in the currently selected work area is searched.

nIndexNumber
Specifies the number of the index file or tag that is used to search for the index key. nIndexNumber refers to the index files as they are listed in USE or SET INDEX. Open .idx files are numbered first in the order in which they appear in USE or SET INDEX. Tags in the structural .cdx file (if one exists) are then numbered in the order in which they were created. Finally, tags in any open independent .cdx files are numbered in the order in which they were created. For more information about index numbering, see SET ORDER.
cIDXIndexFileName
Specifies an .idx file that is used to search for the index key.
cTagName
Specifies a tag of a .cdx file that is used to search for the index key. The tag name can be from a structural .cdx file or any open independent .cdx file.
Note The .idx file takes precedence if duplicate .idx file and tag names exist.

Remarks

You can use SEEK( ) on a table with an index order set, or if an index order is not set on the table, set the controlling index with the 3rd parameter, nIndexNumber, cIDXIndexFileName, or cTagName. The match must be exact unless SET EXACT is set to OFF.

If a match is found, SEEK( ) returns true (.T.), and the record pointer moves to the matching record. If no match is found, SEEK( ) returns false (.F.) and the record pointer moves to the end of the file. Issuing SEEK( ) is equivalent to issuing SEEK and FOUND( ) in succession.

If you omit the nIndexNumber, IDXIndexFileName, and cTagName arguments, SEEK( ) uses the master controlling index or index tag to search for the index key.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer ORDER cust_id  && Opens Customer table
? SEEK('CHOPS')  && Returns .T., record found

See Also

EOF( ) | FOUND( ) | INDEXSEEK( ) | LOCATE | SEEK | SET ORDER


SELECT( ) Function

Returns the number of the currently selected work area or the highest-numbered unused work area.

SELECT([ 0 | 1 | cTableAlias ])

Return Values

Numeric

Parameters

0
Specifies that SELECT( ) return the number of the current work area.
1
Specifies that SELECT( ) return the highest-numbered unused work area.
cTableAlias
Specifies the alias of the table for which SELECT( ) returns the work area.

Remarks

SELECT( ) returns the number of the current work area if SET COMPATIBLE is set to OFF. If SET COMPATIBLE is set to ON, SELECT( ) returns the number of the unused work area with the highest number.

A work area can be selected (activated) with SELECT.

Example

CLOSE DATABASES
SET COMPATIBLE ON
OPEN DATABASE (HOME(2) + 'data\testdata')

SELECT 0  && Unused work area
USE customer  && Opens Customer table

SELECT 0  && Unused work area
USE orders  && Opens Orders table

CLEAR
? SELECT( )  && Returns 3, lowest available work area

See Also

ALIAS( ) | SELECT | SET COMPATIBLE


SET( ) Function

Returns the status of various SET commands.

SET(cSETCommand [, 1 | cExpression | 2 | 3 | 4])

Parameters

cSETCommand
Specifies a character expression of the SET command for which you want to return information. The current setting of the specified command is returned as a character or numeric string.
1 | cExpression | 2 | 3 | 4
Specifies additional information to return about a SET command. The values 1 and cExpression are identical; cExpression can be any expression that evaluates to a character type value.
Note Including an argument does not return additional information for all SET commands, only those specifying values of 1, 2, 3, or 4 in the following table.
SET command | Value returned
ALTERNATE | ON or OFF
ALTERNATE, 1 | FileName
BELL, 1 | cWAVFileName
CARRY | ON or OFF
CENTURY | ON or OFF
CENTURY, 1 | nCentury
CENTURY, 2 | ROLLOVER nYear
CENTURY, 3 | System Regional Calendar setting
CLOCK | ON or OFF
CLOCK, 1 | nRow and nColumn
COMPATIBLE | ON or OFF
COMPATIBLE, 1 | PROMPT or NOPROMPT
COVERAGE, 1 | FileName
CURRENCY | LEFT or RIGHT
CURRENCY, 1 | cCurrencySymbol
DATE | AMERICAN, ANSI, BRITISH/FRENCH, GERMAN, ITALIAN, JAPAN, USA, MDY, DMY, or YMD
DATE, 1 | Date Ordering:0 – MDY1 – DMY2 – YMD
DELIMITERS | ON or OFF
DELIMITERS, 1 | cDelimiters
EVENTTRACKING | ON or OFF
EVENTTRACKING, 1 | FileName
FIELDS | ON or OFF
FIELDS, 1 | FieldName1, FieldName2, ...
FIELDS, 2 | LOCAL or GLOBAL
HELP | ON or OFF
HELP, 1 | cFileName
HELP, 2 | cCollectionURL
HELP, 3 | SYSTEM
KEY | eExpression2, eExpression3
KEY, 1 | eExpression2
KEY, 2 | eExpression3
MESSAGE | nRow
MESSAGE, 1 | cMessageText
MOUSE | ON or OFF
MOUSE, 1 | nSensitivity
NOTIFY | ON or OFF
NOTIFY, 1 | ON or OFF
PRINTER | ON or OFF
PRINTER, 1 | FileName or PortName
PRINTER, 2 | Default Windows printer name
PRINTER, 3 | Default Visual FoxPro printer name(specified in the Visual FoxPro Print or Print Setup dialog boxes)
REFRESH | nSeconds1
REFRESH, 1 | nseconds2
REPROCESS | Current session setting
REPROCESS, 1 | System session setting
RESOURCE | ON or OFF
RESOURCE, 1 | FileName
TALK | ON or OFF
TALK, 1 | WINDOW, NOWINDOW or WindowName
TEXTMERGE | ON or OFF
TEXTMERGE, 1 | cLeftDelimiter and cRightDelimiter
TEXTMERGE, 2 | cFileName
TEXTMERGE, 3 | SHOW/NOSHOW
TEXTMERGE, 4 | Evaluate source of TEXT ... ENDTEXT call and return TEXTMERGE nesting level.
TOPIC | cHelpTopicName | lExpression
TOPIC, 1 | NContextID

Return Values

Character or Numeric data type. SET( ) returns the value of a SET command.

Remarks

SET( ) recognizes the four-character abbreviation for all Visual FoxPro SET keywords, with the exception of HELPFILTER, which can be abbreviated to five characters. For example, you can use STAT and PRIN for SET STATUS and SET PRINTER, respectively.

The SET( ) function is identical to SYS(2001).

SET("CENTURY", 3) passes a Calendar value of 2 (Gregorian (U.S.)) in a call to the Windows GetCalendarInfo( ) API.

See Also

DISPLAY STATUS | LIST | SET | SYS(2001) – SET ... Command Status


SETFLDSTATE( ) Function

Assigns a field modification or deletion state value to a field or record in a table or cursor.

SETFLDSTATE(cFieldName | nFieldNumber, nFieldState [, cTableAlias
   | nWorkArea])

Return Values

Logical

Parameters

cFieldName | nFieldNumber
Specifies the name or the number of the field for which the modification or deletion status is assigned. The field number nFieldNumber corresponds to the position of the field in the table or cursor structure. DISPLAY STRUCTURE or FIELD( ) can be used to determine a field's number.

To set the deletion status for the record, include 0 as the field number.

nFieldState
Specifies a value for the field modification or deletion status. The following table lists the field modification or deletion state value and the corresponding modification or deletion status:
nFieldState | Modification or deletion status
1 | Field has not been modified or deletion status has not changed.
2 | Field has been modified or deletion status has changed.
3 | Field in an appended record has not been modified or deletion status has not changed for the appended record.
4 | Field in an appended record has been modified or deletion status has changed for the appended record.
cTableAlias
Specifies the alias of the table or cursor in which the modification or deletion status is assigned.
nWorkArea
Specifies the work area of the table or cursor in which the modification or deletion status is assigned. The field modification or deletion state value is assigned for the table or cursor open in the currently selected work area if SETFLDSTATE( ) is issued without the optional cTableAlias or nWorkArea arguments.

Remarks

Visual FoxPro uses field state values to determine which fields in tables or cursors are updated. SETFLDSTATE( ) makes it possible for you to control which fields Visual FoxPro attempts to update, regardless of which fields have been modified in the table or cursor.

Example

The following example demonstrates how you can use SETFLDSTATE( ) to change the field status. MULTILOCKS is set to ON, a requirement for table buffering. The customer table in the testdata database is opened, and CURSORSETPROP( ) is then used to set the buffering mode to optimistic table buffering (5).

GETFLDSTATE( ) is issued to display a value (1) corresponding to the unmodified state of the cust_id field before it is modified. The cust_id field is modified with REPLACE, and GETFLDSTATE( ) is issued again to display a value (2) corresponding to the modified state of the cust_id field.

SETFLDSTATE( ) is used to change the field status of the cust_id field back to 1 (unmodified). GETFLDSTATE( ) is issued again and displays 1, corresponding to the state of the cust_id field assigned by SETFLDSTATE( ). TABLEREVERT( ) is used to return the table to its original state.

CLOSE DATABASES
SET MULTILOCKS ON  && Must be on for table buffering
SET PATH TO (HOME(2) + 'Data\')     && Sets path to database
OPEN DATABASE testdata  && Open testdata database
USE Customer     && Open customer table
= CURSORSETPROP('Buffering', 5, 'customer')  && Enable table buffering

CLEAR
? GETFLDSTATE('cust_id')  && Displays 1, not modified
REPLACE cust_id    WITH '***'  && Changes field contents
? GETFLDSTATE('cust_id')  && Returns 2, field modified
= SETFLDSTATE('cust_id', 1)  && Change the field status
? GETFLDSTATE('cust_id')  && Displays 1, not modified
= TABLEREVERT(.T.)  && Discard all table changes

See Also

DELETED( ) | DISPLAY STRUCTURE | FIELD( ) | GETFLDSTATE( )


SIGN( ) Function

Returns a numeric value of 1, –1, or 0 if the specified numeric expression evaluates to a positive, negative, or 0 value.

SIGN(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression SIGN( ) evaluates. SIGN( ) returns 1 if nExpression evaluates to a positive number, –1 if nExpression evaluates to a negative number, and 0 if nExpression evaluates to 0.

Example

STORE 10 TO gnNum1
STORE -10 TO gnNum2
STORE 0 TO gnZero
CLEAR
? SIGN(gnNum1)  && Displays 1
? SIGN(gnNum2)  && Displays -1
? SIGN(gnZero)  && Displays 0

See Also

ABS( ) | COS( ) | SIN( )


SIN( ) Function

Returns the sine of an angle.

SIN(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies an angle whose sine SIN( ) returns. nExpression can assume any value and the value returned by SIN( ) ranges between –1 and 1.
Note nExpression is specified in radians. Use DTOR( ) to convert an angle from degrees to radians. The number of decimal places displayed by SIN( ) can be specified with SET DECIMALS.

Example

CLEAR
? SIN(0)  && Displays 0.00
? SIN(PI( )/2)  && Displays 1.00
? SIN(DTOR(90))  && Displays 1.00

See Also

ACOS( ) | COS( ) | DTOR( ) | RTOD( ) | SET DECIMALS


SKPBAR( ) Function

Determines if a menu item is enabled or disabled with SET SKIP OF.

SKPBAR(cMenuName, MenuItemNumber)

Return Values

Logical

Parameters

cMenuName
Specifies the name of the menu that contains the item.
MenuItemNumber
Specifies the number of the menu item whose status (enabled or disabled) SKPBAR( ) returns. The menu item number is assigned when the menu item is created with DEFINE BAR.

Remarks

SKPBAR( ) returns true (.T.) if the menu item is disabled, and false (.F.) if the menu item is enabled.

See Also

DEFINE BAR | SET SKIP OF | SKPPAD( )


SKPPAD( ) Function

Determines whether a menu title is enabled or disabled with SET SKIP OF.

SKPPAD(cMenuBarName, cMenuTitleName)

Return Values

Logical

Parameters

cMenuBarName
Specifies the name of the menu bar that contains the menu title.
cMenuTitleName
Specifies the name of the menu title whose status (enabled or disabled) SKPPAD( ) returns.

Remarks

SKPPAD( ) returns true (.T.) if the menu title is disabled, and false (.F.) if the menu title is enabled.

See Also

DEFINE BAR | SET SKIP OF | SKPBAR( )


SOUNDEX( ) Function

Returns a phonetic representation of the specified character expression.

SOUNDEX(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression SOUNDEX( ) evaluates.

Remarks

SOUNDEX( ) returns a four-character string. By comparing the results SOUNDEX( ) returns for two character expressions, you can determine if the two expressions are phonetically similar, indicating that they sound alike. This can be useful when searching for duplicate records in a table.

SOUNDEX( ) isn't case sensitive and generally disregards vowels.

Example

CLEAR
? SOUNDEX('Smith') = SOUNDEX('Smyth')  && Displays .T.
? SOUNDEX('Computer')  && Displays C513

See Also

DIFFERENCE( ) | Sound Player | Creating Character Expressions


SPACE( ) Function

Returns a character string composed of a specified number of spaces.

SPACE(nSpaces)

Return Values

Character

Parameters

nSpaces
Specifies the number of spaces that SPACE( ) returns. The maximum value of nSpaces is limited only by memory in Microsoft Visual FoxPro.

See Also

PADC( ) | PADL( ) | PADR( ) | REPLICATE( )


SQLCANCEL( ) Function

Requests cancellation of an executing SQL statement.

SQLCANCEL( ) cancels the execution of SQLCOLUMNS( ), SQLEXEC( ), SQLMORERESULTS( ), and SQLTABLES( ) in asynchronous mode. To establish asynchronous mode, use the SQLSETPROP( ) function.

SQLCANCEL(nStatementHandle)

Parameters

nStatementHandle
Specifies the active statement handle whose SQL statement is to be canceled.

Return Values

Numeric. SQLCANCEL( ) returns 1 if the SQL statement is successfully canceled, – 1 if there is a connection level error, and – 2 if there is an environment level error.

Example

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle.

SQLEXEC( ) is used to sends a SQL statement to the data source and return the results to a cursor. SQLCANCEL( ) is issued to stop the query.

= SQLSETPROP(gnHandle, 'asynchronous', .T.)   && To stop SQLEXEC( )
= SQLEXEC(gnHandle, 'SELECT * FROM authors')
= SQLCANCEL(gnHandle)   && Wrong select statement, cancel

See Also

AERROR( ) | SQLCOLUMNS( ) | SQLEXEC( ) | SQLMORERESULTS( ) | SQLSETPROP( ) | SQLTABLES( )


SQLCOLUMNS( ) Function

Stores a list of column names and information about each column for the specified data source table to a Visual FoxPro cursor.

SQLCOLUMNS(nStatementHandle, cTableName
    [, "FOXPRO" | "NATIVE"] [, cCursorName])

Parameters

nStatementHandle
Specifies an active statement handle.
cTableName
Specifies the name of the table from which the column names are returned. TableName can contain the wildcard characters ? and *. The question mark (?) matches any single character and the asterisk (*) matches any number of characters.
FOXPRO | NATIVE
Specifies the format for the column information in the result set. Be sure to enclose FOXPRO or NATIVE in quotation marks. The NATIVE format option stores column information for tables in the same format as the data source. The FOXPRO format option stores the column information in the same format as that used for the Visual FoxPro table or cursor that would be created if you imported the data source table into Visual FoxPro. If you omit FOXPRO or NATIVE, the format option defaults to FOXPRO.

The following table shows the columns in the result set for the FOXPRO format.

Column name | Description
Field_name | Column name
Field_type | Column data type
Field_len | Column length
Field_dec | Number of decimal places

The following table shows the columns in the result set for the NATIVE format. In NATIVE format, depending on the data source, additional columns not listed in the following table may be included in the result set.

Column name | Description
Table_qualifier | Table qualifier identifier
Table_owner | Table owner identifier
Table_name | Table identifier
Column_name | Column identifier
Data_type | Column data type
Type_name | Column data type name
Precision | Precision of the column
Length | Transfer size of the data
Scale | Scale of the column
Radix | Base for Numeric type
Nullable | Supports null values
Remarks | Description of the column

If the table you specify with cTableName does not exist and the format is set to NATIVE, SQLCOLUMNS( ) returns true (.T.) and creates an empty table or cursor. If the table you specify with cTableName does not exist and the format is set to FOXPRO, SQLCOLUMNS( ) returns false (.F.).

cCursorName
Specifies the name of the Visual FoxPro cursor for the result set. If you do not include a cursor name, Visual FoxPro uses the default name SQLRESULT.

Return Values

Numeric or Logical. SQLCOLUMNS( ) returns 1 if the cursor is successfully created, 0 if SQLCOLUMNS( ) is still executing, – 1 if a connection level error occurs, and – 2 if an environment level error occurs.

Remarks

SQLCOLUMNS( ) is one of the four functions that you can execute either synchronously or asynchronously. The Asynchronous setting of SQLSETPROP( ) determines if these functions execute synchronously or asynchronously. In asynchronous mode, you must call SQLCOLUMNS( ) repeatedly until a value other than false (.F.) (still executing) is returned.

Example

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLCOLUMNS( ) is used to create a cursor named MyCursor containing information about the columns in the authors table.

= SQLCOLUMNS(gnHandle, 'authors', 'FOXPRO', 'MyCursor')

See Also

AERROR( ) | SQLGETPROP( ) | SQLSETPROP( ) | SQLTABLES( )


SQLCOMMIT( ) Function

Commits a transaction.

SQLCOMMIT(nStatementHandle)

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).

Return Values

Numeric. SQLCOMMIT( ) returns 1 if the transaction is successfully committed; otherwise, it returns -1. If SQLCOMMIT( ) returns -1, you can use AERROR( ) to determine why the transaction could not be committed.

Remarks

If manual transactions are in effect (the SQLSETPROP( ) Transactions property is set to Manual), you can send multiple updates to remote tables and commit all the updates with SQLCOMMIT( ).

Updates can be rolled back with SQLROLLBACK( ).

Example

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLSETPROP( ) is used to set the Transactions property to 2 (Manual), allowing you to use SQLCOMMIT( ) and SQLROLLBACK( ).

The authors table is modified with SQLEXEC( ), and the changes to the table are committed with SQLCOMMIT( ).

= SQLSETPROP(gnHandle, 'Transactions', 2)  && Manual transactions
= SQLEXEC(gnHandle, "INSERT INTO authors (au_id, au_lname);
   VALUES ('aupoe', 'Poe')")  && Modify the authors table
= SQLCOMMIT(gnHandle)  && Commit the changes

See Also

AERROR( ) | BEGIN TRANSACTION | END TRANSACTION | SQLCONNECT( ) | SQLROLLBACK( ) | SQLSETPROP( )


SQLCONNECT( ) Function

Establishes a connection to a data source.

SQLCONNECT([nStatementHandle])

-or-

SQLCONNECT([cConnectionName | cDataSourceName [, cUserID [, cPassword ]][, lShared]])

Parameters

nStatementHandle
Specifies that a new statement handle be created for the underlying shared connection that is represented by nStatementHandle. The new statement handle uses the settings provided from nStatementHandle instead of using the default settings.
Note You cannot create a new statement handle for a connection that is not shared. Visual FoxPro generates an error if you attempt to create a new statement handle against a nonshared connection.

You can also use SQLCONNECT( ) to obtain a new statement handle on a shared connection that was opened using SQLSTRINGCONNECT( ).

cConnectionName
Specifies a named connection created by the CREATE CONNECTION command.

When using CREATE CONNECTION or the Connection Designer to create a named connection, you can configure the connection by specifying a data source name, user ID, and password. When using the named connection in SQLCONNECT( ) as cConnectionName, you can pass values different from those in the named connection for the optional cUserID and cPassword parameters. These passed values are used instead of the user ID and password in the named connection specified by cConnectionName.

For example, suppose you create a named connection called myNamedConnection using CREATE CONNECTION or the Connection Designer and specify the values myUserID and myPassword for the named connection. For SQLCONNECT( ), you can specify myNamedConnection as cConnectionName and then specify myAltUserID and myAltPassword as an alternate user ID and password as in the following code:

SQLCONNECT("myNamedConnection", "myAltUserID", "myAltPassword")

However, if you create a named connection using a connection string with CREATE CONNECTION or the Connection Designer, use the named connection in SQLCONNECT( ), and attempt to pass optional user ID and password parameters to SQLCONNECT( ), Visual FoxPro generates the appropriate message.

When creating a new shared connection, the cConnectionName parameter refers to a named connection in the current database container (DBC).

When creating a new statement handle based on an existing shared connection, the cConnectionName parameter refers to a previous connection opened in shared mode.

If you use the cConnectionName parameter without the lShared parameter or with lShared parameter as False (.F.), you will always create a new connection that is not shared.

When using cConnectionName, if lShared is True (.T.) and the named connection is already open in shared mode, the user name and password provided should match those previously used. Otherwise, Visual FoxPro generates the appropriate message.

cDataSourceName
Specifies the name of a data source as defined in your Odbc.ini file.

You can also choose a data source from the Select Connection or Data Source Dialog Box, which appears when you call SQLCONNECT( ) without any additional arguments or with only the lShared parameter.

cUserID
Specifies the user identifier used to log on to the data source.
cPassword
Specifies the password for gaining access to the data source.
lShared
Specifies whether or not to create a shared connection.
lShared | Description
False (.F.) | SQLCONNECT( ) does not create a shared connection. (Default)
True (.T.) | SQLCONNECT( ) creates a shared connection.

Return Values

Numeric data type. SQLCONNECT( ) returns a positive nonzero numeric value as the statement handle if you successfully connect to the data source. SQLCONNECT( ) returns –2 if it cannot make the connection.

Tip You should store this statement handle in a memory variable and use the variable in subsequent function calls that require a connection handle.

Remarks

The SQLCONNECT( ) and SQLSTRINGCONNECT( ) functions return a numeric value as the statement handle rather than a connection handle. You cannot obtain a connection handle directly. You can still set and get connection properties using the SQLSETPROP( ) and SQLGETPROP( ) functions by passing the statement handle for that connection and the string, "Shared", as arguments. All other SQL functions use a statement handle instead of a connection handle.

If you issue a statement such as SQLCONNECT(cConnectionName, .T.), and a shared connection is already open with the same name, then the settings for that connection do not change to the settings stored for that connection in the database container (DBC). However, the new statement handle will use the statement settings from the DBC.

Note You must disable the Open Database Connectivity (ODBC) login dialog box to support SQL pass through with Microsoft Transaction Server. To disable the ODBC login dialog box, use the statement SQLSETPROP(nStatementHandle, 'DispLogin', 3), where cStatementHandle is the statement handle returned by SQLCONNECT( ). You can also disable the ODBC login dialog box in the Connection Designer.

Example

Example 1

The following example assumes that an ODBC data source called MyFoxSQLNT exists and is available. SQLCONNECT( ) returns a numeric value, which is stored to a variable named gnConnHandle.

If you successfully connect to the data source, SQLCONNECT( ) returns a positive number, a dialog box appears, and SQLDISCONNECT( ) is called to disconnect from the data source.

If you cannot connect to the data source, SQLCONNECT( ) returns a negative number and displays a message.

STORE SQLCONNECT('MyFoxSQLNT', 'myUserID', 'myPassword') TO gnConnHandle
IF gnConnHandle <= 0
   = MESSAGEBOX('Cannot make connection', 16, 'SQL Connect Error')
ELSE
   = MESSAGEBOX('Connection made', 48, 'SQL Connect Message')
   = SQLDISCONNECT(gnHandle)
ENDIF

Example 2

Each of the following examples create new shared connections. The Choose Data Source Dialog Box appears, and SQLCONNECT( ) creates the resulting connection as shared.

SQLCONNECT(.T.)
SQLCONNECT( myConnectionName, .T. )
SQLCONNECT( myDataSourceName, myUserID, myPassword, .T. )

Example 3

Each of the following examples creates a new statement handle based on an existing shared connection.

SQLCONNECT( nStatementHandleValue )
SQLCONNECT( myConnectionName, .T. )

See Also

AERROR( ) | CREATE CONNECTION | SQLDISCONNECT( ) | SQLGETPROP( ) | SQLEXEC( ) | SQLSETPROP( ) | SQLSTRINGCONNECT( )


SQLDISCONNECT( ) Function

Terminates a connection to a data source.

SQLDISCONNECT(nStatementHandle)

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ). Specify 0 for nStatementHandle to terminate all active connections.

Return Values

Numeric. SQLDISCONNECT( ) returns 1 if the connection is successfully terminated, – 1 if there is a connection level error, and – 2 if there is an environment level error.

Remarks

SQLDISCONNECT( ) terminates a connection to a data source. You must supply the statement handle that SQLCONNECT( ) returned when you established the connection.

Note If you execute SQLDISCONNECT( ) within an asynchronous function sequence or during a transaction, SQLDISCONNECT( ) generates an error.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. SQLCONNECT( ) is issued, and its return value is stored to a variable named gnHandle.

If you successfully connect to the data source, SQLCONNECT( ) returns a positive number, a dialog is displayed and SQLDISCONNECT( ) is used to disconnect from the data source.

If you cannot connect to the data source, SQLCONNECT( ) returns a negative number and a message is displayed.

STORE SQLCONNECT('MyFoxSQLNT', '<userid>', '<password>') TO gnHandle
IF gnHandle <= 0
   = MESSAGEBOX('Cannot make connection', 16, 'SQL Connect Error')
ELSE
   = MESSAGEBOX('Connection made', 48, 'SQL Connect Message)
   = SQLDISCONNECT(gnHandle)
ENDIF

See Also

AERROR( ) | SQLCONNECT( ) | SQLSTRINGCONNECT( )


SQLEXEC( ) Function

Sends a SQL statement to the data source, where the statement is processed.

SQLEXEC(nStatementHandle, [cSQLCommand, [cCursorName]])

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).
cSQLCommand
Specifies the SQL statement passed to the data source.

The SQL statement can contain a parameterized WHERE clause, which creates a parameterized view. You must define all parameters in the WHERE clause before issuing SQLEXEC( ). For example, if the parameters are variables, the variables must be created and initialized before SQLEXEC( ) is issued. For additional information about creating parameterized views, see Creating Views.

You can include expressions in the SQL statement. Visual FoxPro evaluates all expressions in the SQL statement that you pass before sending them to the data source. Visual FoxPro can evaluate memory variable names, function calls, and expressions enclosed in parentheses as parameter values.

cCursorName
Specifies the name of the Visual FoxPro cursor to which the result set is sent. If you don't include a cursor name, Visual FoxPro uses the default name SQLRESULT.

For multiple result sets, new cursor names are derived by appending an incremented number to the name of the first cursor.

Return Values

Numeric data type. SQLEXEC( ) returns the number of result sets if there is more than one. SQLEXEC( ) returns 0 if it is still executing and returns 1 when it has finished executing. SQLEXEC( ) returns –1 if a connection level error occurs.

Remarks

If the SQL statement you want to pass is quite long, check to see if it exceeds the maximum length of a string literal in Visual FoxPro, which is 255 characters. Longer strings will cause a "Command contains unrecognized phrase/keyword" error. However, you can pass long SQL statements if you break them up into several concatenated literals. For example:

lnRetVal = SQLEXEC(lnHandle, "SELECT <long list of fields> " + ;
   "FROM <several tables> " + ;
   "WHERE <complex filter expression>")

If SQLEXEC( ) is used to execute a SQL statement prepared with SQLPREPARE( ), only the connection handle argument nStatementHandle is required. The cSQLCommand and CursorName arguments should be omitted.

If the SQL statement generates one result set, SQLEXEC( ) stores the result set to the specified Visual FoxPro cursor. If the SQL statement generates two or more result sets and SQLSETPROP( ) is set to 1 (batch mode), you can name each result set by setting the SQLSETPROP( ) BatchMode option to 0 and changing the cursor name each time you call SQLMORERESULTS( ).

SQLEXEC( ) is one of the four functions that you can execute either synchronously or asynchronously. The Asynchronous setting of SQLSETPROP( ) determines whether these functions execute synchronously or asynchronously. In asynchronous mode, you must call SQLEXEC( ) repeatedly until it returns a value other than 0 (still executing).

Example

Example 1

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLEXEC( ) is used to execute a query that returns all the information in the authors table into a cursor named MyCursor.

SQLSETPROP(gnHandle, 'asynchronous', .F.)
SQLEXEC(gnHandle, 'SELECT * FROM authors', 'MyCursor')

Example 2

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLEXEC( ) evaluates variables and expressions in the SQL statements before sending them to the data source.

STORE "MOD(5,2)" to myVar
SQLEXEC(gnHandle, "SELECT * FROM testtable WHERE ikey = ?myVar")
SQLEXEC(handle, "select * from testtable where ikey = ?myVar")
SQLEXEC(handle, "select * from testtable where ikey = ?MOD(5,2)")
STORE 1 TO myVar1
STORE 2 TO myVar2
SQLEXEC(handle, "select * from testtable where ikey = ?(myVar1 + myVar2)")

See Also

AERROR( ) | SQLCANCEL( ) | SQLCONNECT( ) | SQLGETPROP( ) | SQLMORERESULTS( ) | SQLPREPARE( ) | SQLSETPROP( ) | SQLSTRINGCONNECT( )


SQLGETPROP( ) Function

Retrieves the current or default settings for an active connection.

SQLGETPROP(nStatementHandle, cSetting)

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ). If you specify 0 for nStatementHandle, SQLGETPROP( ) returns the environment setting.
cSetting
Specifies the setting. For a list of the settings you can specify, see SQLSETPROP( ) Function.

Return Values

Character, Numeric, or Logical data type. SQLGETPROP( ) returns the current or default settings for an active connection. SQLGETPROP( ) returns -1 if a connection level occurs and -2 if an environment level error occurs.

Example

The following example uses SQLCONNECT( ) to display the Select Connection or Data Source Dialog Box. Choose a data source, the data source connection is tested, and the example displays the results using SQLGETPROP( ) and the cSetting for the data source.

CLOSE ALL
CLEAR ALL
CLEAR
nHandle=SQLCONNECT()
IF nHandle > 0
 cSource= SQLGETPROP(nHandle, "datasource")
 =MESSAGEBOX("Current Data Source = "+cSource,0,"Connection Results")
ELSE
 =MESSAGEBOX("Connection Error = " + ;
  ALLTRIM(STR(nHandle)),0,"Connection Results")
ENDIF
=SQLDISCONNECT(nHandle)

See Also

AERROR( ) | SQLCONNECT( ) | SQLSETPROP( )


SQLMORERESULTS( ) Function

Copies another result set to a Visual FoxPro cursor if more result sets are available.

SQLMORERESULTS(nStatementHandle)

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).

Return Values

Numeric. SQLMORERESULTS( ) returns 0 if the SQL statement is still executing, returns 1 if it is finished executing, and returns 2 if no more data is found. In non-batch mode, SQLMORERESULTS( ) should be called after each successful SQLEXEC( ) call until SQLMORERESULTS( ) returns 2 (no more data found). The setting of the SQLSETPROP( ) batch mode option determines whether SQLEXEC( ) executes a SQL statement in batch or non-batch mode.

SQLMORERESULTS( ) returns – 1 if a connection level error occurs, and returns – 2 if an environment level error occurs.

Remarks

SQLMORERESULTS( ) determines if more result sets are available from a SQL statement executed with SQLEXEC( ) in non-batch mode. If more result sets are available, they are copied to a Visual FoxPro cursor, one set at a time.

SQLMORERESULTS( ) is one of the four functions that you can execute either synchronously or asynchronously. The asynchronous setting of SQLSETPROP( ) determines if these functions execute synchronously or asynchronously. In asynchronous mode, you must call SQLMORERESULTS( ) repeatedly until it returns a value other than 0 (still executing).

Example

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLSETPROP( ) is used to set the BatchMode property to False (.F.) so the individual result sets can be retrieved.

SQLMORERESULTS( ) is issued twice to create two cursors containing the results of the SQLEXEC( ) query. SET is used to display the View window and the cursors created by SQLEXEC( ).

= SQLSETPROP(gnHandle, 'BatchMode', .F.)  && Individual result sets
= SQLEXEC(gnHandle, 'SELECT * FROM authors;
   SELECT * FROM titles')
= SQLMORERES(gnHandle)  && First result set
= SQLMORERES(gnHandle)  && Second result set

See Also

AERROR( ) | SQLCANCEL( ) | SQLCONNECT( ) | SQLEXEC( ) | SQLGETPROP( ) | SQLSETPROP( )


SQLPREPARE( ) Function

Prepares a SQL statement for remote execution by SQLEXEC( ).

SQLPREPARE(nStatementHandle, cSQLCommand, [cCursorName])

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).
cSQLCommand
Specifies the SQL statement passed to the data source.

The SQL statement can contain a parameterized WHERE clause, which creates a parameterized view. All parameters in the WHERE clause must be defined before SQLPREPARE( ) is issued. For example, if the parameters are variables, the variables must be created and initialized before SQLPREPARE( ) is issued.

For additional information about creating parameterized views, see Creating Views.

cCursorName
Specifies the name of the Visual FoxPro cursor to which the result set is sent. If you don't include a cursor name, Visual FoxPro uses the default name SQLRESULT.

For multiple result sets, new cursor names are derived by appending an incremented number to the name of the first cursor.

Return Values

Numeric

Remarks

SQLPREPARE( ) sends the SQL statement to the data source where it is compiled for faster execution. After the SQL statement is compiled, it can be executed with SQLEXEC( ). If SQLEXEC( ) is used to execute a SQL statement prepared with SQLPREPARE( ), only the statement handle is required in SQLEXEC( ).

Example

gcAuthor = 'Smith'
= SQLPREPARE(gnHandle, 'SELECT * FROM authors;   WHERE au_lname = ?gcAuthor')
= SQLEXEC(gnHandle)
...
gcAuthor = 'Jones'
= SQLEXEC(gnHandle)

See Also

SQLCONNECT( ) | SQLEXEC( ) | Creating Views


SQLROLLBACK( ) Function

Cancels any changes made during the current transaction.

SQLROLLBACK(nStatementHandle)

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).

Return Values

Numeric. SQLROLLBACK( ) returns 1 if the transaction is successfully rolled back; otherwise, it returns -1. If SQLROLLBACK( ) returns -1, you can use AERROR( ) to determine why the transaction could not be rolled back.

Remarks

If manual transactions are in effect (the SQLSETPROP( ) transaction property is set to manual), you can send multiple updates to remote tables. The updates can all be rolled back with SQLROLLBACK( ).

Updates can be committed with SQLCOMMIT( ).

Example

The following example assumes SQLCONNECT( ) is successfully issued, and its return value is stored to a memory variable named gnHandle. SQLSETPROP( ) is used to set the Transactions property to 2 (manual), making it possible for you to use SQLCOMMIT( ) and SQLROLLBACK( ).

The authors table is modified with SQLEXEC( ), and the changes to the table are cancelled with SQLROLLBACK( ).

= SQLSETPROP(gnHandle, 'Transactions', 2)  && manual
= SQLEXEC(gnHandle, "INSERT INTO authors (au_id, au_lname);
   VALUES ('aupoe', 'Poe')")
= SQLROLLBACK(gnHandle)

See Also

AERROR( ) | SQLCOMMIT( ) | SQLCONNECT( ) | SQLSETPROP( )


SQLSETPROP( ) Function

Specifies settings for an active connection. You can use SQLSETPROP( ) to specify settings at the connection level. To specify Visual FoxPro default settings at the environment level, include 0 as the statement handle.

SQLSETPROP(nStatementHandle, cSetting [, eExpression])

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).
cSetting
Specifies the setting. The following table lists the values for cSetting.
Setting | Description
Asynchronous Specifies whether result sets are returned synchronously (False (.F.), the default), or asynchronously (True (.T.)).
Read/write.
BatchMode Specifies whether SQLEXEC( ) returns result sets all at once (True (.T.), the default), or individually with SQLMORERESULTS( ) (False (.F.)).
Read/write.
ConnectBusy Contains True (.T.) if a shared connection is busy; otherwise contains False (.F.).
Read-only.
ConnectString The login connection string.
Read-only.
ConnectTimeOut Specifies the time to wait (in seconds) before returning a connection time-out error. If you specify 0, the wait is indefinite and a time-out error is never returned. ConnectTimeOut can be 0 to 600. The default is 15.
Read/write.
DataSource The name of the data source as defined in the ODBC.INI file.
Read/write.
DispLogin Contains a numeric value that determines when the ODBC Login dialog box is displayed. DispLogin may assume the following values:

1 or DB_PROMPTCOMPLETE (from FOXPRO.H).1 is the default.

2 or DB_PROMPTALWAYS (from FOXPRO.H).

3 or DB_PROMPTNEVER (from FOXPRO.H).

If 1 or DB_PROMPTCOMPLETE is specified, Visual FoxPro displays the ODBC Login dialog box only if any required information is missing.

If 2 or DB_PROMPTALWAYS is specified, the ODBC Login dialog box is always displayed, making it possible for you to change settings before connecting.

If 3 or DB_PROMPTNEVER is specified, the ODBC Login dialog box isn't displayed and Visual FoxPro generates an error if the required login information isn't available.
Read/write.
DispWarnings Specifies if error messages are displayed (True (.T.)) or are not displayed (False (.F.), the default).
Read/write.
IdleTimeout The idle timeout interval in seconds. Active connections are deactivated after the specified time interval. The default value is 0 (wait indefinitely).
Read/write.
ODBChdbc The internal ODBC connection handle, which may be used by external library files (FLL files) to call ODBC.
Read-only.
ODBChstmt The internal ODBC statement handle, which may be used by external library files (FLL files) to call ODBC.
Read-only.
PacketSize The size of the network packet used by the connection. Adjusting this value can improve performance. The default value is 4096 bytes (4K).
Read/write
Password The connection password.
Read-only.
QueryTimeOut Specifies the time to wait (in seconds) before returning a general time-out error. If you specify 0 (the default), the wait is indefinite and a time-out error is never returned. QueryTimeOut can be 0 to 600.
Read/write.
Shared Specifies whether the underlying connection is a shared connection (True (.T.)), or not (False (.F.)).

Read-only.
Transactions Contains a numeric value that determines how the connection manages transactions on the remote table. Transactions may assume the following values:

1 or DB_TRANSAUTO (from FOXPRO.H).1 is the default. Transaction processing for the remote table is automatically handled.

2 or DB_TRANSMANUAL (from FOXPRO.H). Transaction processing is handled manually through SQLCOMMIT( ) and SQLROLLBACK( ).
Read/write.
UserId | The user identification. Read-only.
WaitTime The amount of time in milliseconds that elapses before Visual FoxPro checks if the SQL statement has completed executing. The default is 100 milliseconds.
Read/write.
eExpression
Specifies the value for the setting you designate with cSetting. If you omit eExpression, the default value is restored for the setting.

Return Values

Numeric data type. SQLSETPROP( ) returns 1 if it is successful. Otherwise, it returns – 1 if a connection level error occurs or – 2 if an environment level error occurs.

Remarks

You can use SQLGETPROP( ) to return the current value for a specified setting.

Note You must disable the Open Database Connectivity (ODBC) login dialog box to support SQL pass through with Microsoft Transaction Server. To disable the ODBC login dialog box, use the statement SQLSETPROP(cStatementHandle, 'DispLogin', 3), where cStatementHandle is the statement handle returned by SQLCONNECT( ). You can also disable the ODBC login dialog box in the Connection Designer.

The ConnectTimeOut option can be set only at the Visual FoxPro level and has no equivalent at the connection level. You can set all other options at either the connection or the Visual FoxPro level. Each option set at the Visual FoxPro level serves as a default value for subsequent connections.

Example

The following example shows how SQLSETPROP( ) is used to set the packet size for the current connection. SQLCONNECT( ) displays the Select Connection or Data Source Dialog Box for you to choose a connection, and the connection is tested. The packet size is set; the setting is tested; and the results are displayed.

CLOSE ALL
CLEAR ALL
CLEAR
nHandle=SQLCONNECT()
IF nHandle > 0
   nSet=SQLSETPROP(nHandle, "PacketSize", 2048 )
   IF nSet > 0
      =MESSAGEBOX("PacketSize was set to 2048",0,"Connection Results")
   ELSE
      =MESSAGEBOX("Error setting PacketSize",0,"Connection Results")
   ENDIF
ELSE
   =MESSAGEBOX("No Connection",0,"Connection Results")
ENDIF
=SQLDISCONNECT(nHandle)

See Also

AERROR( ) | SQLGETPROP( ) | Connection Designer


SQLSTRINGCONNECT( ) Function

Establishes a connection to a data source using a connection string.

SQLSTRINGCONNECT([lShared] | [cConnectString [, lShared]])

Parameters

lShared
Specifies whether to create a shared connection.
lShared | Description
False (.F.) | SQLSTRINGCONNECT( ) does not create a shared connection. (Default)
True (.T.) | SQLSTRINGCONNECT( ) creates a shared connection.
cConnectString
Specifies the data source connection string required by some Open Database Connectivity (ODBC) drivers. Visual FoxPro passes the connection string to the ODBC driver. For more information about data source connection strings, see your ODBC driver documentation.

You can also choose a data source from the Select Connection or Data Source Dialog Box, which appears when you call SQLSTRINGCONNECT( ) without cConnectString.

Return Values

Numeric data type. SQLSTRINGCONNECT( ) returns a positive nonzero numeric value as the statement handle if you successfully connect to the data source. SQLSTRINGCONNECT( ) returns –1 if it cannot make the connection.

Tip You should store this statement handle in a memory variable and use the variable in subsequent function calls that require a connection handle.

Remarks

The SQLCONNECT( ) and SQLSTRINGCONNECT( ) functions return a numeric value as the statement handle rather than a connection handle. You cannot obtain a connection handle directly. You can still set and get connection properties using the SQLSETPROP( ) and SQLGETPROP( ) functions by passing the statement handle for that connection and the string, "Shared", as arguments. All other SQL functions use a statement handle instead of a connection handle.

SQLSTRINGCONNECT( ) always creates a new connection when it successfully makes a connection. However, setting the lShared parameter determines whether you can share the connection later. If you specify a connection as shareable by setting lShared to True (.T.), you can share the connection later by calling SQLCONNECT( ) and passing the numeric value of the connection handle as the first parameter. For more information, see SQLCONNECT( ) Function.

You can use SQLCONNECT( ) to obtain a new statement handle on a shared connection that was opened using SQLSTRINGCONNECT( ).

Example

Example 1

The following example assumes that an ODBC data source called MyFoxSQLNT exists and is available. SQLSTRINGCONNECT( ) returns a numeric value, which is stored to a variable named gnHandle.

If you successfully connect to the data source, SQLSTRINGCONNECT( ) returns a positive number, a dialog box appears, and SQLDISCONNECT( ) is called to disconnect from the data source.

If you cannot connect to the data source, SQLSTRINGCONNECT( ) returns a negative number and displays a message.

STORE SQLSTRINGCONNECT('dsn=MyFoxSQLNT;uid=myUserID;pwd=myPassword')
   TO gnConnHandle
IF gnConnHandle < 0
   = MESSAGEBOX('Cannot make connection', 16, 'SQL Connect Error')
ELSE
   = MESSAGEBOX('Connection made', 48, 'SQL Connect Message')
   = SQLDISCONNECT(gnHandle)
ENDIF

Example 2

The following examples show how you can use the SQLSTRINGCONNECT( ) function without a Data Source Name (DSN).

lcDSNLess="driver = SQL Server;server=<servername>;uid=<userid>;pwd=<password>"

-or-

lcDSNLess="driver = {SQL Server};server=<servername>;uid=<userid>;pwd=<password>"

-or-

lcDSNLess="DRIVER = {SQL Server};" ;
+ "SERVER=<servername>;" ;
+ "UID=<userid>;" ;
+ "PWD=<password>;" ;
+ "DATABASE=PUBS;" ;
+ "WSID=<machine name or userid>;" ;
+ "APP=MicroX(R) Sample App"
lnConnHandle=SQLSTRINGCONNECT(m.lcDSNLess)

Example 3

Each of the following examples creates a new shared connection. In the first statement, the Select Connection or Data Source Dialog Box appears and SQLSTRINGCONNECT( ) creates the resulting connection as shared.

SQLSTRINGCONNECT(.T.)
SQLSTRINGCONNECT('myConnectionString', .T.)

See Also

AERROR( ) | SQLCONNECT( ) | SQLDISCONNECT( )


SQLTABLES( ) Function

Stores the names of tables in a data source to a Visual FoxPro cursor.

SQLTABLES(nStatementHandle [, cTableTypes] [, cCursorName])

Parameters

nStatementHandle
Specifies the statement handle to the data source returned by SQLCONNECT( ).
cTableTypes
Specifies one or more table types. Valid table types are 'TABLE,' 'VIEW,' 'SYSTEM TABLE,' or any valid data source-specific table type identifier. cTabletypes must be in upper-case. If you include a list of table types, separate the table types with commas.

All table names in the data source are selected if you omit cTableTypes or if cTableTypes is the empty string.

The table type you specify must be delimited with single quotation marks. The following example demonstrates how to specify the 'VIEW' and 'SYSTEM TABLE' table types as a string literal.

? SQLTABLES(handle, "'VIEW', 'SYSTEM TABLE'", "mydbresult")
cCursorName
Specifies the name of the Visual FoxPro cursor to which the result set is sent. If you don't include a cursor name, Visual FoxPro uses the default name SQLRESULT.

The following table shows the columns in the cursor.

Column name | Description
TABLE_QUALIFIER | Table qualifier identifier
TABLE_OWNER | Table owner identifier
TABLE_NAME | The table name as it appears in the data dictionary
TABLE_TYPE | The table type as it appears in the data dictionary
REMARKS | A description of the table

Return Values

Numeric. SQLTABLES( ) returns 1 if the cursor is successfully created, 0 if SQLTABLES( ) is still executing, – 1 if a connection level error occurs, and – 2 if an environment level error occurs.

Remarks

SQLTABLES( ) is one of the four functions that you can execute either synchronously or asynchronously. The setting of the SQLSETPROP( ) asynchronous option determines if these functions execute synchronously or asynchronously. In asynchronous mode, you must call SQLTABLES( ) repeatedly until it returns a value other than False (.F.), meaning the function is still executing.

Example

The following example assumes an ODBC data source called MyFoxSQLNT is available. SQLCONNECT( ) is issued, and its return value is stored to a variable named gnHandle.

If you cannot connect to the data source, SQLCONNECT( ) returns a negative number and a message is displayed.

If you successfully connect to the data source, SQLCONNECT( ) returns a positive number and a dialog is displayed. SQLTABLES( ) is used to create a cursor named mycursor that contains information about tables in the data source. LIST is used to display information about the tables.

STORE SQLCONNECT('MyFoxSQLNT', '<userid>', '<password>') TO gnConnHandle
IF gnConnHandle < 0
   = MESSAGEBOX('Cannot make connection', 16, 'SQL Connect Error')
ELSE
   = MESSAGEBOX('Connection made', 48, 'SQL Connect Message')
   STORE SQLTABLES(gnHandle, 'TABLE', 'mycursor') TO nTables
   IF nTables = 1
      SELECT mycursor
      LIST
   ENDIF
ENDIF

See Also

AERROR( ) | SQLCOLUMNS( ) | SQLCONNECT( ) | SQLGETPROP( ) | SQLSETPROP( )


SQRT( ) Function

Returns the square root of the specified numeric expression.

SQRT(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the numeric expression SQRT( ) evaluates. nExpression cannot be negative.

Remarks

The number of decimal places in the value returned by SQRT( ) is the larger of the current decimal place setting and the number of decimal places contained in nExpression. The current decimal place setting is specified with SET DECIMALS.

Example

CLEAR
? SQRT(4)  && Displays 2.00
? SQRT(2*SQRT(2))  && Displays 1.68

See Also

SET DECIMALS | COS( ) Function | SIN( ) Function


SROWS( ) Function

Returns the number of rows available in the main Visual FoxPro window.

SROWS( )

Return Values

Numeric

Remarks

In Visual FoxPro for Windows, the value returned by SROWS( ) depends on the current display mode. The display mode can be changed with SET DISPLAY.

Example

CLEAR
? SROWS( )

See Also

COL( ) | ROW( ) | SCOLS( ) | SET DISPLAY | WCOLS( ) | WROWS( )


STR( ) Function

Returns the character equivalent of a specified numeric expression.

STR(nExpression [, nLength [, nDecimalPlaces]])

Return Values

Character

Parameters

nExpression
Specifies the numeric expression STR( ) evaluates.
nLength
Specifies the length of the character string STR( ) returns. The length includes one character for the decimal point and one character for each digit to the right of the decimal point.

STR( ) pads the character string it returns with leading spaces if you specify a length larger than the number of digits to the left of the decimal point. STR( ) returns a string of asterisks, indicating numeric overflow, if you specify a length less than the number of digits to the left of the decimal point.

If nExpression is of numeric or float type, STR( ) returns a value using scientific notation if nLength is less than the number of digits in nExpression. If nExpression is an integer, STR( ) returns a string of asterisks, indicating numeric overflow, if nLength is less than the number of digits in nExpression.

If nLength isn't included, the length of the character string defaults to 10 characters.

nDecimalPlaces
Specifies the number of decimal places in the character string STR( ) returns. You must include nLength to specify the number of decimal places.

If you specify fewer decimal places than are in nExpression, the return value is rounded up.

If nDecimalPlaces isn't included, the number of decimal places defaults to zero.

See Also

VAL( ) | Creating Numeric Expressions | STRCONV( ) Function


STRCONV( ) Function

Converts character expressions between single-byte, double-byte, UNICODE, and locale-specific representations.

STRCONV(cExpression, nConversionSetting [, nLocaleID])

Parameters

cExpression
Specifies the character expression that STRCONV( ) converts.
nConversionSetting
Specifies the type of conversion. The following table lists the values of nConversionSetting and the type of conversion performed.
nConversionSetting | Conversion
1 | Converts single-byte characters in cExpression to double-byte characters.
2 | Converts double-byte characters in cExpression to single-byte characters.
3 | Converts double-byte Katakana characters in cExpression to double-byte Hiragana characters.
4 | Converts double-byte Hiragana characters in cExpression to double-byte Katakana characters.
5 | Converts double-byte characters to UNICODE (wide characters).
6 | Converts UNICODE (wide characters) to double-byte characters.
7 | Converts cExpression to locale-specific lowercase.
8 | Converts cExpression to locale-specific uppercase.
9 | Converts double-byte characters in cExpression to UTF-8
10 | Converts Unicode characters in cExpression to UTF-8
11 | Converts UTF-8 characters in cExpression to double-byte characters.
12 | Converts UTF-8 characters in cExpression to UNICODE characters.
13 | Converts single-byte characters in cExpression to encoded base64 binary.
14 | Converts single-byte characters in cExpression to decoded base64 binary.
15 | Converts single-byte characters in cExpression to encoded hexBinary.
16 | Converts single-byte characters in cExpression to decoded hexBinary.
nLocaleID
Specifies the Locale ID to use for the conversion. If nLocaleID is invalid or not supported on the machine, the error "Invalid locale ID" is generated. If nLocaleID is omitted, the system locale ID is used by default.
nLocaleID Language
1029
Czech
1031
German
1033
English (Default)
1034
Spanish
1036
French
1040
Italian
1045
Polish
1046
Portuguese (Brazil)
2070
Portuguese (Portugal)

Return Values

Character data type. STRCONV( ) returns the converted character expression.

Remarks

Visual FoxPro disregards invalid characters or incorrect length in base64- and hexBinary- encoded strings.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

CHRTRANC( ) | IMESTATUS( ) | ISLEADBYTE( )


STREXTRACT( ) Function

Retrieves a string between two delimiters.

STREXTRACT(cSearchExpression, cBeginDelim [, cEndDelim [, nOccurrence
[, nFlag]]]])

Parameters

cSearchExpression
Specifies the string to search.
cBeginDelim
Specifies the character that delimits the beginning of cSearchExpression.
cEndDelim
Specifies the character that delimits the end of cSearchExpression.
nOccurrence
Specifies at which occurrence of cBeginDelim in cSearchExpression to start the extraction.
nFlag
Specify the type of controls placed on the search. The number you specify in nFlag provides a bit-value that determines options according to the following table:
Bit Description
1
Case-insensitive search
2
End delimiter not required. Specifies that a search, which finds no occurrence of cEndDelim, returns the contents of cSearchExpression from the cBeginDelim location.

Returns

Character

Remarks

The default is a case sensitive search in which delimiters must be found (no nFlag value).

If cBeginDelim is an empty string, the search is conducted from the beginning of cSearchExpression to the first occurrence of cEndDelim. If cEndDelim is an empty string STREXTRACT( ) returns a string from nOccurrence of cBeginDelim to the end of cSearchExpression.

Example

clear
USE customer && any table
?cursortoxml(0,"x",1,0,2)   && Produce variable "x" that has XML of  first 2 records of table
?x         && show the XML
xmlproc(x,0)      && Parse the XML

PROCEDURE xmlproc(x as String, nLev as Integer)   as void
   LOCAL cTagName, cContents, mterm
   do while .t.
      cTagName = STREXTRACT(x,"<",">")
      IF LEN(cTagName) = 0   && no tag found
         ??' ',x   && print out raw string as contents
         exit
      endif
      IF RIGHT(cTagName,1) = '/'   && like "<region/>"
         cTagName = LEFT(cTagName, LEN(cTagName)-1)
         cContents=""
         mterm = "<"+cTagName+"/>"   && "<region/>"
      else
         mterm = "</"+cTagName+">"   && "</region>"
         cContents = STREXTRACT(x,"<"+cTagName+">", mterm,1,2)
      endif
      ?REPLICATE("  ",nLev),nLev+1,PADR(cTagName,20)
      xmlproc(cContents, nLev+1)
      x = STREXTRACT(x, mterm)   && get the rest of the xml
   enddo

See Also

STRTRAN( ) Function | RAT( ) Function | RATC( ) Function | SUBSTR( ) Function | SUBSTRC( ) Function | LIKEC( ) Function


STRTOFILE( ) Function

Writes the contents of a character string to a file.

STRTOFILE(cExpression, cFileName [, lAdditive | nFlag])

Return Value

Numeric; the number of bytes written to the file.

Parameters

cExpression
Specifies the character string that is written to the file. cExpression can be a literal character string, an expression that evaluates to a character string, or a character type variable, array element, or field.
cFileName
Specifies the name of the file to which the character string is written. Include a path with the file name if the file is in a directory other than the current default directory. If the file you specify does not exist, Visual FoxPro automatically creates it.
lAdditive (for backward compatibility)
Specifies whether the character string is appended to the end of the file. If lAdditive is true (.T.), the character string is appended to the end of the file.

If lAdditive is false (.F.) (the default), the file is overwritten with the character string. You are asked if you want to overwrite an existing file if SET SAFETY is set to ON. If SET SAFETY is set to OFF, the file is overwritten without warning.

nFlag
Beginning with Visual FoxPro 7, you can use the nFlag parameter instead of lAdditive which enables you to also chose to write UTF-8 and Unicode Byte Order Marks. The following table describes the valid nFlag values.
nFlag | Bit | Description
0 (default) | 0000 | The file is overwritten with the character string (formerly lAdditive=.f.)
1 | 0001 | The string is appended to the end of the file (formerly lAdditive=.t.).
2 | 0010 | Write Unicode Byte Order Mark (BOM) FF FE at the beginning of file. cExpression is assumed to be UNICODE, therefore no translation is performed. The file is overwritten
4 | 0100 | Write UTF-8 Byte Order Mark (BOM) EF BB BF at the beginning of file. cExpression is assumed to be UTF-8, therefore no translation is performed. The file is overwritten.

Remarks

An nFlag value of 3 or 5 is not valid. You cannot attempt to write a new Byte Order Mark if nFlag bit 1, Additive, is set.

Unlike earlier versions of Visual FoxPro, STRTOFILE( ) opens a file in Shared rather than Exclusive mode. This is useful when multiple servers attempt to simultaneously write to the same file. Because of this change, you might not need to check for STRTOFILE( ) to return 0 (failure to open a file).

See Also

FILETOSTR( ) | FWRITE( ) | SET SAFETY


STRTRAN( ) Function

Searches a character expression or memo field for occurrences of a second character expression or memo field, and then replaces each occurrence with a third character expression or memo field.

STRTRAN(cSearched, cExpressionSought [, cReplacement]
   [, nStartOccurrence] [, nNumberOfOccurrences] [, nFlags])

Return Values

Character

Parameters

cSearched
Specifies the character expression that is searched. cSearched can be a memo field.
cExpressionSought
Specifies the character expression that is searched for in cSearched. The search is case-sensitive. cExpressionSought can be a memo field.
cReplacement
Specifies the character expression that replaces every occurrence of cSearchFor in cSearched. If you omit cReplacement, every occurrence of cExpressionSought is replaced with the empty string.
nStartOccurrence
Specifies which occurrence of cExpressionSought is the first to be replaced. For example, if nStartOccurrence is 4, replacement begins with the fourth occurrence of cExpressionSought in cSearched and the first three occurrences of cExpressionSought remain unchanged. The occurrence where replacement begins defaults to the first occurrence of cExpressionSought if you omit nStartOccurrence.
nNumberOfOccurrences
Specifies the number of occurrences of cExpressionSought to replace. If you omit nNumberOfOccurrences, all occurrences of cExpressionSought, starting with the occurrence specified with nStartOccurrence, are replaced.
nFlags
Specifies the case-sensitivity of a search according to the following values:
nFlags Value | Description
0 (default) | Search is case-sensitive, replace is with exact cReplacement text. This is the behavior in versions of Visual FoxPro prior to 7.
1 | Search is case-insensitive, replace is with exact cReplacement text.
2 | Search is case-sensitive, replace is with exact cReplacement text.
3 | Search is case-insensitive; replace is with the case of cReplacement changed to match the case of the string found. The case of cReplacement will only be changed if the string found is all uppercase, lowercase, or title (proper) case.

You can also specify default behavior by passing –1 as the nFlags value.

Remarks

You can specify where the replacement begins and how many replacements are made. STRTRAN( ) returns the resulting character string. Specify –1 for optional parameters you want to skip over if you just need to specify the nFlags setting.

Example

STORE 'abracadabra' TO gcString
? STRTRAN(gcString, 'a', 'z')  && Displays zbrzczdzbrz
? STRTRAN(gcString, 'a', 'q', 2, 3)  && Displays abrqcqdqbra

See Also

CHRTRAN( ) | CHRTRANC( ) | STUFF( ) | Creating Character Expressions | STUFFC( ) Function


STUFF( ) Function

Returns a character string created by replacing a specified number of characters in a character expression with another character expression.

STUFF(cExpression, nStartReplacement, nCharactersReplaced, cReplacement)

Return Values

Character

Parameters

cExpression
Specify the character expression in which the replacement occurs.
nStartReplacement
Specifies the position in cExpression where the replacement begins.
nCharactersReplaced
Specifies the number of characters to be replaced. If nCharactersReplaced is 0, the replacement string cReplacement is inserted into cExpression.
cReplacement
Specifies the replacement character expression. If cReplacement is the empty string, the number of characters specified by nCharactersReplaced are removed from cExpression.

Example

STORE 'abcdefghijklm' TO gcString1
STORE '12345' TO gcString2
CLEAR
? STUFF(gcString1, 4, 0, gcString2)     && insert
? STUFF(gcString1, 4, 3, gcString2)     && replace
? STUFF(gcString1, 4, 6, '')     && delete
? STUFF(gcString1, 4, 1, gcString2)     && replace and insert
? STUFF(gcString1, 4, 4, gcString2)     && replace and delete
? STUFF(gcString1, 4, LEN(gcString1), gcString2)   && replace, delete rest

See Also

LEFT( ) | PADC( ) | PADL( ) | PADR( ) | RIGHT( ) | STRTRAN( ) | SUBSTR( )


STUFFC( ) Function

Returns a character string created by replacing a specified number of characters in a character expression with another character expression.

STUFFC(cExpression, nStartReplacement, nCharactersReplaced, cReplacement)

Return Values

Character

Parameters

cExpression
Specify the character expression in which the replacement occurs.
nStartReplacement
Specifies the character position in cExpression where the replacement begins.
nCharactersReplaced
Specifies the number of characters to be replaced. If nCharactersReplaced is 0, the entire replacement string cReplacement is inserted into cExpression.
cReplacement
Specifies the replacement character expression. If cReplacement is the empty string, the number of characters specified by nCharactersReplaced are removed from cExpression.

Remarks

STUFFC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, STUFFC( ) is equivalent to STUFF( ).

STUFFC( ) returns a character string created by replacing a specified number of characters in a character expression with another character expression. The character expressions can consist of any combination of single-byte and double-byte characters.

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

LEFTC( ) | RIGHTC( ) | STUFF( ) | SUBSTRC( )


SUBSTR( ) Function

Returns a character string from the given character expression or memo field.

SUBSTR(cExpression, nStartPosition [, nCharactersReturned])

Return Values

Character

Parameters

cExpression
Specifies the character expression or memo field from which the character string is returned.
nStartPosition
Specifies the position in the character expression or memo field cExpression from where the character string is returned. The first character of cExpression is position 1.

If nStartPosition is greater than the number of characters in cExpression, the empty string is returned.

nCharactersReturned
Specifies the number of characters to return from cExpression. If you omit nCharactersReturned, characters are returned until the end of the character expression is reached.

Remarks

SUBSTR( ) returns a character string from a character expression or memo field, starting at a specified position in the character expression or memo field and continuing for a specified number of characters.

When using SUBSTR( ) with memo fields in a SELECT – SQL command, include the PADR( ) function in SUBSTR( ) so that empty or variable length memo fields produce consistent results when converted to character strings.

SUBSTR( ) will not return a value for a memo field when issued in the Debug window. To return a value in the Debug window, place the memo field name within ALLTRIM( ), and place ALLTRIM( ) within SUBSTR( ).

Example

STORE 'abcdefghijklm' TO mystring
CLEAR
? SUBSTR(mystring, 1, 5)  && Displays abcde
? SUBSTR(mystring, 6)  && Displays fghijklm

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | PADR( ) | RAT( ) | RATLINE( ) | RIGHT( ) | LEFTC( ) | RIGHTC( ) | SUBSTRC( ) | STRTRAN( ) | STUFF( )


SUBSTRC( ) Function

Returns a character string from the given character expression or memo field.

SUBSTRC(cExpression, nStartPosition [, nCharactersReturned])

Return Values

Character

Parameters

cExpression
Specifies the character expression or memo field from which the character string is returned.
nStartPosition
Specifies the position in the character expression or memo field cExpression from where the character string is returned. The first character of cExpression is position 1.

If TALK is set to ON and nStartPosition is greater than the number of characters in cExpression, Visual FoxPro generates an error message. If TALK is set to OFF, the empty string is returned.

nCharactersReturned
Specifies the number of characters to return from cExpression. If you omit nCharactersReturned, characters are returned until the end of the character expression is reached.

Remarks

SUBSTRC( ) is designed for expressions containing double-byte characters. If the expression contains only single-byte characters, SUBSTRC( ) is equivalent to SUBSTR( ).

SUBSTRC( ) returns a character string from the given character expression or memo field. The character expression or memo field can contain any combination of single-byte and double-byte characters.

SUBSTRC( ) will not return a value for a memo field when issued in the Debug window. To return a value in the Debug window, place the memo field name within ALLTRIM( ), and place ALLTRIM( ) within SUBSTRC( ).

This function is useful for manipulating double-byte character sets for languages such as Hiragana and Katakana.

See Also

AT( ) | AT_C( ) | ATC( ) | ATCC( ) | ATCLINE( ) | ATLINE( ) | LEFT( ) | RAT( ) | RATLINE( ) | RIGHT( ) | LEFTC( ) | RIGHTC( ) | SUBSTR( ) | STRTRAN( ) | STUFFC( )


SYS( ) Functions Overview

Returns Microsoft Visual FoxPro system information.

SYS( )

Return Values

Character

Remarks

Visual FoxPro SYS( ) functions return character values that contain useful system information.

To get help for a SYS( ) function

  • Highlight the SYS( ) function in the Command window or in a program and press the F1 key.

The following table shows what each SYS( ) function returns:

Function | Information returned
SYS(0) | Network machine information
SYS(1) | Julian system date
SYS(2) | Seconds since midnight
SYS(3) | Legal file name
SYS(5) | Default drive or volume
SYS(6) | Current printer device
SYS(7) | Current format file
SYS(9) | Visual FoxPro serial number
SYS(10) | String from Julian day number
SYS(11) | Julian day number
SYS(12) | Available memory in bytes
SYS(13) | Printer status
SYS(14) | Index expression
SYS(15) | Character translation
SYS(16) | Executing program file name
SYS(17) | Processor in use
SYS(18) | Current control
SYS(20) | Transform German text
SYS(21) | Controlling index number
SYS(22) | Controlling tag or index name
SYS(23) | FoxPro EMS memory usage
SYS(24) | EMS memory limit
SYS(100) | Console setting Included for backward compatibility. Use SET("CONSOLE") instead.
SYS(101) | Device setting Included for backward compatibility. Use SET("DEVICE") instead.
SYS(102) | Printer setting Included for backward compatibility. Use SET("PRINTER") instead.
SYS(103) | Talk setting Included for backward compatibility. Use SET("TALK") instead.
SYS(602) | Bitmap Configuration
SYS(1001) | Visual FoxPro memory
SYS(1011) | Number of Memory Handles
SYS(1016) | User object memory use
SYS(1023) | Enable Help diagnostic mode.
SYS(1024) | Disable Help diagnostic mode
SYS(1037) | Page Setup Dialog Box
SYS(1104) | Purge Cached Memory
SYS(1269) | Property Information
SYS(1270) | Object Location
SYS(1271) | Object's .SCX File
SYS(1272) | Object Hierarchy
SYS(1500) | Activate a menu item
SYS(2000) | File name wildcard match
SYS(2001) | SET command status
SYS(2002) | Turn insertion point on or off
SYS(2003) | Current directory
SYS(2004) | Visual FoxPro start directory
SYS(2005) | Current resource file
SYS(2006) | Current graphics card
SYS(2007) | Checksum value
SYS(2010) | CONFIG.SYS file settings
SYS(2011) | Current lock status
SYS(2012) | Memo field block size
SYS(2013) | System menu name string
SYS(2014) | Minimum path
SYS(2015) | Unique procedure name
SYS(2016) | SHOW GETS WINDOW name
SYS(2017) | Checksum value based on the current record in the current work area
SYS(2018) | Error message parameter
SYS(2019) | Configuration file name and location
SYS(2020) | Default disk size
SYS(2021) | Filtered index expression
SYS(2022) | Disk cluster (block) size
SYS(2023) | Temporary Path
SYS(2029) | Table type
SYS(2030) | Debug
SYS(2040) | Detect Report Status
SYS(2060) | Mouse wheel event handling setting
SYS(2300) | Add or Remove Code Page
SYS(2333) | ActiveX Dual Interface Support
SYS(2334) | Automation Server Invocation Mode
SYS(2335) | Unattended Server Mode
SYS(2336) | Critical Section Support
SYS(2339) | Call CoFreeUnusedLibraries when COM object is released
SYS(2340) | NT Service Support
SYS(2410) | Error handler type for an error
SYS(2450) | Application Search Path Order
SYS(2600) | Return Pointer As String
SYS(2700) | Enables Windows XP Themes
SYS(2800) | Accessibility Support
SYS(2801) | Event Tracking Support
SYS(3004) | Return Locale ID
SYS(3005) | Set Locale ID
SYS(3006) | Set Language and Locale IDs
SYS(3050) | Set Buffer Memory Size
SYS(3051) | Set Lock Retry Interval
SYS(3052) | Override SET REPROCESS Locking
SYS(3053) | ODBC Environment Handle
SYS(3054) | Rushmore Query Optimization Level
SYS(3055) | FOR and WHERE Clause Complexity
SYS(3056) | Read Registry Settings
SYS(3095) | IDispatch Pointer
SYS(3096) | IDispatch Object Reference
SYS(3097) | Add Reference to Object
SYS(3098) | Release Object Reference
SYS(3099) | SQL Data Engine Compatibility Mode

See Also

Command Window | SET Command | SET SYSFORMATS Command | SET SYSMENU Command


SYS(0) - Network Machine Information

SYS(0) returns network machine information when using Visual FoxPro in a network environment. The same functionality is available by using ID( ).

SYS(0)

Return Values

Character

Remarks

Machine information must first be assigned by the network software and the network shell must be loaded.

If machine information has not been assigned or the network shell hasn't been loaded, SYS(0) returns a character string consisting of 15 spaces, a number sign (#) followed by another space, and then 0. Consult your network documentation for further information on defining machine information.

SYS(0) returns 1 when using Visual FoxPro in a stand-alone environment.

When the machine is connected to a network, SYS(0) returns the machine name, a space, a number sign (#) followed by another space, and then the id of the current user (or the security context in which Visual FoxPro is running). For example:

? SYS(0)

returns the following format:

MACHINEID # userid

See Also

SYS( ) Functions Overview | ID( ) - Network Machine Information | Considering Hardware, Memory, and Network Issues


SYS(1) - Julian System Date

Returns the current system date as a Julian day number character string.

SYS(1)

Return Values

Character

Remarks

The value returned by SYS(1) is valid in USA versions of Visual FoxPro for any system date after September 14, 1752, and before December 31, 9999.

Example

? SYS(1)
? SYS(10,VAL(SYS(1)))

See Also

CDOW( ) | CTOD( ) | DATE( ) | DATETIME( ) | DAY( ) | DOW( ) | DTOC( ) | SYS( ) Functions Overview | SYS(10) - String from Julian Day Number | SYS(11) - Julian Day Number


SYS(2) - Seconds Since Midnight

Returns the number of seconds elapsed since midnight.

SYS(2)

Return Values

Character

Example

? TIME( )
? SYS(2)

See Also

DATETIME( ) | SECONDS( ) | SYS( ) Functions Overview | TIME( )


SYS(3) - Legal File Name

Returns a legal file name that can be used to create temporary files.

SYS(3)

Return Values

Character

Remarks

SYS(3) may return a non-unique name when issued successively on a fast computer. Use SUBSTR(SYS(2015), 3) to create unique, legal eight character file name.

Note Avoid using this string in CREATE TABLE, CREATE CURSOR, SELECT INTO CURSOR, and other similar commands. Using this string generates an error because a valid FoxPro cursor or alias name cannot begin with a number. If you have used SUBSTR(SYS(2015), 3) to create a unique table or cursor name without explicitly preceding the string with an underscore, (_), or alphabetic character, you can fix your code in the following ways:
On a platform that supports long file names
Use SYS(2015) by itself since it always begins with an underscore.
On platforms and networks that support only the DOS 8+3 naming convention
Change your naming expression to explicitly prefix an underscore as in the following example:
   "_"+SUBSTR(SYS(2015), 4)

See Also

FILE( ) | SYS( ) Functions Overview | SYS(2015) - Unique Procedure Name


SYS(5) - Default Drive

Returns the current Visual FoxPro default drive.

SYS(5)

Return Values

Character

Remarks

This function returns the current Visual FoxPro default drive. Use SET DEFAULT to specify a default drive.

Example

IF _DOS OR _WINDOWS
   SET DEFAULT TO C:
ENDIF
? SYS(5)

See Also

DRIVETYPE( ) | SET DEFAULT | SYS( ) Functions Overview


SYS(6) - Current Printer Device

Returns the current print device.

SYS(6)

Return Values

Character

Remarks

This function returns the current SET PRINTER TO setting.

Example

? SYS(6)
SET PRINTER TO output.txt
? SYS(6)

See Also

SET PRINTER | SYS( ) Functions Overview | GETPRINTER( ) Function


SYS(7) - Current Format File

Returns the name of the current format file.

SYS(7 [, nWorkArea])

Return Values

Character

Parameters

nWorkArea
Specifies the work area number for which SYS(7) returns the format file name. The format file name for the current work area is returned if you omit nWorkArea.

Remarks

A format file is opened with SET FORMAT. The empty string is returned if a format file isn't open for the work area you specify.

See Also

SET FORMAT | SYS( ) Functions Overview | SET SYSFORMATS Command


SYS(9) - Visual FoxPro Serial Number

Returns your Visual FoxPro serial number.

SYS(9)

Return Values

Character

See Also

SYS( ) Functions Overview | VERSION( ) | Configuring Visual FoxPro


SYS(10) - String from Julian Day Number

Converts a Julian day number to a character string.

SYS(10, nJulianDayNumber)

Return Values

Character

Remarks

SYS(10) returns a Character-type date from a Julian day number nJulianDayNumber.

Example

? SYS(1)
? SYS(10,VAL(SYS(1)))

See Also

CDOW( ) | CTOD( ) | DATE( ) | DATETIME( ) | DAY( ) | DOW( ) | DTOC( ) | SYS( ) Functions Overview | SYS(1) - Julian System Date | SYS(11) - Julian Day Number


SYS(11) - Julian Day Number

Converts a date expression or character string in date format to a Julian day number.

SYS(11, dExpression | tExpression | cExpression)

Return Values

Character

Remarks

SYS(11) returns a Julian day number from a date expression dExpression, a datetime expression tExpression, or a character expression cExpression in a date format. The day number is returned as a character string.

Example

? SYS(11, {^1998-06-06})
? SYS(11,'06/06/1998')

See Also

CDOW( ) | CTOD( ) | DATE( ) | DATETIME( ) | DAY( ) | DOW( ) | DTOC( ) | SYS( ) Functions Overview | SYS(10) - String from Julian Day Number


SYS(12) - Available Memory in Bytes

Returns the amount of memory below 640K that is available to execute an external program.

SYS(12)

Return Values

Character

Remarks

In Visual FoxPro, SYS(12) always returns 655,360.

SYS(12) is similar to MEMORY( ), with two exceptions:

  • SYS(12) returns the amount of available memory in bytes. MEMORY( ) returns available memory in kilobytes.
  • SYS(12) returns a character string. MEMORY( ) returns a numeric value.

See Also

MEMORY( ) | RUN | ! | SYS( ) Functions Overview | SYS(23) - FoxPro EMS Memory Usage | SYS(24) - EMS Memory Limit | SYS(1001) - Visual FoxPro Memory | SYS(1016) - User Object Memory Use


SYS(13) - Printer Status

Included for backward compatibility. Returns the status of the printer.

SYS(13)

Return Values

Character

Remarks

OFFLINE is returned if the printer isn't ready. READY is returned if the printer is ready.

If the printer is connected to a COM port, SYS(13) returns READY if the printer returns Clear To Send Data or Data Set Ready.

If the printer is connected to a parallel port, SYS(13) returns OFFLINE if the printer returns Out of Paper, I/O Error, Time Out, Printer Busy, or Printer Not Selected.

Example

IF SYS(13) = 'OFFLINE'
   WAIT WINDOW 'Printer is offline'
ENDIF

See Also

PRINTSTATUS( ) | SET PRINTER | SYS( ) Functions Overview


SYS(14) - Index Expression

Returns index expression of an open single-entry .idx index file or index expressions for tags in compound .cdx index files.

SYS(14, nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nIndexNumber
Specifies which index expression to return from the open index files or tags. SYS(14) returns index expressions from open index files and tags in the following order as nIndexNumber increases from 1 to the total number of open single-entry files and structural compound and independent compound index tags:
  1. Index expressions from single-entry index files (if any are open) are returned first. The order the single-entry index files are included in USE or SET INDEX determines the order the index expressions are returned.
  2. Index expressions for each tag in the structural compound index (if one is present) are returned next. The index expressions are returned from the tags in the order that the tags were created in the structural index.
  3. Index expressions for each tag in any open independent compound indexes are returned last. The index expressions are returned from the tags in the order that the tags were created in the independent compound indexes.

The empty string is returned if nIndexNumber is greater than the total number of open single-entry files and structural compound and independent compound index tags.

nWorkArea | cTableAlias
Specifies a work area number or work area alias. If you omit nWorkArea and cTableAlias, index expressions are returned from index files open in the current work area. If a table doesn't have the alias you specify, Visual FoxPro generates an error message.

Remarks

An index expression is specified when an index file or tag is created with INDEX. The index expression determines how a table is displayed and accessed when an index file or tag is used to order the table.

For more information on index expressions and creating index files and tags, see INDEX. SYS(14) is similar to the KEY( ) function.

USE and SET INDEX both support an index file name list that makes it possible for you to open index files for a table. Any combination of single-entry index files, structural compound or independent compound index file names can be included in the index file list.

See Also

CDX( ) | KEY( ) | INDEX | MDX( ) | NDX( ) | REINDEX | SET INDEX | SET ORDER | SYS( ) Functions Overview | TAG( )


SYS(15) - Character Translation

Included for backward compatibility. Use SET COLLATE instead.

SYS(15, cTranslationExpression, cTranslated)

Return Values

Character

Parameters

cTranslationExpression
Specifies the character expression that SYS(15) uses for the translation of cTranslated.
cTranslated
Specifies the character expression that is translated. SYS(15) takes the first character in cTranslated and determines the character's ASCII value. The character in the same position in cTranslationExpression as the ASCII value is returned. This process is repeated for each additional character in cTranslated. If a character in cTranslated does not have a corresponding character in cTranslationExpression, then the character is not translated.

Remarks

This function is intended primarily for the convenience of European users who must use accented characters. Because there are different versions of most vowels, indexing on fields containing accented characters does not preserve the expected alphabetical order.

Included with Visual FoxPro is a memory variable file called EUROPEAN.MEM that contains sample translation characters. In FoxPro for MS-DOS and Visual FoxPro, EUROPEAN.MEM is located in the HOME( ) directory. In FoxPro for Macintosh, EUROPEAN.MEM is located in the Goodies:Misc folder.

Stored in EUROPEAN.MEM is a character memory variable called EUROPEAN, for use with SYS(15) in FoxPro for MS-DOS. Another character memory variable, EUROANSI, is provided for use with SYS(15) in Visual FoxPro and FoxPro for Macintosh. These memory variables can be used with SYS(15) to translate accented characters to the corresponding characters without the accents.

As an example, the following command can be used in FoxPro for MS-DOS to index a table on a field containing accented characters while preserving normal alphabetical order:

INDEX ON SYS(15, european, field) TO european

See Also

SYS( ) Functions Overview | SET COLLATE


SYS(16) - Executing Program File Name

Returns the file name of the program being executed. You can use SYS(16) to recover from errors.

SYS(16 [, nProgramLevel])

Parameters

nProgramLevel
Indicates from how many levels back the program name is fetched. This value can range from 1 to the depth at which programs are nested.

If nProgramLevel is 0 or 1, SYS(16) returns the name of the main program (the program first executed). The name of the currently executing program is returned if nProgramLevel is omitted. The empty string is returned if nProgramLevel is greater than the program nesting depth.

Return Values

Character

Remarks

SYS(16) is similar to PROGRAM( ) except that SYS(16) returns a path with the program name. When the executing program is part of an application (.app), SYS(16) returns only the name of the program, that is, without the path. SYS(16) returns the name of the executable file if called from an executable (.exe) file; whereas PROGRAM( ) returns just the program name. If a procedure or function is being executed, SYS(16) returns the name of the file containing the procedure or function after the procedure or function name.

Example

The program nesting is returned in the following short program example:

STORE 1 TO gnX
DO WHILE LEN(SYS(16,gnX)) != 0
   ? SYS(16,gnX)
   STORE gnX+1 TO gnX
ENDDO

See Also

LINENO( ) | ON ERROR | PROGRAM( ) | SYS( ) Functions Overview


SYS(17) - Processor in Use

Returns the central processing unit (CPU) being used.

SYS(17)

Return Values

Character

Remarks

This function returns the type of central processing unit you are using.

Example

? 'Processor in use: ', SYS(17)

See Also

SYS( ) Functions Overview | SET DEVICE | SYS(100) - Console Setting


SYS(18) - Current Control

Included for backward compatibility. Use the ActiveControl property instead.


SYS(20) - Transform German Text

Included for backward compatibility. Use SET COLLATE instead.


SYS(21) - Controlling Index Number

Returns, as a character string, the index position number of the master controlling .cdx compound index tag or .idx index file for the currently selected work area.

SYS(21)

Return Values

Character

Remarks

The index position number is determined by the order in which the .idx index files and .cdx compound index tags are specified in USE and SET INDEX.

You can use SET INDEX, SET ORDER, and USE to specify which .idx index file or .cdx compound index tag is the master controlling index file or tag. For more information on specifying a master controlling index or tag, see SET INDEX, SET ORDER, and USE.

"0" is returned if there isn't a master controlling .cdx compound index tag or .idx index file (for example, SET ORDER TO is issued to display and access the table in natural record order).

See Also

CDX( ) | KEY( ) | INDEX | MDX( ) | NDX( ) | REINDEX | SET INDEX | SET ORDER | SYS( ) Functions Overview | SYS(22) - Controlling Tag or Index Name | TAG( ) | USE


SYS(22) - Controlling Tag or Index Name

Returns the name of the master controlling .cdx compound index tag or .idx index file for a table.

SYS(22 [, nWorkArea])

Return Values

Character

Remarks

You can use SET INDEX, SET ORDER, and USE to specify which .idx index file or .cdx compound index tag is the master controlling index file or tag. For more information on specifying a master controlling index or tag, see SET INDEX, SET ORDER, and USE.

The empty string is returned if there isn't a master controlling .cdx compound index tag or .idx index file (for example, SET ORDER TO is issued to display and access the table in natural record order).

nWorkArea
Specifies the work area number of the table for which SYS(22) returns the name of the master controlling .cdx compound index tag or .idx index file.

See Also

CDX( ) | KEY( ) | INDEX | MDX( ) | NDX( ) | REINDEX | SET INDEX | SET ORDER | SYS( ) Functions Overview | SYS(21) - Controlling Index Number | TAG( )


SYS(23) - FoxPro EMS Memory Usage

Included for backward compatibility.


SYS(24) - EMS Memory Limit

Included for backward compatibility.


SYS(602) - Bitmap Configuration

Returns the current setting of the bitmap in the current configuration file and turns off-screen bitmaps off or on at run time.

SYS(602 [, 0 | 1 ])

Parameters

0
Turns off off-screen bitmaps at run time.
1
Turns on off-screen bitmaps at run time.

Return Values

Character data type. The following table lists the possible settings that SYS(602) can return.

Return value | Setting
0 | Off-screen bitmaps are turned off.
1 | Off-screen bitmaps are turned on. (Default)

Remarks

You can use off-screen bitmaps to store an image of the current desktop and forms so that you can render them if another element, such as a window, is drawn over them. However, off-screen bitmaps use a lot of memory, so you can improve performance on Terminal Server applications by turning these bitmaps off using SYS(602).

However, be aware that toggling off-screen bitmaps can affect your application. For example, form controls can appear normal, however, writing directly to a form using a method such as Line requires off-screen bitmaps to be turned on.

If you want to determine whether an application is running on a Terminal Server, use OS(10).

See Also

SYS( ) Functions Overview | OS( ) Function | Special Terms for Configuration Files


SYS(1001) - Visual FoxPro Memory

Returns the total amount of memory available to the Visual FoxPro memory manager.

SYS(1001)

Return Values

Character

Remarks

In Visual FoxPro, SYS(1001) returns the virtual memory pool size, which is approximately four times the amount of physical memory.

See Also

SYS( ) Functions Overview | SYS(12) - Available Memory in Bytes | SYS(23) - FoxPro EMS Memory Usage | SYS(24) - EMS Memory Limit | SYS(1016) - User Object Memory Use


SYS(1011) - Number of Memory Handles

Returns the number of memory handles in use.

SYS(1011)

Return Values

Numeric

Remarks

You can use SYS(1011) to check memory usage as you repeatedly run a test. Increasing values only between the first two runs can be evidence of memory caching. Increasing values beyond this can be evidence of a problem.

See Also

SYS( ) Functions Overview | SYS(12) - Available Memory in Bytes | SYS(1016) - User Object Memory Use


SYS(1016) - User Object Memory Use

Returns amount of memory being used by objects you define.

SYS(1016)

Return Values

Character

Remarks

User-defined objects include: user-defined windows, menu bars, menus, variables, arrays, open tables, files opened with low-level file functions, and so on.

See Also

SYS( ) Functions Overview | SYS(12) - Available Memory in Bytes | SYS(23) - FoxPro EMS Memory Usage | SYS(24) - EMS Memory Limit | SYS(1001) - Visual FoxPro Memory


SYS(1023) - Enable Help Diagnostic Mode

Enables the Help diagnostic mode, making it possible for you to trap the HelpContextID passed to the Visual FoxPro Help system.

SYS(1023)

Return Values

Character

Remarks

SYS(1023) is useful for debugging a custom Help system for your application. SYS(1023) returns the empty string.

When the Help diagnostic mode is enabled with SYS(1023), a dialog box is displayed whenever you press F1 or issue HELP. The dialog box displays the HelpContextID to be passed to the Visual FoxPro Help system, and you are given the option of passing the HelpContextID to the Visual FoxPro Help system.

If you choose Yes, the HelpContextID is passed to the Visual FoxPro Help system and the corresponding Help topic (if available) is displayed. If you choose No, the HelpContextID is not passed to the Visual FoxPro Help system and the corresponding Help topic is not displayed.

Use SYS(1024) to disable the Help diagnostic mode and restore the default Visual FoxPro Help system processing.

See Also

HELP | HelpContextID Property | SET HELP | SYS(1024) - Disable Help Diagnostic Mode


SYS(1024) - Disable Help Diagnostic Mode

Disables the Help diagnostic mode enabled by issuing SYS(1023).

SYS(1024)

Return Values

Character

Remarks

Use SYS(1024) to disable the Help diagnostic mode enabled with SYS(1023) and restore the default Visual FoxPro Help system processing. SYS(1023) is used to debug a custom Help system for your application.

SYS(1024) returns the empty string.

See Also

HELP | HelpContextID Property | SET HELP | SYS(1023) - Enable Help Diagnostic Mode


SYS(1037) - Print Setup Dialog Box

Displays the Print Setup dialog box.

SYS(1037)

Return Values

Character

Remarks

SYS(1037) displays the Print Setup dialog box, making it possible for you to make adjustments to printer settings such as the paper size and orientation. The settings you can adjust in this dialog depend on the printer you've installed.

SYS(1037) always returns the empty string.

See Also

GETPRINTER( ) | PRINTSTATUS( ) | SET DEVICE | SET PRINTER | Print Setup Dialog Box


SYS(1104) - Purge Memory Cache

Purges memory cached by programs and data, and clears and refreshes buffers for open tables.

SYS(1104)

Returns

Numeric. 0, if successful

Remarks

You can improve performance by calling SYS(1104) after executing commands that make extensive use of memory buffers. This function also clears internal buffers for open tables, forcing the tables to be refreshed, which is useful with large tables and in multiuser environments.

Note The use of SYS(1104) will slow performance in applications that have a large number of buffered tables open.

See Also

CLEAR Command | RELEASE Command | CLOSE Command | FLUSH Command | SET REFRESH


SYS(1270) - Object Location

Returns a reference for an object at the specified point.

SYS(1270 [, nXCoord, nYCoord])

Return Values

Object, Logical

Parameters

nXCoord
Specifies the horizontal coordinate in pixels relative to the Windows desktop.
nYCoord
Specifies the vertical coordinate in pixels relative to the Windows desktop.

Remarks

If you omit the coordinates nXCoord and nYCoord, a reference to the object that is under the current mouse position is returned. If you include the coordinates nXCoord and nYCoord, a reference to the object at that location is returned.

False (.F.) is returned if no object is under the mouse pointer or located at the coordinates specified with nXCoord and nYCoord.

See Also

AMOUSEOBJ( ) | CREATE FORM | GETPEM( ) | PEMSTATUS( ) | SYS(1269) - Property Information | SYS(1271) - Object's .SCX File | SYS(1272) - Object Hierarchy | ASELOBJ( ) Function


SYS(1271) - Object's .SCX File

Returns the name of the .SCX file in which the specified instantiated object is stored.

SYS(1271, oObjectName)

Return Values

Character, Logical

Parameters

oObjectName
Specifies the name of the object for which the .scx file is returned.

Remarks

SYS(1271) returns the name of the .scx file in which the specified instantiated object is stored.

SYS(1271) returns a logical false (.F.) if the object cannot be located in an .scx file (for example, if the object was created from the Command window).

See Also

CREATE FORM | GETPEM( ) | PEMSTATUS( ) | SYS(1269) - Property Information | SYS(1270) - Object Location | SYS(1272) - Object Hierarchy


SYS(1272) - Object Hierarchy

Returns the object hierarchy for a specified object. Not available at design time.

SYS(1272, oObjectName)

Return Values

Character

Parameters

oObjectName
Specifies the name of the object for which the hierarchy is returned.

See Also

CREATE FORM | GETPEM( ) | PEMSTATUS( ) | SYS(1269) - Property Information | SYS(1270) - Object Location | SYS(1271) - Object's .SCX File


SYS(1500) - Activate a System Menu Item

Activates a Visual FoxPro system menu item.

SYS(1500, cSystemItemName, cMenuName)

Return Values

Character

Parameters

cSystemItemName
Specifies the name of the Visual FoxPro system menu item to activate.
cMenuName
Specifies the name of the Visual FoxPro system menu or submenu containing the menu item.

Remarks

See System Menu Names for a list of Visual FoxPro menu and menu item names. You can also use SYS(2013) - System Menu Name String to display a list of Visual FoxPro menu and menu item names.

User-defined menu items and disabled system menu items cannot be activated with SYS(1500).

SYS(1500) returns the empty string.

Example

The following example uses SYS(1500) to paste a command into a program file.

_CLIPTEXT = "MESSAGEBOX('TEST')"  && Command to paste
MODIFY COMMAND myprog NOWAIT  && Open a program file
SYS(1500, '_MED_PASTE', '_MEDIT')  && Paste menu item

See Also

SYS(2013) - System Menu Name String | System Menu Names | MODIFY COMMAND Command | _CLIPTEXT System Variable


SYS(2000) - File Name Wildcard Match

Returns the name of the first file in alphabetic order by file name and extension, that matches a file name skeleton.

SYS(2000, Skeleton [, 1])

Return Values

Character

Parameters

Skeleton
Specifies the file name skeleton. The file skeleton can contain the wildcards ? and *.
1
Returns the name of the next matching file.

Remarks

The empty string is returned if a matching file can't be found.

Example

? SYS(2000,'FOX.*')
? SYS(2000,'FOX.*',1)

See Also

LOCFILE( ) | SYS( ) Functions Overview


SYS(2001) – SET ... Command Status

Returns the status of the specified SET commands.

SYS(2001, cSETCommand [, 1 | 2])

Return Values

Character

Parameters

cSETCommand
Specifies the SET command whose status SYS(2001) returns.
1 | 2
Some SET commands have two or more settings; for example, SET PRINTER ON, SET PRINTER OFF, and SET PRINTER TO FileName. Use SYS(2001) without 1 or 2 to return the ON or OFF switch setting. Use SYS(2001) with 1 or 2 to return the additional settings. See SET( ) for a list of SET commands for which additional information is returned when 1 or 2 is included.

Remarks

SYS(2001) is identical to SET( ).

Example

? SYS(2001,'PRINTER')
? SYS(2001,'PRINTER',1)

See Also

SET( ) | SYS( ) Functions Overview | SET PRINTER | SET


SYS(2002) – Turn Insertion Point On or Off

Turns the insertion point on or off.

SYS(2002 [, 1])

Return Values

None

Remarks

SYS(2002) turns the insertion point off. SYS(2002, 1) turns the insertion point on. For more information about turning the insertion point on and off, see SET CURSOR.

See Also

INKEY( ) | SET CURSOR | SYS( ) Functions Overview


SYS(2003) – Current Directory

Returns the name of the current directory on the default drive.

SYS(2003)

Return Values

Character

Remarks

You can use SYS(5) to determine the current drive.

See Also

SYS( ) Functions Overview | Cannot rename the current directory (Error 1253) | SYS(5) - Default Drive


SYS(2004) – Visual FoxPro Start Directory

Returns the name of the directory from which Visual FoxPro was started.

SYS(2004)

Return Values

Character

Remarks

SYS(2004) returns the location of the Vfp8r.dll or Vfp8t.dll file in a run time Visual FoxPro application.

Example

? 'Visual FoxPro launch directory: ', SYS(2004)

See Also

HOME( ) | SET PATH | SYS( ) Functions Overview


SYS(2005) – Current Resource File

Returns the name of the current Visual FoxPro resource file.

SYS(2005)

Return Values

Character

Remarks

The Visual FoxPro resource file is a Visual FoxPro table that contains information on system and user-defined resources like keyboard macros, preferences, system window locations and sizes, diary entries, and so on.

The Visual FoxPro resource file defaults to FoxUser.dbf. Use SET RESOURCE to specify a different Visual FoxPro resource file.

Example

? 'Current resource file: ', SYS(2005)

See Also

SET RESOURCE | SYS( ) Functions Overview


SYS(2006) – Current Graphics Card

Returns the type of graphics card and monitor you are using.

SYS(2006)

Return Values

Character

Example

? 'Current graphics card/monitor: ', SYS(2006)

See Also

ISCOLOR( ) | SET DISPLAY | SYS( ) Functions Overview


SYS(2007) - Checksum Value

Returns the checksum value of a character expression. You can use a checksum to test the validity of data or to compare two character expressions. You can also generate checksum values greater than 16 bits for large strings.

SYS(2017) offers complementary functionality by generating checksum values based on the current record in the current work area. For more information, see SYS(2017) - Record Checksum Value.

SYS(2007, cExpression, [, nSeed, [, nFlags]])

Parameters

cExpression
Specifies a character expression (string) for which SYS(2007) returns a checksum value.
nSeed
Specifies a numeric seed value of 0 that is used to calculate the checksum and is included for backward compatibility. Passing a value of -1 for nSeed uses the default system value of 0. For CRC32 calculations, Visual FoxPro disregards nSeed.
nFlags
Set an additional bit value for generating the checksum.

Versions of Visual FoxPro earlier than 8.0 used a CRC16 16-bit algorithm to calculate the checksum values of strings. Visual FoxPro now includes the CRC32 routine to calculate larger 32-bit values. You can control the setting of this algorithm by setting the first bit value of the nFlags parameter.

The following table lists the bit value you can set to produce one of the values for nFlags.

Value | Bit | Description
1 | 001 | Calculate checksum value using CRC32 checksum algorithm.

The following table lists the possible values for nFlags, produced by setting the bit flag.

nFlags | Description
0 | Calculate checksum based on cExpression parameter using CRC16 checksum algorithm. (Default)
1 | Calculate checksum based on cExpression parameter using CRC32 checksum algorithm.

For example, if you want use checksum using the CRC32 checksum algorithm to calculate the checksum based on cExpression, you should specify an nFlags value of 1. To use the CRC16 checksum algorithm, set the nFlags value to 0.

Return Values

Character data type

See Also

SYS( ) Functions Overview | SET RESOURCE | Creating Character Expressions


SYS(2010) - CONFIG.SYS File Settings

Returns the files setting in CONFIG.SYS.

SYS(2010)

Return Values

Character

Remarks

In FoxPro for MS-DOS, SYS(2010) returns as a character string the files setting in your CONFIG.SYS configuration file.

In Visual FoxPro, SYS(2010) always returns 255.

Most Config.sys files contain a line specifying the maximum number of files that can be opened at the same time under MS-DOS. This line usually reads FILES=NNN, where NNN is a number. SYS(2010) returns this number.

A Config.sys configuration file doesn't have to have a files setting; furthermore, you need not have a Config.sys file. SYS(2010) returns the default MS-DOS files setting in either case.

The number returned by SYS(2010) isn't the number of files you can open in Visual FoxPro, FoxPro for Windows, and FoxPro for MS-DOS. MS-DOS opens files for its own use. Visual FoxPro and FoxPro for Windows also open files for their own internal use, and the number of these open files can vary throughout a FoxPro session. The files setting in your Config.sys file must be somewhat greater than the number of files you would like to open in Visual FoxPro.

For more information on the Config.sys configuration file, see your MS-DOS manual.

See Also

SYS( ) Functions Overview | SYS(2019) - Configuration File Name and Location | Using a Configuration File


SYS(2011) - Current Lock Status

Returns the record or table lock status for the current work area.

SYS(2011)

Return Values

Character

Remarks

Unlike the FLOCK( ), LOCK( ), and RLOCK( ) functions, SYS(2011) doesn't attempt to lock the table or record.

The character string returned by SYS(2011) is identical to the message displayed in the status bar (Exclusive, Record Unlocked, Record Locked ...).

SYS(2011) returns Exclusive only at the workstation that opened the table exclusively, and Record Locked only at the workstation that applied the record lock.

See Also

FLOCK( ) | LOCK( ) | RLOCK( ) | SYS( ) Functions Overview | ISFLOCKED( ) Function | ISRLOCKED( ) Function


SYS(2012) - Memo Field Blocksize

Returns the memo field block size for a table.

SYS(2012 [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nWorkArea | cTableAlias
Specifies the work area number or table alias for the table for which the memo field block size is returned. nWorkArea specifies a work area number and cTableAlias specifies a table alias. If you do not specify a work area or alias, SYS(2012) returns the memo field block size for the table open in the currently selected work area.

SYS(2012) returns 0 if a table isn't open in the specified work area or the table doesn't have a memo field.

Remarks

For more information on specifying the memo field block size for a table, see SET BLOCKSIZE.

See Also

SET BLOCKSIZE | Memo Field Type | Memo Field Input and Output Routines


SYS(2013) - System Menu Name String

Returns a space-delimited character string containing the internal names of the Visual FoxPro menu system.

SYS(2013)

Return Values

Character

Remarks

SYS(2013) facilitates utilization of the Visual FoxPro system menu bar and system menus. The character string returned contains the name of the system menu bar, its menu titles, and the name of each item on the menus.

SYS(2013) returns the names of the menu titles and menu items for every FoxPro platform. See System Menu Names for a listing of Visual FoxPro menu titles and menu items.

See Also

DEFINE BAR | DEFINE MENU | DEFINE POPUP | SYS( ) Functions Overview | SYS(1500) - Activate a System Menu Item | System Menu Names


SYS(2014) - Minimum Path

Returns the minimum path relative to the current or specified directory for a specified file.

SYS(2014, cFileName [, Path])

Return Values

Character

Parameters

cFileName
Specifies the name of the file for which SYS(2014) returns the minimum path. If you omit Path, SYS(2014) returns the minimum path between the file and the current directory. You can change the current directory with SET DEFAULT.
Path
Specifies a directory for which SYS(2014) returns the minimum path between the specified directory and the file specified with cFileName.

Remarks

SYS(2014) can be used with FULLPATH( ) to make applications portable. That is, when given the location of the current program and the location of other files used by the program, FULLPATH( ) and SYS(2014) obtain the proper paths for these files. Once the files' paths are determined, the files can be accessed by the program.

See Also

FULLPATH( ) | SET DEFAULT | SET PATH | SYS( ) Functions Overview


SYS(2015) - Unique Procedure Name

Returns a unique 10-character procedure name that begins with an underscore followed by a combination of letters and numbers.

SYS(2015)

Return Values

Character

Remarks

SYS(2015) can be used to create unique procedure or function names.

The name that SYS(2015) returns is created from the system date and system time. Calling SYS(2015) more than once during the same millisecond interval will return a unique character string.

See Also

SYS( ) Functions Overview | SYS(3) - Legal File Name | SYS(1) - Julian System Date


SYS(2016) - SHOW GETS WINDOW Name

Included for backward compatibility. Use the Refresh method instead of SHOW GETS.


SYS(2017) - Record Checksum Value

Returns a checksum value based on the current record in the current work area. You can use a checksum to test the validity of data. You can also generate checksum values greater than 16 bits for large strings.

SYS(2017) offers complementary functionality to SYS(2007) - Checksum Value.

SYS(2017, cExpression [, nSeed [, nFlags]])

Parameters

cExpression
Specifies a comma-delimited list, with or without spaces, containing one or more fields to exclude from the checksum calculation. The maximum length of the field string is limited to 256 characters.

If cExpression is empty, Visual FoxPro does not exclude fields except for Memo and General fields.

nSeed
Specifies a numeric seed value of 0 that is used to calculate the checksum and is included for backward compatibility. Passing a value of -1 for nSeed uses the default system value of 0. For CRC32 calculations, Visual FoxPro disregards nSeed.
nFlags
Specifies additive bit values for generating the checksum.

Versions of Visual FoxPro earlier than 8.0 used a CRC16 16-bit algorithm to calculate the checksum values of strings. Visual FoxPro now includes the CRC32 routine to calculate larger 32-bit values. You can control the setting of this algorithm by setting the first bit value of the nFlags parameter.

The following table lists the bit values you can add to produce a value for nFlags.

Value | Bits | Description
1 | 001 | Calculate checksum value using CRC32 checksum algorithm.
2 | 010 | Include Memo fields in the checksum calculation.

You can use the second nFlags bit to include Memo fields in the CRC calculation. Visual FoxPro includes all Memo fields except any specified by cExpression in the calculation.

The following table lists the possible values for nFlags, produced by the sum of the bit flags.

nFlags | Description
0 | Calculate checksum based on cExpression parameter using CRC16 checksum algorithm. (Default)
1 | Calculate checksum based on cExpression parameter using CRC32 checksum algorithm.
2 | Calculate checksum based on current record contents including Memo fields using CRC16.
3 | Calculate checksum based on current record contents including Memo fields using CRC32.

Return Values

Character data type. SYS(2017) returns a checksum value.

Remarks

  • Visual FoxPro generates the checksum based on the current record in the current work area and passes the byte values of the string into the CRC32 routine.
  • Visual FoxPro returns a value of "0" if no cursor is open in the current work area or if the record pointer is not valid, for example, pointing to a phantom record.
  • When you create a string expression from a record, Visual FoxPro removes trailing blank spaces and returns the expression as a character string, similar to the ALLTRIM( ) function.
  • When calculating the checksum value from the current record, Visual FoxPro disregards Memo and General fields.
  • Usually, Visual FoxPro uses any excluded fields specified by cExpression to store the checksum value and does not include them in the calculation. Visual FoxPro does not perform any checks on the data type of these fields. If cExpression contains an invalid field, Visual FoxPro disregards that field.
  • Visual FoxPro calculates the checksum from all the fields included except for Memo, General, and those specified by cExpression. You can determine the fields used and their order using the FIELD( ) function. If you specified a setting for SET FIELDS, the checksum is calculated based on the current list specified by SET FIELDS which could include calculated fields.

    Calculated fields are temporary fields that exist in the current cursor based on an expression but are not defined in the actual table structure. For example, the field LOCATION is a calculated field:

    Use Customer
SET FIELDS TO LOCATION = ALLTRIM(city) + ',' + state

See Also

SYS( ) Functions Overview | SYS(2007) - Checksum Value | SET FIELDS Command | FIELD( ) Function | SET RESOURCE | Creating Character Expressions


SYS(2018) - Error Message Parameter

Returns the error message parameter for the most recent error.

SYS(2018)

Return Values

Character

Remarks

Certain error messages return additional information about the cause of the error. For example, if you reference a variable that doesn't exist, the name of the variable is included in the error message. SYS(2018) returns this additional information, called the error message parameter. Names of variables and files are common types of error message parameters.

Suppose you try to run a program named REPORTS, but the program doesn't exist. The text of the error message displayed is:

File REPORTS does not exist.

REPORTS is the error message parameter, and it is returned by SYS(2018):

? SYS(2018)

See Also

ERROR( ) | MESSAGE( ) | ON ERROR | SYS( ) Functions Overview


SYS(2019) - Configuration File Name and Location

Returns the name and location of the Visual FoxPro configuration file.

SYS(2019)

Return Values

Character

Remarks

The Visual FoxPro configuration file is named Config.fpw, and it isn't installed by default. You can create your own Config.fpw configuration file with MODIFY FILE.

If a configuration file can't be located, SYS(2019) returns an empty string.

The Visual FoxPro configuration file is typically located in the directory where Visual FoxPro is started, but can be located elsewhere. Visual FoxPro first looks for it in the startup directory. If the configuration file isn't located in the startup directory, the MS-DOS path is then searched. Two options let you tell Visual FoxPro where your configuration file is located and its name:

  • You can create an MS-DOS environmental variable named FOXPROWCFG with the MS-DOS SET command, and you can store the location and name of your configuration file in FOXPROCFG. In FoxPro for MS-DOS, the MS-DOS environmental variable is named FOXPROCFG.
  • When you start Visual FoxPro, you can also use the -C switch to designate a configuration file. Include the location and name of the configuration file immediately after -C.

For further information about the Visual FoxPro configuration file, see Customizing the Visual FoxPro Environment.

See Also

MODIFY FILE | SYS( ) Functions Overview | Customizing the Visual FoxPro Environment


SYS(2020) – Default Disk Size

Returns the total size in bytes of the default disk.

SYS(2020)

Return Values

Character

Remarks

The default disk can be specified with SET DEFAULT.

See Also

DISKSPACE( ) | SET DEFAULT | SYS( ) Functions Overview


SYS(2021) - Filtered Index Expression

Returns the filter expression for an open single-entry index (.idx) file or filter expressions for tags in compound index (.cdx) files.

SYS(2021, nIndexNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nIndexNumber
The numeric expression nIndexNumber specifies which filter expression to return from the open index files. SYS(2021) returns filter expressions from open index files in the following order as nIndexNumber increases from 1 to the total number of open single-entry .idx files and structural compound and independent compound index tags:
  1. Filter expressions from single-entry .idx files (if any are open) are returned first. The order in which the single-entry .idx files are included in USE or SET INDEX determines the order in which the filter expressions are returned.
  2. Filter expressions for each tag in the structural .cdx file (if one is present) are returned next. The filter expressions are returned from the tags in the order the tags were created in the structural index.
  3. Filter expressions for each tag in any open independent .cdx files are returned last. The filter expressions are returned from the tags in the order the tags were created in the independent compound indexes.

The empty string is returned if nIndexNumber is greater than the total number of open single-entry .idx files and structural and independent .Cdx file tags.

nWorkArea
Specifies the work area number for a table open in another work area.
cTableAlias
Specifies a table alias for a table open in another work area. If a table doesn't have the alias you specify, Visual FoxPro displays an error message.

Remarks

You can create filtered indexes in Visual FoxPro. If you include the optional FOR clause in INDEX, the index file acts as a filter on the table. Only records that match the filter expression lExpression in the FOR clause are available for display and access. Index keys are created in the index file for only those records matching the filter expression.

The empty string is returned if an index or index tag was created without a FOR clause.

USE and SET INDEX both support an index file name list that makes it possible for you to open index files for a table. Any combination of single-entry .idx file names, structural .cdx file names, and independent .cdx file names may be included in the index file name list.

SYS(2021) returns filter expressions from index files open in the current work area unless you include a specific work area or alias.

See Also

CDX( ) | KEY( ) | INDEX | MDX( ) | NDX( ) | REINDEX | SET INDEX | SET ORDER | SYS( ) Functions Overview | TAG( )


SYS(2022) - Disk Cluster Size

Returns the cluster size in bytes of a specified disk.

SYS(2022 [, cDiskName])

Return Values

Character

Parameters

cDiskName
Specifies a drive letter (A, B, C, ...) for a disk other than the current default disk.

See Also

SET DEFAULT | SYS( ) Functions Overview | SYS(2020) - Default Disk Size


SYS(2023) - Temporary Path

Returns the path on which Visual FoxPro stores its temporary files.

SYS(2023)

Return Values

Character

Remarks

You can specify the path on which temporary files are stored by including the special TMPFILES configuration item in your Visual FoxPro configuration file.

For additional information about the special TMPFILES configuration item, see Configuring Visual FoxPro.

See Also

SYS( ) Functions Overview | Configuring Visual FoxPro | SYS(2019) - Configuration File Name and Location


SYS(2029) - Table Type

Returns a value corresponding to the table type.

SYS(2029 [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nWorkArea
Specifies the work area in which the table is open.
cTableAlias
Specifies the alias of the table. If you omit nWorkArea and cTableAlias, SYS(2029) returns a value for the table open in the currently selected work area.

Remarks

The following table lists the values returned by SYS(2029) and the corresponding table type:

Return value | Table type
0 | No table open
3 | Previous versions of FoxPro, FoxBASE+, dBASE III PLUS, and dBASE IV with no memo field
48 | Visual FoxPro with or without a memo field
67 | dBASE IV SQL table with no memo field
99 | dBASE IV SQL System table with a memo field
131 | FoxBASE+ and dBASE III PLUS table with a memo field
139 | dBASE IV table with a memo field
203 | dBASE IV SQL table with a memo field
245 | Previous versions of FoxPro with a memo field

Example

The following example opens the customer table in the testdata database.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table

CLEAR
DO CASE
   CASE SYS(2029) = '3'
      ? 'Previous versions of FoxPro'
   CASE SYS(2029) = '48'
      ? 'Visual FoxPro Table'
   CASE SYS(2029) = '67'
      ? 'dBASE IV SQL table, no memo fields'
   CASE SYS(2029) = '99'
      ? 'dBASE IV SQL System table with a memo field'
   CASE SYS(2029) = '131'
      ? 'FoxBASE+ table with a memo field'
   CASE SYS(2029) = '139'
      ? 'dBASE IV table with a memo field'
   CASE SYS(2029) = '203'
      ? 'dBASE IV SQL table with a memo field'
   CASE SYS(2029) = '245'
      ? 'Previous versions of FoxPro with a memo field'
ENDCASE

See Also

ALTER TABLE - SQL | CREATE | CREATE TABLE - SQL | USE


SYS(2030) - Debug

Enable or disable debug features within system component user code.

SYS(2030[, 0 | 1])

Parameters

0
Disables the debug features.
1
Enables debug features so you can debug system component code.

Returns

Numeric. Value of the current setting.

Remarks

Starting with Visual FoxPro 7, whenever user code directly runs a system component, such as _GENMENU or _BROWSER, certain debugging features (profiling, dohistory, breakpoints, and single step) are disabled. SYS(2030, 1) enables you to run debugger on this type of user code by disabling the default behavior, then re-enabling the behavior after debugging by issuing SYS(2030, 0).

See Also

Debugger | SET ASSERTS | SET STEP


SYS(2040) - Detect Report Status

Detects whether a report is being printed or is in preview mode.

SYS(2040)

Return Values

Character data type. Returns the current status of the report as follows.

Value | Description
0 | There is no active report.
1 | Report is in Preview Mode
2 | Report is being sent as output (such as a printer or file).

Remarks

The SYS(2040) function is useful when you want to control content in a report depending on how its being viewed. For example, you can print a message such as "Confidential" or "Classified" but not display it when the report is in Preview Mode.

Example

The following example displays how SYS(2040) can be used to suppress the _PAGETOTAL system variable when the report is in Preview Mode.

"Page: " + TRANS(_PAGENO) + ;
IIF( SYS(2040) = "1", "", " of " + TRANS(_PAGETOTAL))

See Also

SYS( ) Functions Overview | REPORT Command


SYS(2060) - Mouse Wheel Events

Enables or disables the accumulation of mouse wheel events in the event queue.

SYS(2060 [, 0 | 1])

Return Values

Character data type. Returns the current value of SYS(2060).

Parameters

0
Enables the combining of mouse wheel events in the event queue. (Default)
1
Disables the combining of mouse wheel events in the event queue.

Remarks

When SYS(2060) is set to 0, mouse wheel events are added together in the event queue, rather than adding a new event. This creates smoother scrolling on slower computers.

See Also

SYS( ) Functions Overview | MouseWheel Event


SYS(2300) - Add or Remove Code Page

Adds or removes a code page from the National Language Support (NLS) list.

SYS(2300, nCodePage [, nAction])

Return Values

Numeric. 1 if nCodePage is in the list; 0 if nCodePage is not in the list.

Parameters

nCodePage
Specifies the integer code page value.
nAction
Specifies the action to perform on the specified code page. 0 removes the code page; 1 adds the code page.

Remarks

When a code page is included in the list of those supported by Visual FoxPro, NLS routines are employed for proper indexing, string comparisons, collate keying, and so on. With certain collate sequences (for example, Russian, Czech, or Hungarian), string comparisons can result in unexpected values, depending on which code page is set. To make sure these operations proceed correctly you can use SYS(2300) in your applications to determine whether the correct code page is set.

If you create indexes after using SYS(2300) to enable NLS support for a specific code page, you will get odd behavior in previous versions of Visual FoxPro which do not have NLS support for that code page. Make sure all Visual FoxPro data access is made from clients with SYS(2300) configured in a similar manner.

The NLS list includes 874, 932, 936, 949, 950, 1255, and 1256. For more information, see Code Pages Supported by Visual FoxPro.

Example

Code page 1250 is not included in the NLS list by default. Therefore, certain string comparisons might return unexpected values. To demonstrate this, follow these steps:

  1. Enable code page support for non-NLS code page 1250 by adding the following line to your config.fpw file:
    CODEPAGE = 1250
  2. Restart Visual FoxPro.
  3. Run the following code from a program file:
    SET COLLATE TO 'HUNGARY'  && Requires CODEPAGE = 1250 in config file
CLEAR

? UPPER("B")=LOWER("B"), LOWER("B")=UPPER("B")
? UPPER("F")=LOWER("F"), LOWER("F")=UPPER("F")
? UPPER("H")=LOWER("H"), LOWER("H")=UPPER("H")

=SYS(2300,1250,1)  && Add code page 1250 to NLS list

? UPPER("B")=LOWER("B"), LOWER("B")=UPPER("B")
? UPPER("F")=LOWER("F"), LOWER("F")=UPPER("F")
? UPPER("H")=LOWER("H"), LOWER("H")=UPPER("H")

=SYS(2300,1250,0)  && Restore default setting for code page 1250
RETURN

With the default settings, LOWER("B")=UPPER("B"), LOWER("F")=UPPER("F"), and LOWER("H")=UPPER("H") return .T..

After enabling NLS support for code page 1250, LOWER("B")=UPPER("B"), LOWER("F")=UPPER("F"), and LOWER("H")=UPPER("H") return .F..

See Also

CPCURRENT( ) Function | CPCONVERT( ) Function | CPDBF( ) Function | SET COLLATE Command | SET CPDIALOG Command


SYS(2333) - ActiveX Dual Interface Support

Enables or disables ActiveX dual interface (VTABLE binding) support.

SYS(2333 [, 0 | 1 | 2])

Return Values

Character

Parameters

0
Disables ActiveX dual interface support. If 0 or 1 is omitted, ActiveX dual interface support is disabled. 0 is the startup default for Visual FoxPro 6.0 or later.
1
Enables ActiveX dual interface support. 1 is the startup default for Visual FoxPro 5.0.
2
Returns the current SYS(2333) setting (0 or 1).

Remarks

The ActiveX control dual interface (VTABLE binding) is an optimization supported by Visual FoxPro. If an ActiveX control doesn't use the dual interface, you can disable the optimization while using that control.

If an ActiveX control does not perform properly when the control is instantiated, issue SYS(2333) or SYS(2333, 0) before the control is instantiated to disable dual interface support for the control. After the control has been instantiated, issue SYS(2333, 1) to enable ActiveX dual interface support for any controls that are later instantiated.

See Also

ActiveX Controls Overview. | OLE Container Control | Early (vtable) and Late (IDispatch) Binding


SYS(2334) – Automation Server Invocation Mode

Returns a value indicating how a Visual FoxPro automation server method was invoked.

SYS(2334)

Return Values

Character

Remarks

The following table lists the values SYS(2334) returns for automation servers:

Return value | Invocation method
0 | Unknown (for example, invoked from the INIT method, which is neither VTable or IDispatch)
1 | OLEPUBLIC method invoked via VTable binding
2 | IDispatch

SYS(2334) also returns zero when executed from within a stand-alone executable (.exe). Use the StartMode property to determine how an instance of Visual FoxPro was started.

See Also

StartMode Property | SYS( ) Functions Overview | Automation Server Programming Notes


SYS(2335) – Unattended Server Mode

Enables or disables modal states for distributable Visual FoxPro .exe automation servers.

SYS(2335 [, 0 | 1])

Return Values

Character

Parameters

0
Enables unattended mode. When unattended mode is enabled, a Visual FoxPro error is generated whenever a modal state occurs. Your .exe automation server can trap for these errors with an ON ERROR routine.
1
(Default) Disables unattended mode. Modal states, which require user intervention, can occur. Unattended mode is disabled at startup.

Remarks

Use SYS(2335) to enable or disable modal states in Visual FoxPro .exe automation servers. Automation servers are created with the Project Manager. For additional information about using Visual FoxPro to create .exe automation servers, see Adding OLE.

Modal states occur when dialogs or errors messages are displayed, requiring input from a user to exit the dialog or error message and continue program execution. Modal states can be undesirable in .exe servers that are deployed remotely, possibly without intervention from a user. Program execution is halted, and requires intervention for program execution to continue.

The following table lists some typical examples of modal states that can occur in an .exe server.

Modal State | Examples
WAIT command or MESSAGEBOX( ) function | Can occur in program code.
Visual FoxPro errors such as "File access is denied" or "Allowed DO nesting level exceeded" | Can occur in program code.
Open dialog boxes | Can occur when files included in a SQL statement cannot be located.
SQL Connection Login dialog box | Can occur after a connection cannot be established.

SYS(2335 ,0) should be executed as soon as possible in unattended .exe automation server program code because a modal state can occur anytime after program execution begins.

Note that SYS(2335) applies only to .exe automation servers for which the StartMode property equals two. Unattended mode is always enabled for in-process .dll automation servers (for which the StartMode property equals three).

Issuing SYS(2335) without an argument in a runtime application returns its current setting.

See Also

ON ERROR | StartMode Property | SYS( ) Functions Overview | Adding OLE


SYS(2336) - Critical Section support

Controls entries to or exits from a critical section in MTDLL servers.

SYS(2336 [, nAction])

Parameters

nAction
Specifies the action performed by the SYS(2336) function, according to the following table.
NAction | Description
(none) Default | Returns the current reference count
1 | Calls EnterCriticalSection
2 | Calls LeaveCriticalSection
3 | Calls LeaveCriticalSection as many times as necessary to reduce the reference count to 0, thereby freeing the critical section.

Remarks

SYS(2336) accesses EnterCriticalSection and LeaveCriticalSection Windows API calls. You can find details of these functions in the MSDN Library Platform SDK reference at http://msdn.microsoft.com/library.

See Also

SYS(3095) | Accessing APIs | BUILD MTDLL Command


SYS(2339) - Call CoFreeUnusedLibraries when COM object is released

Sets or returns whether Visual FoxPro calls the operating system function CoFreeUnusedLibraries when a COM object is released.

SYS(2339 [, 0 | 1 ])

Parameters

0
Specifies that CoFreeUnusedLibraries is not called (default).
1
Specifies that CoFreeUnusedLibraries is called.

Return Value

Character

Remarks

If you have problems releasing a COM server even though all references are released, you might need to change this setting. You can also use Declare-DLL to call CoFreeUnusedLIbraries directly.

See Also

VFP8R.DLL Run-Time Library | VFP8T.DLL Run-Time Library | BUILD MTDLL Command | DECLARE - DLL Command


SYS(2340) - NT Service Support

Disables or enables support for NT service.

SYS(2340 [,0 | 1 ])

Parameters

0
Disables support for NT Service (default).
1
Enables support for NT Service.

Return Value

Character

Remarks

This function intercepts Windows logoff messages (WM_QUERYENDSESSION and WM_ENDSESSION) to Visual FoxPro and specifies whether to keep Visual FoxPro COM Server instances running or to shut them down. A Visual FoxPro application will terminate when the current user logs off Windows. If the application is a Windows Service, then that service will terminate. Enabling support for NT service will make it possible for Visual FoxPro applications to continue even if the current user logs off Windows.

See Also

SYS( ) Functions Overview


SYS(2410) - Error Handler

Returns the error handler type for an error. You can use SYS(2410) in your TRY...CATCH...FINALLY code to determine a course of action, for example, by using a DO CASE structure, depending on the type of handler that handles the exception.

SYS(2410)

Return Value

Character data type. The following table lists possible values returned by SYS(2410).

Value | Description
0 | System handler
1 | TRY...CATCH...FINALLY
2 | Error event
3 | ON ERROR command

Remarks

If a TRY...CATCH...FINALLY structure does not contain any CATCH statements or CATCH statements in which the WHEN lExpression evaluates to True (.T.), SYS(2410) might erroneously return an incorrect value.

See Also

SYS( ) Functions Overview | DO CASE ... ENDCASE Command | Exception Class | TRY...CATCH...FINALLY Command | Structured Error Handling


SYS(2450) - Application Search Path Order

Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.

You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.

SYS(2450 [, 0 | 1 ])

Parameters

0
Search along path and default locations before searching in the application. (Default)
1
Search within the application for the specified procedure or UDF before searching the path and default locations.

Return Values

Character data type. Calling SYS(2450) without parameters returns a value of "0" or "1" specifying whether Visual FoxPro searches along the path and default locations before searching in the application or within the application first.

Remarks

You can use SET PROCEDURE to make sure that the file is found before path searching takes place. However, you must call SET PROCEDURE for each file.

See Also

SET DEFAULT Command | SET PATH Command | SET PROCEDURE Command | SYS( ) Functions Overview | DO Command


SYS(2600) - Return Pointer as String

Interprets an integer as pointer into memory and returns the contents of that memory as a string, or writes new data to that memory location.

SYS(2600, dwAddress, nLength [, cNewString])

Parameters

dwAddress
Specifies the pointer to a memory address. This value is interpreted as an integer.
nLength
Specifies the number of bytes to read from dwAddress.
cNewString
Specifies a value to be returned to dwAddress.

Remarks

This function is for advanced programmers only.

Examples

The following code returns the string cRes, which contains the nLen bytes starting at nAddress:

   cRes = SYS(2600, nAddress, nLen)

The following code returns the string cRes and also places nLen bytes of cSrc at nAddress:

   cRes = SYS(2600, nAddress, nLen, cSrc)

See Also

SYS( ) Functions Overview


SYS(2700) - Enables Windows XP Themes

Enables or disables Windows XP Themes support in Visual FoxPro entirely.

SYS(2700 [, nValue ])

Parameters

nValue
Numeric data type. The following table lists the values for nValue.
nValue | Setting
0 | Disables Themes support.
1 | Enables Themes support. (Default)

Return Values

Numeric data type. SYS(2700) without arguments returns a value of 0 if Themes is not turned on or if you are running an older operating system that does not support Themes. SYS(2700) returns a value of 1 if Themes is turned on.

Remarks

The behavior of calling SYS(2700) without any arguments to return the current setting differs from the _SCREEN system variable in that it always returns the state of Themes on the computer. Therefore, if you use SYS(2700,1) to turn on Themes for Visual FoxPro and disable Themes using the Display control panel in Windows, SYS(2700) returns a value of 0 whereas _SCREEN.Themes still returns True (.T.).

When you change Themes support using the SYS(2700) function, Visual FoxPro might not refresh the user interface automatically. However, when Themes is turned on, certain effects such as those that appear when moving the mouse over controls will work. Therefore, it is recommended that you set Themes support at the beginning of an application before the user interface is rendered.

Note If you change Themes support while a form is running, you can call the form's Refresh method to redraw themed controls.

See Also

SYS( ) Functions Overview | _SCREEN System Variable | Refresh Method | Themes Property


SYS(2800) - Accessibility Support

Disables or enables Microsoft Active Accessibility support and sets certain options to track the keyboard focus of the currently selected control in a Visual FoxPro form.

SYS(2800 [,nFlag] )

Parameters

nFlag
Disables accessibility support or enables various accessibility functionality according to the following table.
Note The flags are additive.
nFlags | Description
0 | Disables Active Accessibility (AA).
1 | Enables WM_GETOBJECT.
2 | Enables NotifyWinEvent.
4 | Causes Visual FoxPro to not return to Accessibility clients until a specified action is complete. Overrides the messages of certain methods of IAccessible, such as accDoDefaultAction or accSelect, to process the client's request and return to the client immediately.
16 | Enables ACCNAME. Returns object Name rather than Caption. Use for testing.
32 | For backward compatibility only.

The default for nFlag is 3, which is the sum of "Enables WM_GETOBJECT" (2) + "Enables NotifyWinEvent" (3).

For details on WM_GETOBJECT, NotifyWinEvent, and accDoDefaultAction, see the Accessibility topic in the User Interface Services section of Platform SDK in the MSDN Online Library.

Return Value

Character

Remarks

SYS(2800) returns a numeric value as a character string for the current Active Accessibility setting.

This function enables you to verify the functionality of accessibility aids, such as the Microsoft Magnifier, when you are designing an application to comply with Windows Logo requirements.

This function is only effective for native Visual FoxPro controls. Third party ActiveX controls may or may not correctly track keyboard focus with accessibility aids enabled. Contact the control vendor for information on the accessibility behavior of a specific control.

See Also

SYS( ) Functions Overview


SYS(2801) - Event Tracking Support

Extends event tracking of mouse and keyboard events.

SYS(2801 [, 1 | 2 | 3 ] )

Parameters

1
Record only Visual FoxPro object events.
2
Record only Windows mouse and keyboard events
3
Record both Visual FoxPro and Windows events

Remarks

You can use SYS(2801) to specify which user events are tracked when your code is executed. You can set up event tracking in the Visual FoxPro debugger or use the SET EVENTTRACKING command.

See Also

SET EVENTLIST command | SYS(2800) | Tracking Event Sequences


SYS(3004) - Return Locale ID

Returns the Locale ID used by automation and ActiveX controls.

SYS(3004)

Return Values

Character

Remarks

SYS(3004) returns the current Visual FoxPro Locale ID (LCID), which is determined by the Visual FoxPro Language ID (LangID) and Sort ID.

The Locale ID determines the language in which automation and ActiveX controls exchange information. The default Visual FoxPro Locale ID is 1033, English.

For example, assume you have installed the German version of Microsoft Excel 5.0, which supports both English and German commands. In this case, the following example makes it possible for you to start and close the German version of Microsoft Excel 5.0:

oleExcel1 = CREATEOBJECT('Excel.Application')  && Starts Excel

? SYS(3005, 1033)  && English Locale ID
oleExcel1.Quit  && Closes Excel with English command

oleExcel2 = CREATEOBJECT('Excel.Application')  && Starts Excel

? SYS(3005, 1031)  && German Locale ID
oleExcel2.Beenden  && Closes Excel with German command

For a list of Visual FoxPro Locale IDs, see SYS(3005) - Set Locale ID. For additional information about Locale, Language, and Sort IDs, see the Microsoft Windows Software Development Kit documentation.

See Also

DefOLELCID Property | OLELCID Property | SYS(3005) - Set Locale ID | SYS(3006) - Set Language and Locale IDs


SYS(3005) - Set Locale ID

Sets the Locale ID used by automation and ActiveX controls.

SYS(3005, nLocaleID)

Return Values

Character

Parameters

nLocaleID
Specifies the Locale ID. The following list contains the Locale IDs supported in Visual FoxPro:
nLocaleID | Language
1029 | Czech
1031 | German
1033 | English (Default)
1034 | Spanish
1036 | French
1040 | Italian
1045 | Polish
1046 | Portuguese (Brazil)
2070 | Portuguese (Portugal)

Remarks

SYS(3005) sets the global Locale ID (LCID). The Locale ID determines the language in which automation and ActiveX controls exchange information. The default Visual FoxPro Locale ID is 1033, English.

Note Using the DefOLELCID Property is the preferred method for setting a Locale ID for a form or the main Visual FoxPro window. The automation command language is affected only by the Global LocaleID, set with SYS(3005). The DefOLELCID and OLELCID properties affect only the language of the user interface, which ActiveX controls display, and not the language of the automation commands.

For example, assume you have installed the German version of Microsoft Excel 5.0, which supports both English and German commands. In this case, the following example makes it possible for you to start and close the German version of Microsoft Excel 5.0:

oleExcel1 = CREATEOBJECT('Excel.Application')  && Starts Excel

? SYS(3005, 1033)  && English Locale ID
oleExcel.Quit  && Closes Excel with English command

oleExcel2 = CREATEOBJECT('Excel.Application')  && Starts Excel

? SYS(3005, 1031)  && German Locale ID
oleExcel.Beenden  && Closes Excel with German command

For additional information about Locale IDs, see the Microsoft Windows Software Development Kit documentation.

See Also

DefOLELCID Property | OLELCID Property | SYS(3004) - Return Locale ID | SYS(3006) - Set Language and Locale IDs


SYS(3006) - Set Language and Locale IDs

Sets the Language ID and the Locale ID.

SYS(3006, nLanguageID)

Return Values

Character

Parameters

nLanguageID
Specifies the Language ID.

Remarks

SYS(3006) sets the Visual FoxPro Language ID (LangID), and then sets the Locale ID (LCID) based on the Language ID and the current value of the Sort ID.

Note Using the DefOLELCID Property is the preferred method for setting a Locale ID for a form or the main Visual FoxPro window.

For additional information about Language, Locale, and Sort IDs, see the Microsoft Windows Software Development Kit documentation.

See Also

DefOLELCID Property | OLELCID Property | SYS(3004) - Return Locale ID | SYS(3005) - Set Locale ID


SYS(3050) - Set Buffer Memory Size

Sets the foreground or background buffer memory size.

SYS(3050, nType, [nBuffMemSize])

Return Values

Character

Parameters

nType
Specifies the buffer. The following table lists the values for nType and the corresponding buffer:
nType | Buffer
1 | Foreground
2 | Background
nBuffMemSize
Specifies the maximum buffer memory size in bytes. If you specify a value for nBuffMemSize that is less than 256K bytes, Visual FoxPro sets the buffer memory size to 256K bytes.

Specify 0 for nBuffMemSize to return the buffer memory size to the Visual FoxPro startup value. The startup value depends on the amount of your computer's memory. If you omit nBuffMemSize, SYS(3050) returns the buffer memory size for the buffer specified with nType.

Remarks

SYS(3050) makes it possible for you to optimize Visual FoxPro performance by adjusting the amount of memory Visual FoxPro allocates for the foreground and background buffers. The foreground memory buffer is the memory available to Visual FoxPro when it is operating in the foreground as the currently active application. The background memory buffer is the memory available to Visual FoxPro when it is operating in the background when another application is the foreground application.

SYS(3050) returns a numeric value as a character string that indicates the maximum amount of memory Visual FoxPro allocates for the foreground or background buffers.

See Also

SYS(1001) - Visual FoxPro Memory | DISPLAY MEMORY Command | MEMORY( ) Function | Managing Memory


SYS(3051) - Set Lock Retry Interval

Specifies the time in milliseconds that Visual FoxPro waits before attempting to lock a record, table, memo, or index file after an unsuccessful locking attempt.

SYS(3051, [nWaitMilliseconds])

Return Values

Character

Parameters

nWaitMilliseconds
Specifies the wait time in milliseconds; can be a value from 100 to 1000 milliseconds.

Specify 0 for nWaitMilliseconds to return the lock attempt time interval to the Visual FoxPro default startup value (333 milliseconds). If you omit nWaitMilliseconds, SYS(3051) returns the current lock attempt time interval.

Remarks

SYS(3051) returns a numeric value as a character string that indicates the lock attempt time interval.

See Also

SET REPROCESS | SYS(3052) - Override SET REPROCESS Locking | Locking Data


SYS(3052) - Override SET REPROCESS Locking

Specifies whether Visual FoxPro uses the SET REPROCESS setting when attempting to lock an index or memo file.

SYS(3052, nFileType, [lHonorReprocess])

Return Values

Character

Parameters

nFileType
Specifies the type of file. The following table lists the values for nType and the corresponding file type:
nFileType | File type
1 | Index
2 | Memo
lHonorReprocess
Specifies whether Visual FoxPro uses the SET REPROCESS setting for unsuccessful lock attempts for index and memo files.

Specify true (.T.) to use the SET REPROCESS setting when Visual FoxPro attempts to lock files specified with nFileType. Specify false (.F.), the default, to override the SET REPROCESS setting when Visual FoxPro attempts to lock files specified with nFileType. When set to false, Visual FoxPro waits indefinitely for locks on the specified files; this option is the same as locking behavior in previous versions of FoxPro.

If you omit lHonorReprocess, SYS(3052) returns the current setting for the file type specified with nFileType.

Remarks

SYS(3052) provides additional control over file locking in Visual FoxPro. It's best to set lHonorReprocess to true (.T.) in order to reduce the risk of file lock contention if your application uses transaction processing.

SYS(3052) returns as a character string a numeric value of 0 (corresponding to false (.F.)) or 1 (corresponding to true (.T.)). If lHonorReprocess is included in SYS(3052), the value returned is identical to the logical value you specify for lHonorReprocess. If you omit lHonorReprocess, the value returned is the current setting for the file type specified with nFileType.

See Also

SET REPROCESS | SYS(3051) - Set Lock Retry Interval | Locking Data


SYS(3053) - ODBC Environment Handle

Returns the ODBC environment handle.

SYS(3053)

Return Values

Character

Remarks

If ODBC isn't loaded, SYS(3053) loads it and returns the ODBC environment handle.

The environment handle returned by SYS(3053) provides access to ODBC through ODBC API calls. Access to the ODBC API is available in Visual FoxPro through DECLARE - DLL, and through external Visual FoxPro API library routines.

Only one ODBC environment handle should be used at any time. A Visual FoxPro program using ODBC calls should use SYS(3053) to get the ODBC environment handle rather than reallocating and freeing the ODBC environment handle through ODBC API calls.

Exercise care when manipulating an ODBC environment handle. For further information about the ODBC API, see the Microsoft ODBC SDK documentation.

See Also

DECLARE - DLL | SET LIBRARY | Execution of ODBC Extensions to SQL | Read ODBC Registry Values


SYS(3054) - Rushmore Query Optimization Level

Enables or disables display of Rushmore optimization levels for queries.

SYS(3054 [, 0 | 1 | 11 | 2 | 12] [, cMEMVAR])

Return Values

Character

Parameters

0
(Default) Disables the display of Rushmore optimization levels.
1
Enables the display of the Rushmore filter optimization levels.
11
Enables the display of Rushmore join optimization levels.
2
Includes SQL statement with the display of the Rushmore filter optimization levels.
12
Includes SQL statement with the display of Rushmore join optimization levels.
cMEMVAR
Specifies an undeclared or declared PUBLIC or LOCAL memory variable in which to store the showplan information. If you have not declared cMEMVAR, Visual FoxPro creates it as a PRIVATE variable.

Remarks

SYS(3054) returns the current Rushmore optimization level setting as a character string to the active screen or to a memory variable.

The showplan output displays the table alias as reference for table name.

Use SYS(3054) to improve query performance by determining the extent to which the query is optimized by Rushmore technology.

Issue SYS(3054, 1) to display the Rushmore filter optimization level after a query is executed. The filter optimization level is displayed in the active window.

The following table lists the three levels of Rushmore optimization:

Optimization Level | Description
None | The query could not be optimized with Rushmore technology.
Partial | Some expressions in the query could be optimized with Rushmore technology. The index tags used for Rushmore optimization are listed.
Full | The query was fully optimized with Rushmore technology. The index tags used for Rushmore optimization are listed.

If SYS(3054,1) indicates that a query could not be optimized or could be optimized only partially, you can modify the query to take advantage of Rushmore optimization.

Issue SYS(3054, 11) to display the Rushmore join optimization level after a query is executed. The optimization level is displayed in the active window.

Issue SYS(3054, 0) to stop display of the Rushmore optimization level after a query is executed.

For more information about Rushmore technology and optimizing queries, see Using Rushmore Query Optimization to Speed Data Access.

Example

The following code displays the Rushmore Optimization level after performing a query:

LOCAL cmemvar
=SYS(3054,11,"cmemvar")
SELECT * FROM HOME()+"labels.dbf"
? cmemvar

See Also

PUBLIC Command | LOCAL Command | PRIVATE Command | SELECT - SQL Command | Using Rushmore Query Optimization to Speed Data Access


SYS(3055) – FOR and WHERE Clause Complexity

Sets the complexity level of the FOR and WHERE clauses in commands and functions that support those clauses.

SYS(3055 [, nComplexity])

Return Values

Character

Parameters

nComplexity
Specifies the complexity level. The valid range for nComplexity is 320 to 2040. The default value is 320. If you specify an odd value, it is rounded down to the closest even integer.

Remarks

If you receive the error 1308 - Insufficient Stack Space or 1812 - SQL: Statement Too Long, you can increase the FOR and WHERE clause complexity to help prevent the error.

For example, calling TABLEUPDATE( ) for a local table or view that doesn't use key fields generates a long WHERE clause to find the update row. The default number of fields supported in the WHERE clause is 40. If you receive the error 1812 - SQL: Statement Too Long, you should either use a key field for the update or increase the complexity of the WHERE clause with SYS(3055). If you use SYS(3055), increase its value to 8 times the number of fields in the table:

= SYS(3055, 8 * MIN(40, FCOUNT( )))

If SYS(3055) is issued without the nComplexity argument, its current setting is returned.

The following commands and functions support the FOR or WHERE clauses:

APPEND FROM | APPEND FROM ARRAY | AVERAGE
BLANK | BROWSE | CALCULATE
CHANGE | COPY TO ARRAY | COPY TO
COUNT | DEFINE PAD | DELETE
DELETE - SQL | DISPLAY | EXPORT
FOR( ) | INDEX | LABEL
LIST | LOCATE | RECALL
REPLACE | REPLACE FROM ARRAY | REPORT
SCAN ... ENDSCAN | SELECT - SQL | SORT
SUM | TABLEUPDATE( ) | UPDATE - SQL

See Also

TABLEUPDATE( ) | SYS( ) Functions Overview | 308 - Insufficient Stack Space | 1812 - SQL: Statement Too Long


SYS(3056) – Read Registry Settings

Forces Visual FoxPro to read its registry settings again and update itself with the current registry settings.

SYS(3056 [,1])

Return Values

Character

Parameters

1
Include the 1 option to update only from registry settings, with the exception of SET commands and file locations.

Remarks

Returns the empty string.

Visual FoxPro stores the Options dialog box settings in the Windows registry. You can also store additional Visual FoxPro configuration settings in a text file, normally named Config.fpw. Visual FoxPro is configured when it is started by reading these registry settings and its configuration file (if one exists).

The settings you specify in the Options dialog box are written to the registry when you choose Set As Default. Some settings, such as those for Syntax Coloring, are stored in the registry but have no corresponding SET commands. Other settings do have corresponding SET commands (such as SET BELL, SET CLOCK, and so on) that affect the Visual FoxPro environment. The settings made from the File Locations tab in the Options dialog box are also stored in the registry, and some are accessible through system variables such as _COVERAGE and _SAMPLES.

Issuing SYS(3056) updates information from the registry settings and the corresponding SET commands, registry settings from the Options dialog File Locations tab, and the Visual FoxPro configuration file (if one exists). SYS(3056) reads the registry information first, and then the configuration file.

Issuing SYS(3056,1) updates information from the Visual FoxPro registry settings that don't have corresponding SET commands. The SET commands, File Locations registry settings, and configuration file information aren't updated if the 1 argument is included.

Note that registry settings can also be changed directly through the Windows API. See the Windows API section of Solution.app, located in the Visual FoxPro ...\Samples\Solution directory, for an example of how you can use the Windows API to modify registry settings.

See Also

SET Command | Options Dialog Box | Read and Write Visual FoxPro Registry Values | Changing Configuration Settings in the Windows Registry


SYS(3095) - IDispatch Pointer

Returns an outgoing IDispatch pointer for a COM object

SYS(3095, oObject)

Parameters

oObject
Represents a reference to a COM object such as _VFP or Excel.Application.

Return Value

Numeric

Remarks

This pointer is provided for experienced developers who need an object pointer for use in API routines.

See Also

Early (vtable) and Late (IDispatch) Binding | API Library Routines A-Z | API Library Routines by Category | DECLARE - DLL Command


SYS(3096) - IDispatch Object Reference

Returns a Visual FoxPro COM object reference for an IDispatch pointer.

SYS(3096, nPointer)

Parameters

nPointer
Represents a pointer to a COM object such as _VFP or Excel.Application.

Return Value

Object

Remarks

This pointer is provided for experienced developers who need to determine an object reference for use in API routines. The refcount for the COM object is NOT changed.

See Also

Early (vtable) and Late (IDispatch) Binding | API Library Routines A-Z | API Library Routines by Category | DECLARE - DLL Command | SYS(3097) - Add Reference to Object | SYS(3098) - Release Object reference


SYS(3097) - Add Reference to Object

Performs an IDispatch AddRef call on a COM object.

SYS(3097, oObject)

Returns

Numeric. Returns the current Refcount after adding a new object reference.

Parameters

oObject
Object reference to COM object.
Note This function is provided for experienced developers. Invalid COM object reference counts can yield problems such as objects not being released correctly or calls to objects that no longer exist.

See Also

SYS(3098) | DECLARE - DLL Command


SYS(3098) - Release Object reference

Performs an IDispatch Release call on a COM object.

SYS(3098, oObject)

Returns

Numeric. Returns the current Refcount after releasing an object reference.

Parameters

oObject
Object Reference to COM Object.
Note This function is provided for experienced developers. Invalid COM object reference counts can yield problems such as objects not being released correctly or calls to objects that no longer exist.

See Also

SYS(3097) | DECLARE - DLL Command


SYS(3099) - SQL Data Engine Compatibility Mode

Enables SQL data engine compatibility with Visual FoxPro 7.0 or Visual FoxPro 8.0.

SYS(3099 [, 70 | 80 ])

Parameters

70
Specifies that Visual FoxPro treats SQL SELECT commands as it did in versions prior to Visual FoxPro 8.0
80
Specifies that Visual FoxPro treats SQL SELECT commands with the standard Visual FoxPro 8.0 behavior. For more information, see SET ENGINEBEHAVIOR Command. (Default)

Remarks

Visual FoxPro 7.0 behavior for the SQL SELECT command can be restored by setting SYS(3099) to 70.

See Also

SYS( ) Functions Overview | SELECT - SQL Command | SET ENGINEBEHAVIOR Command | Special Terms for Configuration Files


SYSMETRIC( ) Function

Returns the size of the operating system's screen elements.

SYSMETRIC(nScreenElement)

Return Values

Numeric

Parameters

nScreenElement
Specifies a screen element. The following table shows values for nScreenElement and the corresponding screen element:
nScreenElement | Screen Element
1 | Screen width
2 | Screen height.
3 | Width of sizable window frame
4 | Height of sizable window frame
5 | Width of scroll arrows on vertical scroll bar
6 | Height of scroll arrows on vertical scroll bar
7 | Width of scroll arrows on horizontal scroll bar
8 | Height of scroll arrows on horizontal scroll bar
9 | Height of window title
10 | Width of non-sizable window frame
11 | Height of non-sizable window frame
12 | Width of DOUBLE or PANEL window frame
13 | Height of DOUBLE or PANEL window frame
14 | Scroll box width on horizontal scroll bar in text editing windows
15 | Scroll box height on vertical scroll bar in text editing windows
16 | Minimized window icon width
17 | Minimized window icon height
18 | Maximum insertion point width
19 | Maximum insertion point height
20 | Single-line menu bar height
21 | Maximized window width
22 | Maximized window height
23 | Kanji window height
24 | Minimum sizable window width
25 | Minimum sizable window height
26 | Minimum window width
27 | Minimum window height
28 | Window controls width
29 | Window controls height
30 | 1 if mouse hardware present; otherwise 0
31 | 1 for Microsoft Windows debugging version; otherwise 0
32 | 1 if mouse buttons swapped; otherwise 0
33 | Width of a button in a half-caption window's caption or title bar
34 | Height of half-caption window caption area

Remarks

SYSMETRIC( ) returns the size of screen elements. Screen elements include menus, windows, window controls, and the insertion point. Values are returned in pixels unless otherwise noted and can vary for different displays, display drivers, and video hardware. For further information on screen elements, refer to the GetSystemMetrics function in the MSDN Library at http://msdn.microsoft.com/library.

SYSMETRIC( ) enables you to determine the size of menus, windows, and window controls you create in Visual FoxPro. Windows and menus created with DEFINE WINDOW and DEFINE MENU use the same screen element sizes as the operating system's windows and menus.

See Also

FONTMETRIC( ) | GETFONT( ) | TXTWIDTH( ) | WFONT( )


TABLEREVERT( ) Function

Discards changes made to a buffered row or a buffered table or cursor and restores the OLDVAL( ) data for remote cursors and the current disk values for local tables and cursors.

Note On a network, the data currently on disk might differ from the data on the disk when the table was opened or the cursor was created. Other users on the network might have changed the data after the table was opened or the cursor was created.
TABLEREVERT( [lAllRows [, cTableAlias | nWorkArea] ] )

Parameters

lAllRows
Determines whether all changes made to the table or cursor are discarded. The following table describes the values for lAllRows.
lAllRows | Description
False (.F.) | If table buffering is enabled, only changes made to the current record in the table or cursor are discarded. (Default)
True (.T.) | If table buffering is enabled, changes made to all records are discarded in the table or cursor.

If row buffering is enabled, Visual FoxPro disregards the value of lAllRows, and changes made to the current record in the table or cursor are discarded.

cTableAlias
Specifies the alias of the table or cursor in which the changes are discarded.
nWorkArea
Specifies the work area of the table or cursor in which the changes are discarded.

Return Values

Numeric data type. TABLEREVERT( ) returns the number of records for which changes were discarded.

Remarks

TABLEREVERT( ) cannot discard changes made to a table or cursor that does not have row or table buffering enabled. If you issue TABLEREVERT( ) and row or table buffering is not enabled, Visual FoxPro generates an error message. Use CURSORSETPROP( ) to enable or disable row and table buffering.

Changes are discarded in the table or cursor open in the currently selected work area if TABLEREVERT( ) is issued without the optional cTableAlias or nWorkArea arguments.

TABLEREVERT( ) does not return the record pointer to its original position.

TABLEREVERT( ) operates on CursorAdapter objects in the same way as other buffered cursors.

Example

The following example demonstrates how you can use TABLEREVERT( ) to discard changes made to a buffered table. MULTILOCKS is set to ON, a requirement for table buffering. The customer table in the testdata database is opened, and CURSORSETPROP( ) is then used to set the buffering mode to optimistic table buffering (5).

The value of the cust_id field is displayed and then the cust_id field is modified with REPLACE. The new value of the cust_id field is displayed. TABLEREVERT( ) is then used to return the table to its original state (TABLEUPDATE( ) could be issued instead to commit the changes). The reverted value of the cust_id field is then displayed.

CLOSE DATABASES
SET MULTILOCKS ON  && Must be on for table buffering
SET PATH TO (HOME(2) + 'data\')     && Sets path to database
OPEN DATABASE testdata  && Open testdata database
USE Customer     && Open customer table
= CURSORSETPROP('Buffering', 5, 'customer')  && Enable table buffering

CLEAR
? 'Original cust_id value: '
?? cust_id  && Displays current cust_id value
REPLACE cust_id    WITH '***'  && Changes field contents
? 'New cust_id value: '
?? cust_id  && Displays new cust_id value
= TABLEREVERT(.T.)  && Discard all table changes
? 'Reverted cust_id value: '
?? cust_id  && Displays reverted cust_id value

See Also

CURSORSETPROP( ) | CURVAL( ) | OLDVAL( ) | TABLEUPDATE( )


TABLEUPDATE( ) Function

Commits changes made to a buffered row, a buffered table, cursor, or cursor adapter.

TABLEUPDATE( [nRows [, lForce]] [, cTableAlias | nWorkArea] [, cErrorArray] )

Parameters

nRows
Specifies which changes made to the table or cursor should be committed.
Note Visual FoxPro enables Optimistic Row Buffering by default for those cursors associated with a CursorAdapter object.

The following table describes the values for nRows.

nRows Description
0 If row or table buffering is enabled, commit only the changes made to the current row in the cursor. (Default)

When working with CursorAdapter objects, Visual FoxPro executes the appropriate command in the InsertCmd, UpdateCmd, or DeleteCmd property for that row only.
1 If table buffering is enabled, commit changes made to all records to the table or cursor.

If row buffering is enabled, commit only changes made to the current record in the table or cursor.

When working with CursorAdapter objects, Visual FoxPro executes the appropriate commands in the InsertCmd, UpdateCmd, and DeleteCmd properties for each affected row.
2 Commit changes made to the table or cursor in the same manner as when nRows = 1. However, an error does not occur when a change cannot be committed. Visual FoxPro continues to process any remaining records in the table or cursor.

If cErrorArray is included, an array containing error information is created when an error occurs.

For compatibility with previous Visual FoxPro applications, the nRows parameter also accepts False (.F.) and True (.T.) instead of 0 and 1 respectively.

When specifying 0 or 1 for nRows, the record pointer remains on the record where changes could not be committed. To determine why the changes could not be committed, use the AERROR( ) function.

When working with CursorAdapter objects and specifying 1 or 2 for nRows, all changes made to the cursor in the following CursorAdapter events must be committed during the same call to TABLEUPDATE( ) unless an error occurs:

  • BeforeInsert
  • AfterInsert
  • BeforeDelete
  • AfterDelete
  • BeforeUpdate
  • AfterUpdate

Visual FoxPro passes the values of nRows to the CursorAdapter BeforeCursorUpdate event.

lForce
Determines whether Visual FoxPro overwrites changes made to the table or cursor by another user on a network.

The following table describes the values for lForce.

lForce | Description
False (.F.) Commits changes to the table or cursor, starting with the first record and continuing towards the end of the table or cursor. (Default)

If a record modified by another user on the network is encountered, Visual FoxPro generates an error. When Visual FoxPro generates the error, you can handle the error through an ON ERROR routine, and the ON ERROR routine can issue TABLEUPDATE( ) with lForce set to True (.T.) to commit changes to the record. Alternately, if a transaction is in progress, the ON ERROR routine can handle the error and then issue a ROLLBACK command to revert the table or cursor to its original state.
True (.T.) | Overwrites any changes made to the table or cursor by another user on a network. The WHERE clause uses only key fields.

When working with CursorAdapter objects, Visual FoxPro passes the value of lForce to the following CursorAdapter events:

  • BeforeCursorUpdate
  • BeforeInsert
  • BeforeUpdate
  • BeforeDelete
  • AfterInsert
  • AfterUpdate
  • AfterDelete
cTableAlias
Specifies the alias of the table or cursor in which the changes are committed. If you include a table or cursor alias, you must include the lForce argument.
nWorkArea
Specifies the work area of the table or cursor in which the changes are committed. If you include a work area, you must include the lForce argument.
cErrorArray
Specifies the name of an array created when nRows = 2 and changes to a record cannot be committed. The array contains a single column containing the record numbers of the records for which changes could not be committed. If you include an array name, you must include either a table or cursor alias cTableAlias or a work area number nWorkArea.
Note If an error other than a simple commit error occurs while updating records, the first element of cErrorArray will contain –1, and you can then use AERROR( ) to determine the why the changes could not be committed.

Visual FoxPro passes the value of cErrorArray, when it exists, to the CursorAdapter AfterCursorUpdate event.

Return Values

Logical data type. TABLEUPDATE( ) returns True (.T.) if changes to all records are committed. Otherwise, TABLEUPDATE( ) returns False (.F.).

Remarks

TABLEUPDATE( ) cannot commit changes made to a table or cursor that does not have row or table buffering enabled. If you issue TABLEUPDATE( ) and row or table buffering is not enabled, Visual FoxPro generates an error message. However, TABLEUPDATE( ) can still commit changes to a table or cursor that has validation rules. To enable or disable row and table buffering, use CURSORSETPROP( ).

Changes are committed to the table or cursor open in the currently selected work area if TABLEUPDATE( ) is issued without the optional cTableAlias or nWorkArea arguments.

If table buffering is used and multiple records are updated, TABLEUPDATE( ) moves the record pointer to the last record updated.

Note Calling TABLEUPDATE( ) for a local table or view that does not use key fields generates a long WHERE clause to find the update row. The default number of fields supported in the WHERE clause is 40. If you receive the error 1812 - SQL: Statement Too Long, you should either use a key field for the update or increase the complexity of the WHERE clause with SYS(3055). If you use the SYS(3055) function, increase its value to a number that is eight times the number of fields in the table as shown in the following example:
SYS(3055, 8 * MIN(40, FCOUNT( ))

Interaction with CursorAdapter Objects The following behaviors apply when working with CursorAdapter objects:

  • TABLEUPDATE( ) operates only on the cursor associated with the CursorAdapter object.
  • TABLEUPDATE( ) executes commands according to the data source type and those stored in the CursorAdapter InsertCmd, UpdateCmd, or DeleteCmd properties against the current cursor row or rows as appropriate.
  • TABLEUPDATE( ) passes the value of GETFLDSTATE(1) to the following CursorAdapter events of each row affected:
    • BeforeInsert
    • BeforeUpdate
    • BeforeDelete

    For more information about GETFLDSTATE( ), see GETFLDSTATE( ) Function.

  • The successful completion of TABLEUPDATE( ) resets the field states according to usual TABLEUPDATE( ) behavior.
  • When table buffering is enabled, you can move away from the current record in the following CursorAdapter events:
    • BeforeInsert
    • AfterInsert
    • BeforeUpdate
    • AfterUpdate
    • BeforeDelete
    • AfterDelete

    You can also modify data in the cursor. This functionality supports scenarios such as retrieving the autoincrement value from the base table and inserting it into the cursor. When this scenario occurs, the CursorAdapter object should automatically return to the record whose changes are about to be committed after the event has occurred and commit the changes.

Example

The following example demonstrates how you can use TABLEUPDATE( ) to commit changes made to a buffered table. A table named employees is created, and a SQL INSERT statement inserts the value "Smith" into the cLastName field.

MULTILOCKS is set to ON, which is a requirement for table buffering. CURSORSETPROP( ) is used to set the buffering mode to Optimistic Table Buffering (5).

The original value of the cLastName field (Smith) is displayed, and the cLastName field is modified with REPLACE. The new value of the cLastName field (Jones) is displayed. TABLEUPDATE( ) is used to commit changes to the table (TABLEREVERT( ) could be issued instead to discard the changes). The updated value of the cLastName field (Jones) is then displayed.

CLOSE DATABASES
CREATE TABLE employee (cLastName C(10))
SET MULTILOCKS ON  && Must turn on for table buffering.
= CURSORSETPROP('Buffering', 5, 'employee' )  && Enable table buffering.
INSERT INTO employee (cLastName) VALUES ('Smith')

CLEAR
? 'Original cLastName value: '
?? cLastName  && Displays current cLastName value (Smith).

REPLACE cLastName WITH 'Jones'
? 'New cLastName value: '
?? cLastName  && Displays new cLastName value (Jones).

= TABLEUPDATE(.T.)  && Commits changes.
? 'Updated cLastName value: '
?? cLastName  && Displays current cLastName value (Jones).

See Also

Functions | CURSORSETPROP( ) | CURVAL( ) | OLDVAL( ) | TABLEREVERT( ) | Cursor Object


TAG( ) Function

Returns a tag name from an open, multiple-entry compound .CDX index file or the name of an open, single-entry .IDX index file.

TAG([CDXFileName[, nTagNumber[, nWorkArea | cTableAlias]]])

Return Values

Character

Parameters

CDXFileName
Specifies the name of the multiple-entry compound .cdx index file from which TAG( ) returns a tag name.
nTagNumber
Specifies a number corresponding to the order in which a tag was created in the compound index file. For example, if nTagNumber is 1, TAG( ) returns the name of the first tag created in the compound index file. If nTagNumber is 2, TAG( ) returns the name of the second tag created, and so on. TAG( ) returns the empty string when nTagNumber exceeds the number of tag names.

If you omit CDXFileName, TAG( ) returns compound index file tag names and single-entry index file names in a specific order as follows.

  • Names of single-entry index files are returned based on their order in the INDEX clause of USE or SET INDEX.
  • Tag names from the structural compound index file (if one exists for the table) are returned.
  • Tag names from other open compound index files are returned, again in the order in which the tags were created in the compound index files and in the order in which the compound index files are specified in the INDEX clause for USE or SET INDEX.
nWorkArea | cTableAlias
Returns tag names and index file names from files open in another work area. nWorkArea specifies a work area number and cTableAlias specifies a table alias. By default, tag names and index file names are returned from files in the current work area.

Remarks

Tags are index entries in multiple-entry compound .cdx index files created with INDEX.

Note Multiple-entry compound .cdx index files and single-entry .idx index files can be opened for a table with the INDEX clause in USE or with SET INDEX. A structural compound .cdx index file is automatically opened with its table.

Example

The following example opens the customer table in the testdata database. FOR ... ENDFOR is used to create a loop in which CDX( ) is used to display the name of each structural index.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'data\testdata')
USE Customer     && Open customer table

CLEAR
FOR nCount = 1 TO 254
   IF !EMPTY(TAG(nCount))  && Checks for tags in the index
   ? CDX(nCount)     && Display .CDX names
   ELSE
      EXIT  && Exit the loop when no more tags are found
   ENDIF
ENDFOR

See Also

CDX( ) | DESCENDING( ) | INDEX | MDX( ) | NDX( ) | SET INDEX | SYS(14) - Index Expression | USE Command | ATAGINFO( ) Function


TAGCOUNT( ) Function

Returns the number of .cdx compound index file tags and open .idx single-entry index files.

TAGCOUNT([CDXFileName [, nWorkArea | cTableAlias]])

Return Values

Numeric

Parameters

CDXFileName
Specifies the name of a compound index file for which TAGCOUNT( ) returns the number of tags. If CDXFileName does not exist for the current table, you must specify the nWorkarea or cTableAlias in which it does exist.

If you omit CDXFileName, TAGCOUNT( ) returns the number of tags in all .cdx compound index files and open .idx single-entry index files in the currently selected work area or alias.

nWorkarea
Specifies the work area of the table for which TAGCOUNT( ) returns the number of tags for the .cdx compound index file.
cTableAlias
Specifies the alias of the table for which TAGCOUNT( ) returns the number of tags for the .cdx compound index file.

Remarks

Included for compatibility with dBASE.

See Also

INDEX Command | TAGNO( ) Function


TAGNO( ) Function

Returns the index position for .cdx compound index file tags and open .idx single-entry index files.

TAGNO([IndexName [, CDXFileName [, nExpression | cExpression]]])

Return Values

Numeric

Parameters

IndexName
Specifies the name of a .cdx compound index file tag or an open .idx single-entry index file for which TAGNO( ) returns the index position.
CDXFileName
Specifies the name of a .cdx compound index file containing the name of the tag you specify with IndexName.
nExpression
Specifies the work area of the table for which TAGNO( ) returns the index position for .cdx compound index file tags and .idx single-entry index files.
cExpression
Specifies the alias of the table for which TAGNO( ) returns the index position for .cdx compound index file tags and .idx single-entry index files.

Remarks

TAGNO( ) returns 0 if a master index is not set (the table is in natural record number order) and the optional parameters are omitted.

Included for compatibility with dBASE.

See Also

INDEX Command | TAGCOUNT( ) Function


TAN( ) Function

This trigonometric function returns the tangent of an angle.

TAN(nExpression)

Return Values

Numeric

Parameters

nExpression
Specifies the angle in radians for which TAN( ) returns the tangent. To convert an angle from degrees to radians, use DTOR( ). The number of decimal places returned by TAN( ) can be specified with SET DECIMALS.

Example

CLEAR
? TAN(0)  && Displays 0.00
? TAN(PI( )/4)  && Displays 1.00
? TAN(PI( )*3/4)  && Displays -1.00

See Also

COS( ) | DTOR( ) | RTOD( ) | SET DECIMALS | SIN( )


TARGET( ) Function

Returns the alias of a table that is the target for a relation as specified in the INTO clause of SET RELATION.

TARGET(nRelationshipNumber [, nWorkArea | cTableAlias])

Return Values

Character

Parameters

nRelationshipNumber
Specifies the number of a relationship. Include a number from 1 to the number of relationships out of the specified work area. The aliases of the target tables are returned (in no specific order) until nRelationshipNumber is greater than the number of relationships. When nRelationshipNumber is greater than the number of relationships, the empty string is returned.
nWorkArea | cTableAlias
Returns the alias of the target table in another work area. nWorkArea specifies a work area number and cTableAlias specifies a table alias. By default, the alias of the target table from the current work area is returned if you don't specify the work area or alias.

Example

In the following example, a relation is set on the field order_id from orders into customer. The TARGET( ) function is then used to return the alias of the target table.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE orders IN 0 ORDER order_id
USE customer IN 0 ORDER cust_id
SELECT orders
SET RELATION TO cust_id INTO customer
? TARGET(1)  && Displays customer
? TARGET(2)  && Empty string

See Also

RELATION( ) | SET RELATION | SELECT


TEXTMERGE( ) Function

Provides evaluation of a character expression.

TEXTMERGE(cExpression [, lRecursive [, cLeftDelim [, cRightDelim]]])

Parameters

cExpression
Specifies the string expression to be evaluated.
lRecursive
Specifies whether to repeatedly iterate through all levels of delimiters in cExpression, evaluating until no text merge delimiters remain.
cLeftDelim
Specifies the left delimiter to use for the text merge search. cLeftDelim is limited to two characters.
cRightDelim
Specifies the right delimiter to use for the text merge search. cRightDelim is limited to two characters.

Return Values

Character string. Represents the value of cExpression, the merged text.

Remarks

The cLeftDelim and cRightDelim parameters temporarily override any SET TEXTMERGE DELIMITERS values.

The TEXTMERGE( ) function responds to current settings of SET TEXTMERGE SHOW | NOSHOW.

Example

The following example creates a text string, then outputs the TEXTMERGE of that function.

SET TEXTMERGE OFF
TEXT to myvar noshow &&textm
   this is a test   <<datetime()>>
   <<program(-1)>>
   <<myvar>>
   textmerge(myvar) (this line is literal)
   <<doit(myvar)>>   (cause recursion
   END of orig text
endtext
?myvar
?"Now starting textmerge"
?textmerge(myvar)

PROCEDURE doit(myvar)
*  r=i   && cause an error
   if program(-1) > 3
     return "THEEND*********"
   endif
   return textmerge(myvar)

See Also

SET DELIMITERS Command | SET TEXTMERGE Command | SET TEXTMERGE DELIMITERS Command | Creating Character Expressions | TEXT ... ENDTEXT


TIME( ) Function

Returns the current system time in 24-hour, eight-character string (hh:mm:ss) format.

TIME([nExpression])

Return Values

Character

Parameters

nExpression
The time returned includes hundredths of a second if nExpression is included. The numeric expression nExpression can be any value. However, the actual maximum resolution is about 1/18 second. Use SECONDS( ) for greater resolution.

See Also

CTOT( ) | DATE( ) | DATETIME( ) | DTOT( ) | HOUR( ) | SEC( ) | SECONDS( ) | SET SECONDS | SYS(2) - Seconds Since Midnight


TRANSFORM( ) Function

Returns a character string from an expression in a format determined by a format code.

Note Using TRANSFORM( ) with a large negative number that contains a decimal might result in numeric overflow when that number is passed in as a memory variable. You should use the STR( ) function instead with such numbers.
TRANSFORM(eExpression, [cFormatCodes])

Parameters

eExpression
Specifies the character, currency, date, object, or numeric expression to format.
cFormatCodes
Specifies one or more format codes that determine how the expression is formatted. The following table lists the available format codes.
Format codes | Description
@B | Left-justifies numeric data within the display region.
@C | Appends CR to positive currency or numeric values to indicate a credit.
@D | Converts Date and DateTime values to the current SET DATE format.
@E | Converts Date and DateTime values to a BRITISH date format.
@L | Pads numeric data with leading zeroes.
@R The transformation uses a format mask. The mask characters are not stored to the transformed value. Use only with character or numeric data. Mask characters include:

9 or # Represents a character or number.

! Converts lower-case letters to uppercase letters.

Note Visual FoxPro does not display specified mask characters that exceed the converted string length of the passed expression.
@T | Trims leading and trailing spaces from character values.
@X | Appends DB to negative currency or numeric values to indicate a debit.
@Z | If 0, converts currency or numeric values to spaces.
@( Encloses negative currency or numeric values in parentheses.
@^ Converts currency or numeric values to scientific notation.
@0 | Converts numeric or currency values to their hexadecimal equivalents. The numeric or currency value must be positive and less than 4,294,967,296.
@! Converts an entire character string to uppercase.
@$ Adds the current currency symbol specified by SET CURRENCY to currency and numeric values. By default, the symbol is placed immediately before or after the value. However, the currency symbol and its placement (specified with SET CURRENCY), the separator character (specified with SET SEPARATOR) and the decimal character (specified with SET POINT) can all be changed.
X | Specifies the width of character values. For example, if cFormatCodes is 'XX', 2 characters are returned.
Y | Converts logical True (.T.) and False (.F.) values to Y and N, respectively.
! Converts a lowercase character to uppercase in the corresponding position in a character string.
. Specifies the decimal point position in currency and numeric values.
, Separates digits to the left of the decimal point in currency and numeric values.
9 Specifies width of numeric values.

For example, if cFormatCodes is '999.99', the numeric characters are formatted with three characters to the left of the decimal point, and two characters to the right.

Note When specifying cFormatCodes for numeric values, the format code must be at least the size of the value you want to display.

The following example shows the results when the format code is missing, less than, and equal to the size of the value you want to display.

CREATE CURSOR myCursor (col1 n(5,2))
INSERT INTO myCursor VALUES (-555.5)
* No format code and returns **.**
? TRANSFORM(myCursor.col1 )
* A format code 1 less than value returns ***.**
? TRANSFORM(myCursor.col1,'999.99' )
* A format code same size as value returns -556.00
? TRANSFORM(myCursor.col1,'9999.99' )

When the expression value is longer than the width of the numeric field, Visual FoxPro forces the value to fit by performing the following steps:

  • Truncate decimal places and round the remaining decimal portion of the field.
  • If the value does not fit, store the field contents using scientific notation.
  • If the value still does not fit, replace the field contents with asterisks.

If you omit cFormatCodes, Visual FoxPro performs a default transformation on eExpression. The following table describes the transformation performed for each data type eExpression can assume.

Data type | Transformation description
Character | Performs no transformation.
Currency | Transformation is determined by the settings specified in the Regional tab of the Options dialog box.
Date | Performs a DTOC( ) transformation on the date.
DateTime | Performs a TTOC( ) transformation on the date time.
General | Returns "Gen" if the general field contains an object or "gen" if the general field does not contain an object.
Logical | Transforms Logical True (.T.) and False (.F.) values to the character strings ".T." and ".F." respectively.
Memo | Performs no transformation.
Numeric (includes Double, Float, or Integer data types) Removes trailing zeros from the decimal portion of a numeric value.

If the numeric value is a whole number, a decimal point is not included in the transformed value, for example, 4.0 is transformed to 4.

If the numeric value is less than one but greater than negative one, zero is included before the decimal point, for example, .4 is transformed to 0.4.
Object | Returns the character string "(Object)".

Return Values

Character data type. TRANSFORM( ) returns character string from an expression in a format determined by a format code.

Example

STORE 12.34 TO gnPrice
CLEAR
? TRANSFORM(gnPrice, '$$$$.99')  && Displays $12.34
? TRANSFORM(_SCREEN)   && Displays (Object)

See Also

DTOC( ) | TTOC( ) | InputMask Property


TRIM( ) Function

Returns the specified character expression with all trailing blanks removed.

TRIM(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression from which TRIM( ) removes all trailing blanks.

Remarks

TRIM( ) is identical to RTRIM( ).

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
CLEAR
? 'The contact for '+ TRIM(company) + ' is ' + contact

See Also

ALLTRIM( ) | LTRIM( ) | RTRIM( )


TTOC( ) Function

Converts a DateTime expression to a Character value of a specified format.

TTOC(tExpression [, 1 | 2])

Return Values

Character

Parameters

tExpression
Specifies a DateTime expression from which TTOC( ) returns a Character value. If tExpression contains only a time, Visual FoxPro adds the default date of 12/30/1899 to tExpression. If tExpression contains only a date, Visual FoxPro adds the default time of midnight (12:00:00 A.M.) to tExpression.
1
Specifies that TTOC( ) return a Character string in a format suitable for indexing. The character string has a 14 character yyyy:mm:dd:hh:mm:ss format that is not affected by the current settings of SET CENTURY or SET SECONDS.
2
Specifies that TTOC( ) return a Character string consisting of only the time portion of the DateTime expression. The settings of SET SECONDS and SET DATE specify if the seconds portion of the time is included in the character string. Note that if SET DATE is set to LONG or SHORT, the format of the character string is determined by the format of the Control Panel time setting.

Example

The following example creates a Datetime type variable named gtDtime. TYPE( ) displays T, indicating the variable is a Datetime type. TTOC( ) is used to convert the variable to a character type, and TYPE( ) now displays C, indicating the variable is a character type after the conversion.

STORE DATETIME( ) TO gtDtime  && Creates a Datetime type memory variable
CLEAR
? "gtDtime is type: "
?? TYPE('gtDtime')  && Displays T, Datetime type value

gtDtime = TTOC(gtDtime)     &&  Converts gtDtime to a character value
? "gtDtime is now type: "
?? TYPE('gtDtime')  && Displays C, character type value

See Also

DATE( ) | DATETIME( ) | HOUR( ) | MINUTE( ) | SEC( ) | SECONDS( ) | SET CENTURY | SET DATE, SET SECONDS | TIME( ) | TTOD( )


TTOD( ) Function

Returns a Date value from a DateTime expression.

TTOD(tExpression)

Return Values

Date

Parameters

tExpression
Specifies a date and time expression from which TTOD( ) returns a Date value. tExpression must evaluate to a valid DateTime. If tExpression contains only a time, Visual FoxPro adds the default date of 12/30/1899 to tExpression and returns this default date.

Example

The following example creates a Datetime type variable named gtDtime. TYPE( ) displays T, indicating the variable is a Datetime type. TTOD( ) is used to convert the variable to a date type, and TYPE( ) now displays D, indicating the variable is a date type after the conversion.

STORE DATETIME( ) TO gtDtime  && Creates a Datetime type memory variable
CLEAR
? "gtDtime is type: "
?? TYPE('gtDtime')  && Displays T, Datetime type value

gtDtime = TTOD(gtDtime)     &&  Converts gtDtime to a date value
? "gtDtime is now type: "
?? TYPE('gtDtime')  && Displays D, character type value

See Also

DATE( ) | DATETIME( ) | HOUR( ) | MINUTE( ) | SEC( ) | SECONDS( ) | SET CENTURY | SET SECONDS | TIME( ) | TTOC( )


TXNLEVEL( ) Function

Returns a numeric value indicating the current transaction level.

TXNLEVEL( )

Return Values

Numeric

Remarks

Use BEGIN TRANSACTION to create a transaction. Transactions are nested by issuing BEGIN TRANSACTION when another transaction is in progress. Transactions can be nested in this manner to five levels. Use TXNLEVEL( ) to determine the current transaction level.

TXNLEVEL( ) returns a value from 0 to 5. TXNLEVEL( ) returns 0 if a transaction is not in progress.

Example

In the following example, the customer table in the testdata database is opened. BEGIN TRANSACTION is issued to start a transaction, and TXNLEVEL( ) is used to display the transaction level (1). BEGIN TRANSACTION is issued again to start a nested transaction, and TXNLEVEL( ) displays 2 for the current transaction level.

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE Customer     && Open customer table
CLEAR

BEGIN TRANSACTION
   tLevel = ALLTRIM(STR(TXNLEVEL()))
   =MESSAGEBOX("Current Transaction: " + tLevel, 0, "Trasaction Level")
   BEGIN TRANSACTION
      tLevel = ALLTRIM(STR(TXNLEVEL()))
      =MESSAGEBOX("Current Transaction: " + tLevel, 0, ;
         "Trasaction Level")
   END TRANSACTION
END TRANSACTION

See Also

BEGIN TRANSACTION | END TRANSACTION | ROLLBACK


TXTWIDTH( ) Function

Returns the length of a character expression with respect to the average character width for a font.

TXTWIDTH(cExpression [, cFontName, nFontSize [, cFontStyle]])

Return Values

Numeric

Parameters

cExpression
Specifies a character expression for which TXTWIDTH( ) returns the length. If you include only cExpression, the length of the character expression is returned for the current font for the main Visual FoxPro window or the active output window. A non-proportional font always returns a value equal to the number of characters in cExpression.

Include the optional arguments cFontName, nFontSize and cFontStyle to determine the length of a character expression with a specific font, font point size, or font style.

cFontName
Specifies the name of the font. Include cFontName to return the length of a character expression with a specific font.
nFontSize
Specifies a number that corresponds to the point size of the font. Include nFontSize to return the length of a character expression with a specific point size.
cFontStyle
Specifies a special font style for the character expression. cFontStyle is a font style code specified by a character or a set of characters. The Normal font style is used if cFontStyle isn't included. Here are the characters for each font style:
Character | Font Style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
- Strikeout
T | Transparent
U | Underline

You can include more than one character to specify a combination of font styles. For example, BI specifies a Bold Italic font style.

The following command displays a message in a Courier normal 24-point font, centered horizontally in the main Visual FoxPro window:

@ 25,(WCOLS( )-TXTWIDTH('Hello!','Courier ',24)* ;
   FONTMETRIC(6,'Courier ',24)/FONTMETRIC(6))/2  ;
   SAY 'Hello!' FONT 'Courier ',24

Remarks

TXTWIDTH( ) returns the number of characters a character expression cExpression occupies, based on the average character width of a specified font (the average character width of a font is called a foxel). Use FONTMETRIC(6) to determine the average character width of a font.

If you don't include a font in TXTWIDTH( ), the value returned by TXTWIDTH( ) is determined by the current font for the main Visual FoxPro window, as long as output is directed to the main Visual FoxPro window when TXTWIDTH( ) is issued. If output is being directed to a user-defined window, the value returned is determined by the window's current font.

See Also

FONTMETRIC( ) | GETFONT( ) | LEN( ) | SYSMETRIC( ) | WFONT( )


TYPE( ) Function

Evaluates an expression and returns the data type of its contents.

TYPE(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the expression to be evaluated, which can be a variable, field, memo field, or any other expression. The expression must be passed as a character string; place quotation marks around the names of memory variables, fields, and so on. If you do not place quotation marks around the expression, the TYPE( ) function evaluates the contents of the string. If the contents cannot be evaluated as a valid FoxPro expression, TYPE() returns "U" (undefined expression).

Remarks

The following table lists the character values TYPE( ) returns and their corresponding data types:

Data type | Character returned
Character | C
Numeric (also float, double, and integer) | N
Currency | Y
Date | D
DateTime | T
Logical | L
Memo | M
Object | O
General | G
Screen (created with SAVE SCREEN) | S
Undefined type of expression | U

If you pass an array as a parameter to TYPE( ), then the data type returned corresponds to the first element in the array. If you want to check the data type for a specific array element, then you must specify that element in the parameter. For example:

? TYPE("myarray[3]")

You can also use the TYPE( ) function to check if a memory variable is an array. For example:

? TYPE("myarray[1]")#"U"

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
USE customer  && Opens Customer table
nTest = 1.01
cTest = "String"

CLEAR
? TYPE('customer.contact')  && Displays C
? TYPE('(12 * 3) + 4')  && Displays N
? TYPE('DATE( )')  && Displays D
? TYPE('.F. OR .T.')  && Displays L
? TYPE('ANSWER=42')  && Displays U
? TYPE('$19.99')  && Displays Y
? TYPE('nTest')  && Displays N
? TYPE('cTest')  && Displays C

See Also

EVALUATE( ) | SAVE SCREEN | VARTYPE( )


UNBINDEVENTS() Function

You can use UNBINDEVENTS() to unbind, or detach, an event that was originally bound to a Visual FoxPro object using BINDEVENT(). To detach events from Component Object Model (COM) objects, use the EVENTHANDLER() function.

UNBINDEVENTS( oEventSource, cEvent, oEventHandler, cDelegate )

-or-

UNBINDEVENTS( oEventObject )

The following table describes the ways you can use UNBINDEVENTS().

Syntax Action
UNBINDEVENTS( oEventSource, cEvent, oEventHandler, cDelegate )
 Unbinds a specific event from an event handler.
UNBINDEVENTS( oEventObject )
 Unbinds all events associated with this object. This includes events that are bound to it as an event source and its delegate methods that serve as event handlers.

Parameters

oEventSource
Specifies the event source, which must be a valid Visual FoxPro object.
oEventObject
Specifies an object reference, which can be used as the event source or event handler.
cEvent
Specifies the name of the event, method, or property you want to unbind.
oEventHandler
Specifies the object that is handling the event.
cDelegate
Specifies the delegate method handling the event for oEventHandler.

Return Values

Numeric data type. UNBINDEVENTS() returns the number of events that are unbound if unbinding succeeds. UNBINDEVENTS() returns a value of 0 if no events exist for unbinding. Visual FoxPro generates an error if UNBINDEVENTS() fails to unbind events that are available for unbinding.

Remarks

If an event is occurring, and UNBINDEVENTS() or the delegate method handling the event is called, the event and its delegate method finish running before UNBINDEVENTS() unbinds the event.

You can call the AEVENTS() function retrieve information about all the events and delegate methods attached to a particular object.

Example

The following example shows how to undo a BINDEVENTS( ) call that keeps the Class Browser positioned to the right side of the Visual FoxPro desktop, regardless of how the desktop is resized. UNBINDEVENTS( ) detaches the Resize event of the _SCREEN system variable from the object, oHandler:

PUBLIC oHandler
oHandler=NEWOBJECT("myhandler")
DO (_browser)
BINDEVENT(_SCREEN,"Resize",oHandler,"myresize")
UNBINDEVENTS(_SCREEN,"Resize",oHandler,"myresize")

DEFINE CLASS myhandler AS Session
   PROCEDURE myresize
   _obrowser.left = _SCREEN.Width - _obrowser.width
   RETURN
ENDDEFINE

See Also

Functions | Event Binding for Visual FoxPro Objects | BINDEVENT() Function | EVENTHANDLER( ) Function | RAISEEVENT() Function | AEVENTS() Function


UNIQUE( ) Function

Included for compatibility with dBASE.


UPDATED( ) Function

Included for backward compatibility. Use the InteractiveChange or ProgrammaticChange events instead.


UPPER( ) Function

Returns the specified character expression in uppercase.

UPPER(cExpression)

Return Values

Character

Parameters

cExpression
Specifies the character expression UPPER( ) converts to uppercase.

Remarks

Each lowercase letter (a – z) in the character expression is converted to uppercase (A – Z) in the returned string. This is true for high-ASCII characters as well, even if the current font does not display them as lowercase accented characters.

Example

CLEAR
? UPPER('abcdefgh')  && Displays ABCDEFGH

See Also

ISLOWER( ) | ISUPPER( ) | LOWER( )


USED( ) Function

Determines if an alias is in use or a table is open in a specific work area.

USED([nWorkArea | cTableAlias])

Return Values

Logical

Parameters

nWorkArea | cTableAlias
Specifies a table's work area or alias. USED( ) returns a logical true (.T.) if a table is opened in the work area you specify with nWorkArea; otherwise a logical false (.F.) is returned. USED( ) returns a logical true (.T.) if an alias is in use with the alias you specify with cTableAlias; otherwise false (.F.) is returned.

If you omit nWorkArea and cTableAlias, USED( ) returns a logical true (.T.) if a table is open in the currently selected work; otherwise false (.F.) is returned.

Remarks

USED( ) can determine if an alias is in use or if a table is open in a specific work area.

Example

CLOSE DATABASES
OPEN DATABASE (HOME(2) + 'Data\testdata')
SELECT A
USE customer  && Opens Customer table
SELECT B
USE orders  && Opens Orders table
SELECT C
USE employee  && Opens Employee table
? USED('A')  && Displays .T.
? USED('B')  && Displays .T.
? USED(4)  && Displays .F.

See Also

ALIAS( ) | SELECT( ) | AUSED( )


VAL( ) Function

Returns a numeric or currency value from a character expression composed of numbers. You can use VAL( ) to convert the character strings returned by the Visual FoxPro SYS( ) functions to numeric values.

VAL(cExpression)

Parameters

cExpression
Specifies a character expression composed of up to 16 numbers. Rounding occurs if more than 16 numbers are included in cExpression.

If the first character of cExpression is a dollar sign ($),VAL( ) returns a currency value. In all other situations VAL( ) returns a numeric value.

Return Values

Numeric or Currency data type. VAL( ) returns the numbers in the character expression from left to right until a non-numeric character is encountered. Leading blanks are ignored. VAL( ) returns 0 if the first character of the character expression is not a number, a dollar sign ($), a plus sign (+), or minus sign (-).

Example

CLEAR
STORE '12' TO A
STORE '13' TO B
? VAL(A) + VAL(B)  && Displays 25.00
STORE '1.25E3' TO C
? 2 * VAL(C)  && Displays 2500.00

See Also

SET DECIMALS | STR( ) | SYS( ) Functions Overview


VARREAD( ) Function

Included for backward compatibility in Visual FoxPro. Use the ControlSource or Name properties instead.


VARTYPE( ) Function

Returns the data type of an expression.

VARTYPE(eExpression [, lNullDataType])

Return Values

Character

Parameters

eExpression
Specifies the expression for which the data type is returned. VARTYPE( ) returns a single character indicating the data type of the expression. The following table lists the characters that VARTYPE( ) returns for each data type:
Character returned | Data type
C | Character or Memo
N | Numeric, Integer, Float, or Double
Y | Currency
L | Logical
O | Object
G | General
D | Date
T | DateTime
X | Null
U | Unknown
Note If eExpression is an array, the first element in the array is evaluated.
lNullDataType
Specifies if VARTYPE( ) returns the data type when eExpression contains the null value. If lNullDataType is true (.T.), VARTYPE( ) returns the data type of eExpression. If lNullDataType is false (.F.) or omitted, VARTYPE( ) returns 'X', indicating that eExpression contains the null value.

Remarks

VARTYPE( ) is similar to the TYPE( ) function, but VARTYPE( ) is faster and does not require quotation marks to enclose the expression for which the data type is returned.

VARTYPE( ) returns "U" if you specify a variable that doesn't exist.

See Also

EVALUATE( ) | TYPE( ) | Data Types


VERSION( ) Function

Returns information about the Visual FoxPro version you are using.

VERSION(nExpression)

Return Values

Character, Numeric

Parameters

nExpression
Specifies that VERSION( ) returns additional information about Visual FoxPro. If you omit nExpression, VERSION( ) returns the Visual FoxPro version number.

The following table lists values for nExpression and the additional Visual FoxPro information returned.

nExpression | Additional Visual FoxPro information returned
1 | Visual FoxPro date and serial number.
2 | Visual FoxPro version type:0 - Run time version1 - Standard Edition (earlier versions)2 - Professional Edition (earlier versions)
3 Localized Visual FoxPro language. The following two character values indicate the language for which Visual FoxPro is localized:
00 - English
07 - Russian
33 - French
34 - Spanish
39 - Italian
42 - Czech
48 - Polish
49 - German
55 - Portuguese
82 - Korean
86 - Simplified Chinese
88 - Traditional Chinese
4 The Visual FoxPro version number in a standard, easily parsed format.

For versions prior to Visual FoxPro 8 the standard format is "MM.mm.0000.DDDD" where MM is the major release number, mm is the incremental minor revision number, 0000 is a fixed placeholder, and DDDD is the four digit product date for the day the version was created.

The product date, DDDD, is calculated in the following formula: 8000 + number of days since the beginning of 1998. For example, 8397 corresponds to February 1, 1999.

However, the format for Visual FoxPro 8 is "MM.mm.0000.NNDD" where MM is the major release number, mm is the incremental minor revision number, 0000 is a fixed placeholder, NN is the number of months after December 2000, and DD is the day number of the date the version was created.
5 | The Visual FoxPro release version in the format Mmm where M is the major release number and mm is the incremental minor revision number. For example, VERSION(5) returns 700 in Visual FoxPro 7.

Remarks

Use VERSION( ) to conditionally execute version-specific portions of code.

VERSION( ), VERSION(1), VERSION(3), and VERSION(4) return character strings; VERSION(2) and VERSION(5) return numeric values.

Example

CLEAR
? VERSION( )
? VERSION(1)
? VERSION(2)
? VERSION(3)
? VERSION(4)
? VERSION(5)

See Also

GETCP( ) | GETENV( ) | OS( ) | AGETFILEVERSION


WBORDER( ) Function

Determines whether the active or specified window has a border.

WBORDER([WindowName])

Return Values

Logical

Parameters

WindowName
Specifies the name of the window for which WBORDER( ) returns a logical value.

WBORDER( ) returns a logical value for the active output window if you omit a window name.

Remarks

WBORDER( ) returns true (.T.) if the specified window has a border; otherwise WBORDER( ) returns false (.F.). By default, windows have borders. Include the NONE clause in DEFINE WINDOW to create a window without a border.

See Also

ACTIVATE WINDOW | DEFINE WINDOW | SET BORDER


WCHILD( ) Function

Returns either the number of child windows in a parent window or the names of the child windows in the order in which they are stacked in the parent window.

WCHILD([WindowName] [nChildWindow])

Return Values

Character or Numeric

Parameters

WindowName
Specifies a window other than the active output window for which WCHILD( ) returns the number of child windows. The number of child windows in the specified window is returned if you include just a window name without the numeric expression nChildWindow.

If you include both WindowName and nChildWindow, WCHILD( ) returns the names of the child windows in the specified window. If you include both WindowName and nChildWindow, separate WindowName and nChildWindow with a comma.

You can also include the empty string in WindowName to specify the main Visual FoxPro window.

nChildWindow
Specifies a numeric expression included to return the names of child windows in the active output window when you omit WindowName.

The numeric expression nChildWindow can be 0 or any positive value. The name of the child window at the bottom of the stack of child windows in the current output window is returned if nChildWindow is 0.

If nChildWindow is a positive number, WCHILD( ) returns the name of the next child window in the window stack. The name of next child window in the stack is returned if you issue WCHILD( ) again with a positive number, and so on. The empty string is returned if WCHILD( ) is called more times than the number of child windows in the parent window. For more information on window stacking, see ACTIVATE WINDOW.

Note In Visual FoxPro for Windows, if the main Visual FoxPro window is active, all windows are children of the main Visual FoxPro window. In Visual FoxPro, toolbars that are not docked in the border of the main Visual FoxPro window are children of the main Visual FoxPro window. Issuing a series of WCHILD( ) functions with positive numbers returns the names of the active windows and toolbars.

If you include both WindowName and nChildWindow, separate WindowName and nChildWindow with a comma.

Remarks

You can create a window (the parent window) and place other windows (child windows) inside. Including the IN or IN WINDOW clause in DEFINE WINDOW creates a child window inside the parent window. A child window created and activated inside a parent window cannot be moved outside the parent window. If the parent window is moved, the child window moves with it.

The number of child windows in the active output window is returned if you issue WCHILD( ) without any arguments.

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WPARENT( )


WCOLS( ) Function

Returns the number of columns within the active or specified window.

WCOLS([WindowName])

Return Values

Numeric

Parameters

WindowName
Specifies the window for which WCOLS( ) returns the number of columns. In Visual FoxPro, you can also specify the name of a toolbar. If you do not specify a window, the number of columns in the active output window is returned. If no window is active, WCOLS( ) returns the number of columns in the main Visual FoxPro window.

You can specify the name of a system window (the Command window, the Data Session window, a Browse window, and so on) in WCOLS( ) if the system window has been activated and is visible or hidden. In Visual FoxPro, you can specify the name of a toolbar (the Standard toolbar, the Color Palette toolbar, and so on) in WCOLS( ) if the toolbar has been activated and is visible or hidden. If you specify the name of a system window or toolbar that has not been activated, Visual FoxPro generates an error message. The Debug window is an exception. Once the Debug window has been opened, its name can be included in WCOLS( ) if it is visible, hidden or closed.

You can also include the empty string as the window name to return the number of columns in the main Visual FoxPro window.

The empty string can be used to specify the main Visual FoxPro window in functions such as WLCOL( ), WLROW( ), and WROWS( ), which return window locations or sizes.

Remarks

In Visual FoxPro, the value returned by WCOLS( ) depends on the font specified for the window. Many fonts can be displayed in a wide variety of sizes, and some are proportionally spaced. A column corresponds to the average width of a letter in the current font. For more information, see the Fonts Overview topic.

Example

The following example centers a short output message in the last row of a window of unknown size.

CLEAR
DO SendMesg WITH 'Message', WCOLS( ), WROWS( ) –1

*** SendMesg ***

PROCEDURE SendMesg
PARAMETERS gcMsg, gnCol, gnRow
STORE (gnCol – LEN(gcMsg))/2 TO gnCol
@ gnRow, gnCol SAY gcMsg
RETURN

See Also

SCOLS( ) | SROWS( ) | WLCOL( ) | WLROW( ) | WROWS( ) | Fonts Overview


WDOCKABLE( ) Function

Returns the dockable state of the specified window

WDOCKABLE(cWindowName [, lEnable])

Parameters

cWindowName
Specifies the name of the window to evaluate.
lEnable
Specifies the dockable state for the window specified with the cWindowName parameter. If the specified window does not support docking, then Visual FoxPro ignores the lEnable parameter.

Return Values

Logical data type. Returns the current dockable state for the specified window.

Remarks

The WDOCKABLE( ) function always returns False (.F.) for undockable windows. Use the WDOCKABLE( ) function on Visual FoxPro windows that support docking. For a list of dockable Visual FoxPro windows, see Docking Windows.

See Also

Windows


WEEK( ) Function

Returns a number representing the week of the year from a Date or DateTime expression.

WEEK(dExpression | tExpression [, nFirstWeek] [, nFirstDayOfWeek])

Return Values

Numeric

Parameters

dExpression | tExpression
Specifies the Date or DateTime expression for which WEEK( ) returns the week of the year.

If you omit the optional nFirstWeek and nFirstDayOfWeek arguments, WEEK( ) uses Sunday as the first day of the week.

nFirstWeek
Specifies the requirements for the first week of the year. nFirstWeek may be one of the following values.
nFirstWeek | Description
0 | WEEK( ) returns whatever week is currently selected in the First Week of Year list box on the Regional tab in the Options dialog box.
1 | First week contains January 1st. This is the default when you omit nFirstWeek.
2 | The larger half (four days) of the first week is in the current year.
3 | First week has seven days.
nFirstDayOfWeek
Specifies the first day of the week. nFirstDayOfWeek may be one of the following values.
nFirstDayOfWeek | Description
0 | WEEK( ) returns whatever day is currently selected in the Week Starts on list box on the Regional tab in the Options dialog box.
1 | Sunday. This is the default when you omit nFirstDayOfWeek, and is the first day of the week used in earlier FoxPro versions.
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday

Remarks

WEEK( ) returns a number from 1 to 53 that represents the week of the year. For example, WEEK( ) returns 1 for the first week of the year, 2 for the second week of the year, and so on. Note that a week can be split between years — the first week of the year can be in the current year and the previous year.

Example

The following example displays the week of the year for today's date and for a specific date.

CLEAR
? WEEK(DATE( ))
? WEEK({^1998-02-16})  && Displays 8

See Also

CDOW( ) | DAY( ) | DOW( ) | SET FDOW | SET FWEEK | SYS( ) Functions Overview


WEXIST( ) Function

Determines whether the specified user-defined window exists.

WEXIST(WindowName)

Return Values

Logical

Parameters

WindowName
Specifies the name of the user-defined window.

You can also specify the name of a Visual FoxPro system window (the Command window, the Data Session window, a Browse window, and so on), and in Visual FoxPro, the name of a toolbar. WEXIST( ) returns true (.T.) if the system window or toolbar you specify is visible or hidden. WEXIST( ) returns false (.F.) if the specified system window or toolbar is closed.

Two exceptions are the Command and Debug windows. Including the Command window's name in WEXIST( ) always returns a true value. If the Debug window has been opened, WEXIST( ) returns true, even if the Debug window is closed.

Remarks

WEXIST( ) returns true (.T.) if the user-defined window you specify has been created with DEFINE WINDOW; otherwise WEXIST( ) returns false (.F.). The specified window does not have to be active or visible for WEXIST( ) to return true (.T.), but it must exist.

Example

DEFINE WINDOW wScreen1 FROM 10,10 TO 20,69
DEFINE WINDOW wScreen2 FROM 1,0 TO 19,79
CLEAR

? WEXIST('wScreen1')  && Displays .T.
STORE 'wScreen2' TO gcWinName
? WEXIST('win_name')  && Displays .F.
? WEXIST(gcWinName)  && Displays .T.
RELEASE WINDOWS wScreen1, wScreen2

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WONTOP( ) | WOUTPUT( ) | WVISIBLE( )


WFONT( ) Function

Returns the name, size, or style of the current font for a window in Visual FoxPro for Windows.

WFONT(nFontAttribute [, WindowName])

Return Values

Character and Numeric

Parameters

nFontAttribute
Specifies the font attribute you want to return.

If nFontAttribute is 1, WFONT( ) returns the name of the current font for the active or specified window.

If nFontAttribute is 2, WFONT( ) returns the font size.

If nFontAttribute is 3, WFONT( ) returns a code that identifies the font style.

The font style code is a character or set of characters that correspond to the current font style. For example, the current font style is Bold Italic if WFONT(3) returns BI.

The following table lists the codes for each font style:

Character | Font Style
B | Bold
I | Italic
N | Normal
O | Outline
Q | Opaque
S | Shadow
– StrikeThru
T | Transparent
U | Underline
WindowName
Specifies the name of the window for which you want to determine the current font, font size, or font style. In Visual FoxPro, you can also include the name of a toolbar. Include the empty string to return the current font, font size, or font style for the main Visual FoxPro window.

WindowName can be the name of a user-defined window created with DEFINE WINDOW or a text- or memo-editing window.

You can also include the name of a system window (View, Trace, Debug, and so on). WFONT( ) can return font attributes only for a system window that has been opened and is currently visible or hidden. If the system window you specify is closed, Visual FoxPro generates an error message.

WFONT( ) returns the current font, font size or font style for the active output window if you omit WindowName.

Example

The following example creates a user-defined window called wFontChar. The window is activated and its font characteristics are displayed in the window. The font characteristics are then displayed for the main Visual FoxPro window.

CLEAR
DEFINE WINDOW wFontChar ;
   FROM 1,1 TO 3,35 ;
   FONT 'MS SANS SERIF',8 ;
   STYLE 'BI'  && Define window with font and style
ACTIVATE WINDOW wFontChar
? WFONT(1), WFONT(2), WFONT(3)  && wFontChar window
ACTIVATE SCREEN
?
?
?
? 'Font characteristics for the window wFontChar'
?
?
? WFONT(1,''), WFONT(2,''), WFONT(3,'')  && Main Visual FoxPro window
?
? 'Font characteristics for the main Visual FoxPro window'
WAIT WINDOW
RELEASE WINDOW wFontChar
CLEAR

See Also

FONTMETRIC( ) | GETFONT( ) | SYSMETRIC( ) | TXTWIDTH( )


WLAST( ) Function

Returns the name of the window that was active prior to the current window or determines whether the specified window was active prior to the current window.

WLAST([WindowName])

Return Values

Character or Logical

Parameters

WindowName
Specifies a window that WLAST( ) evaluates. In Visual FoxPro, you can also specify the name of a toolbar. WLAST( ) returns true (.T.) if the specified window was active prior to the current window; otherwise false (.F.) is returned. False (.F.) is also returned if the window you specify doesn't exist.

The name of the window that was active prior to the current window is returned if you omit WindowName.

Remarks

WLAST( ) returns the empty string if the window that was active prior to the current window is the Debug, Trace, or Command window. Program execution isn't affected by bringing these windows forward when you are debugging a program that uses WLAST( ).

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WEXIST( ) | WONTOP( ) | WOUTPUT( ) | WVISIBLE( )


WLCOL( ) Function

Returns the column coordinate of the upper-left corner of the active or specified window.

WLCOL([WindowName])

Return Values

Numeric

Parameters

WindowName
Specifies the window for which WLCOL( ) returns the column coordinate. In Visual FoxPro, you can also specify the name of a toolbar. If you omit WindowName, WLCOLS( ) returns the column coordinate of the active output window. You can also use the empty string for WindowName to specify the main Visual FoxPro window.

In Visual FoxPro, if no window is active, WLCOLS( ) returns the column coordinate of the main Visual FoxPro window relative to the Windows desktop.

If a system window (the Command window, the Data Session window, a Browse window, and so on) has been opened and is visible or hidden (its name appears on the Window menu), you can include its name in WLCOL( ). If you specify the name of a system window that is closed, Visual FoxPro generates an error message. The Debug window is an exception. Once the Debug window has been opened, its name can be included in WLCOL( ) if it is visible, hidden, or closed.

Remarks

The value returned by WLCOL( ) depends on the current video display mode, and is relative to the main Visual FoxPro window. The display mode can be changed with SET DISPLAY.

Windows can be positioned outside the main Visual FoxPro window. If the specified window is to the left of the main Visual FoxPro window, WCOL( ) returns a negative value. If the window's left border is to the right of the main Visual FoxPro window, WCOL( ) returns a positive value greater than the width of the main Visual FoxPro window.

See Also

SET DISPLAY | WCOLS( ) | WLROW( ) | WROWS( )


WLROW( ) Function

Returns the row coordinate of the upper-left corner of the active or specified window.

WLROW([WindowName])

Return Values

Numeric

Parameters

WindowName
Specifies the window for which WLROW( ) returns the row coordinate. In Visual FoxPro, you can also specify the name of a toolbar. If you omit WindowName, WLROW( ) returns the row coordinate of the active output window. You can also use the empty string for WindowName to specify the main Visual FoxPro window.

In Visual FoxPro, if no window is active, WLROW( ) returns the row coordinate of the main Visual FoxPro window relative to the Windows desktop.

If a system window (the Command window, the Data Session window, a Browse window, and so on) has been opened and is visible or hidden (its name appears on the Window menu), you can include its name in WLROW( ). If you specify the name of a system window that is closed, Visual FoxPro generates an error message. The Debug window is an exception. Once the Debug window has been opened, its name can be included in WLROW( ) if it is visible, hidden, or closed.

Remarks

The value returned by WLROW( ) depends on the current video display mode, and the row coordinate is relative to the main Visual FoxPro window. The display mode can be changed with SET DISPLAY.

Windows can be positioned off the main Visual FoxPro window. If the top of the window is above the main Visual FoxPro window, WLROW( ) returns a negative value. If the top of the window is below the bottom of the main Visual FoxPro window, WLROW( ) returns a positive value greater than the height of the main Visual FoxPro window.

See Also

SET DISPLAY | WCOLS( ) | WLCOL( ) | WROWS( )


WMAXIMUM( ) Function

Determines whether the active or specified window is maximized.

WMAXIMUM([WindowName])

Parameters

WindowName
Specifies the name of the window WMAXIMUM( ) evaluates. You can specify the name of a Visual FoxPro system window (the Command window, the Data Session window, a Browse window, and so on).

If you omit WindowName, WMAXIMUM( ) returns a logical value for the active window. You can also use the empty string for WindowName to specify the main Visual FoxPro window.

Remarks

Windows can be enlarged to fill the window that contains them. In Visual FoxPro for Windows, the default container window is the main window.

A user-defined window created with DEFINE WINDOW can be maximized only if the ZOOM keyword is included in its definition.

WMAXIMUM( ) returns true (.T.) if the current or specified window is maximized; otherwise WMAXIMUM( ) returns false (.F.). In Visual FoxPro, you can include the name of a toolbar. However, WMAXIMUM( ) always returns false (.F.) for a toolbar because toolbars cannot be maximized.

See Also

DEFINE WINDOW | WMINIMUM( ) | ZOOM WINDOW


WMINIMUM( ) Function

Determines whether the active or specified window is minimized.

WMINIMUM([WindowName])

Return Values

Logical

Parameters

WindowName
Specifies the name of the window WMINIMUM( ) evaluates. You can specify the name of a Visual FoxPro system window (the Command window, the Data Session window, a Browse window, and so on).

If you omit WindowName, WMINIMUM( ) returns a logical value for the active window. You can also include the empty string in WindowName to specify the main Visual FoxPro window.

Remarks

In Visual FoxPro for Windows, windows can be reduced to an icon.

A user-defined window created with DEFINE WINDOW can be minimized only if the MINIMIZE keyword is included in its definition.

WMINIMUM( ) returns true (.T.) if the current or specified window is minimized; otherwise it returns false (.F.). In Visual FoxPro, you can include the name of a toolbar. However, WMINIMUM( ) always returns false (.F.) for a toolbar because toolbars cannot be minimized.

See Also

DEFINE WINDOW | WMAXIMUM( ) | ZOOM WINDOW


WONTOP( ) Function

Determines whether the active or specified window is in front of all other windows.

WONTOP([WindowName])

Return Values

Character or Logical

Parameters

WindowName
Specifies the name of the window WONTOP( ) evaluates. You can specify the name of a user-defined window created with DEFINE WINDOW or a system window (the Command window, the Data Session window, a Browse window, and so on). If you omit WindowName, WONTOP( ) returns the name of the "frontmost" or active window. You can also include the empty string in WindowName to specify the main Visual FoxPro window.

If the Debug, Trace, or Command window is active and you don't specify a window name, WONTOP( ) returns the name of the window most recently in front. When you are debugging a program that uses WONTOP( ), program execution isn't affected by bringing these windows forward.

Remarks

WONTOP( ) returns true (.T.) if the specified window is active. It returns false (.F.) if the window isn't active or doesn't exist.

Historically in prior versions of Visual FoxPro, the Data Session window has always been referred to as the View window. Additionally, language used to control this window, such as HIDE WINDOW, ACTIVATE WINDOW, WONTOP( ), also refers to this window as the View window. Visual FoxPro continues to refer to the View window for the WONTOP( ) function.

Example

The following example uses WONTOP( ) to display the name of the active window. Before you run this program, open some windows (Browse windows, the Data Session window, and so on), then run the example.

IF NOT EMPTY(WONTOP( ))
   WAIT WINDOW 'Frontmost window: ' + WONTOP( )
ELSE
   WAIT WINDOW 'No windows are open'
ENDIF

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WEXIST( ) | WOUTPUT( ) | WVISIBLE( )


WOUTPUT( ) Function

Determines whether output is being directed to the active or specified window.

WOUTPUT([WindowName])

Return Values

Logical and Character

Parameters

WindowName
Specifies the window WOUTPUT( ) evaluates for output. Output cannot be directed to a system window or toolbar. If you omit WindowName, WOUTPUT( ) returns the name of the window to which output is currently directed. You can also include the empty string in WindowName to specify the main Visual FoxPro window.

WOUTPUT( ) returns the empty string if output is being directed to the main Visual FoxPro window.

Remarks

WOUTPUT( ) returns true (.T.) if the specified user-defined window is the active output window. WOUTPUT( ) returns false (.F.) if the window you specify doesn't exist or is a system window. The last user-defined window activated with ACTIVATE WINDOW is the active output window.

Example

In the following example, a window is created and activated. WOUTPUT( ) is used to display the name of this active output window. The window is closed and removed from memory. If another window is active, its name is displayed. If another window isn't active, a message is displayed indicating that output is directed to the main Visual FoxPro window.

DEFINE WINDOW wOutput1 FROM 2,2 TO 12,32 TITLE 'Output Window'
ACTIVATE WINDOW wOutput1
WAIT WINDOW 'wOutput1 window: ' + WOUTPUT( )
RELEASE WINDOW wOutput1
IF EMPTY(WOUTPUT( ))
   WAIT WINDOW 'Output being directed to the main Visual FoxPro window'
ELSE
   WAIT WINDOW 'Output window: ' + WOUTPUT( )
ENDIF

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WEXIST( ) | WONTOP( ) | WVISIBLE( )


WPARENT( ) Function

Returns the name of the parent window of the active or specified window.

WPARENT([WindowName])

Return Values

Character

Parameters

WindowName
Specifies a window whose parent window name WPARENT( ) returns. WPARENT( ) returns the empty string if the specified window doesn't have a parent window. If you omit WindowName, WPARENT( ) returns the name of the parent window of the active output window. WPARENT( ) returns the empty string if the active output window doesn't have a parent window.

Remarks

You can use DEFINE WINDOW to create a window and place it in a parent window. The child window becomes integrated with its parent window. For example, a child window defined and activated inside a parent window can't be moved outside the parent window. If the parent window is moved, the child window moves with it.

Example

The following example defines a parent and child window. It then uses WPARENT( ) to identify which window is the parent.

CLEAR ALL
CLEAR
DEFINE WINDOW wParent ;
   FROM 1,1 TO 20,20 ;
   TITLE 'wParent'     && Parent window
ACTIVATE WINDOW wParent
DEFINE WINDOW wChild ;
   FROM 1,1 TO 10,10 ;
   TITLE 'wChild' ;
   IN WINDOW wParent  && Child window
ACTIVATE WINDOW wChild
WAIT WINDOW 'The parent window is ' + WPARENT( )
RELEASE WINDOW wParent, wChild

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WCHILD( )


WREAD( ) Function

Included for backward compatibility. Use the Form Designer instead.


WROWS( ) Function

Returns the number of rows within the active or specified window.

WROWS([WindowName])

Return Values

Numeric

Parameters

WindowName
Specifies the window for which WROWS( ) returns the number of rows. In Visual FoxPro, you can also specify the name of a toolbar.

In Visual FoxPro, the value returned by WROWS( ) depends on the font specified for the window. Most fonts can be displayed in a wide variety of sizes, and some are proportionally spaced. A row corresponds to the height of the current font. For more information, see the Fonts Overview topic.

You can specify the name of a system window (the Command window, the Data Session window, a Browse window, and so on) in WROWS( ) if the system window has been opened and is visible or hidden. If you specify the name of a system window that is closed, FoxPro generates an error message. The Debug window is an exception. Once the Debug window has been opened, its name can be included in WROWS( ) if it is visible, hidden, or closed.

You can also include the empty string in WindowName to return the number of rows in the main Visual FoxPro window.

The empty string can be used to specify the main Visual FoxPro window in functions such as WLCOL( ), WLROW( ), and WCOLS( ), which return window locations or sizes.

Remarks

If you don't specify a window name, the number of rows in the active output window is returned. If no window is active, the number of rows in the main Visual FoxPro window is returned.

See Also

SCOLS( ) | SROWS( ) | WCOLS( ) | WLCOL( ) | WLROW( ) | Fonts Overview


WTITLE( ) Function

Returns the title assigned to the active or specified window.

WTITLE([WindowName])

Return Values

Character

Parameters

WindowName
Specifies a window whose title WTITLE( ) returns. The title assigned to the window with the TITLE clause is returned if you include the name of a user-defined window created with DEFINE WINDOW.

When you issue BROWSE WINDOW to open a Browse window in a user-defined window, WTITLE( ) returns the title of the user-defined window if the Browse window doesn't have a title. WTITLE( ) returns the title of the Browse window if the Browse window does have a title.

You can also use the empty string for WindowName to specify the main Visual FoxPro window.

Remarks

WTITLE( ) can be used to return a window's title, which appears in the top border of the window. The title is returned for the active window if you omit WindowName. WTITLE( ) returns the empty string if the Debug, Trace or Command window is active or output is being directed to the main Visual FoxPro window.

Window Names and Titles Names are assigned to user-defined windows, system windows, toolbars (in Visual FoxPro), and Browse windows in the following manner:

User-defined windows are assigned names when they are created with DEFINE WINDOW. There is a distinction between user-defined window names and titles. By default, user-defined windows don't have titles. If the TITLE clause is included when the window is created, the specified title appears in the top border of the window, but isn't the name of the window.

By default, each system window, which is part of the Visual FoxPro interface, derives its name from the title of the window. Examples of system windows include the Command window, the Data Session window, and the Trace window. In Visual FoxPro, each toolbar derives its name from the title of the toolbar.

Program and editing windows and the Label and Report Designer windows derive their names from the name of the file being created or modified.

A Browse window derives its name from the title of the window. The name and title of the Browse window is assigned in one of three ways: either by the default title assignment of the table alias, or by the window title (if any exists), or by the Browse title (if any exists).

By default, the Browse window name is the table alias.

To specify a system window and toolbar names in commands and functions, enclose the entire system window or toolbar name in quotation marks. For example, to hide the Report Controls toolbar in Visual FoxPro, issue the following command:

HIDE WINDOW "Report Controls"

Additional Notes on Window Names If you are unsure of the name assigned to a window, check the Window menu. All window names are listed at the bottom of the Window menu.

Two windows exist if you issue BROWSE WINDOW WindowName. The Browse window is a separate window and takes on the attributes of the specified user-defined window. If a window is active when you issue BROWSE and you don't include the WINDOW clause, the Browse window takes on the attributes of the active window. You can override this behavior by including NORMAL in BROWSE.

You can include window names that contain spaces in commands and functions that accept window names, such as MOVE WINDOW, DEACTIVATE WINDOW, and WONTOP( ), by specifying the part of the window name that begins with the first non-space character and continuing until the last non-space character is encountered.

For example, a Browse window with the name Invoice Entry can be moved with this command:

MOVE WINDOW invoice BY 1,1

The names of user-defined windows cannot contain spaces, but the names of Browse and system windows can.

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WEXIST( ) | WLAST( ) | WONTOP( ) | WOUTPUT( ) | WREAD( )


WVISIBLE( ) Function

Determines if the specified window has been activated and isn't hidden.

WVISIBLE(WindowName)

Return Values

Logical

Parameters

WindowName
Specifies the name of the window WVISIBLE( ) evaluates. In Visual FoxPro, you can also specify the name of a toolbar. You can also include the empty string in WindowName to specify the main Visual FoxPro window.

Remarks

WVISIBLE( ) returns true (.T.) if the specified window is shown or activated and isn't hidden. Windows are shown and activated with SHOW WINDOW and ACTIVATE WINDOW.

WVISIBLE( ) returns false (.F.) if the window has not been activated, has been hidden with HIDE WINDOW, has been deactivated with DEACTIVATE WINDOW, or doesn't exist.

Example

The follow example activates the Data Session window (represented by the name View). Using the WVISIBLE() function, you can print to screen the visible state of the window. The Deactivate window is used to close the Data Session window, and the WVISIBLE() function is used again to print the visible state of the window.

ACTIVATE WINDOW View
? WVISIBLE( "View" ) && return .T.
DEACTIVATE WINDOW View
? WVISIBLE( "View" ) && return .F.

See Also

ACTIVATE WINDOW | DEFINE WINDOW | WEXIST( ) | WONTOP( ) | WOUTPUT( )


XMLTOCURSOR( ) Function

Converts XML text into a Visual FoxPro cursor or table.

XMLTOCURSOR(XMLSource eExpression | cXMLFile [, cCursorName [, nFlags ]])

Parameters

eExpression
Specifies the XML text or an expression that evaluates to valid XML data. This parameter can be a Visual FoxPro memory variable, memo field contents, or the return from an HTTP request. You also can specify the return result from a SOAP method call, XML from the XMLDOM, or an ADO stream. XMLCURSOR( ) generates an error if XMLSource is not found, or if eExpression does not parse to valid XML.
cXMLFile
Specifies the name, and optionally, the path of a physical XML file that resides on your local computer or network. If you do not specify a path, Visual FoxPro searches the FoxPro path for the XML file.
cCursorName
Specifies the name of the cursor for storing the result and creates the cursor in the current work area. If the cursor name already exists or is open, Visual FoxPro closes the cursor and creates a new one in an unused work area. If you omit or pass an empty string ("") for cCursorName, Visual FoxPro creates a cursor named XMLRESULT for returning the result.

When nFlags is set to 8192, and if cCursorName contains data, Visual FoxPro appends the data being imported from the XML file to the existing table or cursor. The table or cursor must be open or in use. If cCursorName is an empty string (""), Visual FoxPro imports XML into the table or cursor that is open in the current work area.

nFlags
Specifies how XMLSource eExpression is handled in XMLTOCURSOR( ). The following table describes the values for nFlags.
nFlags | Bit | Description
0 | 0000 | Treats the first parameter as a string containing XML data. (Default)
4 | 0100 | Preserves white space in data and overrides the xml:space attribute of the XML data.
512 | 01000000000 | Specifies that the first parameter, XMLSource eExpression or cXMLFile, is a string containing the name and path of an XML data file.
1024 10000000000 NOCPTRANS – Creates Character and Memo fields in the resultant cursor with the NOCPTRANS option and inserts the text or XML values in the incoming elements into the Character or Memo field on an untranslated, byte-for-byte basis.

When used with flag 1024, XMLTOCURSOR( ) returns a string padded with trailing spaces equal to the actual string, that is, a string twice the length.
2048 100000000000 Use when the imported schema has an XML Schema Definition (XSD) schema containing decimal data type with restrictions, or facets, of totalDigits="19" and fractionDigits="4".

XSD data type values are mapped to the Visual FoxPro Currency data type in the resulting cursor.
4096 1000000000000 Disables base64 decoding.

In Visual FoxPro, base64 encoding is intended for encoding only binary data.

8192 1100000000 Specifies that cCursorName is the name or alias of an existing table or cursor and imports the data from the specified XML file into an existing table or predefined cursor.

If cCursorName contains data, the data imported from the XML file is appended to the existing data. If cCursorName is an empty string (""), the data from the XML file is imported into the table or cursor in the current work area.

Setting nFlags to 8192 can be useful when an XML schema is not available or not practical for use.

When you use flag 8192, be aware of the following:

  • You must make sure the table schema matches the incoming XML elements in the appropriate manner. Visual FoxPro enforces the data types in cCursorName as described in the Data Type Matching section in this topic but makes no other assumptions about data types. Attempting to import incompatible values generates the appropriate message.
  • If the XML contains or references a schema, and the data types in the schema conflict with the data types of the cursor or table, the data types in the cursor or table are used.
  • Element names in the XML file are mapped to the column names in cCursorName. In addition, Visual FoxPro imports only data from the element names in the XML file that match the column names in cCusorName.
  • The cursor or table can have fewer columns than those in the XML file, but it must have at least one matching column. The cursor or table can have additional columns that do not correspond to an element in the XML file.
  • If the table contains autoincrementing fields, XMLTOCURSOR( ) fails if AUTOINCERROR is set to ON. Setting AUTOINCERROR to OFF or turning off autoincrementing in the target table by using CURSORSETPROP( ) allows XMLTOCURSOR( ) to succeed. The target table's autoincrementing field or fields are incremented according to the values specified, and the values in the source table are not copied.

Return Values

Numeric data type. XMLTOCURSOR( ) returns the number of records created.

Remarks

Visual FoxPro interprets XML files with or without schema. If no schema is provided, Visual FoxPro makes two passes through the XML data. The structure is determined during the first pass; the conversion is performed during the second pass. Visual FoxPro uses either external or internal schema to determine the cursor or table structure before making a single pass through the XML data.

XMLTOCURSOR( ) processes data differently from a variable or string than from a file. When converting XML to a cursor, the method used to pass XML to the function affects how double-byte character sets (DBCS) characters in the XML are handled. DBCS characters are interpreted correctly when using a file for XMLSource. If you need to use a memory variable or string, you can force interpretation to DBCS using the following code in XMLTOCURSOR( ):

STRCONV(string,11)

as shown in the following example:

CLEAR
CLOSE DATABASES ALL
USE HOME()+'samples\data\customer'
CURSORTOXML('customer','lcXML',1,48,5,"","","")
* XMLTOCURSOR() inserts incorrect characters in the resulting cursor.
XMLTOCURSOR(lcXML,"curCustomerList",4)
* Use STRCONV() in XMLTOCURSOR() to convert to DBCS data correctly.
XMLTOCURSOR(STRCONV(lcXML,11),"curCustomerList",4)
BROWSE
RETURN

XMLTOCURSOR( ) does not perform automatic conversions of XML strings, for example, from ANSI to UTF-8. This is likely to occur when reading an XML string from a file. You can use the STRCONV( ) function to do a conversion. The following example demonstrates the parse error when Visual FoxPro encouters the first ASCII character.

CLOSE DATABASE ALL
USE HOME(2)+"\data\customer"
CURSORTOXML("customer","lcXML",1,32)
STRTOFILE(lcXML,"customer.xml")
XMLTOCURSOR("customer.xml","curCustomer",512)
RETURN

You can prevent the parse error generated by converting the string to UTF-8, either when the XML is written or when it is written to the file. The following example converts the string to UTF-8 as it is being written to the file by using the STRCONV( ) function with the STRTOFILE( ) function:

CLOSE DATABASE ALL
USE HOME(2)+"\data\customer"
CURSORTOXML("customer","lcXML",1,32)
STRTOFILE(STRCONV(lcXML,9),"customer.xml")
XMLTOCURSOR("customer.xml","curCustomer",512)
RETURN

In the above example, users could use a value of 48 for the nFlag paramter in the STRCONV( ) function, to create the XML encoded as UTF-8. However, this does not work for XML provided from an external source or with XML that is not generated with the CURSORTOXML( ) function.

When calling XMLTOCURSOR( ) in append mode, Visual FoxPro adds an empty row if no XML element name matches any table or cursor column.

XMLTOCURSOR( ) generates a syntax error for record lengths greater than approximately 160 columns. The exact number of columns that cause an error depends on the length of the column names.

XML that have external or inline XSD schema as generated by Visual Studio .NET DataSets might contain elements not supported by Visual FoxPro, which are disregarded. For example, some of these elements might include the following:

  • xs:unique name
  • xs:annotation
  • Additional processing instructions and attributes such as the following:
    • Schema prefix support, such as msdata:Prefix, that defines the scope of a group of elements
    • XML prefix support, such as the vfpx attribute, that scopes the prefix to root elements
    • msprop attribute and other attributes that use this namespace
    • Other msdata attributes that reference items not supported by Visual FoxPro, such as msdata:Locale or msdata:Comment

XSD Data Type to Visual FoxPro Data Type Mapping

The following table lists how Visual FoxPro handles XSD data types in XMLTOCURSOR( ).

XSD data type | Visual FoxPro data type
xsd:binaryBase64 | Memo (Binary)
xsd:boolean | Logical
xsd:date | Date
xsd:dateTime | DateTime
xsd:decimal | Numeric
xsd:double | Double
xsd:int | Integer
xsd:string | Character
xsd:string (more than 254 characters in length) | Memo

Data Type Matching

The following table describes data type matching restrictions when setting nFlags to 8192.

Visual FoxPro data type | Behavior
Character, Character (Binary), Memo, Memo (Binary) | Accepts any data. Data exceeding the length of a character column is truncated.
Currency | Accepts numeric data within accepted range of the Currency type. Numbers outside this range are truncated.
Date | Accepts XML format date and dateTime values. Visual FoxPro converts the XML date and dateTime formats to the corresponding Visual FoxPro date. Visual FoxPro preserves only the M/D/Y portion of the XML date or dateTime value.
DateTime | Accepts XML format date and dateTime values. Visual FoxPro converts the XML date and dateTime formats to the corresponding Visual FoxPro date. Precision beyond that which is supported by Visual FoxPro is discarded.
Double | Accepts numeric data within accepted range of the Double type. Numbers outside this range are truncated.
Integer | Accepts integer data within accepted range of the Integer type. Numbers outside this range are truncated.
Logical | Accepts the values True, .T., 1, False, .F., and 0.
Numeric, Float | Accepts numeric data with or without decimals. Numbers outside the accepted range for these types are truncated according to Visual FoxPro rules or replaced with the numeric overflow indicator ("*************").

Numeric Overflow Conditions XMLTOCURSOR( ) imports XML data containing Visual FoxPro-type numeric overflow conditions, for example, *****.** in place of a numeric or integer value. If a schema is provided, Visual FoxPro creates the correct data type in the resulting cursor but changes the overflow from containing asterisk (*) characters to 0.0 or 0 values. Therefore, the XML parser used by XMLTOCURSOR( ) does not error as a result of character values stored in a decimal type element.

See Also

XML Functions | CURSORTOXML( ) Function | XML UPDATEGRAM( ) Function


XMLUPDATEGRAM( ) Function

Mirrors changes made in a buffered table or cursor in an XML UpdateGram and returns a character string that contains the UpdateGram. To use XMLUPDATEGRAM( ), you must use SET MULTILOCKS ON and enable table buffering.

An XML UpdateGram represents the before and after conditions of the changed portion of a Visual FoxPro table or cursor. Through additional processes, you can use an UpdateGram to commit these changes to the data represented by the XML UpdateGram document.

SQL Server and Visual Studio .NET support the DiffGram format for updating XML. SQL XML requires mapping schema to support this format. Therefore, XMLUPDATEGRAM( ) does not support this format.

XMLUPDATEGRAM( [ cAliasList [, nFlags [, cSchemaLocation]]])

Parameters

cAliasList
Specifies a comma-separated list of open tables or cursors, listed either by name or work area numbers in any combination, to include in the XML UpdateGram. If you specify no value or an empty string ("") for cAliasList, Visual FoxPro uses all open tables and cursors in the current data session that contain buffered changes.
nFlags
Specifies whether to return a formatted file. The following table lists the additive flags for nFlags.
nFlag | Bit | Output description
0 | 0000 | Use UTF-8 formatted XML (Default)
1 | 0001 | Use unformatted, for example, continuous string XML.
2 | 0010 | Enclose empty elements with both open and closing elements, for example, <cc04><cc04/>.
4 | 0100 | Preserve white space in fields.
8 | 1000 | Wrap Memo fields in CDATA sections.
16 | 10000 | Output encoding
32 | 100000 | Output encoding
Note When Output Encoding is UTF-8 (default), the XML Declaration does not contain an Encoding= attribute (no encoding attribute = UTF-8).

When Output Encoding is set to default to the code page of the cursor or table, the encoding attribute will be written according to the following table.

Note Encoding flags are set by combining bits 4 and 5 (0010000).
Encoding flag | Bits 4 and 5 | Description
+0 | 00 | Windows 1252 (Default)
+16 | 01 | Set output encoding attribute to the code page of the cursor.
+32 | 10 | Set output encoding attribute to UTF-8 (no character translation).
+48 | 11 | Set output encoding attribute to UTF-8 and translate double-byte characters to UTF-8.
cSchemaLocation
Specifies the name and location of the mapping schema, if it exists.
Note You must supply the mapping schema.

For example, suppose you pass the a schema called mySchema.xsd to cSchemaLocation, the UpdateGram created contains a mapping schema attirbute as it appears in the following XML:

<ROOT xmlns:updg="urn:schemas-microsoft-com:xml-updategram">
  <updg:sync mapping-schema="mySchema.xsd" >
    <updg:before>

Return Values

Character data type. XMLUPDATEGRAM( ) returns a character string that contains the XML UpdateGram.

Remarks

Before calling XMLUPDATEGRAM( ), you should specify the key field list by calling CURSORSETPROP( ) with a KeyFieldList clause against existing cursors and tables. If you do not specify key fields, both the before and after representations contains all the fields in the table. If you specify one or more key fields, only those fields appear in the before section. To avoid possible errors generated by XMLUPDATEGRAM( ) on tables containing Memo or General fields, use the CURSORSETPROP( ) function.

To include memo data in the XML UpdateGram, set the KeyFieldList property using CURSORSETPROP( ) as shown in the following example:

SET MULTILOCKS ON
CREATE CURSOR Test (mField M, cField C(10))
APPEND BLANK
CUSORSETPROP("Buffering",5)
CUSORSETPROP("keyfieldlist",'cfield')
Value = REPLICATE('x ',500)
REPLACE mField WITH mValue, cField WITH "Test"
? XMLUPDATEGRAM()
RETURN

You must use an explicit schema on the SQL Server and reference the schema in the XML UpdateGram to write memo data in the XML UpdateGram to SQL Server.

Unlike the CURSORTOXML( ) function, XMLUPDATEGRAM( ) disregards SET FIELDS statements and reads from the underlying cursor directly. If you want to change the table structure before calling XMLUPDATEGRAM( ), you must copy the data into a new cursor. For example, to change a numeric field to a currency field, you can use the following SQL SELECT statement to create a new cursor, then use that cursor with XMLUPDATEGRAM( ) as in the following example for showing context:

* Make Total_Price a currency field.
SELECT OrderID, CustID, NTOM(Total_Price) as Total_Price;
      FROM Orders INTO CURSOR New_Orders READWRITE
   CURSORSETPROP("Buffering", 5, "New_Orders")      && Enable buffering.
   REPLACE Total_Price WITH (Total_Price * 1.083)   && Add sales tax.
   cXMLUpdg = XMLUPDATEGRAM("New_Orders")      && Create XML UpdateGram.

See Also

CURSORTOXML( ) Function | XMLTOCURSOR( ) Function | CURSORSETPROP( ) Function


YEAR( ) Function

Returns the year from the specified date or datetime expression.

YEAR(dExpression | tExpression)

Return Values

Numeric

Parameters

dExpression
Specifies a date expression from which YEAR( ) returns the year. dExpression can be a function that returns a date, or a Date-type memory variable, array element, or field. It can also be a literal date string, such as {^1998-06-06}.
tExpression
Specifies a datetime expression from which YEAR( ) returns the year.

Remarks

YEAR( ) always returns the year with the century. The CENTURY setting (ON or OFF) doesn't affect the returned value.

Example

CLEAR
? YEAR(DATE( ))

See Also

DATE( ) | DATETIME( ) | DOW( ) | SET CENTURY


Operators

Operators make it possible for you to manipulate data of the same type. Visual FoxPro operators can be grouped according to the following data types and functions:

  • Character Operators
  • Date and DateTime Operators
  • Logical Operators
  • Relational Operators
  • Numeric Operators

See Also

Language Reference


Character Operators

You can join and compare character data using the character operators +, -, and $. The following table lists the character expression operators in order of precedence.

Character Operators

Operator Action Code
+
 Concatenation. Joins two strings, a string and a field, or a string and a variable.
? 'Good ' + 'morning'

-
 Concatenation. Removes trailing blanks from the element preceding the operator then joins two elements.
? customer.first - customer.last

$
 Comparison. Seeks one character expression within another.
? 'father' $ 'grandfather'
? 'Main' $ customer.address

See Also

$ Operator | Character Data Type | Creating Character Expressions | Operators


Date and Time Operators

The following operators act on dates and times.

Date and Time Operators

Operator Action Code
+
 Addition
tNewTime = tTime1 + nSeconds
dNewDate = dDate1 + nDays

-
 Subtraction
nSeconds = tTime1 - tTime2
tNewTime = tTime1 - nSeconds
dNewDate = dDate1 - nDays

See Also

Date Data Type | DateTime Data Type | Date and Time Functions | Operators


Logical Operators

Logical operators work with all data types and return a Logical value. The following table lists the logical operators in order of precedence.

Logical Operators

Operator Action Code
( )
 Expression groups
cVar AND (cVar2 AND cVAR3)

NOT, !
 Logical negative
IF NOT cVarA = cVarB
IF ! nVar1 = nVar2

AND
 Logical AND
lVar0 AND lVar9

OR
 Logical inclusive OR
lVarX OR lVarY
Note The Not Equal operator ( # ) can be used to perform XOR comparison (such as lVarX # lVarY).

See Also

BITAND( ) Function | BITNOT( ) Function | BITOR( ) Function | BITXOR( ) Function | Relational Operators | Operators


Numeric Operators

Numeric operators function with all numeric values. The following table lists the numeric operators in order of precedence.

Numeric Operators

Operator Action Code
( )
 Group subexpressions
(4-3) * (12/nVar2)

**, ^
 Exponentiation
? 3 ** 2
? 3 ^ 2

*, /
 Multiplication and division
? 2 * 7
? 14 / 7

%
 Modulus (remainder)
? 15 % 4

+, -
 Addition and subtraction
? 4 + 15

See Also

% Operator | Currency Data Type | Double Field Type | Float Field Type | Numeric Data Type | Operators


Relational Operators

Relational operators work with all data types and return a Logical value. The following table lists the relational operators.

Relational Operators

Operator Action Code
<
 Less than
? 23 < 54

>
 Greater than
? 1 > 2
=
 Equal to
? cVar1 = cVar

<>, #, !=
 Not equal to
? .T. <> .F.

<=
 Less than or equal to
? {^1998/02/16} <= {^1998/02/16}

>=
 Greater than or equal to
? 32 >= nHisAge

==
 Character string comparison
? status == "Open"

The == operator can be used when an exact comparison of character strings is needed. If two character expressions are compared with the == operator, the expressions on both sides of the == operator must contain exactly the same characters, including blanks, to be considered equal. The SET EXACT setting is ignored when character strings are compared using ==. See SET EXACT for more information on using the == operator to compare character strings.

You also can use the equal to (=) operator to determine if two object references refer to the same object. The following example demonstrates a simple usage:

CLEAR ALL
X = CREATEOBJECT('Form')
Y = CREATEOBJECT('Form')
? X = Y  && Displays false (.F.)
Z = X
? X = Z  && Displays true (.T.)

See Also

Logical Operators | CREATEOBJECT( ) Function | SET EXACT Command | Operators


Preprocessor Directives

#DEFINE ... #UNDEF Preprocessor Directive

#IF ... #ENDIF Preprocessor Directive

#IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive

#INCLUDE Preprocessor Directive

#INSERT Preprocessor Directive

#NAME Preprocessor Directive

Coverage Preprocessor Directives

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.


#DEFINE ... #UNDEF Preprocessor Directive

Creates and releases compile-time constants.

You can use the #DEFINE and #UNDEF preprocessor directives to create compile-time constants in programs. By creating constants with #DEFINE instead of using variables, you can reduce memory consumption, increase performance, and simplify programs.

To create a constant with #DEFINE, specify the constant's name with ConstantName and its value with eExpression. When the program is compiled, text substitution is performed and the constant value expression is substituted for the constant name wherever it appears in the program. You can stop the substitution for the constant by issuing #UNDEF.

#DEFINE ConstantName eExpression...
#UNDEF ConstantName

Parameters

ConstantName
Specifies a compile-time constant name. The constant name must be a legitimate Microsoft Visual FoxPro name that begins with a letter or an underscore and consists of up to 254 letters, digits, or underscores. To improve program readability and simplify debugging, capitalize your constant names and use a standard naming convention for them.
Caution Do not use Visual FoxPro keywords for constant names.

To stop text substitution for a constant created with #DEFINE, issue #UNDEF ConstantName.

eExpression
Specifies the value of the compile-time constant. eExpression can be a name or an expression that evaluates to a character, numeric, currency, date, datetime, or logical value.
Caution Do not use system variables for eExpression. System variables are not evaluated until run time.

Remarks

Visual FoxPro performs substitution only in code that follows the #DEFINE statement that creates the constant and that precedes the #UNDEF statement for that constant. The constant is available only to the program that creates the constant.

If you place #DEFINE within an event or method procedure in a form, the #DEFINE compile-time constant is available only within the event or method procedure. To make #DEFINE compile-time constants available to all event and method procedures in a form, choose the Include File menu item from the Form menu and specify a header file containing the #DEFINE compile-time constants.

Note Compile time constants are not recognized when placed within quotation marks.

You can redefine a #DEFINE only if you do not change the value. If you change the #DEFINE to a different value, Visual FoxPro generates an error.

Example

The following program creates a compile-time constant named MAXITEMS. This constant is used in a FOR ... NEXT loop to display the numbers 1 through 10.

#DEFINE MAXITEMS 10
CLEAR
FOR gnCount = 1 TO MAXITEMS
   ? gnCount
NEXT

See Also

COMPILE Command | #IF ... #ENDIF Preprocessor Directive | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive


#IF ... #ENDIF Preprocessor Directive

Conditionally includes source code at compile-time.

#IF nExpression1 | lExpression1
   Commands
[#ELIF nExpression2 | #ELIF lExpression2
   Commands...
#ELIF nExpressionN | #ELIF lExpressionN
   Commands]
[#ELSE
   Commands]
#ENDIF

Parameters

#IF nExpression1 | lExpression1Commands
nExpression1 specifies the numeric expression that is evaluated.
  • If the expression is nonzero, the commands immediately following #IF are included in the compiled code. The #IF ... #ENDIF structure is exited and the first program line following #ENDIF is then compiled.
  • If the expression is 0, the commands immediately following #IF are not included in the compiled code. Any following #ELIF directives are evaluated.

lExpression1 specifies the logical expression that is evaluated.

  • If the expression is True (.T.), the commands immediately following #IF are included in the compiled code. The #IF ... #ENDIF structure is exited, and the first program line following #ENDIF is then compiled.
  • If the expression is False (.F.), the commands immediately following #IF are not included in the compiled code. Any following #ELIF directives are evaluated.
    Note Do not specify system variables for nExpression1 or lExpression1. System variables are not evaluated until run time.
#ELIF nExpression2 | #ELIF lExpression2Commands
...
#ELIF nExpressionN | #ELIF lExpressionNCommands
If nExpression1 is 0 or lExpression1 is False (.F.), the #ELIF directives are evaluated. The first #ELIF expression nExpression2 or lExpression2, if present, is evaluated. If nExpression2 is nonzero or lExpression2 is True (.T.), the commands following #ELIF are included in the compiled code. The #IF ... #ENDIF structure is exited, and the first program line following #ENDIF is then compiled.

If nExpression2 is 0 or lExpression2 is False (.F.), the commands following #ELIF are not included in the compiled code. The next #ELIF directive is evaluated.

#ELSE Commands
If no #ELIF directives are included, or, if those that are included evaluate to 0 or False (.F.), the presence or absence of #ELSE determines whether any additional commands are included in the compiled code:
  • If #ELSE is included, the commands following #ELSE are included in the compiled code.
  • If #ELSE is not included, none of the commands between #IF and #ENDIF are included in the compiled code. The #IF ... #ENDIF structure is exited, and compilation continues on the first program line following #ENDIF.
#ENDIF
Indicates the end of the #IF statement.

Remarks

#IF ... #ENDIF can improve the readability of source code, reduce compiled program size, and, in some cases, improve performance.

When the #IF ... #ENDIF structure is compiled, successive logical or numeric expressions within the structure are evaluated. The evaluation results determine which set of Visual FoxPro commands (if any) are included in the compiled code.

Example

In the following example, the #IF ... #ENDIF structure determines which version of Visual FoxPro compiles the program and then displays the appropriate message.

#If SYS(3004) = "1033"
? "Locale ID is English"
#Elif SYS(3004) = "1034"
? "Locale ID is Spanish"
#Elif SYS(3004) = "1031"
? "Locale ID is German"
#Elif SYS(3004) = "1036"
? "Locale ID is French"
#Endif

See Also

COMPILE Command | #DEFINE ... #UNDEF Preprocessor Directive | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive


#IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive

Conditionally includes a set of commands at compile time if a compile-time constant is defined.

#IFDEF | #IFNDEF ConstantName
   Commands
[#ELSE
   Commands]
#ENDIF

Parameters

#IFDEF
Specifies that a set of commands is included at compile time when the ConstantName is defined.

The following items describe how a set of commands is included at compile time when you include #IFDEF:

  • If ConstantName is defined, the set of commands following #IFDEF and preceding #ELSE or #ENDIF (whichever occurs first) is included at compile time.
  • If ConstantName is not defined and #ELSE is included, the set of commands following #ELSE and preceding #ENDIF is included at compile time.
  • If ConstantName is not defined and #ELSE is not included, no commands within the #IFDEF ... #ENDIF structure are included at compile time.
#IFNDEF
Specifies that a set of commands is included at compile time when the ConstantName is not defined.

The following items describe how a set of commands is included at compile time when you include #IFNDEF:

  • If ConstantName is not defined, the set of commands following #IFNDEF and preceding #ELSE or #ENDIF (whichever occurs first) is included at compile time.
  • If ConstantName is defined and #ELSE is included, the set of commands following #ELSE and preceding #ENDIF is included at compile time.
  • If ConstantName is defined and #ELSE is not included, no commands within the #IFNDEF ... #ENDIF structure are included at compile time.
ConstantName
Specifies the compile-time constant whose existence determines whether a set of commands is included at compile time. Compile-time constants are defined with #DEFINE.
Commands
Specifies the set of commands that is included at compile time.

Remarks

You can nest an #IFDEF | #IFNDEF ... #ENDIF structure within another #IFDEF | #IFNDEF ... #ENDIF structure.

Comments can be placed on the same line after #IFDEF, #IFNDEF, #ELSE, and #ENDIF. These comments are ignored during compilation and program execution.

Example

The following example creates a compile-time constant named MYDEFINE. #IFDEF ... #ENDIF displays a message if the compile-time constant has been defined.

#DEFINE MYDEFINE 1

#IFDEF MYDEFINE
   WAIT WINDOW "MYDEFINE exists"
#ELSE
   WAIT WINDOW "MYDEFINE does not exist"
#ENDIF

See Also

COMPILE Command | #DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | #INCLUDE Preprocessor Directive


#INCLUDE Preprocessor Directive

Tells the Visual FoxPro preprocessor to treat the contents of a specified header file as if it appeared in a Visual FoxPro program.

#INCLUDE FileName

Parameters

FileName
Specifies the name of the header file that is merged into the program during compilation.

You can include a path with the header file name. When you include a path with the header file name, Visual FoxPro searches for the header file only in the specified location.

If you do not include a path with the header file name, Visual FoxPro searches for the header file in the default Visual FoxPro directory, and then along the Visual FoxPro path. The Visual FoxPro path is specified with SET PATH.

Remarks

You can create header files containing preprocessor directives and then use #INCLUDE to merge the contents of the header file into a program when the program is compiled. The contents of the header file are inserted into the program during compilation at the point where #INCLUDE appears in the program.

Only the #DEFINE ... #UNDEF, #IF ... #ENDIF, and #INCLUDE preprocessor directives are recognized in a header file. Comments and Visual FoxPro commands included in a header file are ignored.

A program can contain any number of #INCLUDE directives. These directives can appear anywhere within the program. Putting #INCLUDE directives in header files makes it possible for you to nest #INCLUDE directives.

Header files typically have an .h extension, although they can have any extension. A Visual FoxPro header file, Foxpro.h, is included. It contains many of the constants described throughout this documentation.

Example

In the following example, two files are used: Const.h, a header file, and Myprog.prg, a program file. The header file contains several #DEFINE directives that create compile-time constants. The program file uses #INCLUDE to merge the Const.h header file at compilation, making the compile-time constants in the header file available to the program.

*** Header file CONST.H ***
#DEFINE ERROR_NODISK     1
#DEFINE ERROR_DISKFULL  2
#DEFINE ERROR_UNKNOWN  3

*** Program file MYPROG.PRG ***
#INCLUDE CONST.H

FUNCTION chkerror
PARAMETER errcode
  DO CASE
  CASE errcode = ERROR_NODISK
  ?"Error - No Disk"
  CASE errcode = ERROR_DISKFULL
  ?"Error - Disk Full"
  CASE errcode = ERROR_UNKNOWN
  ?"Unknown Error"
  ENDCASE
RETURN

See Also

#DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive | #INCLUDE Preprocessor Directive


#INSERT Preprocessor Directive

Places text from a text file into a generated menu file.

#INSERT FileName

Parameters

FileName
Specifies the name of the header file that is merged into the program during menu generation.

Remarks

The #INSERT menu generator directive inserts the contents of FileName into generated menu code.

Use #INSERT to include a file in a generated menu program. For example, use #INSERT to place #DEFINE ... #UNDEF statements from a file in the beginning of a generated menu program.

This directive can appear in any procedure; it does not have to be in a particular procedure, such as the setup code. Additionally, the directive can appear anywhere in a procedure.

FileName must be a text file. The generator searches for the file in the current directory, in the FoxPro directory and subdirectories and along the MS-DOS path. If the file cannot be found, the menu generator comments your code - indicating that the file could not be found - and then continues the generation process.

See Also

#DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive


#NAME Preprocessor Directive

This screen and menu generator directive names a snippet produced by clauses such as SHOW, WHEN and VALID, whether the snippet is produced at the object or READ level.

#NAME SnippetName

Parameters

SnippetName
Specifies the name assigned to the snippet. SnippetName must conform to the rules for naming procedures and functions.

Remarks

The #NAME directive must appear at the top of a snippet, before any code statements. You can precede the #NAME directive with blank lines or comments.

Note Visual FoxPro does not check for duplicate names.

See Also

#DEFINE ... #UNDEF Preprocessor Directive | #IF ... #ENDIF Preprocessor Directive | #IFDEF | #IFNDEF ... #ENDIF Preprocessor Directive


Coverage Preprocessor Directives

The following #DEFINE statements support this enhancement of Coverage Profiler.

*COV_LOCS.H

Added four #DEFINEs in the section handling wait window nowait/statusbar messages:

#DEFINE COV_LOADING_STACKINFO_LOC "Loading log for StackLevel analysis"
#DEFINE COV_GENERATING_STACKXML_LOC "Generating StackLevel XML..."
#DEFINE COV_WRITING_STACKXML_LOC "Writing StackLevel XML to disk"
#DEFINE COV_WRITING_TRANSFORM_LOC "Writing transformed file to disk"

Added four #DEFINEs to the shortcut prompts section:

#DEFINE COV_SC_STACKLEVEL_LOC "\<Generate StackLevel XML"
#DEFINE COV_SC_VIEW_STACKLEVEL_LOC "View Stac\<klevel XML"
#DEFINE COV_SC_STACK_TRANSFORM_LOC "\<Transform StackLevel XML"
#DEFINE COV_SC_STACKLEVEL_EXTENDED_LOC "E\<xtended StackLevel XML"

Added seven #DEFINEs to the section handling GETFILE/PUTFILE dialog titles, filters, and so on:

#DEFINE COV_SETSTACKXML_TITLE_LOC "Please specify location to save Coverage StackLevel XML for"
#DEFINE COV_XMLFILES_LOC "XML Files"
#DEFINE COV_XSLFILES_LOC "XSL Transforms"
#DEFINE COV_HTMFILES_LOC "HTML Files"
#DEFINE COV_SAVEDSTACKXML_AS_LOC "Your coverage stack analysis is saved as"
#DEFINE COV_SETTRANSFORMEDXML_TITLE_LOC "Please specify location to save transformed file for"
#DEFINE COV_GETXSLTFILE_TITLE_LOC "Please specify an XSL Transformation file"

Added three #DEFINES to the section handling options dialog prompts and captions:

#DEFINE COV_OPT_STACK_LOC "StackLevel XML analysis"
#DEFINE COV_OPT_STACK_EXTENDED_LOC "\<Generate extended StackLevel XML tree"
#DEFINE COV_OPT_STACK_XSLT_LOC "XSL \<Transform..."

COV_TUNE.H

New tunable settings (and associated comments) supporting the new feature:

Two settings are used for in tagname creation:

* the first two represent element node prefixes
#DEFINE COV_STACKROOT "VFPCallStackLog"
#DEFINE COV_STACK_ONEVENT_TAG event

* these are similar to COV_SKIPFILEDBF_SUFFIX and COV_TARGETDBF_SUFFIX

*the next items are used to help identify the XML and HTM files written to
* disk as being generated from this particular process.
#DEFINE COV_STACKXML_SUFFIX "_STACK"
#DEFINE COV_STACKXMLEXT_SUFFIX "_STACKX"
#DEFINE COV_TRANSFORM_SUFFIX "_XSL"

The following is a performance option that, like COV_TOPSPEED, is rarely needed.

* the next item indicates whether lines are loaded from the Coverage
* source workfile .dbf file or are gathered directly by from the original
* text log. Coverage Profiler has a very slight speed advantage but will
* not include ON ... events, since those lines are ignored by the
* Coverage source and target workfiles (there is no code
* to mark or profile for these lines).
#DEFINE COV_LOAD_STACK_FROM_DBF .F.

This definition provides an expression for the tags in the XML derived from the items available in the source log.

* the variables in the next item have the same meaning as the columns
* of the same name in the Coverage source workfile .dbf file
* -- equivalents for these items are read in from the source text log
* when COV_LOAD_STACK_FROM_DBF is .F., and this expression stays the same.
* You can change it as long as you ensure that the result will  be empty
* only for ON ... events.
* Load a log into COVERAGE.APP,
* SET DATASESSION TO _oCoverage.DataSessionID, and refer to the
* source workfile (by default, its alias is FromLog) for some indication
* on the possible contents of these columns.
#DEFINE COV_STACKEXPR ALLTR(IIF(INLIST(FileType,".fxp",".mpx",".qpx",".spx"), ;
                      IIF(EMPTY(ObjClass), ;
                      IF(NOT EMPTY(Executing),ALLTR(Executing),""),;
                      IIF(LEFT(Executing,1)=".",ALLTR(ObjClass),"")+ALLTR(Executing)), ;
                      ALLTR(Executing)))

See Also

Coverage Profiler Application


System Variables

For information about backward compatible-only language reference, see Backward-Compatible Language Elements.

A

_ASCIICOLS

_ASCIIROWS

B

_BEAUTIFY

_BROWSER

_BUILDER

C

_CALCMEM

_CALCVALUE

_CLIPTEXT

_CODESENSE

_CONVERTER

_COVERAGE

D

_DBLCLICK

_DIARYDATE

_DOS

E

F

_FOXCODE

_FOXREF

_FOXTASK

G

_GALLERY

_GENHTML

_GENMENU

_GETEXPR

H

I

_INCSEEK

_INCLUDE

J

K

L

M

_MAC

_MLINE

N

O

_OBJECTBROWSER

P

_PAGENO

_PAGETOTAL

_PRETEXT

Q

R

S

_SAMPLES

_SCCTEXT

_SCREEN

_SHELL

_SPELLCHK

_STARTUP

T

_TASKLIST

_TALLY

_TEXT

_THROTTLE

_TOOLBOX

_TRIGGERLEVEL

U

_UNIX

V

_VFP

W

_WINDOWS

_WIZARD

X

Y

Z

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


System Variables Overview

System variables are built-in variables that Visual FoxPro creates and maintains automatically. They are PUBLIC by default, but you can declare them PRIVATE.

Note The functionality of many system variables has been replaced by new features in Visual FoxPro. For details, see the description for each system variable.

The following table lists the five types of Visual FoxPro system variables and their designation in expressions:

Variable type | Description | Expression
C | Character | cExpression
D | Date | dExpression
L | Logical | lExpression
N | Numeric | nExpression
O | Object | oExpression

The following table lists all system variables — their types and default values:

Variable | Type | Default value
_ALIGNMENT | C | LEFT
_ASCIICOLS | N | 80
_ASCIIROWS | N | 63
_ASSIST | C | Empty string
_BEAUTIFY | C | Empty string
_BOX | L | .T.
_BROWSER | C | Browser.app
_BUILDER | C | Builder.app
_CALCMEM | N | 0.0
_CALCVALUE | N | 0.0
_CLIPTEXT | C | Empty string
_CONVERTER | C | Empty string
_COVERAGE | C | Coverage.app
_CUROBJ | N | -1
_DBLCLICK | N | 0.5
_DIARYDATE | D | Current date
_DOS | L | .T. in FoxPro for MS-DOS
_FOXDOC | C | Empty string
_FOXREF | C | FoxRef.app
_GALLERY | C | Gallery.app
_GENGRAPH | C | Empty string
_GENHTML | C | Genhtml.prg
_GENMENU | C | Genmenu.prg
_GENPD | C | Empty string
_GENSCRN | C | Genscrn.prg
_GENXTAB | C | Empty string
_GETEXPR | C | Empty string
_INCLUDE | C | Empty string
_INCSEEK | N | .5
_INDENT | N | 0
_LMARGIN | N | 0
_MAC | L | .T. in Visual FoxPro for Macintosh
_MLINE | N | 0
_PADVANCE | C | FORMFEED
_PAGENO | N | 1
_PAGETOTAL | N | 0
_PBPAGE | N | 1
_PCOLNO | N | Current column
_PCOPIES | N | 1
_PDRIVER | C | Empty string
_PDSETUP | C | Empty string
_PECODE | C | Empty string
_PEJECT | C | NONE
_PEPAGE | N | 32767
_PLENGTH | N | 66
_PLINENO | N | 0
_PLOFFSET | N | 0
_PPITCH | C | DEFAULT
_PQUALITY | L | .F.
_PRETEXT | C | Empty string
_PSCODE | C | Empty string
_PSPACING | N | 1
_PWAIT | L | .F.
_RMARGIN | N | 80
_SAMPLES | C | HOME() + "SAMPLES"
_SCCTEXT | C | Scctext.prg
_SCREEN | O | FORM
_SHELL | C | Empty string
_SPELLCHK | C | Spellchk.app
_STARTUP | C | Empty string
_TABS | C | Empty string
_TALLY | N | 0
_TASKPANE | C | Taskpane.app
_TEXT | C | –1
_THROTTLE | N | 0
_TOOLBOX | C | Toolbox.app
_TRANSPORT | C | Empty string
_TRIGGERLEVEL | N | 0
_UNIX | L | .T. in FoxPro for UNIX
_VFP | O | Microsoft Visual FoxPro Application 8.0
_WINDOWS | L | .T. in Visual FoxPro for Windows
_WIZARD | C | Wizard.app
_WRAP | L | .F.

See Also

PUBLIC | PRIVATE | STORE


_ASCIICOLS System Variable

Specifies the number of columns in a text file created with REPORT ... TO FILE ASCII.

_ASCIICOLS = nExpression

Parameters

nExpression
Specifies the number of columns in the text file. The default value is 80.

Remarks

Include the TO FILE ASCII clause in REPORT to create a text file.

See Also

_ASCIIROWS | CREATE REPORT | MODIFY REPORT | REPORT | System Variables A-Z | System Variables Overview


_ASCIIROWS System Variable

Specifies the number of rows in a text file created with REPORT ... TO FILE ASCII.

_ASCIIROWS = nExpression

Parameters

nExpression
Specifies the number of rows in the text file. The default value is 63.

Remarks

Include the TO FILE ASCII clause in REPORT to create a text file.

See Also

_ASCIICOLS | CREATE REPORT | MODIFY REPORT | REPORT | System Variables A-Z | System Variables Overview


_BEAUTIFY System Variable

Specifies the beautification application for Visual FoxPro programs. The application is run when you choose the Beautify command on the Tools menu.

_BEAUTIFY = cProgramName

Parameters

cProgramName
Specifies a beautification application. If your beautification application is in a directory other than the current default directory, include a path with the application name.

You can also specify a beautification application in your configuration file by including a line using this syntax:

_BEAUTIFY = cProgramName

Note that your beautification application must accept a single parameter, the name of the program to beautify. Your beautification application can modify the program, write the modifications to a temporary file, and then return the name of the temporary file to FoxPro. FoxPro reads the temporary file back into the editing session under the original FoxPro program name and then deletes the temporary file.

Remarks

The Beautify command appears on the Tools menu when you open a program or text file in an editing window.

See Also

Documenting Wizard | Beautify Options Dialog Box


_BROWSER System Variable

Contains the name of the class browser application.

_BROWSER = cProgramName

Parameters

cProgramName
Specifies a class browser application. _BROWSER contains Browser.app if you have installed the class browser application.

If the class browser is in a directory other than the current default, include a path with the class browser application name.

If the class browser is in a folder other than the current default, include a path with the class browser application name.

You can also specify a class browser application in your Visual FoxPro configuration file by including a line using this syntax:

_BROWSER = cProgramName

A different class browser application can be specified by storing the new application name in _BROWSER from within the Command window or a program.

Remarks

Browser.app displays the relationships between classes in a visual class library (.vcx) and is installed by default in the directory in which Visual FoxPro is installed.

You can run the class browser by issuing the following command:

DO (_BROWSER)

Issuing this command displays the class browser Open dialog so you can select a class library to open. You can run more than one instance of the class browser simultaneously by choosing the class browser menu item in the Tools menu or issuing the command again.

You can also run the class browser for a specific visual class library or an object reference, and you can optionally include the name of a class that is initially selected. For example, the following command starts the class browser, opens the Buttons visual class library, and selects the VCR class:

DO (_BROWSER) WITH HOME(2) + 'CLASSES\BUTTONS.VCX', 'VCR'

For additional information about the Visual FoxPro Class Browser, see Managing Classes with the Class Browser.

See Also

CREATE CLASS | CREATE CLASSLIB | CREATE FORM | CREATEOBJECT( ) | DEFINE CLASS | System Variables Overview


_BUILDER System Variable

Contains the name of the Visual FoxPro builder application.

_BUILDER = cProgramName

Parameters

cProgramName
Specifies a builder application. If your builder application is in a directory other than the current Visual FoxPro default directory, include a path with the application name.

Remarks

The _BUILDER system variable contains the name of the application that Visual FoxPro uses when you choose a builder in the Form Designer. By default, _BUILDER contains BUILDER.APP, installed in your Visual FoxPro directory. You can specify a different name for the builder application.

See Also

System Variables Overview | Adding Visual FoxPro Controls to a Form | Form Designer


_CALCMEM System Variable

Contains the numeric value that Microsoft Visual FoxPro stores in the Calculator's memory.

_CALCMEM = nCalculatorValue

Parameters

nCalculatorValue
Specifies the numeric value that _CALCMEM stores in memory.

Remarks

You can save the result of a calculation in the Calculator's memory and return the result to a program, or you can place a specific value in the Calculator's memory before using the Calculator.

To initialize the Calculator's memory, store a numeric value to _CALCMEM with STORE or the = assignment operator. When you use the Calculator, its memory contains the value you specified.

Example

The following program example stores the numeric constant 1234 to _CALCMEM. The program then displays the Calculator and stuffs the keyboard with the letter R. The keystroke R displays the value stored in the Calculator's memory.

STORE 1234 TO _CALCMEM
ACTIVATE WINDOW calculator
CLEAR TYPEAHEAD
KEYBOARD CHR(82)

See Also

ACTIVATE WINDOW | _CALCVALUE | STORE | CALCULATE Command


_CALCVALUE System Variable

Contains the numeric value that the Calculator displays.

_CALCVALUE = nCalculatorDisplayValue

Parameters

nCalculatorDisplayValue
Specifies the numeric value that the Calculator displays.

Remarks

You can return the result of a calculation to a program or you can place a specific value in the Calculator's display before using the Calculator.

To initialize the Calculator's display, store a numeric value to _CALCVALUE with STORE or the = assignment operator. When you use the Calculator, it displays the value you specified.

Example

In the following example, the numeric value 1234 is stored to _CALCVALUE. The Calculator then displays the value 1234.

STORE 1234 TO _CALCVALUE
ACTIVATE WINDOW calculator

See Also

ACTIVATE WINDOW | _CALCMEM | STORE | CALCULATE Command | Display Calculated Values in a Column


_CLIPTEXT System Variable

Contains the contents of the Clipboard.

_CLIPTEXT = cExpression

Parameters

cExpression
Specifies the character expression to store in the Clipboard.

Remarks

You can place a character expression cExpression on the Clipboard with STORE or the = assignment operator.

Example

These examples will put long pathnames on the clipboard.

_cliptext=_vfp.ServerName

or

_cliptext=getfile()

See Also

PRIVATE | PUBLIC | STORE | Text Editor and Clipboard Manipulation Routines | = | DataToClip Method


_Codesense System Variable

Contains the name of the application that provides IntelliSense functionality.

_Codesense = [cFilename]

Parameters

cFilename
Name of the Visual FoxPro application that provides IntelliSense functionality, such as tooltips in the editor and code editor windows, list members, and others.

Remarks

The _Codesense application also enhances IntelliSense functionality for native commands and functions. By default, _Codesense contains FoxCode.app, installed in your Windows user application folder or HOME( ) location. You can specify a different cFilename for the _Codesense application.

See Also

_FOXCODE System Variable | ToolTipText Property | Customizing IntelliSense Using FoxCode | Visual FoxPro IntelliSense Manager Window


_CONVERTER System Variable

Contains the name of the Microsoft Visual FoxPro converter application.

_CONVERTER = cProgramName

Parameters

cProgramName
Specifies a converter application. If your converter application is in a directory other than the current Visual FoxPro default directory, include a path with the application name.

You can also specify a converter application in your Visual FoxPro configuration file by including a line using the following syntax:

_CONVERTER = cProgramName

Remarks

The _CONVERTER system memory variable contains the name of the application that Visual FoxPro uses when you attempt to open a screen, report, or project created in an earlier FoxPro version. By default, _CONVERTER contains Convert.app, installed in your Visual FoxPro directory. You can specify a different name for the converter application.

See Also

System Variables Overview | Visual FoxPro Converter Dialog Box | Specifying the Configuration File to Use


_COVERAGE System Variable

Contains the name of the Visual FoxPro application that creates the Debugger coverage and profiler output.

_COVERAGE = cProgramName

Parameters

cProgramName
Specifies a coverage output application. If your coverage output application is in a directory other than the current Visual FoxPro default directory, include a path with the application name.

You can also specify a coverage output application in your Visual FoxPro configuration file by including a line using this syntax:

_COVERAGE = cProgramName

Remarks

By default, _COVERAGE contains Coverage.app, installed in your Visual FoxPro directory. You can specify a different name for the coverage output application.

See Also

SET COVERAGE Command | SET EVENTTRACKING Command | Coverage Profiler Modification | Coverage Profiler Application


_DBLCLICK System Variable

Specifies the time interval between double and triple mouse clicks.

_DBLCLICK = nTicks

Parameters

nTicks
Specifies the time interval in seconds. Internal timing is measured in clock "ticks," which are each about 1/18th of a second. If you store an integer or decimal value to _DBLCLICK, Visual FoxPro may store it as a slightly different value due to rounding to ticks.

At the startup of Visual FoxPro, the double-click setting in the Windows Mouse Properties Control Panel determines the _DBLCLick default value. _DBLCLICK can range from 0.05 to 5.5 seconds (1 to 100 ticks). _DBLCLICK applies to double click rate only and not to incremental search key capture period as in versions of Visual FoxPro prior to version 7.

Remarks

The _DBLCLICK setting overrides the setting specified in the Windows Mouse Control Panel.

_DBLCLICK contains a numeric value that determines the time interval Visual FoxPro uses to check for a double or triple mouse click. _DBLCLICK is the time interval between mouse clicks. For example, if _DBLCLICK is set to 0.5 seconds, you have one half second to click twice for a double-click, and 1 second to click three times for a triple-click.

The larger the value of _DBLCLICK, the longer you can wait between the first and second click for Visual FoxPro to interpret the two clicks as a double-click. If _DBLCLICK is set to a very small value, even quick double-(or triple-) clicks may be interpreted as two (or three) single clicks.

See Also

INKEY( ) | DblClick Event | MouseUp Event | MouseDown Event | Click Event | _INCSEEK System Variable


_DIARYDATE System Variable

Contains the current date in the Calendar/Diary.

_DIARYDATE = dExpression

Parameters

dExpression
Specifies the date for the Calendar/Diary.

Remarks

With _DIARYDATE, you can display the Calendar/Diary with a specific date selected, or you can return the selected Calendar/Diary date.

By default, the current date is stored in _DIARYDATE. When you open the Calendar/Diary, the current date is selected. You can store a different date to _DIARYDATE so that the Calendar/Diary opens with this new date selected.

Selecting a new date when the Calendar/Diary is open causes the new date to be stored to _DIARYDATE. When you close the Calendar/Diary, _DIARYDATE contains the last selected date.

Example

In the following program example, the Calendar/Diary opens with March 28, 2001, selected and the value of _DIARYDATE appears below. July 4, 1776, is then stored to _DIARYDATE and _DIARYDATE displays again. The program then uses the DATE( ) function to select the current date, and displays _DIARYDATE.

SET CENTURY ON
STORE {^2001-03-28} TO _DIARYDATE
=MESSAGEBOX(DTOC(_DIARYDATE),64)
ACTIVATE WINDOW calendar
=MESSAGEBOX("Change date to July 4, 1776",48))
STORE {^1776-07-04} TO _DIARYDATE
=MESSAGEBOX(DTOC(_DIARYDATE),64)
=MESSAGEBOX("Change date to today's date",48)
STORE DATE( ) TO _DIARYDATE
=MESSAGEBOX(DTOC(_DIARYDATE),64)
RELEASE WINDOW calendar

See Also

STORE | Add a Data-Bound Calendar | SET CENTURY Command | ACTIVATE WINDOW Command


_DOS System Variable

Included for backward compatibility. Always returns false (.F.) in Visual FoxPro.

See Also

_MAC | _UNIX | VERSION( ) | _WINDOWS


_FOXCODE System Variable

Contains the name of the FoxCode table used for Visual FoxPro IntelliSense.

_FOXCODE [= cDBFFileName]

Parameters

cDBFFileName
Specifies the name of the file to be used by IntelliSense in editors and the Command window.

Remarks

By default, the file is named FoxCode.dbf and stored in your Windows user application folder or HOME( ) location.

The FoxCode system table, like FoxUser resource file, is opened at startup by Visual FoxPro. You can access the information in FoxCode.dbf with the following code.

USE (_FOXCODE) AGAIN SHARED

This setting is ignored at run time.

See Also

_Codesense System Variable | FoxCode Object Reference | Customizing IntelliSense | IntelliSense Overview | Using IntelliSense in Visual FoxPro | HOME( ) Function


_FOXREF System Variable

Contains the name of the application that provides the Code References tool.

_FOXREF = cFoxRefApplication

Parameters

cFoxRefApplication
Specifies the name of the Visual FoxPro program used to handle Code Reference searches.

Remarks

By default, the _FOXREF system variable points to the following file:

HOME( ) + "FoxRef.app"

You can change this setting in the File Locations tab of the Options dialog box.

You can call this application directly as follows:

DO (_FOXREF) WITH ParameterList

ParameterList specifies parameters to pass to the program or procedure. The parameters listed in ParameterList can be expressions, memory variables, literals, fields, or user-defined functions. By default, parameters are passed to programs and procedures by reference. You can pass a parameter by value by placing it in parentheses.

See Also

System Variables | DO Command | File Locations Tab, Options Dialog Box | Look Up Reference Dialog Box | Code References Window | Viewing Code Definitions


_FoxTask System Variable

Specifies the name of the FOXTASK table that supports Visual FoxPro Task Manager.

_FoxTask [= cDBFFileName]

Parameters

cDBFFileName
Specifies the name of the file to be used by the Visual FoxPro Editor and the Task List Manager to store Tasklist Shortcuts.

Remarks

By default, the file is named foxtask.dbf and stored in your Windows user application folder or HOME( ) location. The following table describes the structure of foxtask.dbf

Field Name | Type | Width | Description
UNIQUEID | C | 10 | Specifies the Visual FoxPro Unique ID
TIMESTAMP | N | 10 | Specifies the Visual FoxPro timestamp
FILENAME | M | 4 | Specifies file name
CLASS | M | 4 | Specifies the class name (.vcx, .scx)
METHOD | M | 4 | Method name (.vcx, .scx)
LINE | N | 6 | Specifies the line number
CONTENTS | M | 4 | Specifies the contents of the line
TYPE | C | 1 | "S" – for shortcut; others can be user-defined
DUEDATE | D | 8 | User-defined Date due
PRIORITY | N | 1 | Specifies a user-defined priority setting for the item 0 = low1 = medium2 = high
STATUS | N | 1 | Completion state of a task 0 = not completed1 = completed

You can specify a different name for the tasklist table by using the FoxTask property as in the following example:

Example

_FOXTASK = MyTasks.dbf

See Also

_TASKLIST System Variable


_GALLERY System Variable

Specifies the program that is executed when you choose Component Gallery from the Tools menu.

_GALLERY = ProgramName

Parameters

ProgramName
Specifies a program. If your program is in a directory other than the current default directory, include a path with the program name.

Remarks

_GALLERY contains GALLERY.APP by default.

See Also

Component Gallery Overview| Starting with the Component Gallery | System Variables A-Z | System Variables Overview


_GENHTML System Variable

Specifies an HTML (Hypertext Markup Language) generation program.

_GENHTML = ProgramName

Parameters

ProgramName
Specifies a program that generates HTML. If your HTML generation program is in a directory other than the current default directory, include a path with the program name.

Remarks

_GENHTML contains Genhtml.prg by default. Genhtml.prg is executed when you choose Save As HTML from the File menu. A text file that contains a hypertext markup language version of the form, menu, report, or table is created. The Save As HTML option is available only when the Form, Menu, or Report designers are active and the form, menu, or report has been saved, or when a Browse window is open.

See Also

CREATE FORM | CREATE MENU | CREATE REPORT | USE | System Variables A-Z | System Variables Overview


_GENMENU System Variable

Specifies a menu generation program.

_GENMENU = ProgramName

Parameters

ProgramName
Specifies a program that previous versions used to generate menu code from an .mnx menu definition table. If your program is in a directory other than the current default directory, include a path with the program name.

Remarks

_GENMENU contains Genmenu.prg by default. A directive (#IMAGEPATHS) controls if full paths are generated for menu images.

See Also

CREATE MENU | _GENSCRN | System Variables A-Z | System Variables Overview


_GETEXPR System Variable

Specifies the program that is executed when you issue the GETEXPR command or invoke the Expression Builder dialog box from within Visual FoxPro.

_GETEXPR = ProgramName

Parameters

ProgramName
Specifies a program that is executed when you issue the GETEXPR command or invoke the Expression Builder dialog box from within Visual FoxPro. If your program is in a directory other than the current default directory, include a path with the program name.

Remarks

_GETEXPR contains the empty string by default; the empty string indicates that the standard Visual FoxPro Expression Builder dialog box is displayed when the GETEXPR command is executed or when you invoke the Expression Builder dialog box from within Visual FoxPro.

You can create your own Expression Builder program that is executed when the GETEXPR command is executed or when you invoke the Expression Builder dialog box from within Visual FoxPro. Your Expression Builder program must contain an LPARAMETERS or PARAMETERS statement as the first executable line of the program to accept four parameters that Visual FoxPro passes to the program. The parameters are listed below in the order they are passed:

Parameter | Description
cExpressionType | Specifies the expression type.
cErrorMessageText | Specifies the error message displayed if the expression isn't valid.
cDefaultExpression | Specifies the initial default expression in the Expression Builder.
cCaptionText | Specifies the caption that appears in the Expression Builder.

For example, the following could be the first executable line of your Expression Builder program:

LPARAMETERS cExpressionType, cErrorMessageText, ;   cDefaultExpression, cCaptionText

If your Expression Builder program is executed when the Expression Builder dialog box is invoked from within Visual FoxPro, the first three parameters contain the empty string and the fourth parameter contains cCaptionText, the caption that appears in the Expression Builder.

Note that the Visual FoxPro Expression Builder is a modal dialog. Your Expression Builder program should set its form properties to the following values to create a modal dialog:

Form property | Property value
AlwaysOnTop | True (.T.)
Desktop | True (.T.)
WindowType | 1 – Modal

See Also

GETEXPR | LPARAMETERS Command | PARAMETERS Command | System Variables A-Z | System Variables Overview


_INCLUDE System Variable

Specifies a default header file included with user-defined classes, forms, or form sets.

_INCLUDE = HeaderFileName

Parameters

HeaderFileName
Specifies a default header file of predefined compile-time constants automatically included with user-defined classes, forms, or form sets. If your header file is in a directory other than the current default directory, include a path with the header file name. Contains the empty string by default.

Remarks

You can also specify the default header file with the Default Include File item in the File Locations tab of the Options dialog box.

See Also

CREATE CLASS | CREATE FORM | File Locations Tab, Options Dialog Box | #INCLUDE | System Variables A-Z | System Variables Overview


_INCSEEK System Variable

Specifies the time interval that is open for keystrokes within an incremental seek such as within a Listbox or ComboBox control.

_INCSEEK = nTicks

Parameters

nTicks
Specifies the time interval in seconds. Internal timing is measured in clock "ticks," which are each about 1/18th of a second. If you store an integer or decimal value to _INCSEEK, Visual FoxPro may store it as a slightly different value due to rounding to ticks. _INCSEEK can range from 0.05 to 5.5 seconds (1 to 100 ticks).

Remarks

In earlier versions of Visual FoxPro, the value for _DBLCLICK also determined the incremental search interval. The default value for _INCSEEK is 0.50.

See Also

_DBLCLICK | System Variables A-Z | System Variables Overview

Applies To: IncrementalSearch Property


_MAC System Variable

Contains true (.T.) if the user is using FoxPro for Macintosh or Microsoft Visual FoxPro for Macintosh.

_MAC = lExpression

Remarks

_MAC contains false (.F.) for any other platform version of FoxPro (Visual FoxPro for Windows, FoxPro for Windows, FoxPro for MS-DOS, or FoxPro for UNIX).

The value contained in _MAC cannot be changed with STORE or =.

See Also

_DOS | _UNIX | VERSION( ) | _WINDOWS


_MLINE System Variable

Contains the memo field offset for the MLINE( ) function.

_MLINE = nNumberOfCharacters

Parameters

nNumberOfCharacters
Specifies the memo field offset. For more information about the use of _MLINE and an example of its use, see MLINE( ).

Remarks

MLINE( ) returns one line of text from a memo field. MLINE( ) stores the location of its memo field offset to the _MLINE system variable. Use _MLINE as the second numeric argument in the MLINE( ) function to increase the performance of MLINE( ).

The startup default value for _MLINE is 0. Be sure to reset _MLINE to 0 before using _MLINE again with the MLINE( ) function.

See Also

ALINES( ) | MEMLINES( ) | MLINE( ) | SET MEMOWIDTH


_ObjectBrowser System Variable

Contains the name of the object browser application.

_ObjectBrowser = cObjectBrowserApplication

Parameters

cObjectBrowserApplication
Specifies the name of the Visual FoxPro program that makes it possible for you to view COM type libraries.

Remarks

By default, _ObjectBrowser contains objectbrowser.app, installed in your Windows user application folder or HOME( ) location. You can specify a different name for the object browser application.

See Also

System Variables A-Z | System Variables Overview | Object Browser | Using Object Browser


_PAGENO System Variable

Contains the current page number.

_PAGENO = nCurrentPageNumber

Parameters

nCurrentPageNumber
Specifies a numeric value from 1 to 32,767 for the current page number. _PAGENO, _PBPAGE and _PEPAGE work in unison. If _PAGENO is set (or incremented) such that it falls outside the range of _PBPAGE to _PEPAGE, no pages are printed.

Remarks

_PAGENO contains a numeric value that determines the current page number. The startup default is 1. _PAGENO allows you to print page numbers in streaming output without defining, initializing, and incrementing a memory variable for that purpose.

See Also

ON PAGE | _PBPAGE | _PEPAGE | _PLENGTH | _PLINENO | _PAGETOTAL System Variable


_PAGETOTAL System Variable

Contains the total number of pages in a report.

You can use _PAGETOTAL to set up "Page X of Y" numbering in reports. _PAGETOTAL is supported in both development and run-time versions of Visual FoxPro and in all reporting operations, including REPORT FORM...TO FILE...ASCII and with optional arguments such as RANGE.

_PAGETOTAL [ = nValue ]

Parameters

nValue
Specifies a positive number representing the total number of pages in a report.

Remarks

You can set _PAGETOTAL at any time. Visual FoxPro evaluates and updates _PAGETOTAL only when a report operation such as REPORT FORM occurs. At the beginning of the report operation, Visual FoxPro initializes _PAGETOTAL to a value of 0, regardless of whether _PAGETOTAL is used on the report.

If you include _PAGETOTAL anywhere in a Visual FoxPro report, Visual FoxPro performs two passes through the report. The first pass is not visible or printed and calculates the _PAGETOTAL variable. During the first pass, _PAGETOTAL is set to a value of -1.

For performance reasons, you can suppress a two-pass report by not calling _PAGETOTAL in a print preview using an expression such as the following:

TRANS(_PAGENO) + IIF(SYS(2040)="1", "", " OF " + TRANS(_PAGETOTAL))

If you do not include a reference to _PAGETOTAL in the report, Visual FoxPro sets the value of _PAGETOTAL to the total number of pages at the end of printing and performs only one pass through the report.

You can force a second pass through the report using an expression such as the following:

IIF( _PAGETOTAL = 0, "","" )

For a second pass to occur, Visual FoxPro must evaluate _PAGETOTAL. Initiating another pass allows for additional operations using report variables such as reporting % of the total number of pages.

The value of _PAGETOTAL should equal the value of _PAGENO at the end of printing a report, regardless whether the report includes _PAGETOTAL.

Example

The following example illustrates how to include "Page X of Y" numbering in your report by using the _PAGETOTAL system variable and adding the following expression in the report textbox:

"Page " + TRANS(_PAGENO) + " of " + TRANS( _PAGETOTAL)

See Also

System Variables | System Variables Overview | _PAGENO System Variable


_PRETEXT System Variable

Specifies a character expression to preface text merge lines.

_PRETEXT = cExpression

Remarks

Used with SET TEXTMERGE, you can merge text within a program. You can output lines of text, the contents of variables, and the results of expressions and functions to the screen, a window, a printer, a text file, or a low-level file.

If you store a character expression to _PRETEXT, the character expression is added to the beginning of the output text line. To facilitate program indentation, you can store a tab or tabs to _PRETEXT.

See Also

\ | \\ | SET TEXTMERGE | _TEXT


_SAMPLES System Variable

Contains the path of the directory in which the Microsoft Visual FoxPro samples are installed.

_SAMPLES = cPath

Parameters

cPath
Specifies the complete path to the directory containing the Visual FoxPro samples.

Remarks

_SAMPLES specifies the path of the directory that contains the samples for Visual FoxPro. This path is usually the \Samples subdirectory in your Visual FoxPro root directory, which you can determine by using the HOME() function. If you do not install the Visual FoxPro samples, _SAMPLES still points to the \Samples subdirectory because it is the default location for installing samples.

The path that _SAMPLES contains is read from an MSDN registry key in the Windows Registry. If this registry key doesn't exist (for example, if you didn't install the samples), _SAMPLES contains the empty string.

You can also specify a path to the samples directory with the Samples Directory item in the File Locations tab of the Options dialog box. If you use the Options dialog box to specify a path to the samples directory, _SAMPLES contains the path you specify. If you choose Set As Default, the path is saved for subsequent Visual FoxPro sessions.

HOME(2) returns the path contained in _SAMPLES.

See Also

HOME( ) | File Locations


_SCCTEXT System Variable

Specifies a Visual FoxPro conversion program that handles translating Visual FoxPro binary files into text equivalents and back.

_SCCTEXT = cProgramName

Parameters

cProgramName
Specifies a source control conversion program. If your source control conversion program is in a directory other than the current default directory, include a path with the program name.

You can also specify a source control conversion program in your configuration file by including a line using this syntax:

_SCCTEXT = cProgramName

Remarks

By default, _SCCTEXT contains Scctext.prg, a Visual FoxPro conversion program that handles translating Visual FoxPro binary files into text equivalents and back. These text files are used as the basis for comparing and merging versions of Visual FoxPro binary files through a source control application.

See Also

Projects Tab, Options Dialog Box | Data Conversion Functions | CREATEBINARY( ) Function


_SCREEN System Variable

Specifies properties and methods for the main Visual FoxPro window.

_SCREEN.PropertyName [= eValue]

-or-

_SCREEN.MethodName

Parameters

PropertyName
Specifies a property for the main Visual FoxPro window.
eValue
Specifies a value for the property.
MethodName
Specifies a method to execute for the main Visual FoxPro window.

Remarks

_SCREEN allows the main Visual FoxPro window to be manipulated as an object. Events procedures cannot be created for _SCREEN. _SCREEN is an object type system variable.

Beginning with Visual FoxPro 7, the Top, Height, Left, Width, and hWnd properties of _SCREEN apply only to the Visual FoxPro client area (the area where text can be displayed). In prior versions, the Top and Left properties referenced the entire Visual FoxPro application window. CLEAR WINDOWS or RELEASE WINDOWS also sets ReleaseType to 1. Closing the Windows Operating System will set ReleaseType to 2.

Note The value returned by _SCREEN.ReleaseType can differ from the value returned by other forms because it is the main Visual FoxPro window.

See Also

_SCREEN System Variable Properties, Methods and Events | MODIFY WINDOW | Form Object


_SCREEN System Variable Properties, Methods and Events

Properties

ActiveControl | ActiveForm | AlwaysOnBottom
AlwaysOnTop | Application | AutoCenter
BackColor | BaseClass | BorderStyle
BufferMode | Caption | Class
ClassLibrary | ClipControls | Closable
Comment | ControlBox | ControlCount
Controls | CurrentX | CurrentY
DataSession | DataSessionID | DefOLELCID Property
Desktop | DrawMode | DrawStyle
DrawWidth | Enabled | FillColor
FillStyle | FontBold | FontCharSet
FontItalic | FontName | FontOutline
FontShadow | FontSize | FontStrikeThru
FontUnderline | Forecolor | FormCount
Forms | HalfHeightCaption | Height
HelpContextID | HWnd | Icon
KeyPreview | Left | LockScreen
MaxButton | MaxHeight | MaxLeft
MaxTop | MaxWidth | MDIForm
MinButton | MinHeight | MinWidth
MousePointer | Movable | Name
Objects | ParentClass | Picture
ReleaseType | RightToLeft | ScaleMode
ShowTips | TabIndex | TabStop
Tag | Top | Visible
Width | WindowState | WindowType

Methods

AddObject | AddProperty | Box
Circle | Cls | Draw
Hide | Line | Move
Point | Print | Pset
Refresh | Release | RemoveObject
SaveAs | SaveAsClass | SetAll
Show | TextHeight | TextWidth
ZOrder |  |

Events

Activate | Click | DblClick
Deactivate | Destroy | DragDrop
DragOver | Error | GotFocus
Init | KeyPress | Load
LostFocus | MiddleClick Event | MouseDown
MouseMove | MouseUp | MouseWheel
Moved | OLECompleteDrag | OLEDragDrop
OLEDragOver | OLEGiveFeedBack | OLESetData
OLEStartDrag | Paint | QueryUnload
Resize | RightClick | Scrolled
Unload |  |

Example 1

The following example demonstrates how to hook into _SCREEN methods.

*
* Use the following to modify _SCREEN methods:
*
* For VFP6 & 7:
*
     _SCREEN.NewObject("oSH","ScreenHook","screenmethods.prg")
*
* For VFP3 & 5:
*
*     SET PROCEDURE TO screenmethods ADDITIVE
*     _SCREEN.AddObject("oSH","ScreenHook")
*
* Any of the main VFP screen methods can be hooked into in this manner.
*
DEFINE CLASS ScreenHook AS CUSTOM
 oScr = _SCREEN
 PROCEDURE oScr.RESIZE()
  *
  * Code to handle the main VFP screen being resized
  *
  WAIT WINDOW NOWAIT TRANSFORM(THIS.WIDTH)+" "+TRANSFORM(THIS.HEIGHT)
 ENDPROC
 PROCEDURE oScr.moved()
  *
  * Code to handle the main VFP screen being resized
  *
  WAIT WINDOW NOWAIT "moved"
 ENDPROC
 PROCEDURE oScr.RIGHTCLICK
  *
  * Code to do a "shortcut" menu on main VFP screen RightClick
  *
  * DO ..\menus\testmenu.mpr
 ENDPROC
 *
 * Custom methods work, too.
 *
 PROCEDURE oScr.MyMethod
  WAIT WINDOW "my method fired!"
 ENDPROC
ENDDEFINE

Example 2

The following example demonstrates the use of _SCREEN to customize the main Visual FoxPro window.

* Local variables to store current settings
Local oldScreenLeft
Local oldScreenTop
Local oldScreenHeight
Local oldScreenWidth
Local oldScreenColor
WITH _Screen
 oldScreenLeft=.Left       && Save current position and size
 oldScreenTop=.Top
 oldScreenHeight=.Height
 oldScreenWidth=.Width
 oldScreenColor = .Backcolor
 .LockScreen=.T.       && Disable screen redraw
 .BackColor=rgb(192,192,192)   && Change the background to grey
 .BorderStyle=2        && Change the border to double
 .Closable=.F.         && Remove window control buttons
 .ControlBox=.F.
 .MaxButton=.F.
 .MinButton=.T.
 .Movable=.T.
 .Height=285
 .Width=550
 .Caption="Custom Screen"    && Set a caption
 .LockScreen=.F.       && Enable screen redraw
ENDWITH
=MESSAGEBOX("Return to normal  ",48,WTITLE())
With _Screen
 .Left = oldScreenLeft     && Reset original
 .Top = oldScreenTop       && position and size
 .Height = oldScreenHeight
 .Width  = oldScreenWidth
 .BackColor=oldScreenColor     && Change background to white
 .LockScreen=.T.       && Disable screen redraw
 .BorderStyle=3        && Change border to sizeable
 .Closable=.T.         && Reset window control buttons
 .ControlBox=.T.
 .MaxButton=.T.
 .MinButton=.T.
 .Movable=.T.
 .Caption="Microsoft Visual FoxPro"  && Reset the caption
 .LockScreen=.F.       && Enable screen redraw
Endwith

See Also

_SCREEN System Variable | MODIFY WINDOW | Form Object


_SHELL System Variable

Specifies a program shell.

_SHELL = cCommand

Remarks

The _SHELL system memory variable is used to prevent access to the Command window while a program is running in Visual FoxPro. The DO command with the name of a program to execute is usually stored to _SHELL.

You can also specify a command to execute when Visual FoxPro is started by placing the SHELL configuration item in your Visual FoxPro configuration file.

The following example demonstrates how _SHELL typically can be used.

  1. A startup program named Mystart.prg is used to launch another program named Myapp.prg. Mystart.prg stores the command to run Myapp.prg to _SHELL. This starts Myapp.prg. Before Visual FoxPro displays the Command window, _SHELL is checked for a command. If _SHELL contains a command, it is executed and Visual FoxPro then stores the empty string to _SHELL.
  2. After the initialization code in Myapp.prg is successfully executed, the command to launch Myapp.prg is stored again to _SHELL. Visual FoxPro does not execute the command or store the empty string to _SHELL, and access to the Command window is prevented. (The Command window cannot be accessed when _SHELL contains anything but the empty string).
  3. Before Myapp.prg finishes execution, it stores the empty string to _SHELL to restore access to the Command window.
    *** MYSTART.PRG ***
...
_SHELL = "DO MYAPP.PRG"

*** MYAPP.PRG ***
*** Initialization Code ***
...
*** Initialization Code successfully completed? ***
_SHELL = "DO MYAPP.PRG" && Prevents access to Command window
...
*** Clean up Code ***
_SHELL = ""

See Also

DO Command | RUN | ! | _STARTUP System Variable


_SPELLCHK System Variable

Specifies a spelling checker program for the Visual FoxPro text editor.

_SPELLCHK = ProgramName

Parameters

ProgramName
Specifies a spelling checker program. If your spelling checker program is in a directory other than the current default directory, include a path with the program name.

You can also specify a spelling checker program in your Visual FoxPro configuration file. Include the line:

_SPELLCHK = ProgramName

Remarks

By default, _SPELLCHK is unassigned. You can use a spelling checking program by providing the program name and its path in _SPELLCHK. Once you specify a program programmatically or in the File Locations tab of the Tools, Options menu, access the program with the DO command as in the following sample.

DO Spellchk

See Also

MODIFY COMMAND | MODIFY FILE | MODIFY MEMO


_STARTUP System Variable

Specifies the name of the application that runs when you start Visual FoxPro.

_STARTUP = ProgramName

Parameters

ProgramName
Specifies the application that is run when you start Visual FoxPro. You must include _STARTUP in your Visual FoxPro configuration file.

You can also specify a command or program to run when Visual FoxPro starts by including one of the following in your configuration file:

COMMAND = cVisualFoxProCommand

- Or -

COMMAND = DO ProgramName

A startup application specified with _STARTUP always runs before a command or program specified with COMMAND in your configuration file.

Remarks

You can also specify a startup application in the Files Location tab of the Options dialog.

See Also

DO Command | Options Dialog Box


_TALLY System Variable

Contains the number of records processed by the most recently executed table command.

_TALLY = nRecords

Parameters

nRecords
Contains a numeric value indicating the number of records processed by the most recently executed table command.

Remarks

Certain table processing commands return information about their status ("talk") while they execute. When such a command finishes executing, it displays the number of records it processed (if SET TALK is ON), and stores this number to the _TALLY system variable.

The following commands return status information:

APPEND FROM | AVERAGE
CALCULATE | COPY TO
COUNT | DELETE
DELETE - SQL | INDEX
INSERT - SQL (Used with SELECT) | PACK
REINDEX | REPLACE
REQUERY | SELECT - SQL
SORT | SUM
TOTAL | UPDATE
UPDATE - SQL |

When you start Visual FoxPro, _TALLY is set to 0. Executing one of the commands above replaces the _TALLY value with the number of records the command processed.

Example

This example uses SELECT to return the number of customers in the USA. The result is automatically stored to _TALLY. The _TALLY value is displayed.

SELECT * FROM customer ;
   WHERE country = 'USA' ;
   INTO CURSOR temp
? _TALLY

See Also

SET ODOMETER | SET TALK | SELECT


_TASKLIST System Variable

This system variable contains the name of the task list manager program.

_TASKLIST = cTasklistApplication

Parameters

cTasklistApplication
Name of the Visual FoxPro program that manages the task list information. The task list manager program enables you to manage the list of persistent bookmarks (Tasklist Shortcuts) for an open document, and to add or delete task list items.

Task list items are records in foxtask.dbf that contain timestamp, filename, class, method, line number and line contents information.

Remarks

By default, _TASKLIST contains tasklist.app, installed in your Windows user application folder or HOME( ) location. You can specify a different name for the task list manager application.

The main difference between persistent bookmarks (Shortcuts) and Bookmarks is that Shortcuts are available between editing sessions.

See Also

Task List Manager | _FoxTask System Variable | System Variables A-Z | System Variables Overview


_TASKPANE System Variable

Contains the path and file name for the Visual FoxPro Task Pane Manager.

_TASKPANE = cPath

Parameters

cPath
Specifies the complete path and file name for the Visual FoxPro Task Pane Manager.

Remarks

_TASKPANE specifies the path and file name for the Visual FoxPro Task Pane Manager. This path is usually your Visual FoxPro root directory, and the file name is usually Taskpane.app.

You can specify a path and file name for _TASKPANE on the File Locations tab in the Options dialog box. For more information, see File Locations and Options Dialog Box.

See Also

System Variable | System Variables Overview | Task Pane Manager


_TEXT System Variable

Directs output from the \ | \\ and TEXT ... ENDTEXT text merge commands to a low-level file.

_TEXT = nFileHandle

Parameters

nFileHandle
Specifies a numeric value that determines the low-level file to which output is directed.

Remarks

\ | \\ and TEXT ... ENDTEXT facilitate the merging of text with the contents of tables, memory variables, and the results of functions and expressions. Output generated by these text merge commands can be directed to the screen or a window or to a low-level file. The _TEXT system memory variable lets you direct text merge output from these commands to a low-level file.

To send output from the \ and \\ and TEXT ... ENDTEXT text merge commands to a low-level file, include the TO FileName clause in SET TEXTMERGE. The file handle of FileName is stored to _TEXT. If the file handle of another low-level file was previously stored in _TEXT, that low-level file is closed.

FCREATE( ) creates and opens low-level files and FOPEN( ) opens existing files. These functions return a positive file handle if the file is successfully created or opened. Storing this file handle to _TEXT directs any subsequent output from the \, \\ and TEXT ... ENDTEXT text merge commands to the file. Use STORE or = to store a file handle to _TEXT. You must open a low-level file with write privileges in order for it to accept output from the text merge commands.

You can close low-level files with FCLOSE( ) or CLOSE ALL. You can also use SET TEXTMERGE TO without a file name to close the low-level file whose handle is stored in _TEXT.

The startup default value of _TEXT is –1. If you are directing text merge output to a file whose file handle is stored in _TEXT, you can turn off the output to that file without closing the file by storing –1 to _TEXT. By storing different file handles and –1 to _TEXT, you can direct text merge output to alternate files.

Example

The following program demonstrates how to direct text merge output to alternate files:

SET TALK OFF
SET TEXTMERGE ON NOSHOW      && Enable text merge, no output to screen
SET TEXTMERGE DELIMITERS TO   && Default text merge delimiters <<,>>
SET TEXTMERGE TO date.txt   && Create and send output to date.txt
STORE _TEXT TO gcDateHandle   && Save date.txt's file handle
STORE -1 TO _TEXT         && Output off to date.txt; keep it open
SET TEXTMERGE TO time.txt   && Create and send output to time.txt
STORE _TEXT TO gcTimeHandle   && Save time.txt's file handle
*** Send the following text to time.txt ***
\The time is:
STORE gcDateHandle TO _TEXT    && Now direct output to date.txt
*** Send the following text to date.txt ***
\Today's date is:
STORE gcTimeHandle TO _TEXT   && Now direct output to time.txt
*** Output the time on the same line ***
\\ <<TIME( )>>
STORE gcDateHandle TO _TEXT   && Now direct output to date.txt
*** Output the date on the same line ***
\\ <<DATE( )>>
CLOSE ALL  && Close all files
TYPE date.txt  && See what's in this file...
WAIT WINDOW  && Pause
TYPE time.txt  && ...and what's in this file
ERASE date.txt
ERASE time.txt

See Also

\ | \\ | FOPEN( ) | FCLOSE( ) | FCREATE( ) | _PRETEXT | SET TEXTMERGE | SET TEXTMERGE DELIMITERS | System Variables A-Z | System Variables Overview


_THROTTLE System Variable

Specifies the execution speed of programs when the Trace window is open.

_THROTTLE = nSeconds

Parameters

nSeconds
Specifies the delay in seconds between execution of each program line. The startup default value is 0, with no pause between execution of program lines. nSeconds can range from 0 to 5.5 seconds. For example, if nSeconds is 0.5 seconds, a 1/2-second delay occurs between execution of program lines.

Remarks

The Trace window, one of the debugging tools available in Visual FoxPro, displays a program's source code as the program executes. The Trace window highlights each line in the program when the line executes. The numeric value of _THROTTLE determines the delay between execution of each program line when the Trace window is open.

Note The Trace Between Breaks option on the Trace window's Program menu must be on for a delay to occur.

See Also

SET DEBUG | SET STEP | Trace Window


_TOOLBOX System Variable

Contains the path and file name for the Visual FoxPro Toolbox. _TOOLBOX specifies the path and file name for the Visual FoxPro Toolbox. This path is usually the Visual FoxPro root directory, and the file name is usually Toolbox.app.

_TOOLBOX = cPath

Parameters

cPath
Specifies the complete path and file name for the Visual FoxPro Toolbox.

Remarks

You can specify a path and file name for _TOOLBOX on the File Locations tab in the Options dialog box. For more information, see File Locations Tab, Options Dialog Box.

See Also

System Variables | System Variables Overview | Toolbox


_TRIGGERLEVEL System Variable

Contains a read-only numeric value indicating the current trigger procedure nesting level.

_TRIGGERLEVEL = nExpression

Parameters

nExpression
Contains the current trigger procedure nesting level. _TRIGGERLEVEL contains 1 when the initial trigger procedure is executing. If a trigger procedure causes another trigger procedure to fire, _TRIGGERLEVEL is incremented by 1. _TRIGGERLEVEL contains 0 if a trigger procedure is not executing.

Remarks

Use CREATE TRIGGER to create a Delete, Insert, or Update trigger for a table. You can use APPEND PROCEDURES and MODIFY PROCEDURES to create stored procedures that are executed when a Delete, Insert, or Update trigger occurs.

_TRIGGERLEVEL contains a numeric value that is read-only. If you use STORE or = to assign a value to _TRIGGERLEVEL, the value is ignored.

See Also

APPEND PROCEDURES | CREATE TRIGGER | MODIFY PROCEDURE


_UNIX System Variable

Contains true (.T.) if you are using FoxPro for UNIX.

_UNIX = lExpression

Remarks

The _UNIX system variable contains true (.T.) if you are using FoxPro for UNIX. _UNIX contains false (.F.) if you are using a different platform version of FoxPro or Visual FoxPro.

The value contained in _UNIX cannot be changed with STORE or =.

See Also

_DOS | _MAC | VERSION( ) | _WINDOWS


_VFP System Variable

References the Application object for the current instance of Visual FoxPro.

_VFP.PropertyName[ = eValue]

-or-

_VFP.Method

Parameters

PropertyName
Specifies a property for the application object.
eValue
Specifies a value for the property.
Method
Specifies a method to execute for the application object.

Remarks

_VFP provides access to the Objects and Projects collections.

Beginning with Visual FoxPro 7, the Top, Height, Left, Width, and hWnd properties of _VFP apply only to main Visual FoxPro window properties. In prior versions of Visual FoxPro, the Height and Width properties referred to those of the Visual FoxPro client area (area where text can be displayed). Now, the Top, Height, Left, and Width properties of _SCREEN are those of the Visual FoxPro Client area.

See Also

_VFP System Variable Properties, Methods and Events | Application Object | CREATEOBJECT( ) | _SCREEN System Variable Properties, Methods and Events | System Variables A-Z | System Variables Overview

Applies To: Projects Collection


_VFP System Variable Properties, Methods, and Events

Properties

ActiveForm | ActiveProject | Application
AutoYield | Caption | Count
DefaultFilePath | EditorOptions | Forms
FullName | Height | HWND
LanguageOptions | Left | Name
Objects Collection | OLERequestPendingTimeout | OLEServerBusyRaiseError
OleServerBusyTimeout | Parent | ProcessID
Projects Collection | ServerName | StartMode
StatusBar | ThreadID | Top
Version | VFPXMLProgID | Visible
Width |  |

Methods

DataToClip | DoCmd | Eval
Help | Item | Quit
RequestData | SetVar |

See Also

_VFP System Variable | Application Object | CREATEOBJECT( ) | Objects Collection | Projects Collection


_WINDOWS System Variable

Contains true (.T.) if you are using Visual FoxPro for Windows.

_WINDOWS = lExpression

Remarks

_WINDOWS contains false (.F.) if you are using a different platform version of FoxPro or Visual FoxPro.

The value contained in _WINDOWS cannot be changed with STORE or =.

See Also

_DOS | _MAC | _UNIX | VERSION( )


_WIZARD System Variable

Contains the name of the Visual FoxPro wizard application.

_WIZARD = cProgramName

Parameters

cProgramName
Specifies a wizard application. If your wizard application is in a directory other than the current Visual FoxPro default directory, include a path with the application name.

You can also specify a wizard application in your Visual FoxPro configuration file by including a line using the following syntax:

_WIZARD = cProgramName

Remarks

The _WIZARD system variable contains the name of the application that Visual FoxPro uses when you choose a wizard to run. By default, _WIZARD contains Wizard.app, installed in your Visual FoxPro directory. You can specify a different name for the wizard application.

See Also

System Variables Overview | Wizards Overview


API Library Construction

This section includes topics on API library routines, system events, and key codes.

In This Section

API Library Routines A-Z
Contains an alphabetical listing of the API Library Routines.
API Library Routines by Category
Contains a categorized list of the API Library Routines.
Visual FoxPro System Events (API Library Construction)
Lists each Microsoft Visual FoxPro event along with the layout of its event record fields and a description of when the event occurs.
Visual FoxPro Key Codes (API Library Construction)
Provides information about keyboard keys and how Visual FoxPro interprets them depending on the modifier with which they are combined.

Related Sections

Accessing the Visual FoxPro API
Describes how you can write your own Microsoft ActiveX control or Visual FoxPro -specific dynamic-link library (.fll file). By calling the functions available in the API available in Visual FoxPro, you can create controls or libraries that are tightly integrated with and optimized for use in Visual FoxPro
Extending Visual FoxPro with External Libraries
Discusses how you can add Microsoft ActiveX controls (.ocx files) to your application easily, providing you with new objects to use in forms, to subclass, and to manage the way you work with native Visual FoxPro controls.
Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


API Library Routines A-Z

A

_ActivateHandler( )

_ActivateIdle( )

_ActivateMenu( )

_ALen( )

_Alloca( )

_AllocHand( )

_AllocMemo( )

B

_BreakPoint( )

C

_CountItems( )

D

_DBAppend( )

_DBLock( )

_DBRead( )

_DBRecCount( )

_DBRecNo( )

_DBReplace( )

_DBRewind( )

_DBSeek( )

_DBSkip( )

_DBStatus( )

_DBUnlock( )

_DBUnwind( )

_DBWrite( )

_DeActivateHandler( )

_DeActivateIdle( )

_DeActivateMenu( )

_DefaultProcess( )

_Dialog( )

_DisposeItem( )

_DisposeMenu( )

E

_EdActive( )

_EdCloseFile( )

_EdCopy( )

_EdCut( )

_EdDelete( )

_EdGetChar( )

_EdGetEnv( )

_EdGetLineNum( )

_EdGetLinePos( )

_EdGetPos( )

_EdGetStr( )

_EdIndent( )

_EdInsert( )

_EdLastError( )

_EdOpenFile( )

_EdPaste( )

_EdPosInView( )

_EdRedo( )

_EdRevert( )

_EdSave( )

_EdScrollToPos( )

_EdScrollToSel( )

_EdSelect( )

_EdSendKey( )

_EdSetEnv( )

_EdSetPos( )

_EdSkipLines( )

_EdUndo( )

_EdUndoOn( )

_Error( )

_ErrorInfo( )

_Evaluate( )

_Execute( )

F

_FCHSize( )

_FClose( )

_FCopy( )

_FCreate( )

_FEOF( )

_FError( )

_FFlush( )

_FGets( )

_FindMemo( )

_FindVar( )

_FindWindow( )

_FindWindowP( )

_FOpen( )

_FPuts( )

_FRead( )

_FreeHand( )

_FreeObject( )

_FSeek( )

_FWrite( )

G

_GetAPIHandle( )

_GetHandSize( )

_GetItemCmdKey( )

_GetItemId( )

_GetItemSubMenu( )

_GetItemText( )

_GetNewItemId( )

_GetNewMenuId( )

_GetNextEvent( )

_GetObjectProperty( )

_GlobalToLocal( )

_GlobalToLocalP( )

H

_HandToPtr( )

_HLock( )

_HUnLock( )

I

_InKey( )

J

K

L

_Load( )

M

_MemAvail( )

_MemCmp( )

_MemFill( )

_MemMove( )

_MemoChan( )

_MemoSize( )

_MenuId( )

_MenuInteract( )

_MousePos( )

_MousePosP( )

N

_NameTableIndex( )

_NewItem( )

_NewMenu( )

_NewVar( )

O

_ObjectCmp( )

_ObjectReference( )

_ObjectRelease( )

_OnSelection( )

P

_PutChr( )

_PutStr( )

_PutValue( )

Q

R

_Release( )

_RetChar( )

_RetCurrency( )

_RetDateStr( )

_RetDateTimeStr( )

_RetFloat( )

_RetInt( )

_RetLogical( )

_RetVal( )

S

_SetHandSize( )

_SetItemCmdKey( )

_SetItemSubMenu( )

_SetItemText( )

_SetMenuPoint( )

_SetMenuPointP( )

_SetObjectProperty( )

_Store( )

_StrCmp( )

_StrCpy( )

_StrLen( )

T

U

_UserError( )

V

W

_WAttr( )

_WBottom( )

_WBottomP( )

_WClear( )

_WClearRect( )

_WClearRectP( )

_WClose( )

_WFindTitle( )

_WGetCursor( )

_WGetCursorP( )

_WGetObjectClientWindow( )

_WGetObjectWindow( )

_WGetPort( )

_WHeight( )

_WHeightP( )

_WHide( )

_WhToHwnd( )

_WLeft( )

_WLeftP( )

_WMainWindow( )

_WMove( )

_WMoveP( )

_WOnTop( )

_WOpen( )

_WOpenP( )

_WPosCursor( )

_WPosCursorP( )

_WPutChr( )

_WPutStr( )

_WRight( )

_WRightP( )

_WScroll( )

_WScrollP( )

_WSelect( )

_WSendBehind( )

_WSetAttr( )

_WSetPort( )

_WSetTitle( )

_WShow( )

_WSize( )

_WSizeP( )

_WTitle( )

_WTop( )

_WTopP( )

_WWidth( )

_WWidthP( )

_WZoom( )

X

Y

Z

Send feedback on this topic to Microsoft

For technical support and product issues, see the "Microsoft Visual FoxPro Technical Support" topic..

© 1992 - 2003 Microsoft Corporation. All rights reserved.


_ActivateHandler( ) API Library Routine

Adds a handler function to the end of the list of event handlers.

unsigned int _ActivateHandler(FPFI handler)
FPFI handler               /* Event handler to be added. */

Remarks

_ActivateHandler( ) returns an integer identifier for this handler. Use this identifier to remove the handler from the event processor list with _DeActivateHandler( ).

The handler is invoked with two parameters: the WHANDLE of the window to which the event belongs, and a FAR (32-bit) pointer to an event record. If your handler doesn't look for an event, or modifies an event for subsequent event handlers, it returns False (0) to indicate that the event must still be passed on to other handlers or to the Visual FoxPro interface routines. If the handler determines that the event doesn't need to be passed on, it returns True (an integer other than 0) to indicate that the event has been handled.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example activates an event handler when the library is loaded. The event handler prints a message for every event and lets Visual FoxPro process the event as it does normally. The event handler is deactivated when the library is unloaded.

Visual FoxPro Code

SET LIBRARY TO ACTIHAND
WAIT WINDOW TO m.test TIMEOUT 5
SET LIBRARY TO

C Code

#include <pro_ext.h>

static int HandlerID;

//   This is the routine that is registered as an event handler.
FAR EventHandler(WHandle theWindow, EventRec FAR *ev)
{
   _PutStr("\nEventHandler() called.");
   return NO;   // event still needs to be handled by Visual FoxPro
}

FAR Activate()
{
   HandlerID = _ActivateHandler(EventHandler);
}

//   When the library is unloaded we must deactivate the event handler
//   in a CALLONUNLOAD function.
FAR DeActivate()
{
   _DeActivateHandler(HandlerID);
}

FoxInfo myFoxInfo[] = {
   {"ACTIVATE",  Activate,   CALLONLOAD, ""},
   {"DEACTIVATE", DeActivate, CALLONUNLOAD, ""}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DeActivateHandler( ) API Library Routine | _FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePos( ) API Library Routine | Event Handlers | EventHandler( ) Function


_ActivateIdle( ) API Library Routine

Adds an idle handler function to the end of the list of idle event handlers called when Visual FoxPro is waiting for user input or for an event to time out.

unsigned int _ActivateIdle(FPFI handler)
FPFI handler               /* Event handler. */

Remarks

_ActivateIdle( ) returns an integer identifier for this routine. Use the identifier to remove the idle event handler from the idle loop with _DeActivateIdle( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example activates an idle event handler when the library is loaded. The idle event handler just prints a message. The idle event handler is deactivated when the library is unloaded.

Visual FoxPro Code

SET LIBRARY TO ACTIIDLE
WAIT WINDOW TO m.test TIMEOUT 5
SET LIBRARY TO

C Code

#include <pro_ext.h>

static unsigned IdlerID;

//   This is the routine that is registered as an idle event handler.
void FAR IdleHandler(WHandle wh, EventRec *ev)
{
   _PutStr("\nIdleHandler() called.");
}

void FAR Activate(ParamBlk FAR *parm)
{
   IdlerID = _ActivateIdle((FPFI) IdleHandler);
}

//   When the library is unloaded we must deactivate the idle event
//   handlerin a CALLONUNLOAD function.
void FAR DeActivate(ParamBlk FAR *parm)
{
   _DeActivateIdle(IdlerID);
}

FoxInfo myFoxInfo[] = {
   {"ACTIVATE",  (FPFI) Activate, CALLONLOAD,   ""},
   {"DEACTIVATE",  (FPFI) DeActivate, CALLONUNLOAD, ""}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DeActivateIdle( ) API Library Routine | _FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePos( ) API Library Routine | Event Handlers | EventHandler( ) Function


_ActivateMenu( ) API Library Routine

Displays the specified menu on the screen and immediately returns control to the calling routine.

void _ActivateMenu(MENUID menuid)
MENUID menuid            /* Menu identifier.

Remarks

If you detect the press of a mouse button or a keystroke on the menu, you can call _MenuInteract( ) to determine which menu item the user chose.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a menu with three items. _ActivateMenu( ) displays the menu. This menu is non-modal in that interaction is not forced as with _MenuInteract( ). Rather, when the user makes a selection the _OnSelection( ) routine is called, the selected item is printed on the screen, and the menu is disposed of.

Visual FoxPro Code

SET LIBRARY TO ACTIMENU
WAIT WINDOW "Make selection from menu." NOWAIT
SUSPEND

C Code

#include <pro_ext.h>

static MENUID menuId;

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
}

FAR deactivateMenu(ParamBlk FAR *parm)
{
   _DeActivateMenu(menuId);
   _DisposeMenu(menuId);
}

FAR activateMenu(ParamBlk FAR *parm)
{
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _OnSelection(menuId, -1, onSelection);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) activateMenu, CALLONLOAD, ""},
   {"ONUNLOAD", (FPFI) deactivateMenu, CALLONUNLOAD, ""},
};

FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DeActivateMenu( ) API Library Routine | _MenuId( ) API Library Routine | _NewItem( ) API Library Routine | _NewMenu( ) API Library Routine | _OnSelection( ) API Library Routine | _MenuInteract( ) API Library Routine | _OnSelection( ) API Library Routine


_ALen( ) API Library Routine

Returns information about the dimensions of the array whose name table index is nti.

long _ALen(NTI nti, int mode)
NTI nti;                     /* Array name table index. */
int mode;                     /* Mode to determine return value. */

Remarks

If mode is AL_ELEMENTS, _ALen( ) returns the total number of elements in the array. If mode is AL_SUBSCRIPT1, _ALen( ) returns the value of the first subscript used to declare the array. If mode is AL_SUBSCRIPT2, _ALen( ) returns the value of the second subscript used to declare the array.

If nti doesn't represent the name of an existing array, _ALen( ) returns – 1 regardless of the value of mode.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example provides a Visual FoxPro API routine for each of the three possible mode values.

Visual FoxPro Code

SET LIBRARY TO ALEN
DIMENSION a[10, 11]
? ALENELEM(@a)  && returns 110
? ALENSUB1(@a)  && returns 10
? ALENSUB2(@a)  && returns 11

DIMENSION b[3]
? ALENELEM(@b)  && returns 3
? ALENSUB1(@b)  && returns 3
? ALENSUB2(@b)  && returns 0; no second subscript

c = .F.
? ALENELEM(@c)  && returns -1 because variable "c" is not an array
? ALENSUB1(@c)  && returns -1 because variable "c" is not an array
? ALENSUB2(@c)  && returns -1 because variable "c" is not an array

C Code

#include <pro_ext.h>

void FAR alenElem(ParamBlk FAR *parm)
{
   _RetInt(_ALen(parm->p[0].loc.l_NTI, AL_ELEMENTS), 10);
}

void FAR alenSub1(ParamBlk FAR *parm)
{
   _RetInt(_ALen(parm->p[0].loc.l_NTI, AL_SUBSCRIPT1), 10);
}

void FAR alenSub2(ParamBlk FAR *parm)
{
   _RetInt(_ALen(parm->p[0].loc.l_NTI, AL_SUBSCRIPT2), 10);
}

FoxInfo myFoxInfo[] = {
   {"ALENELEM", (FPFI) alenElem, 1, "R"},
   {"ALENSUB1", (FPFI) alenSub1, 1, "R"},
   {"ALENSUB2", (FPFI) alenSub2, 1, "R"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindVar( ) API Library Routine | _Load( ) API Library Routine | _NameTableIndex( ) API Library Routine | _NewVar( ) API Library Routine | _ObjectRelease( ) API Library Routine | _Store( ) API Library Routine


_Alloca( ) API Library Routine

Allocates a block of stack space for the calling routine.

void FAR * _Alloca(unsigned int size)
unsigned int size;            /* Size of stack space to allocate in
bytes. */

Remarks

_Alloca( ) returns a pointer to the block if the block is successfully allocated, or returns zero if the block isn't allocated. _Alloca( ) automatically frees memory when the routine ends, so no corresponding release routine is necessary.

Caution Some C compilers, such as MPW C, do not support memory allocation from the stack; calls to _Alloca( ) using such compilers will have unpredictable results. Instead, use local variables, or calls to _AllocHand( ) and _FreeHand( ), in your code to reserve memory.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example duplicates the action of the Visual FoxPro REPLICATE( ) function. The memory temporarily used to duplicate the character comes from _Alloca( ).

Visual FoxPro Code

SET LIBRARY TO ALLOCA
x = xREPLICATE("x", 120)
? x
? LEN(x)

C Code

#include <pro_ext.h>

void FAR allocaEx(ParamBlk FAR *parm)
{
   char FAR *rep;
   char c = *(char *) _HandToPtr(parm->p[0].val.ev_handle);

   rep = _Alloca((int) parm->p[1].val.ev_long + 1);
   _MemFill(rep, c, (int) parm->p[1].val.ev_long);
  rep[parm->p[1].val.ev_long] = '\0';  // null terminate

   _RetChar(rep);
}

FoxInfo myFoxInfo[] =
{
   {"XREPLICATE", (FPFI) allocaEx, 2, "C,I"},
};

FoxTable _FoxTable =
{
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | REPLICATE( ) Function | Accessing the Visual FoxPro API


_AllocHand( ) API Library Routine

Returns a new MHANDLE of size hsize.

MHANDLE _AllocHand(unsigned int hsize)
unsigned int hsize;            /* Size of new memory handle in bytes. */

Remarks

_AllocHand( ) returns 0 when there is insufficient memory to fulfill the request. Memory allocated with _AllocHand( ) isn't initialized, and must be freed after use.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

In The following example, a character is replicated in memory supplied by _AllocHand( ). The API function REPLTOMH( ) below returns the memory handle to Visual FoxPro. From Visual FoxPro the memory handle is passed to API functions, which expect a memory handle argument (passed as an integer, "I").

Visual FoxPro Code

SET LIBRARY TO ALLOCHAN
mh = REPLTOMH("x", 120)
? MHTOFOX(mh)
? LEN(MHTOFOX(mh))
? MHTOFOX(mh)
= FREEMH(mh)

C Code

#include <pro_ext.h>

//   Replicate char argument to memory allocated with _AllocHand().
//   Return the memory handle to Visual FoxPro.
void FAR replToMH(ParamBlk FAR *parm)
{
   char FAR *rep;
   char c = *(char *) _HandToPtr(parm->p[0].val.ev_handle);
   MHANDLE mh;

   if ((mh = _AllocHand((int) parm->p[1].val.ev_long + 1)) == 0)
   {
      _Error(182);  // "Insufficient memory"
   }
   _HLock(mh);
   rep = _HandToPtr(mh);
   _MemFill(rep, c, (int) parm->p[1].val.ev_long);
   rep[parm->p[1].val.ev_long] = '\0';  // null terminate
   _HUnLock(mh);

   _RetInt(mh, 10);
}

//   Returns characters in memory handle.
//   Argument in call from Visual FoxPro
//   must be a valid Visual FoxPro memory handle.
void FAR MHToFoxString(ParamBlk FAR *parm)
{
   char FAR *string;
   MHANDLE mh = parm->p[0].val.ev_long;

   _HLock(mh);
   string = _HandToPtr(mh);
   _RetChar(string);
   _HUnLock(mh);
}

//   Frees memory handle.  Argument in call from
//   Visual FoxPro must be a valid
//   Visual FoxPro memory handle.
void FAR freeMH(ParamBlk FAR *parm)
{
   _FreeHand((MHANDLE) parm->p[0].val.ev_long);
}

FoxInfo myFoxInfo[] = {
   {"REPLTOMH", (FPFI) replToMH, 2, "C,I"},
   {"MHTOFOX", (FPFI) MHToFoxString, 1, "I"},
   {"FREEMH", (FPFI) freeMH, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) | _HUnLock( ) API Library Routine | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine


_AllocMemo( ) API Library Routine

Allocates size bytes of space in the memo file for a field and inserts the new block number in the associated record in the database.

long _AllocMemo(Locator FAR *fld, long size)
Locator FAR *fld;            /* Pointer to locator
 that defines the memo field. */
long size;                     /* Size of allocated space in bytes. */

Remarks

When _AllocMemo( ) is successful, it returns the location in the file to begin writing; otherwise, it returns – 1.

Caution Writing more than size bytes causes memo file corruption.

If you plan to replace a memo field using direct methods, be sure your routine calls _AllocMemo( ) before writing to the memo file, even if the new value is the same length or smaller than the original. This prevents problems in multiuser situations. _AllocMemo( ) reuses the previously allocated space when it's safe to do so.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates new memo field contents.

Visual FoxPro Code

SET LIBRARY TO ALLOMEMO
CREATE TABLE wMemo (memoField M)
APPEND BLANK
= NewMemo(@MemoField, "Hello, World.")
APPEND BLANK
= NewMemo(@MemoField, "Isn't this fun?")

C Code

#include <pro_ext.h>

FAR newMemo(ParamBlk FAR *parm)
{
   Locator FAR *memoFldLoc;
   FCHAN fchMemo;
   int memoLen;
   long loc;

   if ((fchMemo = _MemoChan(-1)) == -1)
   {
      _UserError("_MemoChan() failed");
   }
   memoFldLoc = &parm->p[0].loc;
   memoLen = parm->p[1].val.ev_length;

   if ((loc = _AllocMemo(memoFldLoc, memoLen)) == -1)
   {
      _UserError("_AllocMemo() failed");
   }
   _FSeek(fchMemo, loc, FS_FROMBOF);
   _HLock(parm->p[1].val.ev_handle);
   _FWrite(fchMemo, _HandToPtr(parm->p[1].val.ev_handle), memoLen);
   _HUnLock(parm->p[1].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"NEWMEMO", (FPFI) newMemo, 2, "R,C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBReplace( ) API Library Routine | _FindMemo( ) API Library Routine | _MemoChan( ) API Library Routine | _MemoSize( ) API Library Routine | Accessing the Visual FoxPro API


_BreakPoint( ) API Library Routine

_BreakPoint( ) is a macro that generates the debugger breakpoint instruction, INT 3. This can be helpful for debugging external routines.

void _BreakPoint(void any)
void any;                     /* Pointer. */

Remarks

When a _BreakPoint( ) call is encountered, control transfers to your debugger. Most debuggers return control to the program line that includes the INT3 instruction, and you have to manually increment the instruction pointer (IP) past this instruction. At that time you can use your debugger to set additional breakpoints. Always remove any breakpoints before exiting the external routine. For more information about debugging, see Accessing the Visual FoxPro API.

Example

The following example uses the macro _BreakPoint( ) to place an INT 3 that debuggers recognize as a breakpoint.

Visual FoxPro Code

SET LIBRARY TO BPOINT

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int RetValue;

   _BreakPoint(); // debugger breaks execution here

   _HLock(parm->p[0].val.ev_handle);
   _HLock(parm->p[1].val.ev_handle);

   RetValue = _StrCmp(_HandToPtr(parm->p[0].val.ev_handle),
      _HandToPtr(parm->p[1].val.ev_handle));

   _RetInt(RetValue, 10); // does return control here

   _HUnLock(parm->p[0].val.ev_handle);
   _HUnLock(parm->p[1].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"STRCMP", (FPFI) Example, 2, "C,C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Accessing the Visual FoxPro API | Debugging Routines | Debugging and Error Handling


_CountItems( ) API Library Routine

Returns the number of menu titles or bars on the specified menu.

int _CountItems(MENUID menuid)
MENUID menuid;            /* Menu identifier. */

Example

The following example creates a menu with three items, and calls _CountItems( ) to show that the function correctly returns the number of items on the menu. The routine then disposes of menu items, and calls _CountItems( ) again.

Visual FoxPro Code

SET LIBRARY TO CNTITEMS

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR CountItemsEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _PutStr("\n_CountItems() ="); putLong(_CountItems(menuId));
   _Execute("WAIT");

   _DisposeItem(menuId, _GetItemId(menuId, 1));
   _PutStr("\n_CountItems() ="); putLong(_CountItems(menuId));
   _Execute("WAIT");

   _DisposeItem(menuId, _GetItemId(menuId, 0));
   _PutStr("\n_CountItems() ="); putLong(_CountItems(menuId));
   _Execute("WAIT");

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) CountItemsEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetNewMenuId( ) API Library Routine | _GetNewMenuId( ) API Library Routine | _NewMenu( ) API Library Routine | Creating Menus, Shortcut Menus, Menu Items, and Submenus


_DBAppend( ) API Library Routine

Attempts to append a new record to the table open in the specified workarea.

int _DBAppend(int workarea, int carryflag)
int workarea;               /* Work area number. */
int carryflag;               /* SET CARRY setting. */

Remarks

The current work area is represented by – 1. _DBAppend( ) returns 0 if the routine is successful. If the routine fails, _DBAppend( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

Values for carryflag

Value | Effect
1 | Carries information from the previous record into the new record.
0 | Makes the new record blank.
– 1 | Uses the setting of SET CARRY to determine whether information from the previous record is carried to the new record.

_DBAppend( ) automatically performs any necessary locking. If it's unable to lock the file header, _DBAppend( ) fails and returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _DBAppend( ) to append a record to the table open in the current work area.

Visual FoxPro Code

SET LIBRARY TO DBAPPEND
DO CreateTest

SET CARRY ON
= DBAPPEND(-1)   && SET CARRY is ON, so carry
SET CARRY OFF
= DBAPPEND(1)   && carry regardless of SET CARRY
= DBAPPEND(-1)   && SET CARRY is OFF, so no carry

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "Golly month of"
   APPEND BLANK
   REPLACE ABC WITH "A twelfth of"
   APPEND BLANK
   REPLACE ABC WITH "Hello, world"
   APPEND BLANK
   REPLACE ABC WITH "When in the"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int RetCode;
   if ((RetCode = _DBAppend(-1, (int) parm->p[0].val.ev_long)) < 0) {
      _Error(-RetCode);
   }
}

FoxInfo myFoxInfo[] = {
   {"DBAPPEND", (FPFI) Example, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBLock( ) API Library Routine | _DBUnlock( ) API Library Routine | Appending Data to an Existing Table | SET CARRY Command | APPEND Command


_DBLock( ) API Library Routine

Attempts to lock the current record or the table open in the work area specified by workarea.

int _DBLock(int workarea, int RecOrFile)
int workarea;               /* Work area. */
int RecOrFile;               /* What is to be locked. */

Remarks

The RecOrFile parameter can be DBL_RECORD, to specify the current record, or DBL_FILE, to specify the table file. _DBLock( ) returns True (an integer other than 0) if the lock is successful, or False (0) if the lock isn't successful.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example provides two API functions you can call from Visual FoxPro: XRLOCK( ), which locks the current record of the current work area; and XFLOCK( ), which locks the table open in the current work area. XRLOCK( ) calls _DBLock( – 1, DBL_RECORD( )), and XFLOCK( ) calls _DBLock( – 1, DBL_FILE( )).

Visual FoxPro Code

SET LIBRARY TO DBLOCK
DO CreateTest
USE Test SHARED
GO 2
= XRLOCK()
LIST STAT  && shows that record #2 is locked
= XFLOCK()
LIST STAT  && shows that whole DBF is locked

PROCEDURE CreateTest

CREATE TABLE test (ABC C(20))
APPEND BLANK
REPLACE ABC WITH "Golly month of"
APPEND BLANK
REPLACE ABC WITH "A twelfth of"
APPEND BLANK
REPLACE ABC WITH "Hello, world"
APPEND BLANK
REPLACE ABC WITH "When in the"
GO TOP

RETURN

C Code

#include <pro_ext.h>

FAR xLockRecord(ParamBlk FAR *parm)
{
   _DBLock(-1, DBL_RECORD);
}

FAR xLockFile(ParamBlk FAR *parm)
{
   _DBLock(-1, DBL_FILE);
}

FoxInfo myFoxInfo[] =
{
   {"XRLOCK", (FPFI) xLockRecord, 0, ""},
   {"XFLOCK", (FPFI) xLockFile, 0, ""},
};

FoxTable _FoxTable =
{
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBAppend( ) API Library Routine | _DBUnlock( ) API Library Routine | Accessing the Visual FoxPro API | Passing of Parameters to Visual FoxPro API Functions


_DBRead( ) API Library Routine

Moves the current record pointer to the specified record in the specified work area.

int _DBRead(int workarea, long record)
int workarea;               /* Work area. */
long record;                  /* Record number. */

Remarks

_DBRead( ) returns 0 if the routine is successful. If the routine fails, _DBRead( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

Specifying 0 for record is equivalent to issuing GO TOP; specifying – 1 for record is equivalent to issuing GO BOTTOM.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example provides similar functionality to that of the Visual FoxPro command GO. XGO(n) moves the current record pointer to record number n in the current work area.

Visual FoxPro Code

SET LIBRARY TO DBREAD
DO CreateTest
USE Test SHARED
GO BOTTOM
? RECNO()
= XGO(2)
? RECNO()

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _DBRead(-1, parm->p[0].val.ev_long);
}

FoxInfo myFoxInfo[] = {
   {"XGO", (FPFI) Example, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRewind( ) API Library Routine | _DBSkip( ) API Library Routine | _DBUnwind( ) API Library Routine | GO | GOTO Command


_DBRecCount( ) API Library Routine

Returns the total number of records in the table open in the specified work area.

long _DBRecCount(int workarea)
int workarea;               /* Work area. */

Remarks

If no table is open in the specified work area, _DBRecCount( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example calls _DBRecCount( ) to count the number of records in the table open in the current work area.

Visual FoxPro Code

SET LIBRARY TO DBRECCNT
DO CreateTest
? DBRECCOUNT()   && call API routine
? RECCOUNT()   && call built-in Visual FoxPro Function

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_DBRecCount(-1), 10);
}

FoxInfo myFoxInfo[] = {
   {"DBRECCOUNT", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRecNo( ) API Library Routine | Accessing the Visual FoxPro API | Working with Records | Records | Working with Fields and Records


_DBRecNo( ) API Library Routine

Returns the number of the current record in the table open in the specified work area.

long _DBRecNo(int workarea)
int workarea;               /* Work area. */

Remarks

If no table is open in the specified work area, _DBRecNo( ) returns a negative integer whose absolute value is a Visual FoxPro error number. If the record pointer is at the end of file, _DBRecNo( ) returns a number that is 1 greater than that returned by _DBRecCount( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example provides functionality similar to that of the Visual FoxPro RECNO( ) function.

Visual FoxPro Code

SET LIBRARY TO DBRECNO
DO CreateTest
GO 3
? DBRECNO()
GO 6
? DBRECNO()
USE
? DBRECNO()  && returns -119

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   APPEND BLANK
   REPLACE ABC WITH "This is record 5"
   APPEND BLANK
   REPLACE ABC WITH "This is record 6"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_DBRecNo(-1), 10);
}

FoxInfo myFoxInfo[] = {
   {"DBRECNO", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRecCount( ) | Accessing the Visual FoxPro API | Working with Records | Records | Working with Fields and Records


_DBReplace( ) API Library Routine

_DBReplace( ) places a new value in a field.

int _DBReplace(Locator FAR *fld, Value FAR *val)
Locator FAR *fld;            /* Field to be replaced. */
Value FAR *val;            /* Value to be placed in field. */

Remarks

_DBReplace( ) returns 0 if the replacement is successful. If the replacement fails, _DBReplace( ) returns a negative integer whose absolute value is a Visual FoxPro error number. _DBReplace( ) can be used on a memo field to replace its value with a new value that's shorter than 65,000 bytes. To perform operations on memo fields that are larger than 65,000 bytes, you must use direct memo field routines and buffered file input/output routines.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example provides functionality similar to the Visual FoxPro REPLACE command, but replaces the value of only one record at a time.

Visual FoxPro Code

SET LIBRARY TO DBREPLAC
DO CreateTest
? DBREPLACE(@ABC, "Replacement record 1")
? DBREPLACE(@ABC, 2)  && returns -302 - field ABC is character field

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_DBReplace(&parm->p[0].loc, &parm->p[1].val), 10);
}

FoxInfo myFoxInfo[] = {
   {"DBREPLACE", (FPFI) Example, 2, "R,?"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBLock( ) API Library Routine | _DBUnlock( ) API Library Routine | REPLACE Command | Accessing the Visual FoxPro API


_DBRewind( ) API Library Routine

Works like the Visual FoxPro GO TOP command in the specified work area, and then returns the current record number.

long _DBRewind(int workarea)
int workarea;               /* Work area. */

Example

The following example calls _DBRewind( ) for the table open in the current work area. This has the same effect as the Visual FoxPro GO TOP command.

Visual FoxPro Code

SET LIBRARY TO DBREWIND
DO CreateTest
GO BOTTOM
? RECNO()
? DBREWIND()    && returns 1
? RECNO()  && yes, we're at record 1

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_DBRewind(-1), 10);
}
FoxInfo myFoxInfo[] = {
   {"DBREWIND", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBSkip( ) API Library Routine | _DBUnwind( ) API Library Routine | GO | GOTO Command | Accessing the Visual FoxPro API


_DBSeek( ) API Library Routine

Searches an indexed table in the current work area for the first record whose index key matches the value val.

long _DBSeek(Value FAR *val)
Value FAR *val;            /* Sought value. */

Remarks

If _DBSeek( ) finds a matching record, it moves the record pointer to the matching record and returns the record number. The match must be exact unless you SET EXACT is set to OFF. If _DBSeek( ) doesn't find a matching record, it returns 0. If no match is found and SET NEAR is set to ON, the record pointer is positioned immediately after the closest matching record. If SET NEAR is set to OFF, the record pointer is positioned at the end of the file.

If the matching record is an added buffered record that has not been committed, the value returned by _DBSeek( ) differs from the value returned by RECNO( ). RECNO( ) returns a negative value, indicating the record is buffered. The value returned by _DBSeek( ) is one greater than the number of records in the table plus the number of buffered records before the matching record.

If an error occurs, _DBSeek( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

When seeking a numeric field, val must be set to ev_type 'N', even if that field has no decimal digits. If val has an ev_type of 'I', _DBSeek( ) will return the internal error number -302, "Data type mismatch".

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example performs a seek on whatever index controls the order of the table open in the current work area. Note the "?" in the FoxInfo structure is required because the type of index expression is not known.

Visual FoxPro Code

SET LIBRARY TO DBSEEK
DO CreateTest

INDEX ON ABC TAG ABC
SET ORDER TO TAG ABC
= DBSEEK("This is record 3")  && seeks ABC = "This is record 3"
LIST NEXT 1
USE

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _DBSeek(&parm->p[0].val);
}

FoxInfo myFoxInfo[] = {
   {"DBSEEK", (FPFI) Example, 1, "?"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRecCount( ) API Library Routine | _DBRecNo( ) API Library Routine | _DBSkip( ) API Library Routine | SET EXACT Command


_DBSkip( ) API Library Routine

_DBSkip( ) moves the record pointer in the specified work area the specified number of records.

long _DBSkip(int workarea, long distance)
int workarea;               /* Work area. */
long distance;               /* Number of records to skip. */

Remarks

_DBSkip( ) respects the active index and filter expressions, just like the Visual FoxPro SKIP command. The distance may be positive or negative. _DBSkip( ) returns the record number of the new record.

Use _DBStatus( ) to check for end of file and beginning of file conditions. If you try to skip forward from the end of the file, or skip backwards from the beginning of the file, _DBSkip( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example works like the Visual FoxPro SKIP command.

Visual FoxPro Code

SET LIBRARY TO DBSKIP
ON ERROR DO expectError
DO CreateTest
USE
= DBSKIP(1)       && _Error() called: no DBF in use
USE test
GO TOP
= DBSKIP(-1)
= DBSKIP(-1)      && _Error() called: at top of file
GO BOTT
= DBSKIP(1)
= DBSKIP(1)      && _Error() called: at bottom of file
ON ERROR

PROCEDURE expectError
   ? "ERROR: " + MESSAGE()
RETURN

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *pblk)
{
   int RetCode;

   if ((RetCode = _DBSkip(-1, pblk->p[0].val.ev_long)) < 0) {
      _PutStr("\nError encountered in example program.");
      _Error(-RetCode);  // _DBSkip() returns negative error code
   }
   _RetInt(RetCode, 10);
}

FoxInfo myFoxInfo[] = {
   {"DBSKIP", (FPFI) Example, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRecCount( ) API Library Routine | _DBRecNo( ) API Library Routine | Accessing the Visual FoxPro API | _DBStatus( ) API Library Routine


_DBStatus( ) API Library Routine

Returns status flags for the specified work area.

int _DBStatus(int workarea)
int workarea;               /* Work area. */

Remarks

If no table is open in the specified work area, _DBStatus( ) returns a negative integer whose absolute value is a Visual FoxPro error number. The following table shows returned status flags:

Flag | Setting
DB_BOF | Set under the same conditions as the Visual FoxPro function BOF( ).
DB_EOF | Set under the same conditions as the Visual FoxPro function EOF( ).
DB_RLOCKED | Set when the current record is locked, the table is locked, or the table is open exclusively.
DB_FLOCKED | Set when the table is locked or the table is open exclusively.
DB_EXCLUSIVE | Set when the table is open exclusively.
DB_READONLY | Set when the table is open without write access.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the status of the table open in the current work area. It checks each bit in the value returned by _DBStatus( ) and displays an appropriate message to the screen.

Visual FoxPro Code

SET LIBRARY TO DBSTATUS
= DBSTATUS()  && displays status of DBF in current work area

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int dbstatus = _DBStatus(-1);
   _PutStr("\nStatus of DBF in current work area:");
   if (dbstatus & DB_BOF)
      _PutStr("\nBOF()");
   if (dbstatus & DB_EOF)
      _PutStr("\nEOF()");
   if (dbstatus & DB_RLOCKED)
      _PutStr("\nCurrent record is RLOCKed");
   if (dbstatus & DB_FLOCKED)
      _PutStr("\nDatabase is FLOCKed");
   if (dbstatus & DB_EXCLUSIVE)
      _PutStr("\nDatabase is open EXCLUSIVEly");
   if (dbstatus & DB_READONLY)
      _PutStr("\nDatabase is READONLY");
}

FoxInfo myFoxInfo[] = {
   {"DBSTATUS", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBLock( ) API Library Routine | _DBUnlock( ) API Library Routine | Accessing the Visual FoxPro API | BOF( ) Function | EOF( ) Function | ISRLOCKED( ) Function | ISFLOCKED( ) Function | ISEXCLUSIVE( ) Function | ISREADONLY( ) Function


_DBUnlock( ) API Library Routine

Releases all user-obtained locks on records or the file in the work area specified by workarea.

void _DBUnlock(int workarea)
int workarea;               /* Work area. */

Example

The following example uses _DBUnlock( ) to unlock all records of the table open in the current work area. The Visual FoxPro code demonstrates _DBUnlock( ) and verifies that it's working properly.

Visual FoxPro Code

SET LIBRARY TO DBUNLOCK
DO CreateTest
USE Test SHARED
GO 2
= XRLOCK()
LIST STAT  && shows that record #2 is locked
= XUNLOCK()
LIST STAT  && shows no records are locked
= XFLOCK()
LIST STAT  && shows that whole DBF is locked
= XUNLOCK()
LIST STAT  && shows no records are locked

PROCEDURE CreateTest

CREATE TABLE test (ABC C(20))
APPEND BLANK
REPLACE ABC WITH "Golly month of"
APPEND BLANK
REPLACE ABC WITH "A twelfth of"
APPEND BLANK
REPLACE ABC WITH "Hello, world"
APPEND BLANK
REPLACE ABC WITH "When in the"
GO TOP

RETURN

C Code

#include <pro_ext.h>

FAR xLockRecord(ParamBlk FAR *parm)
{
   _DBLock(-1, DBL_RECORD);
}
FAR xLockFile(ParamBlk FAR *parm)
{
   _DBLock(-1, DBL_FILE);
}
FAR xUnLockFile(ParamBlk FAR *parm)
{
   _DBUnLock(-1);
}
FoxInfo myFoxInfo[] = {
   {"XRLOCK",  (FPFI) xLockRecord, 0, ""},
   {"XFLOCK",  (FPFI) xLockFile, 0, ""},
   {"XUNLOCK", (FPFI) xUnLockFile, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBAppend( ) API Library Routine | _DBLock( ) API Library Routine | _DBReplace( ) API Library Routine | _DBStatus( ) API Library Routine | _DBWrite( ) API Library Routine


_DBUnwind( ) API Library Routine

Works like the Visual FoxPro GO BOTTOM command in the specified work area, and then returns the current record number.

long _DBUnwind(int workarea)
int workarea;               /* Work area. */

Example

The following example calls _DBUnwind( ) for the table open in the current work area.

Visual FoxPro Code

SET LIBRARY TO DBUNWIND
DO CreateTest
? DBUNWIND()   && returns new record #
SKIP
? EOF()       && now EOF() returns .T.

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_DBUnwind(-1), 10);
}

FoxInfo myFoxInfo[] = {
   {"DBUNWIND", (FPFI) Example, 0, ""},
};

FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBRewind( ) API Library Routine | _DBWrite( ) API Library Routine | Working with Fields and Records | Records


_DBWrite( ) API Library Routine

Writes to disk the current record in the specified work area and updates all affected indexes.

int _DBWrite(int workarea)
int workarea;               /* Work area. */

Remarks

Any time the record pointer is moved to another record, this updating occurs automatically. If no field data has been replaced, _DBWrite( ) has no effect. _DBWrite( ) returns 0 if the routine is successful. If the routine fails, _DBWrite( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example carries out a _DBReplace( ) using the two calling parameters, one a table field passed by reference, the other a value of the appropriate type. It executes a LIST NEXT 1 Visual FoxPro command before and after a call to _DBWrite( ).

Visual FoxPro Code

SET LIBRARY TO DBWRITE
DO CreateTest
GO 3
=DBWRITE( @ABC, "Replacement Record 1")

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int RetValue;

   if (RetValue = _DBReplace(&parm->p[0].loc, &parm->p[1].val)) {
      _UserError("\n_DBReplace() failed");
   }

   if (RetValue = _DBWrite(-1)) {
      _Error(-RetValue);
   }
   _Execute("LIST NEXT 1");
}

FoxInfo myFoxInfo[] = {
   {"DBWRITE", (FPFI) Example, 2, "R,?"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DBLock( ) API Library Routine | _DBReplace( ) API Library Routine | _DBUnlock( ) API Library Routine | Accessing the Visual FoxPro API


_DeActivateHandler( ) API Library Routine

_DeActivateHandler( ) removes the specified event handler from the event processor list.

void _DeActivateHandler(unsigned int EventIdentifier)
unsigned int EventIdentifier;      /* ID of event handler
 to be removed from list. */

Remarks

You must remove each event handler, indicated by EventIdentifier, from the handler list when its library is unloaded.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example activates an event handler when the library is loaded. The event handler prints a message for every event and lets Visual FoxPro process the message. The event handler is deactivated when the library is unloaded. As in the following example, _DeActivateHandler( ) is usually called from a CALLONUNLOAD function.

Visual FoxPro Code

SET LIBRARY TO DEACTHAN

C Code

#include <pro_ext.h>

static int HandlerID;

//   This is the routine that is registered as an event handler.
FAR EventHandler(WHandle theWindow, EventRec FAR *ev)
{
   _PutStr("\nEventHandler() called.");
   return NO;   // event still needs to be handled by Visual FoxPro
}

FAR Activate()
{
   HandlerID = _ActivateHandler(EventHandler);
}

//   When the library is unloaded we must deactivate the event handler
//   in a CALLONUNLOAD function.
FAR DeActivate()
{
   _DeActivateHandler(HandlerID);
}

FoxInfo myFoxInfo[] = {
   {"ACTIVATE",  (FPFI) Activate, CALLONLOAD, ""},
   {"DEACTIVATE", (FPFI)  DeActivate, CALLONUNLOAD, ""}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ActivateHandler( ) API Library Routine | _FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePos( ) API Library Routine


_DeActivateIdle( ) API Library Routine

Removes the specified routine from the idle loop.

void _DeActivateIdle(unsigned int IdleIdentifier)
unsigned int IdleIdentifier;         /* Routine to be removed
 from idle list. */

Remarks

You must remove each idle routine from the idle routine list when its library is unloaded.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example activates an idle event handler when the library is loaded. The idle event handler simply prints a message and is deactivated when the library is unloaded. As in the following example, _DeActivateIdle( ) is usually called from a CALLONUNLOAD function.

Visual FoxPro Code

SET LIBRARY TO DEACTIDL

C Code

#include <pro_ext.h>

static unsigned IdlerID;

//   This is the routine that is registered as an idle event handler.
void FAR IdleHandler(WHandle wh, EventRec *ev)
{
   _PutStr("\nIdleHandler() called.");
}

void FAR Activate(ParamBlk FAR *parm)
{
   IdlerID = _ActivateIdle((FPFI) IdleHandler);
}

//   When the library is unloaded we must deactivate the idle event
//   handler in a CALLONUNLOAD function.
void FAR DeActivate(ParamBlk FAR *parm)
{
   _DeActivateIdle(IdlerID);
}

FoxInfo myFoxInfo[] = {
   {"ACTIVATE",  (FPFI) Activate, CALLONLOAD,   ""},
   {"DEACTIVATE",  (FPFI) DeActivate, CALLONUNLOAD, ""}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ActivateIdle( ) API Library Routine | _FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePos( ) API Library Routine


_DeActivateMenu( ) API Library Routine

Removes a menu from the screen.

void _DeActivateMenu(MENUID menuid)
MENUID menuid;            /* Menu identifier. */

Remarks

The menu isn't released from memory and can be reactivated with _ActivateMenu( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example activates and deactivates a menu several times.

Visual FoxPro Code

SET LIBRARY TO DEACTMEN

C Code

#include <pro_ext.h>

FAR DeActMenuEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Menu activated'");
   _DeActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Menu deactivated'");
   _ActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Menu activated'");
   _DeActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Menu deactivated'");

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) DeActMenuEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ActivateMenu( ) API Library Routine | Accessing the Visual FoxPro API | DEACTIVATE MENU Command | ACTIVATE MENU Command | HIDE MENU Command


_DefaultProcess( ) API Library Routine

Provides the default event processing for an event returned by _GetNextEvent( ) when the event does not need special handling.

void _DefaultProcess(EventRec FAR *event)
EventRec FAR *event;      /* Event to be processed. */

Remarks

This makes it easier for an external routine to use windows and still have them act consistently with the rest of the product.

Note Don't call _DefaultProcess( ) from an event handler.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example is a loop consisting of a call to _GetNextEvent( ) followed by a call to _DefaultProcess( ). All events during this procedure receive their default processing.

Visual FoxPro Code

SET LIBRARY TO DEFAPROC

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   EventRec ev;
   int i;

   for (i = 0; i < 16; i++)
{
      _GetNextEvent(&ev);
      _DefaultProcess(&ev);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _GetNextEvent( ) API Library Routine | _GlobalToLocal( ) API Library Routine | Events in Visual FoxPro | Accessing the Visual FoxPro API


_Dialog( ) API Library Routine

Displays on the screen a dialog box that is the specified color scheme and contains the specified body text and button text.

int _Dialog(int scheme, char FAR *body_text, char FAR *button1,
            char FAR *button2, char FAR *button3, int default, int
 escape)
int scheme;                  /* Color scheme number. */
char FAR *body_text;         /* Text in dialog. */
char FAR *button1;         /* Button prompt. */
char FAR *button2;         /* Button prompt. */
char FAR *button3;         /* Button prompt. */
int default;                  /* Number of the default button. */
int escape;                  /* Number of the button to press if Esc. */

Remarks

_Dialog( ) returns the number of the button the user chooses.

To specify fewer than three buttons for the displayed dialog box, specify 0 as a button prompt to leave any of the three buttons blank. The default parameter specifies which button to highlight in the dialog box as the default button, and the escape parameter specifies which button to process as chosen if the user presses ESC.

If you specify no buttons, Visual FoxPro displays the dialog box and waits for the user to press a key or click the left mouse button. If the user presses Esc, _Dialog( ) returns the escape value; otherwise, it returns the default value.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates four dialog boxes with three, two, one, and no buttons.

Visual FoxPro Code

SET LIBRARY TO DIALOG

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

void FAR dialogEx(ParamBlk FAR *parm)
{
   int selection;

   selection = _Dialog(DIALOG_SCHEME, "Example dialog with 3 buttons.",
      "First", "Second", "Third", 2, 3);

   _PutStr("\nItem selected ="); putLong(selection);

   selection = _Dialog(DIALOG_SCHEME, "Example dialog with 2 buttons.",
      "First", "Second", 0, 2, 2);

   _PutStr("\nItem selected ="); putLong(selection);

   selection = _Dialog(DIALOG_SCHEME, "Example dialog with 1 button.",
      "First", (char *)0, (char *)0, 1, 1);

   _PutStr("\nItem selected ="); putLong(selection);

   selection = _Dialog(DIALOG_SCHEME, "Example dialog no buttons.",
      (char *)0, (char *)0, (char *)0, 1, 2);

   _PutStr("\nItem selected ="); putLong(selection);
}

FoxInfo myFoxInfo[] = {
   {"DIALOGEX", (FPFI) dialogEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Accessing the Visual FoxPro API | SET LIBRARY Command


_DisposeItem( ) API Library Routine

Releases from memory the specified menu item, and frees all memory storage associated with this item.

void _DisposeItem(MENUID menuid, ITEMID itemid)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */

Remarks

_DisposeItem( ) doesn't release any submenus that are associated with the item.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items and then uses _DisposeItem( ) to remove two of the items.

Visual FoxPro Code

SET LIBRARY TO DISPITEM

C Code

#include <pro_ext.h>

FAR DisposeItemEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Menu has three items'");

   _DisposeItem(menuId, _GetItemId(menuId, 1));
   _Execute("WAIT WINDOW 'Menu has two items'");

   _DisposeItem(menuId, _GetItemId(menuId, 0));
   _Execute("WAIT WINDOW 'Menu has one item'");

   _DisposeMenu(menuId);
}
FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) DisposeItemEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_NewItem( ) API Library Routine | _GetItemId( ) API Library Routine | Enabling and Disabling Menu Items | Creating Menus, Shortcut Menus, Menu Items, and Submenus


_DisposeMenu( ) API Library Routine

Releases the specified menu and all its items and frees all memory associated with this menu.

void _DisposeMenu(MENUID menuid)
MENUID menuid;            /* Menu identifier. */

Remarks

_DisposeMenu( ) doesn't release any submenus that are associated with the menu.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example calls _DisposeMenu( ) after the user chooses a menu item.

Visual FoxPro Code

SET LIBRARY TO DISPMENU

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
   _DisposeMenu(menuId);
}

FAR activateMenu(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _OnSelection(menuId, -1, onSelection);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) activateMenu, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetNewMenuId( ) API Library Routine | _GetNewMenuId( ) API Library Routine | _NewMenu( ) API Library Routine | Accessing the Visual FoxPro API


_EdActive( ) API Library Routine

Allows you to hide (deactivate) or show (activate) the selection range or the insertion point position in the specified window.

void _EdActive(WHANDLE wh, int Show)
WHANDLE wh;            /* Handle of editing window.*/
int Show;                     /* Boolean hide or show selection. */

Remarks

Specifying the Show parameter as TRUE shows the selection range or insertion point position, and specifying Show as FALSE hides the selection range or insertion point position.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens an edit window for a file whose name is passed as a parameter and selects the first character in the file. Using _EdActive( ), the example activates and then deactivates the selection.

Visual FoxPro Code

SET LIBRARY TO EDACTIVE
fc = FCREATE("x", 0)
FOR i = 1 TO 90
   = FPUTS(fc, REPL(ALLT(STR(i)), i), i)
ENDFOR
= FCLOSE(fc)

= EDACTIVE("x")   && Call our API routine

C Code

#include <pro_ext.h>

FAR EdActiveEx(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFILENAME[parm->p[0].val.ev_length] = '\0';
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);

   _EdActive(wh, TRUE);
   _Execute("WAIT WINDOW 'Selection active'");

   _EdActive(wh, FALSE);
   _Execute("WAIT WINDOW 'Selection inactive'");
}

FoxInfo myFoxInfo[] = {
   {"EDACTIVE", (FPFI) EdActiveEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdSelect( ) API Library Routine | _EdCloseFile( ) API Library Routine | SYS(2002) - Turn Insertion Point On or Off | _EdCopy( ) API Library Routine


_EdCloseFile( ) API Library Routine

Closes both the specified editing window and the file displaying in the window.

int _EdCloseFile(WHANDLE wh, int option)
WHANDLE wh;            /* Handle of editing window. */
int option;                  /* Closing options. */

Remarks

The option parameter can be one of the following:

Option parameter values

int | result
0 | Immediately save.
1 | Save after dialog box confirmation.
2 | Open Save As dialog box.

_EdCloseFile( ) returns one of the following:

_EdCloseFile( ) return values

int | meaning
1 | Cancel without saving file.
0 | Save and close file.
– 1 | Discard changes and close file.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a single file specified by a parameter, deletes a character, and closes the edit session three times. The first time, the routine calls _EdCloseFile( ) with the "Immediately save" option, the second time with the "Save after dialog box" option, and the third time with the "Open Save As dialog box" option. Each time, the routine shows the return value of _EdCloseFile( ).

Visual FoxPro Code

SET LIBRARY TO EDCLOSE
= EDCLOSE("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 5;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   int retValue;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   // Open, delete a character, close "save without asking"
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);

   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdDelete(wh);
   retValue = _EdCloseFile(wh, 0); // save without asking
   _PutStr("\n_EdCloseFile() ="); putLong(retValue);

   // Open, delete a character, close "save with asking"
   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdDelete(wh);
   retValue = _EdCloseFile(wh, 1); // save with asking
   _PutStr("\n_EdCloseFile() ="); putLong(retValue);

   // Open, delete a character, close "save as"
   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdDelete(wh);
   retValue = _EdCloseFile(wh, 2); // save as
   _PutStr("\n_EdCloseFile() ="); putLong(retValue);
}

FoxInfo myFoxInfo[] = {
   {"EDCLOSE", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdOpenFile( ) API Library Routine | _EdRevert( ) API Library Routine | _EdSave( ) API Library Routine | _EdSelect( ) API Library Routine


_EdCopy( ) API Library Routine

Copies the selected portion of the file in the specified editing window to the clipboard.

void _EdCopy(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter, copies the first character to the clipboard using _EdCopy( ), and pastes the character after the second character using _EdPaste( ).

Visual FoxPro Code

SET LIBRARY TO EDCOPY
= EDCOPY("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdCopy(wh);
   _EdSetPos(wh, 2);
   _EdPaste(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDCOPY", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdPaste( ) API Library Routine | _EdSelect( ) API Library Routine | _EdSetPos( ) | _EdCloseFile( ) API Library Routine


_EdCut( ) API Library Routine

Copies the selected portion of the file in the specified editing window to the clipboard, and deletes it from the specified window.

void _EdCut(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter, cuts the first character to the clipboard using _EdCut( ), and pastes the character after the second character using _EdPaste( ).

Visual FoxPro Code

SET LIBRARY TO EDCUT
= EDCUT("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdCut(wh);
   _EdSetPos(wh, 2);
   _EdPaste(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDCUT", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine |_EdPaste( ) API Library Routine | _EdSelect( ) API Library Routine | _EdSetPos( ) API Library Routine


_EdDelete( ) API Library Routine

Deletes the selected portion of the file in the specified editing window.

void _EdDelete(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Remarks

If nothing is selected, _EdDelete( ) deletes the character at the current insertion point position.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter and deletes the first character in the file using _EdDelete( ).

Visual FoxPro Code

SET LIBRARY TO EDDELETE
= EDDELETE("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   int retValue;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdDelete(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDDELETE", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdSelect( ) API Library Routine | _EdSetPos( ) API Library Routine | Accessing the Visual FoxPro API


_EdGetChar( ) API Library Routine

_EdGetChar( ) returns the character at the specified offset position in the file in the specified editing window.

TEXT _EdGetChar(WHANDLE wh, EDPOS thePos)
WHANDLE wh;         /* Handle of editing window. */
EDPOS thePos;            /* Offset position in file of character
 to be returned. */

Example

The following example opens for editing a file specified by a parameter and displays on the screen the entire contents of the file.

Visual FoxPro Code

SET LIBRARY TO EDGETCHA
= EDGETCHAR("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFILENAME[parm->p[0].val.ev_length] = '\0';
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdGetEnv(wh, &EdEnv);

   for (edpos = 0; edpos <= EdEnv.length; edpos++)
   {
      _PutChr(_EdGetChar(wh, edpos));
   }
}

FoxInfo myFoxInfo[] = {
   {"EDGETCHAR", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdSetPos( ) API Library Routine | _EdGetStr( ) API Library Routine | _EdGetEnv( ) API Library Routine


_EdGetEnv( ) API Library Routine

_EdGetEnv( ) provides the editor environment information in *EDENV.

int _EdGetEnv(WHANDLE wh, *EDENV theEdEnv)
WHANDLE wh;            /* Handle of editing window. */
*EDENV theEdEnv;         /* Environment settings. */

Remarks

The structure of *EDENV is listed below.

Note In the comments below, an (R) indicates that this member is read-only and can't be set using _EdSetEnv( ). A (B) indicates that this member takes on one of two Boolean values: 1 (True) or 0 (False).
typedef struct
{
   char            filename[MAXFILENAME];   // (R)
   EDPOS         length;         // # of bytes in text. (R)
   unsigned short   lenLimit;         // Max allowable length.
 0 = infinite.

   unsigned short   dirty,            // Has the file been changed?
 (R, B)
                  autoIndent,      // Auto indent? (B)
                  backup,         // Make backup files? (B)
                  addLineFeeds,   // Add line feeds when saving? (B)
                  autoCompile,      // Shall we auto compile this thing?
 (B)
                  addCtrlZ,         // Add end of file ctrl-z? (B)
                  savePrefs,      // Save edit preferences? (B)
                  dragAndDrop,   // Allow drag-and-drop. (B)
                  readOnly,         // 0 = not r/o, 1 = file is r/o,
                                 // 2 = file is r/w, opened r/o,
                                 // 3 = file is r/o, opened r/o. (R)
                  status,            // Display status bar? (B)
                  lockPrefs,         // Can update the preferences ? (B)
                  insertMode;      // (B)

   short            wrap;            // If < 0, new line at Return only.
   EDPOS         selStart;         // Selection start. (R)
   EDPOS         selEnd;         // Selection end. (R)
   EDPOS         selAnchor;      // Selection anchor point. (R)
   short            justMode;      // Justification (0 = left, 1 =
 right, 2 = center).
   short            tabWidth;      // TAB size in spaces.

   char            fontName[MAXFONTNAME];
   short            fontSize;
   short            fontStyle;      // 0 = plain, 1 = bold, 2 =
 italic, 3 = bold italic.
   short            kind;         // Kind of editor session (R);
                              // EDCOMMAND, EDPROGRAM, etc.
} EDENV;

1 is returned if called in a Command or Editor session, otherwise 0 is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens an editing session for a file specified by a parameter and displays each field of the EDENV structure for that file as returned by _EdGetEnv( ).

Visual FoxPro Code

SET LIBRARY TO EDGETENV
= EDGETENV("x")

C Code

#include <pro_ext.h>

void putLong(unsigned long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 6;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdGetEnv(wh, &EdEnv);

   _PutStr("\nfilename: ");    _PutStr(EdEnv.filename);
   _PutStr("\nlength: ");    putLong(EdEnv.length);
   _PutStr("\nlenLimit: ");    putLong(EdEnv.lenLimit);
   _PutStr("\ndirty: ");     putLong(EdEnv.dirty);
   _PutStr("\nautoIndent: ");  putLong(EdEnv.autoIndent);
   _PutStr("\nbackup: ");    putLong(EdEnv.backup);
   _PutStr("\naddLineFeeds: ");  putLong(EdEnv.addLineFeeds);
   _PutStr("\nautoCompile: ");   putLong(EdEnv.autoCompile);
   _PutStr("\naddCtrlZ: ");    putLong(EdEnv.addCtrlZ);
   _PutStr("\nsavePrefs: ");   putLong(EdEnv.savePrefs);
   _PutStr("\ndragAndDrop: ");   putLong(EdEnv.dragAndDrop);
   _PutStr("\nreadOnly: ");    putLong(EdEnv.readOnly);
   _PutStr("\nstatus: ");    putLong(EdEnv.status);
   _PutStr("\nlockPrefs: ");   putLong(EdEnv.lockPrefs);
   _PutStr("\ninsertMode: ");  putLong(EdEnv.insertMode);
   _PutStr("\nwrap: ");    putLong(EdEnv.wrap);
   _PutStr("\nselStart: ");    putLong(EdEnv.selStart);
   _PutStr("\nselEnd: ");    putLong(EdEnv.selEnd);
   _PutStr("\nselAnchor: ");   putLong(EdEnv.selAnchor);
   _PutStr("\njustMode: ");    putLong(EdEnv.justMode);
   _PutStr("\ntabWidth: ");    putLong(EdEnv.tabWidth);
   _PutStr("\nfontName: ");    _PutStr(EdEnv.fontName);
   _PutStr("\nfontSize: ");    putLong(EdEnv.fontSize);
   _PutStr("\nfontStyle: ");   putLong(EdEnv.fontStyle);
   _PutStr("\nkind: ");    putLong(EdEnv.kind);
}

FoxInfo myFoxInfo[] = {
   {"EDGETENV", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdLastError( ) | _EdSetEnv( ) | _EdGetLineNum( ) API Library Routine | _EdGetChar( ) API Library Routine


_EdGetLineNum( ) API Library Routine

Returns the line number of the passed offset position thePos in the file in the specified editing window.

EDLINE _EdGetLineNum(WHANDLE wh, EDPOS thePos)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Offset position in the file. */

Example

The following example opens an editing session for a file specified by a parameter and gets the EDPOS for line 12 by calling _EdGetLinePos( ). It then calls _EdGetLineNum( ) on this EDPOS, and this returns 12. Next, it increments the EDPOS and each time calls _EdGetLineNum( ) until the returned EDLINE changes. At this point, it calls _EdGetLinePos( ) for line 13.

Visual FoxPro Code

SET LIBRARY TO EDGETLIN
= EDGETLPOS("x")

C Code

#include <pro_ext.h>

void putLong(unsigned long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 6;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;
   EDPOS edpos;
   EDLINE edlin, original;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   edpos = _EdGetLinePos(wh, 12);
   _PutStr("\n_EdGetLinePos(wh, 12) =");
   putLong(edpos);

   original = edlin = _EdGetLineNum(wh, edpos);

   for (;;)
   {
      _PutStr("\n_EdGetLineNum(wh,");
      putLong(edpos);
      _PutStr(") = ");
      putLong(edlin);

      if (edlin != original)
      {
         break;
      }
      edpos++;
      edlin = _EdGetLineNum(wh, edpos);
   }

   edpos = _EdGetLinePos(wh, 13);
   _PutStr("\n_EdGetLinePos(wh, 13) ="); putLong(edpos);
}

FoxInfo myFoxInfo[] = {
   {"EDGETLPOS", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetChar( ) API Library Routine | _EdGetLinePos( ) API Library Routine | _EdGetEnv( ) API Library Routine


_EdGetLinePos( ) API Library Routine

Returns the offset position of the first character of the specified line in the file in the specified editing window.

EDPOS _EdGetLinePos(WHANDLE wh, EDLINE theLine)
WHANDLE wh;            /* Handle of editing window. */
EDLINE theLine;            /* Line number. */

Example

The following example opens an editing session for a file specified by a parameter and gets the EDPOS for line 12 by calling _EdGetLinePos( ). It then calls _EdGetLineNum( ) on this EDPOS, and this returns 12. Next, it increments the EDPOS and each time calls _EdGetLineNum( ) until the EDLINE returned is changed. At this point, it calls _EdGetLinePos( ) for line 13.

Visual FoxPro Code

SET LIBRARY TO EDGETLPO
= EDGETLPOS("x")

C Code

#include <pro_ext.h>

void putLong(unsigned long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 6;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;
   EDPOS edpos;
   EDLINE edlin, original;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   edpos = _EdGetLinePos(wh, 12);
   _PutStr("\n_EdGetLinePos(wh, 12) =");
   putLong(edpos);

   original = edlin = _EdGetLineNum(wh, edpos);

   for (;;)
   {
      _PutStr("\n_EdGetLineNum(wh,");
      putLong(edpos);
      _PutStr(") = ");
      putLong(edlin);

      if (edlin != original)
      {
         break;
      }
      edpos++;
      edlin = _EdGetLineNum(wh, edpos);
   }

   edpos = _EdGetLinePos(wh, 13);
   _PutStr("\n_EdGetLinePos(wh, 13) ="); putLong(edpos);
}
FoxInfo myFoxInfo[] = {
   {"EDGETLPOS", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetLineNum( ) API Library Routine | _EdGetPos( ) API Library Routine | _EdGetChar( ) API Library Routine


_EdGetPos( ) API Library Routine

Returns the current offset position of the insertion point in the file in the specified editing window.

EDPOS _EdGetPos(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Remarks

If text is selected, _EdGetPos( ) returns the offset position of the anchor.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens an edit session for a file specified by a parameter. After setting the current insertion point with _EdSetPos( ), a call to _EdGetPos( ) is made to verify that it returns the insertion point offset position. After selecting text with _EdSelect( ), a call to _EdGetPos( ) is made to verify that it returns the anchor point offset position.

Visual FoxPro Code

SET LIBRARY TO EDGETPOS
= EDGETPOS("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 6;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, 19);
   _PutStr("\n_EdSetPos(wh, 19)");
   edpos = _EdGetPos(wh);
   _PutStr("\n_EdGetPos(wh) ="); putLong(edpos);

   _EdSelect(wh, 5, 12);
   _PutStr("\n_EdSelect(wh, 5, 12)");
   edpos = _EdGetPos(wh);
   _PutStr("\n_EdGetPos(wh) ="); putLong(edpos);
}

FoxInfo myFoxInfo[] = {
   {"EDGETPOS", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetChar( ) API Library Routine | _EdSetPos( ) API Library Routine | _EdGetLinePos( ) API Library Routine


_EdGetStr( ) API Library Routine

Places the text between and including the specified offset positions into the specified address.

void _EdGetStr(WHANDLE wh, EDPOS thePos, EDPOS thePos,
               TEXT *theStr)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Starting offset position. */
EDPOS thePos;               /* Stopping offset position. */
TEXT *theStr;               /* Where to put the text. */

Example

The following example takes a file name as a parameter and returns the first 16 bytes of the file.

Visual FoxPro Code

SET LIBRARY TO EDGETSTR
? EDGETSTR("x") && returns the first 16 characters of file "x"

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   char FAR *buffer;
   char FAR *pFileName;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFileName = _HandToPtr(parm->p[0].val.ev_handle);
   pFileName[parm->p[0].val.ev_length] = '\0';
   wh = _EdOpenFile(pFileName, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);
   if ((buffer = _Alloca(17)) == 0) {
      _Error(182); // "Insufficient memory"
   }
   _EdGetStr(wh, 0, 15, buffer);
   buffer[16] = '\0';
   _RetChar(buffer);
}

FoxInfo myFoxInfo[] = {
   {"EDGETSTR", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetChar( ) API Library Routine | _EdSetPos( ) API Library Routine | _EdGetLinePos( ) API Library Routine


_EdIndent( ) API Library Routine

Indents the selected text in the file in the specified window the specified number of tab stops.

void _EdIndent(WHANDLE wh, int tabstops)
WHANDLE wh;            /* Handle of editing window. */
int tabstops;                  /* Number of tab stops. */

Remarks

You can specify a negative number for tabstops to cause a hanging indent for the selection.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens an editing session for a file specified by a parameter, and indents lines 13 and 15 in the file by a single tab stop.

Visual FoxPro Code

SET LIBRARY TO EDINDENT
= EDINDENT("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1)) {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, _EdGetLinePos(wh, 12), _EdGetLinePos(wh, 14));
   _EdIndent(wh, 1);
}
FoxInfo myFoxInfo[] = {
   {"EDINDENT", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetLineNum( ) API Library Routine | _EdGetLinePos( ) API Library Routine | _EdGetPos( ) API Library Routine | _EdSetPos( ) API Library Routine


_EdInsert( ) API Library Routine

Inserts the specified number of bytes, starting with the specified TEXT * address, at the insertion point.

void _EdInsert(WHANDLE wh, TEXT *theStr, unsigned long Bytes)
WHANDLE wh;            /* Handle of editing window. */
TEXT *theStr;               /* Address of beginning of insertion
 text. */
unsigned long Bytes;         /* Number of bytes to insert. */

Example

The following example opens an editing session for a file specified by a parameter and inserts the line of text "Hello, world" as the new fourteenth line in the file.

Visual FoxPro Code

SET LIBRARY TO EDINSERT
= EDINSERT("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1)) {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\n", _StrLen("Hello, world\n"));
}
FoxInfo myFoxInfo[] = {
   {"EDINSERT", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdSetPos( ) API Library Routine | Accessing the Visual FoxPro API


_EdLastError( ) API Library Routine

_EdLastError( ) returns the error number of the most recent editor error associated with the specified editing window.

int _EdLastError(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example displays the error code returned by _EdLastError( ) after a number of editor operations. Since editor errors are reserved for severe situations, such as low memory, the following example will usually display an error code of 0.

Visual FoxPro Code

SET LIBRARY TO EDLASTER
= EDLASTERR("x")  && displays _EdLastError() after operations on file "x"

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;
   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   char FAR *pFileName;
   WHANDLE wh;
   EDENV EdEnv;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFileName = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   pFileName[parm->p[0].val.ev_length] = '\0';

   wh = _EdOpenFile(pFileName, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

//   Position past end of file
   _EdGetEnv(wh, &EdEnv);
   _EdSetPos(wh, EdEnv.length + 128);
   _PutStr("\n_EdLastError() ="); putLong(_EdLastError(wh));

//   _EdCopy() with no selection
   _EdSetPos(wh, 1);
   _EdCopy(wh);
   _PutStr("\n_EdLastError() ="); putLong(_EdLastError(wh));

//   _EdScrollToSel() with no selection
   _EdScrollToSel(wh, TRUE);
   _PutStr("\n_EdLastError() ="); putLong(_EdLastError(wh));
}

FoxInfo myFoxInfo[] = {
   {"EDLASTERR", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetEnv( ) API Library Routine | _EdSetEnv( ) API Library Routine | Accessing the Visual FoxPro API


_EdOpenFile( ) API Library Routine

Opens the specified file in a window, in order to begin an editing session.

WHANDLE _EdOpenFile(TEXT *filename, int mode)
TEXT *filename;            /* File to open. */
int mode;                     /* Mode option. */

Remarks

The following mode options are available: FO_READONLY, FO_WRITEONLY, and FO_READWRITE.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens an editor session for a file specified by a parameter.

Visual FoxPro Code

SET LIBRARY TO EDOPEN
= EDOPEN("x")  && opens editor session for file "x"

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"EDOPEN", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdCloseFile( ) API Library Routine | _EdRevert( ) API Library Routine | _EdSave( ) API Library Routine


_EdPaste( ) API Library Routine

Copies the contents of the clipboard into the file in the specified editing window at the insertion point.

void _EdPaste(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter, copies the first character to the clipboard using _EdCopy( ), and pastes the character after the second character using _EdPaste( ).

Visual FoxPro Code

SET LIBRARY TO EDPASTE
= EDCOPY("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdCopy(wh);
   _EdSetPos(wh, 2);
   _EdPaste(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDCOPY", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdCopy( ) API Library Routine |_EdCut( ) API Library Routine | _EdGetPos( ) API Library Routine | _EdSelect( ) API Library Routine | _EdSetPos( ) API Library Routine


_EdPosInView( ) API Library Routine

int _EdPosInView(WHANDLE wh, EDPOS thePos)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Offset position. */

Remarks

_EdPosInView( ) returns True (an integer other than 0) if the offset position in the file in the specified editing window is visible, or False (0) if not.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter. After scrolling to the top of the file, the example calls _EdPosInView( ) to check whether the top of file and bottom of file are in view and the results are printed to the screen. Then the example scrolls to the bottom of the file, and again calls _EdPosInView( ) to check whether the top of file and bottom of file are in view.

Visual FoxPro Code

SET LIBRARY TO EDPOSINV
= POSINVIEW("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdGetEnv(wh, &EdEnv);

   _EdScrollToPos(wh, 0, FALSE);
   _PutStr("\n_EdScrollToPos(wh, 0)");
   _PutStr("\n_EdPosInView(wh, 0) =");
   putLong(_EdPosInView(wh, 0));
   _PutStr("\n_EdPosInView(wh, EdEnv.length) =");
   putLong(_EdPosInView(wh, EdEnv.length));

   _EdScrollToPos(wh, EdEnv.length, FALSE);
   _PutStr("\n_EdScrollToPos(wh, EdEnv.length)");
   _PutStr("\n_EdPosInView(wh, 0) =");
   putLong(_EdPosInView(wh, 0));
   _PutStr("\n_EdPosInView(wh, EdEnv.length) =");
   putLong(_EdPosInView(wh, EdEnv.length));
}

FoxInfo myFoxInfo[] = {
   {"POSINVIEW", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdGetPos( ) API Library Routine | _EdSetPos( ) API Library Routine | Accessing the Visual FoxPro API


_EdRedo( ) API Library Routine

Performs again the change made to the file in the specified editing window that was undone by the most recent _EdUndo( ).

void _EdRedo(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter. After inserting a new line, the new line is removed using _EdUndo( ), and then inserted again using _EdRedo( ).

Visual FoxPro Code

SET LIBRARY TO EDREDO
= EDREDO("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\n", _StrLen("Hello, world\n"));

   _Execute("WAIT WINDOW 'New line inserted.  Press any key to undo.'");
   _EdUndo(wh);

   _Execute("WAIT WINDOW 'Insertion undone.  Press any key to redo.'");
   _EdRedo(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDREDO", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdUndo( ) API Library Routine | _EdUndoOn( ) API Library Routine | _EdRevert( ) API Library Routine


_EdRevert( ) API Library Routine

Discards all changes made to the file displaying in the specified editing window since it was most recently saved with _EdSave( ).

void _EdRevert(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter. After some editing, insertion of a new line, indenting of two lines, and deletion of two lines, the changes are discarded using _EdRevert( ).

Visual FoxPro Code

SET LIBRARY TO EDREVERT
= EDREVERT("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\r\n", _StrLen("Hello, world\n"));

   _EdSelect(wh, _EdGetLinePos(wh, 14), _EdGetLinePos(wh, 16));
   _EdIndent(wh, 1);

   _EdSelect(wh, _EdGetLinePos(wh, 9), _EdGetLinePos(wh, 12));
   _EdDelete(wh);

   _EdRevert(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDREVERT", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdRedo( ) API Library Routine | _EdUndo( ) API Library Routine | _EdUndoOn( ) API Library Routine | _EdSave( ) API Library Routine


_EdSave( ) API Library Routine

_EdSave( ) saves the file in the specified window without ending the editing session.

void _EdSave(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Example

The following example opens for editing a file specified by a parameter. The example inserts a new line, indents two lines, and deletes two lines. After the insertion of the new line, the example calls _EdSave( ). Then, after the indentation and deletion, the example calls _EdUndo( ) three times in an attempt to undo all of the editing, but the insertion made before the call to _EdSave( ) can't be undone. The example performs two more editing operations, inserting two lines and deleting two lines, with a call to _EdSave( ) between them. Last, the example calls _EdRevert( ), but it too can only undo changes made since the last _EdSave( ).

Visual FoxPro Code

SET LIBRARY TO EDSAVE
= EDSAVE("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\r\n", _StrLen("Hello, world\n"));

   _EdSave(wh);

   _EdSelect(wh, _EdGetLinePos(wh, 14), _EdGetLinePos(wh, 16));
   _EdIndent(wh, 1);

   _EdSelect(wh, _EdGetLinePos(wh, 9), _EdGetLinePos(wh, 12));
   _EdDelete(wh);

   _Execute("WAIT WINDOW 'Press any key to undo changes.'");
   _EdUndo(wh);  // undo deletion
   _EdUndo(wh);  // undo indent
   _EdUndo(wh);  // attempt to undo insertion, but can't

   _EdSelect(wh, _EdGetLinePos(wh, 14), _EdGetLinePos(wh, 16));
   _EdIndent(wh, 1);

   _EdSave(wh);

   _EdSelect(wh, _EdGetLinePos(wh, 9), _EdGetLinePos(wh, 12));
   _EdDelete(wh);

   _EdRevert(wh);   // undoes deletion
}

FoxInfo myFoxInfo[] = {
   {"EDSAVE", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdCloseFile( ) API Library Routine | _EdOpenFile( ) API Library Routine | _EdRevert( ) API Library Routine | _EdUndo( ) API Library Routine


_EdScrollToPos( ) API Library Routine

Ensures that the offset position you specify in the file in the designated editing window is visible.

void _EdScrollToPos(WHANDLE wh, EDPOS thePos, int Center)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Offset position to make visible. */
int Center;                  /* Whether or not to center position
 in window. */

Remarks

_EdScrollToPos( ) doesn't move the insertion point. Specify Center as TRUE to center the position vertically in the window, or as FALSE to not center the position vertically.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter. After scrolling to the top of the file by calling _EdScrollToPos( ), the procedure calls _EdPosInView( ) to check whether the top of file and bottom of file are in view, and prints the results on the screen. Then it scrolls to the bottom of the file by calling _EdScrollToPos( ), and again calls _EdPosInView( ) to check whether the top of file and bottom of file are in view.

Visual FoxPro Code

SET LIBRARY TO EDSCTOPO
= POSINVIEW("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1)) {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdGetEnv(wh, &EdEnv);

   _EdScrollToPos(wh, 0, FALSE);
   _PutStr("\n_EdScrollToPos(wh, 0)");
   _PutStr("\n_EdPosInView(wh, 0) =");
   putLong(_EdPosInView(wh, 0));
   _PutStr("\n_EdPosInView(wh, EdEnv.length) =");
   putLong(_EdPosInView(wh, EdEnv.length));

   _EdScrollToPos(wh, EdEnv.length, FALSE);
   _PutStr("\n_EdScrollToPos(wh, EdEnv.length)");
   _PutStr("\n_EdPosInView(wh, 0) =");
   putLong(_EdPosInView(wh, 0));
   _PutStr("\n_EdPosInView(wh, EdEnv.length) =");
   putLong(_EdPosInView(wh, EdEnv.length));
}

FoxInfo myFoxInfo[] = {
   {"POSINVIEW", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdPosInView( ) API Library Routine | Accessing the Visual FoxPro API | SYS(2002) - Turn Insertion Point On or Off | _EdInsert( ) API Library Routine


_EdScrollToSel( ) API Library Routine

Ensures that the selected text in the designated window is visible.

void _EdScrollToSel(WHANDLE wh, int Center)
WHANDLE wh;            /* Handle of editing window. */
int Center;                  /* Whether to center anchor point in
 window. */

Remarks

Specify Center as TRUE to center the anchor point vertically in the window, or as FALSE to not center the anchor point.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter. The example makes a selection near the bottom of the file. After the user presses a key in response to a Visual FoxPro WAIT command, the example scrolls the editing window to the selection by calling _EdScrollToSel( ). The example then repeats the operation for a selection made near the top of the file.

Visual FoxPro Code

SET LIBRARY TO EDSCTOSE
= TOSEL("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READONLY);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdScrollToPos(wh, 0, TRUE);

   _EdGetEnv(wh, &EdEnv);
   _EdSelect(wh, EdEnv.length - 16, EdEnv.length);

   _PutStr("\nMade selection at end of file.");
   _Execute("WAIT WINDOW 'Press any key to scroll to selection.'");

   _EdScrollToSel(wh, TRUE);
   _EdSelect(wh, 1, 16);

   _PutStr("\nMade selection at beginning of file.");
   _Execute("WAIT WINDOW 'Press any key to scroll to selection.'");

   _EdScrollToSel(wh, TRUE);
}

FoxInfo myFoxInfo[] = {
   {"TOSEL", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine | _EdSelect( ) API Library Routine | _EdSetPos( ) API Library Routine


_EdSelect( ) API Library Routine

Selects the range between the two specified offset positions, inclusive, of the file in the designated editing window.

void _EdSelect(WHANDLE wh, EDPOS startPos, EDPOS endPos)
WHANDLE wh;            /* Handle of editing window. */
EDPOS startPos;         /* Beginning offset position of selection. */
EDPOS endPos;         /* Ending offset position of selection. */

Example

The following example opens for editing a file specified by a parameter, selects the first character in the file using _EdSelect( ), copies the selection to the clipboard using _EdCopy( ), and pastes it after the second character using _EdPaste( ).

Visual FoxPro Code

SET LIBRARY TO EDSELECT
= EDCOPY("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSelect(wh, 0, 1);
   _EdCopy(wh);
   _EdSetPos(wh, 2);
   _EdPaste(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDCOPY", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdCopy( ) API Library Routine | _EdCut( ) API Library Routine | _EdPaste( ) API Library Routine


_EdSendKey( ) API Library Routine

Simulates the key press associated with the ASCII character number specified by charNum.

void _EdSendKey(WHANDLE wh, int charNum)
WHANDLE wh;            /* Handle of editing window. */
int charNum;               /* Number of character. */

Example

The following example opens for editing a file specified by a parameter. It inserts a line of text, "Hello, World", by sending the individual characters with _EdSendKey( ). It then uses _EdSendKey( ) to send a carriage return and linefeed and to insert an ASCII escape character. Notice that the escape character isn't interpreted as "discard editing session."

Visual FoxPro Code

SET LIBRARY TO EDSENDKE
= SENDKEY("x")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   // Insert a line of text using _EdSendKey()
   _EdSetPos(wh, 0);
   _EdSendKey(wh, 'H');
   _EdSendKey(wh, 'e');
   _EdSendKey(wh, 'l');
   _EdSendKey(wh, 'l');
   _EdSendKey(wh, 'o');
   _EdSendKey(wh, ',');
   _EdSendKey(wh, ' ');
   _EdSendKey(wh, 'W');
   _EdSendKey(wh, 'o');
   _EdSendKey(wh, 'r');
   _EdSendKey(wh, 'l');
   _EdSendKey(wh, 'd');
   _EdSendKey(wh, '.');
   _EdSendKey(wh, 0x0d); // carriage return
   _EdSendKey(wh, 0x0a); // line feed
   _EdSendKey(wh, 0x1b); // esc char code is inserted in file
}

FoxInfo myFoxInfo[] = {
   {"SENDKEY", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdInsert( ) API Library Routine | _EdGetChar( ) API Library Routine | _ASCIICOLS System Variable | _ASCIIROWS System Variable


_EdSetEnv( ) API Library Routine

Determines various editor settings.

int _EdSetEnv(WHANDLE wh, *EDENV theEdEnv)
WHANDLE wh;            /* Handle of editing window. */
*EDENV theEdEnv;         /* Editor settings. */

Remarks

For the structure of *EDENV, see _EdGetEnv( ) API Library Routine.

1 is returned if called in a Command or Editor session, otherwise 0 is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter. After indenting the first two lines of the file, it uses _EdSetEnv( ) to change the size of a tab stop to 6 characters and then to 9 characters.

Visual FoxPro Code

SET LIBRARY TO EDSETENV
= EDSETENV("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDENV EdEnv;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
{
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdGetEnv(wh, &EdEnv);

   _EdSelect(wh, _EdGetLinePos(wh, 1), _EdGetLinePos(wh, 3));
   _EdIndent(wh, 1);

   _Execute("WAIT WINDOW 'Press any key\
      to change tabs to 6 characters.'");
   EdEnv.tabWidth = 6;
   _EdSetEnv(wh, &EdEnv);

   _Execute("WAIT WINDOW 'Press any key \
      to change tabs to 9 characters.'");
   EdEnv.tabWidth = 9;
   _EdSetEnv(wh, &EdEnv);
}

FoxInfo myFoxInfo[] = {
   {"EDSETENV", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetEnv( ) API Library Routine | _EdLastError( ) API Library Routine | _EdGetEnv( ) API Library Routine | Accessing the Visual FoxPro API


_EdSetPos( ) API Library Routine

Moves the insertion point to the specified offset position in the file in the specified editing window, unselecting any selected text.

void _EdSetPos(WHANDLE wh, EDPOS thePos)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Specified offset position. */

Example

The following example opens for editing a file specified by a parameter. Using _EdSetPos( ), it sets the insertion point to position 19 of the file. It calls _EdGetPos( ) and inserts some text to verify that the insertion point has been set.

Visual FoxPro Code

SET LIBRARY TO EDSETPOS
= EDSETPOS('x')

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 6;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, 19);
   _PutStr("\n_EdSetPos(wh, 19)");
   edpos = _EdGetPos(wh);
   _PutStr("\n_EdGetPos(wh) ="); putLong(edpos);
   _EdInsert(wh, "*** Inserted at EDPOS = 19 ***",
      _StrLen("*** Inserted at EDPOS = 19 ***"));
}

FoxInfo myFoxInfo[] = {
   {"EDSETPOS", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetLineNum( ) API Library Routine | _EdGetChar( ) API Library Routine | _EdGetPos( ) API Library Routine


_EdSkipLines( ) API Library Routine

Moves the insertion point to the beginning of the line int lines from its current offset position thePos.

EDPOS _EdSkipLines(WHANDLE wh, EDPOS thePos, int offset)
WHANDLE wh;            /* Handle of editing window. */
EDPOS thePos;               /* Current offset position. */
int offset;                     /* Number of lines to skip. */

Remarks

You can specify a positive or negative number of lines.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens for editing a file specified by a parameter. It uses _EdSkipLines( ) to find the offset positions, then selects lines 3 and 4.

Visual FoxPro Code

SET LIBRARY TO EDSKIPLI
= SKIPLINE("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;
   EDPOS edpos;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   // select next two lines
   edpos = _EdSkipLines(wh, 0, 2); // skip to two lines from top
   _EdSelect(wh, edpos, _EdSkipLines(wh, edpos, 2));
   _Execute("WAIT WINDOW 'Using _EdSkipLines() \
      to select lines 3 and 4'");
}

FoxInfo myFoxInfo[] = {
   {"SKIPLINE", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdGetPos( ) API Library Routine |_EdSetPos( ) API Library Routine | Accessing the Visual FoxPro API


_EdUndo( ) API Library Routine

Undoes the single most recent change made to the file in the specified window.

void _EdUndo(WHANDLE wh)
WHANDLE wh;            /* Handle of editing window. */

Remarks

When the user makes changes to a file, these changes are recorded in the undo buffer. _EdUndo( ) can be issued multiple times to undo multiple changes. You can't undo a change made prior to issuing _EdSave( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens a file specified by a parameter for editing. After inserting a new line, it uses _EdUndo( ) to delete the line, and then calls _EdRedo( ) to restore the inserted line.

Visual FoxPro Code

SET LIBRARY TO EDUNDO
= EDREDO("x")

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define pFILENAME ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   pFILENAME[parm->p[0].val.ev_length] = '\0';

   _HLock(parm->p[0].val.ev_handle);
   wh = _EdOpenFile(pFILENAME, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\n", _StrLen("Hello, world\n"));

   _Execute("WAIT WINDOW 'New line inserted.\
      Press any key to undo.'");
   _EdUndo(wh);

   _Execute("WAIT WINDOW 'Insertion undone.  Press any key to redo.'");
   _EdRedo(wh);
}

FoxInfo myFoxInfo[] = {
   {"EDREDO", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdRedo( ) API Library Routine | _EdUndoOn( ) API Library Routine | _EdSave( ) API Library Routine | Accessing the Visual FoxPro API


_EdUndoOn( ) API Library Routine

Enables you to group a series of actions as a single action for use with _EdUndo( ) and _EdRedo( ).

void _EdUndoOn(WHANDLE wh, int Grouped)
WHANDLE wh;            /* Window handle. */
int Grouped;                  /* Toggle grouping off. */

Remarks

Actions that occur after you pass the Grouped parameter as FALSE with _EdUndoOn( ), or after you issue _EdUndo( ), are no longer grouped as a single action.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example shows how to use _EdUndoOn( ) to group edit operations that you can undo as a group using _EdUndo( ).

Visual FoxPro Code

SET LIBRARY TO EDUNDOON
= EDUNDOON("x")  && edit file "x"

C Code

#include <pro_ext.h>
#define TRUE   1
#define FALSE   0

FAR Example(ParamBlk FAR *parm)
{
   char FAR *pFileName;
   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pFileName = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   pFileName[parm->p[0].val.ev_length] = '\0';
   wh = _EdOpenFile(pFileName, FO_READWRITE);
   _HUnLock(parm->p[0].val.ev_handle);

   _EdUndoOn(wh, TRUE); // start undo group

   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\n", _StrLen("Hello, world\n"));
   _EdSelect(wh, _EdGetLinePos(wh, 14), _EdGetLinePos(wh, 16));
   _EdIndent(wh, 1);

   _EdUndoOn(wh, FALSE); // end undo group
   _EdUndoOn(wh, TRUE); // start another undo group

   _EdSelect(wh, _EdGetLinePos(wh, 9), _EdGetLinePos(wh, 12));
   _EdDelete(wh);
   _EdSetPos(wh, _EdGetLinePos(wh, 13));
   _EdInsert(wh, "Hello, world\n", _StrLen("Hello, world\n"));

   _Execute("WAIT WINDOW 'Press any key to undo changes.'");
   _EdUndoOn(wh, TRUE); // undoes to start of undo group
}

FoxInfo myFoxInfo[] = {
   {"EDUNDOON", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_EdRedo( ) API Library Routine | _EdUndo( ) API Library Routine | Accessing the Visual FoxPro API


_Error( ) API Library Routine

Signals the error specified by the value in code to the Visual FoxPro run time.

void _Error(int code)
int code;                     /* Internal Visual FoxPro
 error number. */

Remarks

The code parameter is a Visual FoxPro internal error number and can be passed as a positive or negative value. _Error( ) gives control to the Visual FoxPro error handler so that the error can be handled like any other Visual FoxPro error. Control of program flow doesn't return to the routine that called _Error( ), even when the user chooses to ignore the error. Execution resumes at the next Visual FoxPro statement.

See the Visual FoxPro Error Numbers topic in Help for error numbers and their meanings.

Note Do not use _Error( ) from an event handler.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example calls _Error( ) when _DBSkip( ) returns an error number. The Visual FoxPro code shows how to cause _Error( ) to be called.

Visual FoxPro Code

SET LIBRARY TO ERROR
DO CreateTest

ON ERROR DO expectError
USE
= DBSKIP(1)  && _Error() called: no DBF in use
USE test
GO TOP
= DBSKIP(-1)
= DBSKIP(-1)    && _Error() called: at top of file
GO BOTT
= DBSKIP(1)
= DBSKIP(1)  && _Error() called: at bottom of file
ON ERROR

PROCEDURE expectError
   ? "ERROR: " + MESSAGE()
RETURN

PROCEDURE CreateTest
   CREATE TABLE test (ABC C(20))
   APPEND BLANK
   REPLACE ABC WITH "This is record 1"
   APPEND BLANK
   REPLACE ABC WITH "This is record 2"
   APPEND BLANK
   REPLACE ABC WITH "This is record 3"
   APPEND BLANK
   REPLACE ABC WITH "This is record 4"
   GO TOP
RETURN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *pblk)
{
   int RetCode;

   if ((RetCode = _DBSkip(-1, pblk->p[0].val.ev_long)) < 0) {
      _PutStr("\nError encountered in example program.");
      _Error(-RetCode);  // _DBSkip() returns negative error code
   }
   _RetInt(RetCode, 10);
}

FoxInfo myFoxInfo[] = {
   {"DBSKIP", (FPFI) Example, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ErrorInfo( ) API Library Routine | _UserError( ) API Library Routine | _DBSkip( ) API Library Routine


_ErrorInfo( ) API Library Routine

Returns the external error number that corresponds to the Visual FoxPro internal error number specified by code.

int _ErrorInfo(int code, char FAR *message)
int code;                     /* Internal Visual FoxPro error number. */
char FAR *message;         /* Pointer to space for an error message. */

Remarks

The message parameter is a pointer to a character string that is the Visual FoxPro error message. If message isn't a null pointer, Visual FoxPro fills in the error message text associated with the external error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example shows the information returned by _ErrorInfo( ).

Visual FoxPro Code

SET LIBRARY TO ERRORINF
= ERRORINFO(0)
= ERRORINFO(1)

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

void FAR ErrorInfo(ParamBlk FAR *parm)
{
   int ext;
   char FAR *message;

   if ((message =_Alloca(128)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   ext = _ErrorInfo((int) parm->p[0].val.ev_long, message);

   _PutChr('\n'); putLong(ext); _PutStr(" "); _PutStr(message);
}

FoxInfo myFoxInfo[] = {
   {"ERRORINFO", (FPFI) ErrorInfo, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_Error( ) API Library Routine | _UserError( ) API Library Routine | Accessing the Visual FoxPro API


_Evaluate( ) API Library Routine

Compiles and executes a Visual FoxPro expression you specify with expr, placing the result in res.

int _Evaluate(Value FAR *res, char FAR *expr)
Value FAR *res;            /* Address for result. */
char FAR *expr;            /* Expression. */

Remarks

You can specify any expression that can be evaluated by the Visual FoxPro EVALUATE( ) function. After the expression is evaluated, control usually returns to the C statement immediately following the call to _Evaluate( ). Exceptions include evaluating a Visual FoxPro expression that carries out a Visual FoxPro CANCEL or QUIT command.

_Evaluate( ) returns the Visual FoxPro internal error number for any errors that occur during evaluation of the Visual FoxPro expression, or returns 0 if no errors occur. The contents of res are valid only when _Evaluate( ) returns a value of 0.

Note Do not call _Evaluate( ) from an event handler.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example has the same functionality as the Visual FoxPro EVALUATE( ) function.

Visual FoxPro Code

SET LIBRARY TO EVALUATE
? XEVAL("2 + 3")
? XEVAL("'a' + 'b'")
? XEVAL("SIN(PI()/2))")

C Code

#include <pro_ext.h>

FAR EvaluateEx(ParamBlk FAR *parm)
{
   char FAR *expr;
   Value result;

//   Null terminate character string
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   expr = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   expr[parm->p[0].val.ev_length] = '\0';

   _Evaluate(&result, expr);
   _RetVal(&result);

   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"XEVAL", (FPFI) EvaluateEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_Execute( ) API Library Routine | CANCEL Command | QUIT Command | Accessing the Visual FoxPro API


_Execute( ) API Library Routine

Compiles and executes the null-terminated statement you specify in stmt.

int _Execute(char FAR *stmt)
char FAR *stmt;            /* Statement to execute. */

Remarks

The stmt parameter can be any command or function that can be executed from the Command window. When execution of the statement is complete, control normally returns to the C statement immediately following the call to _Execute( ). Exceptions include executing code that performs a Visual FoxPro CANCEL or QUIT command.

_Execute( ) returns the Visual FoxPro internal error number for any error that occurs during execution of the statement, or 0 if no error occurs.

Note Do not call _Execute( ) from an event handler.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _Execute( ) to execute the passed Visual FoxPro statement.

Visual FoxPro Code

SET LIBRARY TO EXECUTE
= EXEC("? 'Hello, world.'")
= EXEC("DISPLAY STATUS")

C Code

#include <pro_ext.h>

FAR ExecuteEx(ParamBlk FAR *parm)
{
   char FAR *cmd;

   // Null terminate character string
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   cmd = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   cmd[parm->p[0].val.ev_length] = '\0';

   _Execute(cmd);

   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"EXEC", (FPFI) ExecuteEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_Evaluate( ) API Library Routine | CANCEL Command | QUIT Command | Accessing the Visual FoxPro API


_FCHSize( ) API Library Routine

Sets the size on disk of the specified file to the specified length.

int _FCHSize(FCHAN chan, long length)
FCHAN chan;               /* File to change. */
long length;                  /* New length for the file in bytes. */

Remarks

The specified length may extend or truncate the file. _FCHSize( ) returns 0 if it's successful in changing the length of the file, or – 1 if it fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a file Temp.txt and sets its size to 8196 bytes using _FCHSize( ).

Visual FoxPro Code

SET LIBRARY TO FCHSIZE
DIR  temp.txt

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan = _FCreate("temp.txt", FC_NORMAL);
   _FCHSize(fchan, 8196);
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FCHSIZE", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FGets( ) API Library Routine |_FPuts( ) API Library Routine | _FWrite( ) API Library Routine


_FClose( ) API Library Routine

Terminates access to a file.

int _FClose(FCHAN chan)
FCHAN chan;               /* File channel of file to close. */

Remarks

Any buffers that have been modified while the buffer is open are automatically flushed to disk. If the file has the TEMPORARY attribute, FClose( ) deletes the file. _FClose( ) returns 0 if the file is closed successfully, or – 1 if the file isn't closed successfully.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a file Temp.txt, sets its size to 8196 bytes, and closes it using _FClose( ).

Visual FoxPro Code

SET LIBRARY TO FCLOSE
DIR temp.txt

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan = _FCreate("temp.txt", FC_NORMAL);
   _FCHSize(fchan, 8196);
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FCHSIZE", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FOpen( ) API Library Routine | _FCopy( ) API Library Routine | Accessing the Visual FoxPro API


_FCopy( ) API Library Routine

Attempts to copy len bytes from the offset position spos in source file sc to the offset position dpos in destination file dc.

int _FCopy(FCHAN dc, long dpos, FCHAN sc, long spos, long len)
FCHAN dc;                  /* File channel of destination file. */
long dpos;                  /* Offset position to start copying to. */
FCHAN sc;                  /* File channel of source file. */
long spos;                  /* Offset position to start copying from. */
long len;                     /* Number of bytes to copy. */

Remarks

_FCopy( ) returns True (an integer other than 0) if it succeeds, or False (0) if it fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates two files. It writes the text "Hello, world" to the first of these files and then copies the contents of this file, beginning with the third byte, to the second file.

Visual FoxPro Code

SET LIBRARY TO FCOPY

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan1, fchan2;
   int len;

   fchan1 = _FCreate("temp1.txt", FC_NORMAL);
   _FPuts(fchan1, "Hello, world.");
   _FFlush(fchan1);

   len = _FSeek(fchan1, 0, FS_FROMEOF); // determine length of file

   fchan2 = _FCreate("temp2.txt", FC_NORMAL);
   _FCopy(fchan2, 0, fchan1, 2, len - 2);

   _FClose(fchan1);
   _FClose(fchan2);
}

FoxInfo myFoxInfo[] = {
   {"FCOPY", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FPuts( ) API Library Routine | _FWrite( ) API Library Routine | _FCreate( ) API Library Routine | Accessing the Visual FoxPro API


_FCreate( ) API Library Routine

Assigns a Visual FoxPro channel to a new file.

FCHAN _FCreate(char FAR *filename, int mode)
char FAR *filename;         /* Name of file to create. */
int mode;                     /* File attributes. */

Remarks

If a file with the specified name already exists, _FCreate( ) truncates the existing file to zero bytes.

The mode parameter may be one or more of the following flags: FC_READONLY, FC_SYSTEM, FC_HIDDEN, and FC_TEMPORARY. You can combine these flags using the C | or + operator. An additional flag, FC_NORMAL, specifies that the file has none of the other attributes. FC_TEMPORARY files are automatically deleted when you call _FClose( ) to close the file.

_FCreate( ) returns the file channel if it succeeds in creating the file, or – 1 if it fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _FCreate( ) to create a number of files using the various mode flags of _FCreate( ).

Visual FoxPro Code

SET LIBRARY TO FCREATE

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;

   fchan = _FCreate("normal.tmp", FC_NORMAL);
   _FClose(fchan);

   fchan = _FCreate("readonly.tmp", FC_READONLY);
   _FClose(fchan);

   fchan = _FCreate("hidden.tmp", FC_HIDDEN);
   _FClose(fchan);

   fchan = _FCreate("system.tmp", FC_SYSTEM);
   _FClose(fchan);

   fchan = _FCreate("temp.tmp", FC_TEMPORARY);
   _FClose(fchan);

   fchan = _FCreate("multi.tmp", FC_SYSTEM | FC_READONLY);
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FCREATE", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FClose( ) API Library Routine | _FOpen( ) API Library Routine | Accessing the Visual FoxPro API


_FEOF( ) API Library Routine

int _FEOF(FCHAN chan)
FCHAN chan;               /* File channel of file. */

Remarks

_FEOF( ) returns True (an integer other than 0) if the file pointer in the specified file is currently at the end of the file; or False (0) if not.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a file and sets its length to 8192 bytes. Then it moves the file pointer to the beginning of the file and calls _FEOF( ), which returns 0 (False). Next, it moves the file pointer to the end of the file and again calls _FEOF( ), which this time returns 1 (True).

Visual FoxPro Code

SET LIBRARY TO FEOF

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

    PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan =  FCreate("temp.txt", FC NORMAL);
    FCHSize(fchan, 8196);
    FFlush(fchan);

    FSeek(fchan, 0, FS FROMBOF);
    PutStr("\n FSeek(fchan, 0, FS FROMBOF)");
    PutStr("\n FEOF(fchan) ="); putLong(_FEOF(fchan));

   _FSeek(fchan, 0, FS_FROMEOF);
   _PutStr("\n_FSeek(fchan, 0, FS_FROMEOF)");
   _PutStr("\n_FEOF(fchan) ="); putLong(_FEOF(fchan));
}

FoxInfo myFoxInfo[] = {
   {"FEOF", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FSeek( ) API Library Routine | _FCopy( ) API Library Routine |_FWrite( ) API Library Routine | Accessing the Visual FoxPro API


_FError( ) API Library Routine

Returns the number of the last file operation error recorded for any file channel.

int _FError(void any)
void any;                     /* Pointer. */

Example

The following example uses _FOpen( ) to attempt to open a file called Nofile.abc, which presumably doesn't exist. It then calls _FError( ), which returns error number 2, for "file not found."

Visual FoxPro Code

SET LIBRARY TO FERROR

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan = _FOpen("nofile.abc", FC_READONLY);
   _PutStr("\nAttempted to _FOpen() a file which does not exist.");
   _PutStr("\n_FError() ="); putLong(_FError());
}

FoxInfo myFoxInfo[] = {
   {"FERROR", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FClose( ) API Library Routine | _FCreate( ) API Library Routine | _FOpen( ) API Library Routine


_FFlush( ) API Library Routine

Flushes to disk all modified buffers in memory for the specified file.

int _FFlush(FCHAN chan)
FCHAN chan;               /* File channel of file to flush. */

Remarks

_FFlush( ) returns 0 if it is successful in flushing the buffers, or – 1 if it fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a file and sets its length to 8196 bytes. Executing the Visual FoxPro command line DIR TEMP.TXT in the Command window shows that the size of the file on disk is still 0. However, after executing = XFFLUSH( ), issuing the command line DIR TEMP.TXT shows that the file on disk reflects the _FCHSize( ) call, and has a file size of 8196 bytes.

Visual FoxPro Code

SET LIBRARY TO FFLUSH
DIR temp.txt  && size on disk is still 0
WAIT WINDOW "File Size = 0"
= XFFLUSH()
DIR temp.txt  && size on disk is 8196
WAIT WINDOW "File Size Does Not Equal 0"
CLOSE ALL

C Code

#include <pro_ext.h>

static FCHAN fchan;

FAR CreateIt(ParamBlk FAR *parm)
{
   fchan = _FCreate("temp.txt", FC_NORMAL);
   _FCHSize(fchan, 8196);
}

FAR FFlushEx(ParamBlk FAR *parm)
{
   _FFlush(fchan);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) CreateIt, CALLONLOAD, ""},
   {"XFFLUSH", (FPFI) FFlushEx, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FPuts( ) API Library Routine | _FWrite( ) API Library Routine | _FError( ) API Library Routine | Accessing the Visual FoxPro API


_FGets( ) API Library Routine

Copies to the buffer a single line from the specified file, starting at the current position in the file.

unsigned int _FGets(FCHAN chan, char FAR *buffer, int maxlen)
FCHAN chan;               /* File channel of file from which to copy. */
char FAR *buffer;            /* Buffer address. */
int maxlen;                  /* Maximum length of line in bytes. */

Remarks

_FGets( ) copies a line of maxlen length, delimited with a carriage return. The carriage return is translated to a null terminator and stored in the buffer. Line feeds are ignored and aren't copied into the buffer. _FGets( ) returns the number of bytes copied to the buffer.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens a file specified by a parameter, and copies and shows each line in the file.

Visual FoxPro Code

SET LIBRARY TO FGETS
fc = FCREATE("x", 0)
= FPUTS(fc, REPL("X", 512), 512)
= FCLOSE(fc)
= XFGETS("x")
DELETE FILE x

C Code

#include <pro_ext.h>

#define BUFFSIZE 256
static char lineBuffer[BUFFSIZE];

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;

//   Null terminate file name
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);

   ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))
      [parm->p[0].val.ev_length] = '\0';

   if ((fchan=_FOpen((char FAR*)_HandToPtr(parm->p[0].val.ev_handle),
      FC_NORMAL)) < 0)
   {
      _UserError("Could not open file.");
   }
   _HUnLock(parm->p[0].val.ev_handle);

   while (!_FEOF(fchan))
   {
      _FGets(fchan, lineBuffer, BUFFSIZE);
      _PutStr(lineBuffer); _PutChr('\n');
   }
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"XFGETS", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FRead( ) API Library Routine | _FSeek( ) API Library Routine | Accessing the Visual FoxPro API


_FindMemo( ) API Library Routine

Returns the memory address of the first character in the memo field fld for the current record in the selected work area.

long _FindMemo(Locator FAR *fld)
Locator FAR *fld;            /* Memo field name. */

Remarks

_FindMemo( ) enables you to directly gain access to memo field contents for the current record. When the memo field for the current record is empty, or when fld is not the name of a memo field, _FindMemo( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example retrieves the contents of a memo field for the current record. It uses FindMemo( ) to find the location of the memo contents for the current record within the memo file. The example then moves the file pointer to this location with _FSeek( ), and stores the memo field contents in memory using _FRead( _MemoSize( )).

Visual FoxPro Code

SET LIBRARY TO FINDMEMO
CREATE TABLE WMemo (MemoField M)
APPEND BLANK
REPLACE MemoField WITH "Hello, World."
? GETMEMO(@MemoField)

C Code

#include <pro_ext.h>

FAR FindMemoEx(ParamBlk FAR *parm)
{

   Locator FAR *memoFldLoc;
   FCHAN fchMemo;
   char FAR *memoContents;
   int memoLen;
   long loc;

   if ((fchMemo = _MemoChan(-1)) == -1)
   {
      _UserError("_MemoChan() failed");
   }
   memoFldLoc = &parm->p[0].loc;

   if ((loc = _FindMemo(memoFldLoc)) < 0)
   {
      _UserError("_FindMemo() failed");
   }
   if ((memoLen = _MemoSize(memoFldLoc)) < 0)
   {
      _UserError("_MemoSize() failed");
   }
   if ((memoContents = _Alloca(memoLen + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _FSeek(fchMemo, loc, FS_FROMBOF);
   _FRead(fchMemo, memoContents, memoLen);
   memoContents[memoLen] = '\0';
   _RetChar(memoContents);
}

FoxInfo myFoxInfo[] = {
   {"GETMEMO", (FPFI) FindMemoEx, 1, "R"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocMemo( ) API Library Routine | _DBReplace( ) API Library Routine | _MemoChan( ) API Library Routine | _MemoSize( ) API Library Routine


_FindVar( ) API Library Routine

Provides a way to initialize a Locator so you can use _Store( ) to place data in an existing memory variable or field.

int _FindVar(NTI nti, int where, Locator FAR *loc)
NTI nti;                     /* NTI number of variable or field. */
int where;                  /* Work area number. */
Locator FAR *loc;            /* Locator. */

Remarks

_FindVar( ) fills in the passed Locator with information about a variable or field named nti that exists in a work area specified by where.

  • If where is – 1, nti is assumed to be a memory variable.
  • If where is 1 – 225, nti is assumed to be a field in the work area of the specified number.
  • If where is 0, _FindVar first checks to see if nti is a memory variable. If it's not a memory variable, the current work area is checked for a field with the specified NTI.

_FindVar( ) returns True (an integer other than 0) if a variable or field nti is found in where; otherwise, _FindVar( ) returns False (0).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the value of a Visual FoxPro variable in a very roundabout way.

Visual FoxPro Code

SET LIBRARY TO FINDVAR
TestVar= "This is a test"
= QMARK("TestVar")

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR NameTableIndexEx(ParamBlk FAR *parm)
{
   NTI nti;
   char FAR *name;
   Locator loc;
   Value val;

//   Null terminate character string, name of variable
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   name = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   name[parm->p[0].val.ev_length] = '\0';

   nti = _NameTableIndex(name);

   _FindVar(nti, 0, &loc);
   _Load(&loc, &val);
   _PutValue(&val);
}

FoxInfo myFoxInfo[] = {
   {"QMARK", (FPFI) NameTableIndexEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _Load( ) API Library Routine | _NameTableIndex( ) API Library Routine | _NewVar( ) API Library Routine | _ObjectRelease( ) API Library Routine | _Store( ) API Library Routine


_FindWindow( ) API Library Routine

Places the handle of the window that the point pt belongs to on the screen into wh.

int _FindWindow(WHANDLE FAR *wh, Point pt)
WHANDLE FAR *wh;      /* Pointer to window handle. */
Point pt;                     /* Point. */

Remarks

_FindWindow( ) returns an integer indicating the portion of the window where the point is located. For example, _FindWindow( ) returns the value inContent if the point is inside the window.

Possible return values, as defined in PRO_EXT.H, are listed in the following table.

_FindWindow( ) Return Values

Value | Point Location
inBorder | In the window border
inHelp | In the help region
inContent | In the content/text area
inDrag | On the title bar
inGrow | On the size control
inGoAway | On the close box
inZoom | On the zoom control
inVUpArrow | On the up arrow in the vertical scroll bar
inVDownArrow | On the down arrow in the vertical scroll bar
inVPageUp | In the page up region of the vertical scroll bar
inVPageDown | In the page down region of the vertical scroll bar
inVThumb | On the thumb in the vertical scroll bar
inHUpArrow | On the right arrow in the horizontal scroll bar
inHDownArrow | On the left arrow in the horizontal scroll bar
inHPageUp | In the page right region of the horizontal scroll bar
inHPageDown | In the page left region of the horizontal scroll bar
inHThumb | On the thumb in the horizontal scroll bar
inMenuBar | On the menu bar

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example waits for a left mouse button click and then uses _FindWindow( ) to get the window handle for the mouse down position.

Visual FoxPro Code

WAIT WINDOW  "Click mouse on a window" NOWAIT
SET LIBRARY TO FINDWIND

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}
FAR FindWindowFn(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point mousePos;
   int where;

//  Get mouse position when left button goes down
   while (_InKey(0, MOUSEACTIVE | HIDECURSOR) != 151);
   while (!_MousePos(&mousePos));

   switch (where = _FindWindow(&wh, mousePos))
   {
      case inBorder:
         _PutStr("\nMouse down inBorder"); break;
      case inHelp:
         _PutStr("\nMouse down inHelp"); break;
      case inContent:
         _PutStr("\nMouse down inContent"); break;
      case inDrag:
         _PutStr("\nMouse down inDrag"); break;
      case inGrow:
         _PutStr("\nMouse down inGrow"); break;
      case inGoAway:
         _PutStr("\nMouse down inGoAway"); break;
      case inZoom:
         _PutStr("\nMouse down inZoom"); break;
      case inVUpArrow:
         _PutStr("\nMouse down inVUpArrow"); break;
      case inVDownArrow:
         _PutStr("\nMouse down inVDownArrow"); break;
      case inVPageUp:
         _PutStr("\nMouse down inVPageUp"); break;
      case inVPageDown:
         _PutStr("\nMouse down inVPageDown"); break;
      case inVThumb:
         _PutStr("\nMouse down inVThumb"); break;
      case inHUpArrow:
         _PutStr("\nMouse down inHUpArrow"); break;
      case inHDownArrow:
         _PutStr("\nMouse down inHDownArrow"); break;
      case inHPageUp:
         _PutStr("\nMouse down inHPageUp"); break;
      case inHPageDown:
         _PutStr("\nMouse down inHPageDown"); break;
      case inHThumb:
         _PutStr("\nMouse down inHThumb"); break;
      case inMenuBar:
         _PutStr("\nMouse down inMenuBar"); break;
      default:
         _PutStr("\nMouse down someplace else"); break;
   }
   _GlobalToLocal(&mousePos, wh);
   _PutStr("\nPosition relative to window:");
   putLong(mousePos.v, 5);
   _PutChr(' ');
   putLong(mousePos.h, 5);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) FindWindowFn, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_MousePos( ) API Library Routine | Accessing the Visual FoxPro API | _FindWindowP( ) API Library Routine


_FindWindowP( ) API Library Routine

Places the handle of the window that the point pt belongs to on the screen into wh.

int _FindWindowP(WHANDLE FAR *wh, Point pt)
WHANDLE FAR *wh;      /* Pointer to window handle. */
Point pt;                     /* Point in pixels. */

Remarks

_FindWindowP( ) returns an integer indicating the portion of the window where the point is located. For possible return values, see _FindWindow( ) API Library Routine.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example waits for a left mouse button click and then uses _FindWindowP( ) to get the window handle for the mouse down position.

Visual FoxPro Code

WAIT WINDOW "Click Mouse In Window" NOWAIT
SET LIBRARY TO FINDWINP

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR FindWindowEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point mousePos;
   int where;

//  Get mouse position when left button goes down
   while (_InKey(0, MOUSEACTIVE | HIDECURSOR) != 151);
   while (!_MousePosP(&mousePos));

   switch (where = _FindWindowP(&wh, mousePos))
   {
      case inBorder:
         _PutStr("\nMouse down inBorder"); break;
      case inHelp:
         _PutStr("\nMouse down inHelp"); break;
      case inContent:
         _PutStr("\nMouse down inContent"); break;
      case inDrag:
         _PutStr("\nMouse down inDrag"); break;
      case inGrow:
         _PutStr("\nMouse down inGrow"); break;
      case inGoAway:
         _PutStr("\nMouse down inGoAway"); break;
      case inZoom:
         _PutStr("\nMouse down inZoom"); break;
      case inVUpArrow:
         _PutStr("\nMouse down inVUpArrow"); break;
      case inVDownArrow:
         _PutStr("\nMouse down inVDownArrow"); break;
      case inVPageUp:
         _PutStr("\nMouse down inVPageUp"); break;
      case inVPageDown:
         _PutStr("\nMouse down inVPageDown"); break;
      case inVThumb:
         _PutStr("\nMouse down inVThumb"); break;
      case inHUpArrow:
         _PutStr("\nMouse down inHUpArrow"); break;
      case inHDownArrow:
         _PutStr("\nMouse down inHDownArrow"); break;
      case inHPageUp:
         _PutStr("\nMouse down inHPageUp"); break;
      case inHPageDown:
         _PutStr("\nMouse down inHPageDown"); break;
      case inHThumb:
         _PutStr("\nMouse down inHThumb"); break;
      case inMenuBar:
         _PutStr("\nMouse down inMenuBar"); break;
      default:
         _PutStr("\nMouse down someplace else"); break;
   }
   _GlobalToLocalP(&mousePos, wh);
   _PutStr("\nPosition relative to window:");
   putLong(mousePos.v, 5);
   _PutChr(' ');
   putLong(mousePos.h, 5);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", FindWindowEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _MousePos( ) API Library Routine | Accessing the Visual FoxPro API


_FOpen( ) API Library Routine

Assigns a Visual FoxPro channel to an existing file.

FCHAN _FOpen(char FAR *filename, int mode)
char FAR *filename;         /* Name of existing file */
int mode;                     /* Mode option. */

Remarks

The following mode options are available: FO_READONLY, FO_WRITEONLY, and FO_READWRITE. _FOpen( ) opens a file with exclusive access. _FOpen( ) returns the file channel if it's successful in opening the file, or returns – 1 if it can't open the file.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a test file. It then opens the file in FO_READONLY mode and attempts to write to it. As a result _FError( ) returns 5 for "Access denied." Next, the example opens the test file in FO_WRITEONLY mode, and attempts to read from it. Again, _FError( ) returns 5.

Visual FoxPro Code

SET LIBRARY TO FOPEN

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

#define BUFFSIZE 256
static char lineBuffer[BUFFSIZE];

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;

   fchan = _FCreate("temp.tmp", FC_NORMAL);
   _FCHSize(fchan, 8192);
   _FClose(fchan);

   fchan = _FOpen("temp.tmp", FO_READONLY);
   _FPuts(fchan, "Hello, world");
   _PutStr("\nAttempt to _FPuts() to file _FOpen()d FO_READONLY");
   _PutStr("\n_FError() ="); putLong(_FError());
   _FClose(fchan);

   fchan = _FOpen("temp.tmp", FO_WRITEONLY);
   _FGets(fchan, lineBuffer, BUFFSIZE);
   _PutStr("\nAttempt to _FGets() from file _FOpen()d FO_WRITEONLY");
   _PutStr("\n_FError() ="); putLong(_FError());
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FOPEN", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FClose( ) API Library Routine | _FCreate( ) API Library Routine | _FError( ) API Library Routine | Accessing the Visual FoxPro API


_FPuts( ) API Library Routine

Writes a specified null-terminated string to a file, followed by a carriage return/line feed pair.

unsigned int _FPuts(FCHAN chan, char FAR *buffer)
FCHAN chan;               /* File channel of file to write to. */
char FAR *buffer;            /* String to write. */

Remarks

_FPuts( ) returns the total number of bytes it writes to the file.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a file, and writes the text "Hello, world." to the file using _FPuts( ).

Visual FoxPro Code

SET LIBRARY TO FPUTS

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;

   fchan = _FCreate("temp.tmp", FC_NORMAL);
   _FPuts(fchan, "Hello, world.");
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FPUTS", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FFlush( ) API Library Routine | _FSeek( ) API Library Routine | _FWrite( ) API Library Routine | Accessing the Visual FoxPro API


_FRead( ) API Library Routine

Copies to the buffer exactly length bytes from a file into buffer.

unsigned int _FRead(FCHAN chan, char FAR *buffer, int length)
FCHAN chan;               /* File channel of file from which to copy. */
char FAR *buffer;            /* Buffer address. */
int length;                  /* Number of bytes to be copied. */

Remarks

_FRead( ) doesn't add a terminator to the end of the bytes in the buffer. No translation is performed on the bytes when they are stored in the buffer. _FRead( ) returns the number of bytes read.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a test file and places text in it. The example then attempts to read 32 bytes from the file using _FRead( ).

Visual FoxPro Code

SET LIBRARY TO FREAD

C Code

#include <pro_ext.h>

#define BUFFSIZE 32
static char buffer[BUFFSIZE];

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;
   int bytesRead;

   fchan = _FCreate("temp.tmp", FC_NORMAL);
   _FPuts(fchan, "Hello, world.");
   _FPuts(fchan, "Hello, world.");
   _FPuts(fchan, "Hello, world.");
   _FPuts(fchan, "Hello, world.");
   _FPuts(fchan, "Hello, world.");

   _FSeek(fchan, 0, FS_FROMBOF);

   bytesRead = _FRead(fchan, buffer, BUFFSIZE - 1);
   buffer[bytesRead] = '\0';
   _PutStr(buffer);

   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FREAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FGets( ) API Library Routine | _FSeek( ) API Library Routine | Accessing the Visual FoxPro API


_FreeHand( ) API Library Routine

Releases a memory handle hand previously allocated by means such as _AllocHand( ).

void _FreeHand(MHANDLE hand)
MHANDLE hand;            /* Memory handle. */

Example

The following example allocates 1024 blocks of 16384-byte memory blocks, for a total of 16 MB, freeing each memory block using _FreeHand( ) before allocating the next.

Visual FoxPro Code

SET LIBRARY TO FREEHAND

C Code

#include <pro_ext.h>

void FAR Example(ParamBlk FAR *parm)
{
   MHANDLE mh;
   int i;

   for (i = 0; i < 1024; i++)
   {
      if ((mh = _AllocHand(16384)) == 0)
      {
         _Error(182);  // "Insufficient memory"
      }
      _FreeHand(mh);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) API Library Routine | _HUnLock( ) API Library Routine | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine


_FreeObject( ) API Library Routine

Releases an object from the Visual FoxPro API data pool.

void _FreeObject(Value FAR *objct)

Remarks

Use _FreeObject( ) to free an object from the Visual FoxPro API object table.

_FreeObject( )is used in the following cases:

1. If an object reference is returned from any Visual FoxPro API function (for example, _Evaluate( ) or _GetObjectProperty( )), you must use _FreeObject( ) to release the object when you are no longer using it.

2. If you keep a reference to an object across different Visual FoxPro API calls, you must first use _ObjectReference( ) to increment the count for the object. When you are no longer using the object, you must then use _ObjectRelease( ) to decrement the count for the object and then use _FreeObject( ) to release the object.

In addition to the previous rules, you should always clear the Value structure you pass to any Visual FoxPro API function that returns a value into the passed Value structure. For example, you can create and call a function that clears the structure prior to calling any function that returns a value into your structure. You can also create and call a function to cleanup any object references or unused handles.

0 is returned unless an error occurs. When an error occurs, a negative number representing an internal error code is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

See Also

_ObjectReference( ) API Library Routine | _ObjectRelease( ) API Library Routine | _GetObjectProperty( ) API Library Routine | _Evaluate( ) API Library Routine


_FSeek( ) API Library Routine

Moves the file pointer to a new location as specified by position and mode.

long _FSeek(FCHAN chan, long position, int mode)
FCHAN chan;               /* File channel. */
long position;               /* Position in file. */
int mode;                     /* How to determine new location */

Remarks

If mode is 0 (absolute), the file pointer is set to the value of position. If mode is 1, (relative to file pointer), the value of position is added to the current file pointer position. If mode is 2 (relative to the end of the file), _FSeek( ) moves the file pointer past the end of the file. _FSeek( ) returns the new position of the file pointer. For example, _FSeek(chan, 0L, 2) moves the file pointer to the end of the file and returns the file length in bytes.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example consists of one API routine, which takes two parameters, a file name, and an integer. It opens the file. Using _FSeek( ) with the FS_FROMBOF flag, it then moves the file pointer to the offset position specified by the integer parameter, and reads a single byte from the file at that position.

Visual FoxPro Code

SET LIBRARY TO FSEEK
fc = FCREATE("x", 0)
= FPUTS(fc, "abcdefghijklmnopqrstuvwxyz", 26)
= FCLOSE(fc)

? XFSEEK("x", 2)  && displays 3rd byte of file x as an integer
? XFSEEK("x", 4)  && displays 5th byte of file x as an integer

DELETE FILE x

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;
   char x;

   // Null terminate file name
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);

   ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))
      [parm->p[0].val.ev_length] = '\0';

   if ((fchan=_FOpen((char FAR*)_HandToPtr(parm->p[0].val.ev_handle),
      FC_NORMAL)) < 0)
   {
      _UserError("Could not open file.");
   }
   _HUnLock(parm->p[0].val.ev_handle);

   _FSeek(fchan, parm->p[1].val.ev_long, FS_FROMBOF);
   _FRead(fchan, &x, 1);
   _RetInt(x, 10);
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"XFSEEK", (FPFI) Example, 2, "C,I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FCopy( ) API Library Routine | _FFlush( ) API Library Routine | _FGets( ) API Library Routine | _FPuts( ) API Library Routine


_FWrite( ) API Library Routine

Writes exactly length bytes from your buffer to a file specified by chan.

unsigned int _FWrite(FCHAN chan, char FAR *buffer, int length)
FCHAN chan;               /* File channel of file to write to. */
char FAR *buffer;            /* Buffer address. */
int length;                  /* Number of bytes to write. */

Remarks

_FWrite( ) doesn't add a terminator to the file. No translation is performed on the bytes before they are written. _FWrite( ) returns the number of bytes written.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a test file and writes some data to it using _FWrite( ).

Visual FoxPro Code

SET LIBRARY TO FWRITE

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   FCHAN fchan;

   fchan = _FCreate("temp.tmp", FC_NORMAL);
   _FWrite(fchan, "Hello, world.", _StrLen("Hello, world."));
   _FWrite(fchan, "\xd\xa", 2);
   _FWrite(fchan, "1234567890", 10);
   _FClose(fchan);
}

FoxInfo myFoxInfo[] = {
   {"FWRITE", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FFlush( ) API Library Routine | _FPuts( ) API Library Routine | _FSeek( ) API Library Routine | Accessing the Visual FoxPro API


_GetAPIHandle( ) API Library Routine

Returns the handle of the current FLL.

void _GetAPIHandle( )

Example

The following example returns the handle of the current FLL.

Visual FoxPro Code

SET LIBR TO GETAPIHA.FLL
? GETAPIHAND( )

C Code

#include <pro_ext.h>

void getAPIHandle()
{
_RetInt((int) _GetAPIHandle(),15);

}

FoxInfo myFoxInfo[] =
{
   {"GETAPIHAND",  (FPFI) getAPIHandle, 0, ""},
};

FoxTable _FoxTable =
{
   (FoxTable  *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Accessing the Visual FoxPro API | Creating a Basic FLL Library | _ActivateHandler( ) API Library Routine | _DeActivateHandler( ) API Library Routine


_GetHandSize( ) API Library Routine

Returns the usable number of bytes associated with a specified memory block handle hand.

unsigned long _GetHandSize(MHANDLE hand)
MHANDLE hand;            /* Handle of memory block. */

Remarks

The usable number of bytes is always greater than or equal to the number of bytes most recently requested for this MHANDLE by _AllocHand( ) or by a successful _SetHandSize( ) call.

Note _GetHandSize( ) doesn't cause memory reorganization.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example allocates memory blocks of various size from 1 to 215 and shows the value returned by _GetHandSize( ) for these allocations. Notice that the value returned by _GetHandSize( ) is only sometimes exactly equal to the size requested by _AllocHand( ); usually it's a bit more.

Visual FoxPro Code

SET LIBRARY TO GETHANDS

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 5;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   MHANDLE mh;
   unsigned int allocSize;

   for (allocSize = 1;; allocSize *= 2)
   {
      if ((mh = _AllocHand(allocSize)) == 0)
      {
         _Error(182);  // "Insufficient memory"
      }
      _PutStr("\n_AllocHand("); putLong(allocSize); _PutStr(")");
      _PutStr("\n_GetHandSize() ="); putLong(_GetHandSize(mh));
      _FreeHand(mh);
      if (allocSize == 32768)
      {
         break;
      }
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) | _HUnLock( ) API Library Routine | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine


_GetItemCmdKey( ) API Library Routine

Copies the displayed keyboard shortcut string for the specified menu item to the buffer pointed to by the text parameter.

int _GetItemCmdKey(MENUID menuid, ITEMID itemid, char FAR *text)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */
char FAR *text;            /* Where to store the shortcut string. */

Remarks

_GetItemCmdKey( ) returns the internal keyboard code for the keyboard shortcut. If there is no keyboard shortcut for the specified menu item, _GetItemCmdKey( ) returns 0.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items, setting up a keyboard shortcut for each item. It uses _GetItemCmdKey( ) to display the shortcut keys.

Visual FoxPro Code

SET LIBRARY TO GETICMDK

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;
   _PutValue(&val);
}

FAR GetItemCmdKeyEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;
   char FAR *shortcutString;
   int intKeyCode;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x78, "Alt+1");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x79, "Alt+2");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x7a, "Alt+3");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);

   if ((shortcutString = _Alloca(64)) == 0)
   {
      _DisposeMenu(menuId);
      _Error(182); // "Insufficient memory"
   }
   intKeyCode = _GetItemCmdKey(menuId, _GetItemId(menuId, 0),
      shortcutString);
   _PutStr("\nShortcut string = "); _PutStr(shortcutString);
   _PutStr("\nInternal key code ="); putLong(intKeyCode);

   intKeyCode = _GetItemCmdKey(menuId, _GetItemId(menuId, 1),
      shortcutString);
   _PutStr("\nShortcut string = "); _PutStr(shortcutString);
   _PutStr("\nInternal key code ="); putLong(intKeyCode);

   intKeyCode = _GetItemCmdKey(menuId, _GetItemId(menuId, 2),
      shortcutString);
   _PutStr("\nShortcut string = "); _PutStr(shortcutString);
   _PutStr("\nInternal key code ="); putLong(intKeyCode);
   _Execute("WAIT");
   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetItemCmdKeyEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemSubMenu( ) API Library Routine | _NewItem( ) API Library Routine | _SetItemCmdKey( ) API Library Routine | Accessing the Visual FoxPro API


_GetItemId( ) API Library Routine

Returns the item identifier of the specified item in the specified menu.

ITEMID _GetItemId(MENUID menuid, long index)
MENUID menuid;            /* Menu identifier. */
long index;                  /* Menu item number. */

Remarks

You can use _GetItemId( ) to gather menu bar or menu identifiers, so you can perform an operation on all the items. _GetItemId( ) returns 0 when index exceeds the number of items on the menu.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items. It uses _GetItemId( ) to get the ITEMID of each menu item. After removing one item from the menu, you can see that the ITEMID isn't always equal to the item index.

Visual FoxPro Code

SET LIBRARY TO GETIID

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetItemIdEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);

   _PutStr("\nitemid for index 0 ="); putLong(_GetItemId(menuId, 0));
   _PutStr("\nitemid for index 1 ="); putLong(_GetItemId(menuId, 1));
   _PutStr("\nitemid for index 2 ="); putLong(_GetItemId(menuId, 2));

   _Execute("WAIT WINDOW");
   _DisposeItem(menuId, _GetItemId(menuId, 1));

   _PutStr("\nitemid for index 0 ="); putLong(_GetItemId(menuId, 0));
   _PutStr("\nitemid for index 1 ="); putLong(_GetItemId(menuId, 1));

   _Execute("WAIT WINDOW");
   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetItemIdEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemSubMenu( ) API Library Routine | _GetNewItemId( ) API Library Routine | Accessing the Visual FoxPro API | NewItemID Property


_GetItemSubMenu( ) API Library Routine

Returns the menu item identifier of a submenu assigned to a menu item.

MENUID _GetItemSubMenu(MENUID menuid, ITEMID itemid);
MENUID menuid;            /* Menu identifier */
ITEMID itemid;            /* Menu item identifier*/

Remarks

A submenu is treated as an independent menu. _GetItemSubMenu( ) returns the MENUID of the submenu assigned to a specified menu item, or a – 1 if there is no submenu assigned to the menu item.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu system and returns the sub menu ID.

Visual FoxPro Code

SET LIBRARY TO GETITEMS

C Code

#include <pro_ext.h>

MENUID SysMenuId, retMenuId;
MENUID PopupId;
ITEMID PadId;

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
}

void FAR StartUp()
{
      ITEMID Bar1Id;
      ITEMID Bar2Id;

    int Error;
//
//   Add new menu title to SYSMENU.
//
  SysMenuId = _MenuId(_SYSMENU);
  PadId = _GetNewItemId(SysMenuId);

   if (_NewItem(SysMenuId, PadId, _LASTITEM, "\\<Added menu title"))
  {
    _Error(623); /* "Menu item cannot be defined." */
  }
//
//   Define menu.
//
  PopupId = _GetNewMenuId();

  if (Error = _NewMenu(MPOPUP, PopupId))
  {
    _Error(-Error);
  }
   Bar1Id = _GetNewItemId(PopupId);
//
//      WARNING: Call _NewItem() before another _GetNewItemId().
//
   if (_NewItem(PopupId, Bar1Id, _LASTITEM, "\\<1st item"))
  {
    _Error(623); /* "Menu item cannot be defined." */
  }
   Bar2Id = _GetNewItemId(PopupId);

   if (_NewItem(PopupId, Bar2Id, _LASTITEM, "\\<2nd item"))
  {
    _Error(623); /* "Menu item cannot be defined." */
  }
//
//   Attach menu to menu title.
//
  _SetItemSubMenu(SysMenuId, PadId, PopupId);

  _PutStr("\nSubMenu Id = "); putLong(PopupId);

//
//  Set up selection action.
//
   retMenuId = _GetItemSubMenu(SysMenuId,PadId);
   _PutStr("\nThis is the return value from  _GetItemSubMenu.  retMenuId = "); putLong(retMenuId);

   _OnSelection(PopupId, -1, onSelection);
}

void FAR ShutDown()
{
  _DisposeItem(SysMenuId, PadId);
  _DisposeMenu(PopupId);
}

FoxInfo myFoxInfo[] =
{
   {"STARTUP",   (FPFI) StartUp,  CALLONLOAD, ""},
   {"SHUTDOWN",  (FPFI) ShutDown, CALLONUNLOAD, ""},
};

FoxTable _FoxTable =
{
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemId( ) API Library Routine | _NewItem( ) API Library Routine | _SetItemText( ) API Library Routine | Accessing the Visual FoxPro API


_GetItemText( ) API Library Routine

Copies the text of a menu bar or menu title to the buffer pointed to by text.

void _GetItemText(MENUID menuid, ITEMID itemid, char FAR *text)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */
char FAR *text;            /* Buffer address for text. */

Remarks

The buffer must be at least 80 bytes long.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items and then retrieves the text of each item with _GetItemText( ).

Visual FoxPro Code

SET LIBRARY TO GETITEXT

C Code

#include <pro_ext.h>

FAR GetItemTextEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;
   char FAR *itemText;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);

   if ((itemText = _Alloca(80)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _GetItemText(menuId, _GetItemId(menuId, 0), itemText);
   _PutStr("\nItem text of 1st item = "); _PutStr(itemText);

   _GetItemText(menuId, _GetItemId(menuId, 1), itemText);
   _PutStr("\nItem text of 2nd item = "); _PutStr(itemText);

   _GetItemText(menuId, _GetItemId(menuId, 2), itemText);
   _PutStr("\nItem text of 3rd item = "); _PutStr(itemText);

   _Execute("WAIT WINDOW");
   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetItemTextEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemSubMenu( ) API Library Routine | _NewItem( ) API Library Routine | _SetItemText( ) API Library Routine | Accessing the Visual FoxPro API


_GetNewItemId( ) API Library Routine

Returns an identifier that's currently available for use as an item identifier in the specified menu.

ITEMID _GetNewItemId(MENUID menuid)
MENUID menuid;            /* Menu identifier. */

Remarks

Every item in a menu must have an identifier that's unique to that menu.

After using _GetNewItemId( ), add the new item to the menu with _NewItem( ) before using _GetNewItemId( ) again. If you don't add the item to the menu, subsequent calls to _GetNewItemId( ) return the same ITEMID.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items. Before each item is added to the menu, a unique ITEMID is generated by calling _GetNewItemId( ).

Visual FoxPro Code

SET LIBRARY TO GETNWIID

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetNewItemId(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _MenuInteract(&menuId, &itemId);

   _PutStr("\nmenuId ="); putLong(menuId);
   _PutStr("\nitemId ="); putLong(itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetNewItemId, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemId( ) API Library Routine | Accessing the Visual FoxPro API | _SetItemText( ) API Library Routine | _NewItem( ) API Library Routine | _GetNewMenuId( ) API Library Routine


_GetNewMenuId( ) API Library Routine

Returns a menu identifier for use with other menu-related functions.

MENUID _GetNewMenuId(void any)
void any;                     /* Pointer. */

Remarks

Every menu must have a unique identifier.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a menu with three items. Before the example can create a menu using _NewMenu( ), it must use _GetNewMenuId( ) to generate a unique MENUID.

Visual FoxPro Code

SET LIBRARY TO GETNWMID

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetNewItemId(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _MenuInteract(&menuId, &itemId);

   _PutStr("\nmenuId ="); putLong(menuId);
   _PutStr("\nitemId ="); putLong(itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetNewItemId, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_DisposeMenu( ) API Library Routine | _MenuId( ) API Library Routine | Accessing the Visual FoxPro API


_GetNextEvent( ) API Library Routine

Reads the next event into the EventRec and returns the event type.

int _GetNextEvent(EventRec FAR *event)
EventRec FAR *event;   /* Event. */

Remarks

Null events are generated when no other activity has taken place. Idle routines shouldn't call _GetNextEvent( ). You can call _GetNextEvent( ) from an event handler but you must be careful, because _GetNextEvent( ) calls the event handler recursively.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example is a loop consisting of a call to _GetNextEvent( ), followed by a call to _DefaultProcess( ). All events during this procedure receive their default processing.

Visual FoxPro Code

SET LIBR TO GETNXEV

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   EventRec ev;
   int i;

   for (i = 0; i < 16; i++) {
      _GetNextEvent(&ev);
      _DefaultProcess(&ev);
   }
}
FoxInfo myFoxInfo[] = {
   {"ONLOAD", Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ActivateHandler( ) API Library Routine | _FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePos( ) API Library Routine | Accessing the Visual FoxPro API | _DefaultProcess( ) API Library Routine


_GetObjectProperty( ) API Library Routine

Returns a property value for an object.

int _GetObjectProperty(Value FAR *retval, Value FAR *objct,
   char FAR *prop)

Remarks

The object to return a property for is specified with *objct, and the property to return is specified with *prop.

The value returned is placed in the *retval value structure.

Note You must always fill the *retval structure with 0 prior to calling _GetObjectProperty( ).

_GetObjectProperty( ) returns 0 if it is successful; otherwise, the negative value of the corresponding Visual FoxPro error code is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

See Also

_SetObjectProperty( ) API Library Routine | Object Property | ReadObject Property


_GetOSPrompt( ) API Library Routine

Returns the text of a specified menu item. If the menu item contains an access key definition, the ampersand character is returned as well.

void _GetOSPrompt(MENUID menuid, ITEMID itemid, char FAR *text)
MENUID menuid;            /* ID of menu from which to get prompt */
MENUID itemuid ;            /* Index (0-based) of menu item. */
char FAR *text;               /* Text of menu command. */

Remarks

Can be used for developing applications with language-independent access keys.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example returns the text of the first command on the File menu.

Visual FoxPro Code

SET LIBRARY TO MENUPROMPT

C Code

#include <pro_ext.h>

void FAR menuprompt(ParamBlk FAR *parm)
{
   char prompt[256] ;
   MenuId men ;

   men = _MenuId(_FILE);
   _GetOSPrompt(men, 0, prompt); //File New...

   _RetChar(prompt);
}
FoxInfo myFoxInfo[] = {
   {"MENUPROMPT", (FPFI) menuprompt, 0, ""}
};

FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetNewMenuId( ) | _MenuId( ) | _NewMenu( ) | Accessing the Visual FoxPro API


_GlobalToLocal( ) API Library Routine

Translates a point in screen-relative coordinates to window-relative coordinates.

void _GlobalToLocal(Point FAR *pt, WHANDLE wh)
Point FAR *pt;               /* Point. */
WHANDLE wh;            /* Window handle. */

Remarks

Before calling _GlobalToLocal( ), call _FindWindow( ) to determine which window owns the point.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example waits for a left mouse button click and then uses _FindWindow( ) to get the window handle for the mouse position. _GlobalToLocal( ) takes both the window handle and the absolute mouse position as parameters, and returns the mouse position to a position relative to the window.

Visual FoxPro Code

SET LIBRARY TO GLTOLOC

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR FindWindowEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point mousePos;
   int where;

   // Get mouse position when left button goes down
   _Execute("WAIT WINDOW 'Click In A Window' NOWAIT");
   while (_InKey(0, MOUSEACTIVE | HIDECURSOR) != 151);
   while (!_MousePos(&mousePos));

   switch (where = _FindWindow(&wh, mousePos))
   {
      case inBorder:
         _PutStr("\nMouse down inBorder"); break;
      case inHelp:
         _PutStr("\nMouse down inHelp"); break;
      case inContent:
         _PutStr("\nMouse down inContent"); break;
      case inDrag:
         _PutStr("\nMouse down inDrag"); break;
      case inGrow:
         _PutStr("\nMouse down inGrow"); break;
      case inGoAway:
         _PutStr("\nMouse down inGoAway"); break;
      case inZoom:
         _PutStr("\nMouse down inZoom"); break;
      case inVUpArrow:
         _PutStr("\nMouse down inVUpArrow"); break;
      case inVDownArrow:
         _PutStr("\nMouse down inVDownArrow"); break;
      case inVPageUp:
         _PutStr("\nMouse down inVPageUp"); break;
      case inVPageDown:
         _PutStr("\nMouse down inVPageDown"); break;
      case inVThumb:
         _PutStr("\nMouse down inVThumb"); break;
      case inHUpArrow:
         _PutStr("\nMouse down inHUpArrow"); break;
      case inHDownArrow:
         _PutStr("\nMouse down inHDownArrow"); break;
      case inHPageUp:
         _PutStr("\nMouse down inHPageUp"); break;
      case inHPageDown:
         _PutStr("\nMouse down inHPageDown"); break;
      case inHThumb:
         _PutStr("\nMouse down inHThumb"); break;
      case inMenuBar:
         _PutStr("\nMouse down inMenuBar"); break;
      default:
         _PutStr("\nMouse down someplace else"); break;
   }
   _GlobalToLocal(&mousePos, wh);
   _PutStr("\nPosition relative to window:");
   putLong(mousePos.v, 5);
   _PutChr(' ');
   putLong(mousePos.h, 5);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) FindWindowEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _MousePos( ) API Library Routine | Accessing the Visual FoxPro API | _GlobalToLocalP( ) API Library Routine


_GlobalToLocalP( ) API Library Routine

Translates a point in screen-relative pixel coordinates to window-relative pixel coordinates.

void _GlobalToLocalP(Point FAR *pt, WHANDLE wh)
Point FAR *pt;               /* Point. */
WHANDLE wh;            /* Window handle. */

Remarks

Before calling _GlobalToLocalP( ), call _FindWindow( ) to determine which window owns the point.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example waits for a left mouse button click and then uses _FindWindowP( ) to get the window handle for the mouse position. _GlobalToLocalP( ) takes the window handle and the absolute mouse position as parameters, and returns the mouse position to a position relative to the window.

Visual FoxPro Code

SET LIBRARY TO GLTOLOCP

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR FindWindowEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point mousePos;
   int where;

   // Get mouse position when left button goes down
   _Execute("WAIT WINDOW 'Click In A Window' NOWAIT" );
   while (_InKey(0, MOUSEACTIVE | HIDECURSOR) != 151);
   while (!_MousePosP(&mousePos));

   switch (where = _FindWindowP(&wh, mousePos))
   {
      case inBorder:
         _PutStr("\nMouse down inBorder"); break;
      case inHelp:
         _PutStr("\nMouse down inHelp"); break;
      case inContent:
         _PutStr("\nMouse down inContent"); break;
      case inDrag:
         _PutStr("\nMouse down inDrag"); break;
      case inGrow:
         _PutStr("\nMouse down inGrow"); break;
      case inGoAway:
         _PutStr("\nMouse down inGoAway"); break;
      case inZoom:
         _PutStr("\nMouse down inZoom"); break;
      case inVUpArrow:
         _PutStr("\nMouse down inVUpArrow"); break;
      case inVDownArrow:
         _PutStr("\nMouse down inVDownArrow"); break;
      case inVPageUp:
         _PutStr("\nMouse down inVPageUp"); break;
      case inVPageDown:
         _PutStr("\nMouse down inVPageDown"); break;
      case inVThumb:
         _PutStr("\nMouse down inVThumb"); break;
      case inHUpArrow:
         _PutStr("\nMouse down inHUpArrow"); break;
      case inHDownArrow:
         _PutStr("\nMouse down inHDownArrow"); break;
      case inHPageUp:
         _PutStr("\nMouse down inHPageUp"); break;
      case inHPageDown:
         _PutStr("\nMouse down inHPageDown"); break;
      case inHThumb:
         _PutStr("\nMouse down inHThumb"); break;
      case inMenuBar:
         _PutStr("\nMouse down inMenuBar"); break;
      default:
         _PutStr("\nMouse down someplace else"); break;
   }
   _GlobalToLocalP(&mousePos, wh);
   _PutStr("\nPosition relative to window:");
   putLong(mousePos.v, 5);
   _PutChr(' ');
   putLong(mousePos.h, 5);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", FindWindowEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _MousePos( ) API Library Routine | _GlobalToLocal( ) API Library Routine | Accessing the Visual FoxPro API


_HandToPtr( ) API Library Routine

Translates a memory handle to a FAR (32-bit) pointer, which points to the memory allocated to this handle.

void FAR * _HandToPtr(MHANDLE hand)
MHANDLE hand;            /* Memory handle. */

Remarks

Visual FoxPro may reorganize memory any time control is passed to it or to another routine outside of the current module.

Note _HandToPtr( ) doesn't cause memory reorganization. The pointer returned by _HandToPtr( ) may become invalid any time control is passed back to Visual FoxPro, unless the MHANDLE is locked. Don't keep pointers to unlocked memory handles across an external function call, unless it is documented that the call doesn't cause memory reorganization.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays its character parameter on the screen. It uses _HandToPtr( ) to translate the memory handle of the API parameter to a C pointer.

Visual FoxPro Code

SET LIBRARY TO HANDTOPT
= HANDTOPTR("Hello, world.")  && displays "Hello, world" on screen

C Code

#include <pro_ext.h>

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   NullTerminate(&parm->p[0].val);
   _HLock(parm->p[0].val.ev_handle);
   _PutStr(_HandToPtr(parm->p[0].val.ev_handle));
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"HANDTOPTR", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HLock( ) API Library Routine | _HUnLock( ) | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine | Accessing the Visual FoxPro API


_HLock( ) API Library Routine

Locks a memory handle to prevent it from moving if Visual FoxPro requires memory reorganization.

void _HLock(MHANDLE hand)
MHANDLE hand;            /* Memory handle. */

Remarks

_HLock( ) doesn't cause memory reorganization. Unlock the MHANDLE as soon as the lock has served its purpose.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays its character parameter on the screen. It uses _HandToPtr( ) to translate the memory handle of the API parameter to a C pointer. Because Visual FoxPro may decide to reorganize memory during the call to _PutStr( ), to insure proper execution, the example locks the memory handle with _HLock( ). The example also calls _HUnLock( ) at the end, because the performance of Visual FoxPro can be adversely affected by locked memory handles.

Visual FoxPro Code

SET LIBRARY TO HLOCK
= HLOCK("Hello, world.") && displays "Hello, world" on screen

C Code

#include <pro_ext.h>

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   NullTerminate(&parm->p[0].val);
   _HLock(parm->p[0].val.ev_handle);
   _PutStr(_HandToPtr(parm->p[0].val.ev_handle));
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"HLOCK", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HUnLock( ) API Library Routine | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine | Accessing the Visual FoxPro API


_HUnLock( ) API Library Routine

Unlocks a memory handle so that Visual FoxPro can access it during memory reorganization.

void _HUnLock(MHANDLE hand)
MHANDLE hand;            /* Memory handle. /

Remarks

_HUnLock( ) doesn't cause memory reorganization.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _RetDateStr( ) to return a Visual FoxPro date type, assuming that the character parameter is a proper date. It issues _HUnLock( ) when memory handles no longer need to be locked, because the performance of Visual FoxPro can be adversely affected by locked memory handles.

Visual FoxPro Code

SET LIBRARY TO HUNLOCK
? DATES("2/16/95")  && returns date {02/16/95}

C Code

#include <pro_ext.h>

void FAR dates(ParamBlk FAR *parm)
{
   MHANDLE mh;
   char FAR *instring;

   if ((mh = _AllocHand(parm->p[0].val.ev_length + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   instring = _HandToPtr(parm->p[0].val.ev_handle);
   instring[parm->p[0].val.ev_length] = '\0';
   _RetDateStr(instring);
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"DATES", (FPFI) dates, 1, "C"}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) API Library Routine | _MemAvail( ) API Library Routine | _SetHandSize( ) API Library Routine


_InKey( ) API Library Routine

Returns the first key typed during the timeout period.

int _InKey(int timeout, int flag)
int timeout;                  /* Timeout period. */
int flag;                     /* Option(s). */

Remarks

The timeout period is specified as a number of operating system timer ticks (1000/second). A timeout period of 0 causes Visual FoxPro to wait until the user presses a key. A negative timeout value causes _InKey( ) to return to the calling program immediately if the user doesn't press a key.

You can specify flag as one or both of the following options:

  • SHOWCURSOR or HIDECURSOR
  • MOUSEACTIVE

Use SHOWCURSOR to force the cursor to appear, or HIDECURSOR to force the cursor to disappear. If neither is specified, the cursor respects the SYS(2002) setting. The additional flag value MOUSEACTIVE causes _InKey( ) to treat mouse clicks as keystrokes. _InKey returns 151 for a mouse click. To specify two flag values, use the C | or + operator.

Note Idle routines must not call _InKey( ).

You can write event handlers that call _InKey( ), but you must be careful because _InKey( ) calls the event handler recursively.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example calls _InKey( ) from Visual FoxPro with two flags.

Visual FoxPro Code

SET LIBRARY TO INKEY
#define SHOWCURSOR   1
#define HIDECURSOR   2
#define MOUSEACTIVE 4
= XINKEY(0, SHOWCURSOR + MOUSEACTIVE)

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetInt(_InKey((int) parm->p[0].val.ev_long,
      (int) parm->p[1].val.ev_long), 10);
}

FoxInfo myFoxInfo[] = {
   {"XINKEY", (FPFI) Example, 2, "I,I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

INKEY( ) Function | Accessing the Visual FoxPro API | ReadTimeout Property


_Load( ) API Library Routine

Places the value of the memory variable or current record field specified by loc into val.

int _Load(Locator FAR *loc, Value FAR *val)
Locator FAR *loc;         /* Variable location. */
Value FAR *val;            /* Holds value of the variable. */

Remarks

_Load( ) returns 0 if the routine is successful. If the routine fails, it returns a negative integer whose absolute value is a Visual FoxPro error number. You can use _Load( ) to retrieve the contents of a memo field, but it doesn't retrieve characters in the field after the first 65,000 bytes. If loc specifies a one-dimensional array, Visual FoxPro returns the value of the first element of the array.

_Load( ) doesn't work with objects. If loc specifies an object reference, _Load( ) returns 0 without filling the val Value structure. Use _Evaluate( ) to obtain an object reference.

If the setting of the Locator field l_offset is – 1, Visual FoxPro returns a logical value structure that indicates whether the current record in the specified work area is deleted:

  • ev_length = .T. = DELETED( )
  • ev_length = .F. = NOT DELETED( )
    Note _Load( ) creates a handle only when the memory variable your program is loading is a character string (ev_type = 'C'). All other data types store their values in the Value structure itself. Your program must free the handles created with _Load( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example converts to uppercase a string argument passed by reference.

Visual FoxPro Code

SET LIBRARY TO LOAD
x = "abc"
= XUPPER(@x)
? x

C Code

#include <pro_ext.h>

void FAR Upper(ParamBlk FAR *parm)
{
      char FAR *pString;
      Value val;
      int i;
//
//   _Load() and _Store are the functions of interest for pass-by-reference.
//
   _Load(&parm->p[0].loc, &val);
//
//   FoxPro doesn't check the type of pass-by-reference arguments, so we do.
//
  if (val.ev_type != 'C')
   {
      _Error(9); // "Data type mismatch"
   }
  pString = _HandToPtr(val.ev_handle);

   for (i = 0; i < val.ev_length; i++)
   {
      if ('a' <= *pString && *pString <= 'z')
      {
         *pString += ('A' - 'a');
      }
      pString++;
   }
   _Store(&parm->p[0].loc, &val);
   //
   // We need to free the handle that we created with  _LOAD()
   //
   _FreeHand(val.ev_handle);
}

FoxInfo myFoxInfo[] =
{
   {"XUPPER", (FPFI) Upper, 1, "R"},
};

FoxTable _FoxTable =
{
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _FindVar( ) API Library Routine | _NameTableIndex( ) API Library Routine | _NewVar( ) API Library Routine | _Release( ) | _Store( ) API Library Routine | Accessing the Visual FoxPro API


_MemAvail( ) API Library Routine

Determines whether enough memory is available for you to allocate a memory handle of size bytes.

BOOL _MemAvail(unsigned long size)
unsigned int size;            /* Size of memory handle in bytes. */

Remarks

The function returns True (an integer other than 0) if enough memory is available, or False (0) if not.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a linked list of 1K memory handle allocations until available memory is used. It then frees allocations and returns the number of allocations made. _MemAvail( ) is used to terminate the first while loop.

Visual FoxPro Code

SET LIBRARY TO MEMAVAIL
? MEMAVAIL()  && displays approx. memory available in K

C Code

#include <pro_ext.h>

#define ALLOCSIZE 1024

FAR Example(ParamBlk FAR *parm)
{
   int nHandles = 0;
   MHANDLE head = 0, mh;

   while (_MemAvail(ALLOCSIZE))
   {
      mh = _AllocHand(ALLOCSIZE);
      *((MHANDLE *) _HandToPtr(mh)) = head;
      head = mh;
      nHandles++;
   }
   _RetInt(nHandles, 10);
   while (head != 0)
   {
      mh = *((MHANDLE *) _HandToPtr(head));
      _FreeHand(head);
      head = mh;
   }
}

FoxInfo myFoxInfo[] = {
   {"MEMAVAIL", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) API Library Routine | _HUnLock( ) API Library Routine | _SetHandSize( ) API Library Routine | Accessing the Visual FoxPro API


_MemCmp( ) API Library Routine

Compares two length byte memory areas.

int _MemCmp(void FAR *ptr1, void FAR *ptr2, unsigned int length)
void FAR *ptr1;            /* First point to start compare. */
void FAR *ptr2;            /* Second point to start compare. */
unsigned int length;         /* How much to compare in bytes. */

Remarks

_MemCmp( ) compares each byte in the two areas, starting with the leftmost byte in each, until two bytes don't match. _MemCmp( ) returns 0 if all bytes in the areas match, a positive number if the first unmatched byte in the first area is greater than the corresponding byte in the second area, or a negative number if the first unmatched byte in the second area is greater than the corresponding byte in the first area.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _MemCmp( ) to compare two character parameters up to the length of the first unmatched byte.

Visual FoxPro Code

SET LIBRARY TO MEMCMP
? MEMCMP("Hello, world.", "Hello, world.")  && returns 0
? MEMCMP("Hello, world.", "Hello, wurld.")  && returns non-0

C Code

#include <pro_ext.h>

#define min(a, b) ((a) < (b) ? (a) : (b))

FAR Example(ParamBlk FAR *parm)
{
   int LenToCmp, RetValue;

   LenToCmp = min(parm->p[0].val.ev_length, parm->p[1].val.ev_length);

   _HLock(parm->p[0].val.ev_handle);
   _HLock(parm->p[1].val.ev_handle);

   RetValue = _MemCmp(_HandToPtr(parm->p[0].val.ev_handle),
      _HandToPtr(parm->p[1].val.ev_handle), LenToCmp);

   _RetInt(RetValue, 10); // does return control here

   _HUnLock(parm->p[0].val.ev_handle);
   _HUnLock(parm->p[1].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"MEMCMP", (FPFI) Example, 2, "C,C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_MemFill( ) API Library Routine | _MemMove( ) API Library Routine | Accessing the Visual FoxPro API


_MemFill( ) API Library Routine

Fills an area of memory starting at the location pointed to by ptr with length copies of the byte in character.

void _MemFill(void FAR *ptr, int character, unsigned int length)
void FAR *ptr;               /* Starting point for fill. */
int character;               /* Character for fill. */
unsigned int length;         /* How many bytes to fill. */

Example

The following example uses _MemFill( ) to duplicate the functionality of the Visual FoxPro function REPLICATE( ).

Visual FoxPro Code

SET LIBRARY TO MEMFILL
x = xREPLICATE("x", 120)
? x
? LEN(x)

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   char FAR *rep;
   char c = *(char *) _HandToPtr(parm->p[0].val.ev_handle);

   rep = _Alloca((int) parm->p[1].val.ev_long + 1);

   _MemFill(rep, c, (int) parm->p[1].val.ev_long);

  rep[parm->p[1].val.ev_long] = '\0';
   _RetChar(rep);
}
FoxInfo myFoxInfo[] = {
   {"XREPLICATE", (FPFI) Example, 2, "C,I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_MemCmp( ) API Library Routine | _MemMove( ) API Library Routine | _MemAvail( ) API Library Routine


_MemMove( ) API Library Routine

Copies length bytes starting from src to dest.

void _MemMove(void FAR *dest, void FAR *src, unsigned int length)
void FAR *dest;            /* Destination. */
void FAR *src;               /* Starting position. */
unsigned int length;         /* How many bytes to move. */

Remarks

Overlapping moves are performed in the appropriate direction to prevent data corruption.

For more information on how to create an API library and integrate it with Visual FoxPro, see see Accessing the Visual FoxPro API.

Example

The following example uses _MemMove( ) to implement a substring function. From Visual FoxPro, MEMMOVE(s, n1, n2) returns the substring of s starting from position n1 and through position n2.

Visual FoxPro Code

SET LIBRARY TO MEMMOVE
? MEMMOVE("Hello, world.", 8, 10)  && returns "wor"

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int SubstrLen;
   MHANDLE bufferHandle;
   char FAR *FirstDest;

   SubstrLen = parm->p[2].val.ev_long - parm->p[1].val.ev_long + 1;
   if ((bufferHandle = _AllocHand(SubstrLen + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(bufferHandle);
   _HLock(parm->p[0].val.ev_handle);
   FirstDest = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle) +
      parm->p[1].val.ev_long - 1;

   _MemMove(_HandToPtr(bufferHandle), FirstDest, SubstrLen);

   ((char FAR *) _HandToPtr(bufferHandle))[SubstrLen] = '\0';
   _RetChar(_HandToPtr(bufferHandle));
   _HUnLock(bufferHandle);
   _HUnLock(parm->p[0].val.ev_handle);
}
FoxInfo myFoxInfo[] = {
   {"MEMMOVE", (FPFI) Example, 3, "C,I,I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_MemCmp( ) API Library Routine | _MemFill( ) API Library Routine | Accessing the Visual FoxPro API


_MemoChan( ) API Library Routine

Returns the file channel of the memo file associated with the specified workarea.

FCHAN _MemoChan(int workarea)
int workarea;               /* Work area number. */

Remarks

If no database is open in that work area or the database has no memo file, _MemoChan( ) returns – 1.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example retrieves the contents of a memo field. _MemoChan( – 1) returns a file channel to the memo file for the current work area. This FCHAN is used as an argument to the low-level file I/O API callbacks.

Visual FoxPro Code

SET LIBRARY TO MEMOCHAN
CREATE TABLE WMemo (MemoField M)
APPEND BLANK
REPLACE MemoField WITH "Hello, World."
? GETMEMO(@MemoField)

C Code

#include <pro_ext.h>

FAR FindMemoEx(ParamBlk FAR *parm)
{
   Locator FAR *memoFldLoc;
   FCHAN fchMemo;
   char FAR *memoContents;
   int memoLen;
   long loc;

   if ((fchMemo = _MemoChan(-1)) == -1)
   {
      _UserError("_MemoChan() failed");
   }
   memoFldLoc = &parm->p[0].loc;

   if ((loc = _FindMemo(memoFldLoc)) < 0)
   {
      _UserError("_FindMemo() failed");
   }
   if ((memoLen = _MemoSize(memoFldLoc)) < 0)
   {
      _UserError("_MemoSize() failed");
   }
   if ((memoContents = _Alloca(memoLen + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _FSeek(fchMemo, loc, FS_FROMBOF);
   _FRead(fchMemo, memoContents, memoLen);
   memoContents[memoLen] = '\0';
   _RetChar(memoContents);
}

FoxInfo myFoxInfo[] = {
   {"GETMEMO", (FPFI) FindMemoEx, 1, "R"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocMemo( ) API Library Routine | _DBReplace( ) API Library Routine | _FindMemo( ) API Library Routine | _FOpen( ) API Library Routine | _MemoSize( ) API Library Routine | Accessing the Visual FoxPro API


_MemoSize( ) API Library Routine

Returns the length of the specified memo field in the memo file for the current record.

long _MemoSize(Locator FAR *fld)
Locator FAR *fld;            /* Memo field address. */

Remarks

When the memo field for the current record is empty, or when fld isn't a memo field, _MemoSize( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example retrieves the contents of a memo field for the current record. _MemoSize( ) is used to determine how much memory should be allocated for a buffer, and how many bytes should be read from the memo file.

Visual FoxPro Code

SET LIBRARY TO MEMOSIZE
CREATE TABLE WMemo (MemoField M)
APPEND BLANK
REPLACE MemoField WITH "Hello, World."
? GETMEMO(@MemoField)

C Code

#include <pro_ext.h>

FAR FindMemoEx(ParamBlk FAR *parm)
{

   Locator FAR *memoFldLoc;
   FCHAN fchMemo;
   char FAR *memoContents;
   int memoLen;
   long loc;

   if ((fchMemo = _MemoChan(-1)) == -1)
   {
      _UserError("_MemoChan() failed");
   }
   memoFldLoc = &parm->p[0].loc;

   if ((loc = _FindMemo(memoFldLoc)) < 0)
   {
      _UserError("_FindMemo() failed");
   }
   if ((memoLen = _MemoSize(memoFldLoc)) < 0)
   {
      _UserError("_MemoSize() failed");
   }
   if ((memoContents = _Alloca(memoLen + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _FSeek(fchMemo, loc, FS_FROMBOF);
   _FRead(fchMemo, memoContents, memoLen);
   memoContents[memoLen] = '\0';
   _RetChar(memoContents);
}

FoxInfo myFoxInfo[] = {
   {"GETMEMO", (FPFI) FindMemoEx, 1, "R"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocMemo( ) API Library Routine | _DBReplace( ) API Library Routine | _FindMemo( ) API Library Routine | _MemoChan( ) API Library Routine | Accessing the Visual FoxPro API


_MenuId( ) API Library Routine

Returns the menu identifier that corresponds to the system-defined literal for the system menu or menu title.

MENUID _MenuId(long literal)
long literal;                  /* System-defined literal. */

Remarks

Literals are defined in the API include file PRO_EXT.H.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example adds a menu title to the system menu. It then attaches a drop-down menu with two items on it. _MenuId( ) is used to obtain the MENUID of the system menu.

Visual FoxPro Code

SET LIBRARY TO MENUID

C Code

#include <pro_ext.h>

MENUID SysMenuId;
MENUID PopupId;
ITEMID PadId;

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
}

void FAR StartUp()
{
   ITEMID Bar1Id;
   ITEMID Bar2Id;
   int Error;

   // Add new menu title to SYSMENU.
   SysMenuId = _MenuId(_SYSMENU);
   PadId = _GetNewItemId(SysMenuId);

   if (_NewItem(SysMenuId, PadId, _LASTITEM, "\\<Added menu title"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }

   // Define menu.
   PopupId = _GetNewMenuId();

   if (Error = _NewMenu(MPOPUP, PopupId))
   {
      _Error(-Error);
   }
   Bar1Id = _GetNewItemId(PopupId);

   // WARNING: Call _NewItem() before another _GetNewItemId().
   if (_NewItem(PopupId, Bar1Id, _LASTITEM, "\\<1st item"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }
   Bar2Id = _GetNewItemId(PopupId);

   if (_NewItem(PopupId, Bar2Id, _LASTITEM, "\\<2nd item"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }

   // Attach menu to menu title
   _SetItemSubMenu(SysMenuId, PadId, PopupId);

   // Set up selection action.
   _OnSelection(PopupId, -1, onSelection);
}

void FAR ShutDown()
{
   _DisposeItem(SysMenuId, PadId);
   _DisposeMenu(PopupId);
}

FoxInfo myFoxInfo[] = {
   {"STARTUP",   (FPFI) StartUp,   CALLONLOAD,""},
   {"SHUTDOWN",   (FPFI) ShutDown,   CALLONUNLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

SYS(1500) - Activate a System Menu Item | _GetNewMenuId( ) API Library Routine | System Menu Names | _MenuInteract( ) API Library Routine


_MenuInteract( ) API Library Routine

Sets the itemid and the menuid to indicate which menu item was chosen, if any.

int _MenuInteract(MENUID FAR *menuid, ITEMID FAR *itemid)
MENUID FAR *menuid;      /* Pointer to menu identifier. */
ITEMID FAR *itemid;      /* Pointer to menu item identifier. */

Remarks

If the user chooses any menu item, _MenuInteract( ) returns 1. If no item is chosen (for example, if the user presses ESC) _MenuInteract( ) returns 0.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a menu with three items, and then requires the user to interact with the menu by calling _MenuInteract( ).

Visual FoxPro Code

SET LIBRARY TO MENUINTE

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetNewItemId(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _MenuInteract(&menuId, &itemId);

   _PutStr("\nmenuId ="); putLong(menuId);
   _PutStr("\nitemId ="); putLong(itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetNewItemId, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_MenuId( ) API Library Routine | Accessing the Visual FoxPro API | _OnSelection( ) | _GetNewMenuId( ) API Library Routine


_MousePos( ) API Library Routine

Fills in pt with the current position of the mouse pointer.

int _MousePos(Point FAR *pt)
Point FAR *pt;               /* Pointer. */

Remarks

_MousePos( ) returns True (an integer other than 0) if the left mouse button is down when the function is called, or False (0) if the left mouse button isn't down.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the current mouse pointer position until it detects a left mouse button click.

Visual FoxPro Code

SET LIBRARY TO MOUSEPOS

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR MousePosEx(ParamBlk FAR *parm)
{
   Point mousePos;

   while (!_MousePos(&mousePos))
   {
      _PutStr("\nvertical =");
      putLong(mousePos.v, 5);
      _PutStr("; horizontal =");
      putLong(mousePos.h, 5);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) MousePosEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | _MousePosP( ) API Library Routine | Accessing the Visual FoxPro API


_MousePosP( ) API Library Routine

Fills in pt with the current position of the mouse pointer in pixels.

int _MousePosP(Point FAR *pt)
Point FAR *pt;               /* Pointer. */

Remarks

_MousePosP( ) returns True (an integer other than 0) if the left mouse button is down when the function is called, or False (0) if the left mouse button isn't down.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the current mouse pointer position until it detects a left mouse button click.

Visual FoxPro Code

SET LIBRARY TO MOUSEPOP

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR MousePosPEx(ParamBlk FAR *parm)
{
   Point mousePos;

   while (!_MousePosP(&mousePos))
   {
      _PutStr("\nvertical =");
      putLong(mousePos.v, 5);
      _PutStr("; horizontal =");
      putLong(mousePos.h, 5);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) MousePosPEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_FindWindow( ) API Library Routine | _GlobalToLocal( ) API Library Routine | Accessing the Visual FoxPro API


_NameTableIndex( ) API Library Routine

Returns the name table index that corresponds to a given name, or returns – 1 if that name isn't in the name table.

NTI _NameTableIndex(char FAR *name)
char FAR *name;            /* Name. */

Remarks

The name may be found in the name table even though a variable with the name name doesn't exist. To determine whether a variable with the name name exists, use _FindVar( ), specifying the name table index returned by _NameTableIndex( ) as the nti parameter.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example releases a memory variable whose name is given as a character argument. Note that _NameTableIndex( ) finds the variable name after it has been released. Therefore, _NameTableIndex( ) is used in combination with _FindVar( ) to make sure the memory variable is currently defined.

Visual FoxPro Code

SET LIBRARY TO NTI
x = 123
= XRELEASE("x")

C Code

#include <pro_ext.h>

FAR ReleaseEx(ParamBlk FAR *parm)
{
   NTI nti;
   char FAR *name;
   int exitCode;
   Locator loc;

   //   Null terminate character string, name of variable
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   name = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   name[parm->p[0].val.ev_length] = '\0';

   if ((nti = _NameTableIndex(name)) == -1)
   {
      _HUnLock(parm->p[0].val.ev_handle);
      _UserError("Cannot find variable in name table.");
   }
   _HUnLock(parm->p[0].val.ev_handle);

   if (_FindVar(nti, -1, &loc))
   {
      _PutStr("\nVariable exists prior to _Release().");
   }
   if ((exitCode =_Release(nti)) < 0)
   {
      _Error(-exitCode);
   }

   _HLock(parm->p[0].val.ev_handle);
   name = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   name[parm->p[0].val.ev_length] = '\0';

   if ((nti = _NameTableIndex(name)) != -1)
   {
      _PutStr("\n_NameTableIndex() still finds variable \
         after it is released.");
   }
   _HUnLock(parm->p[0].val.ev_handle);

   if (!_FindVar(nti, -1, &loc))
   {
      _PutStr("\nVariable does not exist after _Release().");
   }
}

FoxInfo myFoxInfo[] = {
   {"XRELEASE", (FPFI) ReleaseEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _FindVar( ) API Library Routine | _Load( ) API Library Routine | _NewVar( ) API Library Routine | _ObjectRelease( ) API Library Routine | _Store( ) API Library Routine | Accessing the Visual FoxPro API


_NewItem( ) API Library Routine

Adds an item with the specified identifier itemid to the menu specified by menuid.

int _NewItem(MENUID menuid, ITEMID itemid, ITEMID
beforeid, char FAR *prompt)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* New item identifier. */
ITEMID beforeid;            /* Identifier of item the new item
 precedes. */
char FAR *prompt;         /* Text for new menu item. */

Remarks

The type of the new menu item is automatically a menu title or a bar, depending on the type of menu into which the item is being inserted.

The beforeid parameter specifies the identifier of the item the new item is to precede. Specify beforeid as – 1 to specify the new item will be the first item in the list, or as -2 to specify the item is to be added at the end of the list. The prompt specifies the text for the new menu item. _NewItem( ) returns 0 if it succeeds in adding an item, or – 1 if not.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a menu with three items. It uses _NewItem( ) to add each item to the menu.

Visual FoxPro Code

SET LIBRARY TO NEWITEM

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetNewItemId(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -1, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _MenuInteract(&menuId, &itemId);

   _PutStr("\nmenuId ="); putLong(menuId);
   _PutStr("\nitemId ="); putLong(itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetNewItemId, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_SetItemCmdKey( ) API Library Routine | _SetItemSubMenu( ) API Library Routine | Accessing the Visual FoxPro API


_NewMenu( ) API Library Routine

Creates a new menu of the specified menu type.

int _NewMenu(int mtype, MENUID menuid)
int mtype;                  /* Menu type. */
MENUID menuid;            /* Menu identifier. */

Remarks

You can specify MPOPUP or MBAR as the mtype parameter. The menu identifier must be unique.

Use _GetNewMenuId( ) to obtain an available menu id. _NewMenu( ) returns 0 if it succeeds in creating a new menu. If it's unsuccessful, _NewMenu( ) returns a negative integer whose absolute value is a Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _NewMenu( ) to create a menu.

Visual FoxPro Code

SET LIBRARY TO NEWMENU

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR GetNewItemId(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -1, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _MenuInteract(&menuId, &itemId);

   _PutStr("\nmenuId ="); putLong(menuId);
   _PutStr("\nitemId ="); putLong(itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) GetNewItemId, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ActivateMenu( ) API Library Routine | _GetNewMenuId( ) API Library Routine | _GetNewMenuId( ) API Library Routine | Accessing the Visual FoxPro API


_NewVar( ) API Library Routine

Creates a variable or an array.

NTI _NewVar(char FAR *name, Locator FAR *loc, int flag)
char FAR *name;            /* Variable name. */
Locator FAR *loc;            /* Place. */
int flag;                     /* Scope. */

Remarks

The NTI type definition stands for Name Table Index. See _NameTableIndex( ) API Library Routine for more information about Name Table Index use.

The variable or array name must follow standard Visual FoxPro rules for variable names. The new variable is initialized to the logical value False.

The setting of the Locator field l_subs determines the variable or array type:

  • 0 – a scalar variable
  • 1 – a one-dimensional array of size l_sub1
  • 2 – an array of size l_sub1 by l_sub2 For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

The flag parameter can be NV_PUBLIC or NV_PRIVATE. NV_PRIVATE variables are created as though they were created by the Visual FoxPro routine that called the external routine.

If _NewVar( ) successfully creates the variable, the field l_NTI is filled in with the non-negative NTI of the created variable, and _NewVar( ) returns this number. If _NewVar( ) fails, it returns a negative integer whose absolute value is an internal Visual FoxPro error number.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _NewVar( ) to create three variables.

Visual FoxPro Code

SET LIBRARY TO NEWVAR
*
* As defined in "pro_ext.h"
*
#define NV_PUBLIC   0
#define NV_PRIVATE   1

= xNewVar('var', 0, 0, 0, NV_PUBLIC)
DISPLAY MEMORY LIKE var

= xNewVar('onedim', 1, 5, 0, NV_PUBLIC)
DISPLAY MEMORY LIKE onedim

= xNewVar('twodim', 2, 5, 6, NV_PUBLIC)
DISPLAY MEMORY LIKE twodim

C Code

#include <pro_ext.h>

void FAR NewVarEx(ParamBlk FAR *parm)
{
   char FAR *varName;
   Locator loc;
   int flag;
   int retValue;

   // Null terminate character string
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   varName = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   varName[parm->p[0].val.ev_length] = '\0';
   loc.l_subs = parm->p[1].val.ev_long;
   loc.l_sub1 = parm->p[2].val.ev_long;
   loc.l_sub2 = parm->p[3].val.ev_long;
   flag = parm->p[4].val.ev_long;
   if ((retValue = _NewVar(varName, &loc, flag)) < 0)
   {
      // _NewVar() returns negative Visual FoxPro error number
      _Error(-retValue);
   }
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"XNEWVAR", (FPFI) NewVarEx, 5, "C,I,I,I,I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _FindVar( ) API Library Routine | _Load( ) API Library Routine | _NameTableIndex( ) API Library Routine | _ObjectRelease( ) API Library Routine | _Store( ) API Library Routine | Accessing the Visual FoxPro API


_ObjectCmp( ) API Library Routine

Compares the properties of two objects and returns 0 if their properties and property values are identical.

int _ObjectCmp(Value FAR *objct1, Value FAR *objct2)

Remarks

0 is returned if the objects have identical properties and property values. -1 is returned if an object has a property that the other object doesn't have, or if the objects have identical properties but the values of one or more properties differ.

If an error occurs (for example, if you omit one of the objects), the negative value of the corresponding Visual FoxPro error code is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

See Also

_GetObjectProperty( ) API Library Routine | _SetObjectProperty( ) API Library Routine | Accessing the Visual FoxPro API


_ObjectReference( ) API Library Routine

Increments the reference count of an object.

int _ObjectReference(Value FAR *objct)

Remarks

CLEAR MEMORY or CLEAR ALL releases an API object from memory.

0 is returned unless an error occurs. When an error occurs, a negative number representing an internal error code is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

See Also

_FreeObject( ) API Library Routine | _ObjectRelease( ) API Library Routine | Accessing the Visual FoxPro API


_ObjectRelease( ) API Library Routine

Decrements the reference count of an object.

int _ObjectRelease(Value FAR *objct)

Remarks

0 is returned unless an error occurs. When an error occurs, a negative number representing an internal error code is returned.

See Also

_FreeObject( ) API Library Routine | _ObjectReference( ) API Library Routine | Accessing the Visual FoxPro API


_OnSelection( ) API Library Routine

Specifies a routine to execute when the user chooses the specified menu and item.

void _OnSelection(MENUID menuid, ITEMID itemid, FPFI routine)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Item identifier. */
FPFI routine;               /* Routine to execute. */

Remarks

If you specify itemid as – 1, the routine executes when the user chooses any item on the menu. A routine associated with an individual item overrides one associated with the entire menu. To cancel a selection routine for a specified menu and item, pass (FPFI)0 as the routine parameter.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu with three items. It calls _OnSelection( ) with an ITEMID parameter of –1, indicating that the function USERCHOICE( ) is to be called when the user chooses any item from this menu.

Visual FoxPro Code

SET LIBRARY TO ONSELECT

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
   _DisposeMenu(menuId);
}

FAR activateMenu(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _OnSelection(menuId, -1, onSelection);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) activateMenu, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Accessing the Visual FoxPro API | _ActivateMenu( ) API Library Routine | _MenuInteract( ) API Library Routine


_PutChr( ) API Library Routine

Displays the one character char at the output position in the current output window in its normal attribute (color 0).

void _PutChr(int char)
int char;                     /* Character to display. */

Remarks

_PutChr( ) treats special characters such as newline, carriage return, and bell as control characters and doesn't display them on the screen.

To display the character that corresponds to one of these control characters, add 256 to the value of the character.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _PutChr( ) to display all 8-bit characters on the screen.

Visual FoxPro Code

SET LIBRARY TO PUTCHR

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int ch;

   for (ch = 0; ch < 256; ch++)
   {
      _PutChr(ch);
   }
}

FoxInfo myFoxInfo[] = {
   {"PUTCHR", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_PutStr( ) API Library Routine | _PutValue( ) API Library Routine | Accessing the Visual FoxPro API


_PutStr( ) API Library Routine

Displays a null-terminated string at the output position in the current output window in its normal attribute (color 0).

void _PutStr(char FAR *str)
char FAR *str;               /* String to display. */

Remarks

_PutStr( ) treats special characters such as newline, carriage return, and bell as control characters and doesn't display them on the screen.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _PutStr( ) to display its character type parameter in uppercase on the screen.

Visual FoxPro Code

SET LIBRARY TO PUTSTR
= XUPPER("upper")  && displays "UPPER" on the screen

C Code

#include "pro_ext.h"

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   char FAR *pString;
   int i;

   NullTerminate(&parm->p[0].val);
   pString = _HandToPtr(parm->p[0].val.ev_handle);
   for (i = 0; i < parm->p[0].val.ev_length; i++)
   {
      if ('a' <= *pString && *pString <= 'z')
      {
         *pString += ('A' - 'a');
      }
      pString++;
   }
   _HLock(parm->p[0].val.ev_handle);
   _PutStr(_HandToPtr(parm->p[0].val.ev_handle));
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"XUPPER", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_PutChr( ) API Library Routine | _PutValue( ) API Library Routine | Accessing the Visual FoxPro API | _WPutChr( ) API Library Routine | _WPutStr( ) API Library Routine


_PutValue( ) API Library Routine

Writes the value val at the output position in the current output window.

void _PutValue(Value FAR *val)
Value FAR *val;            /* Value to display. */

Example

The following example uses _PutValue( ) to display its Character-type parameter in uppercase on the screen.

Visual FoxPro Code

SET LIBRARY TO PUTVALUE
= XUPPER("upper")  && displays "UPPER" on screen

C Code

#include "pro_ext.h"

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}
FAR Example(ParamBlk FAR *parm)
{
   char FAR *pString;
   int i;

   NullTerminate(&parm->p[0].val);
   pString = _HandToPtr(parm->p[0].val.ev_handle);
   for (i = 0; i < parm->p[0].val.ev_length; i++)
   {
      if ('a' <= *pString && *pString <= 'z')
      {
         *pString += ('A' - 'a');
      }
      pString++;
   }
   _PutValue(&parm->p[0].val);
}

FoxInfo myFoxInfo[] = {
   {"XUPPER", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_PutChr( ) API Library Routine | _PutStr( ) API Library Routine | Accessing the Visual FoxPro API | _WPutChr( ) API Library Routine | _WPutStr( ) API Library Routine


_Release( ) API Library Routine

Releases from memory the specified memory variable or array.

int _Release(NTI n)
NTI n;                     /* NTI number of variable or array
 to release. */

Remarks

_Release( ) returns 0 if it successfully releases the memory variable or array, or an integer whose absolute value is a Visual FoxPro error number if it fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example releases a memory variable whose name is given as a character argument. _NameTableIndex( ) is used to find the NTI of the variable.

Visual FoxPro Code

SET LIBRARY TO RELEASE
x = 123
= XRELEASE("x")

C Code

#include <pro_ext.h>

FAR ReleaseEx(ParamBlk FAR *parm)
{
   NTI nti;
   char FAR *name;
   int exitCode;
   Locator loc;

   // Null terminate character string, name of variable
   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   name = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   name[parm->p[0].val.ev_length] = '\0';

   if ((nti = _NameTableIndex(name)) == -1)
   {
      _HUnLock(parm->p[0].val.ev_handle);
      _UserError("Cannot find variable in name table.");
   }

   _HUnLock(parm->p[0].val.ev_handle);
   if (_FindVar(nti, -1, &loc))
   {
      _PutStr("\nVariable exists prior to _Release().");
   }
   if ((exitCode =_Release(nti)) < 0)
   {
      _Error(-exitCode);
   }
   _HLock(parm->p[0].val.ev_handle);
   name = (char FAR *) _HandToPtr(parm->p[0].val.ev_handle);
   name[parm->p[0].val.ev_length] = '\0';

   if ((nti = _NameTableIndex(name)) != -1)
   {
      _PutStr("\n_NameTableIndex() still finds variable \
         after it is released.");
   }
   _HUnLock(parm->p[0].val.ev_handle);

   if (!_FindVar(nti, -1, &loc))
   {
      _PutStr("\nVariable does not exist after _Release().");
   }
}

FoxInfo myFoxInfo[] = {
   {"XRELEASE", (FPFI) ReleaseEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _FindVar( ) API Library Routine | _Load( ) | _NameTableIndex( ) API Library Routine | _NewVar( ) API Library Routine | _Store( ) API Library Routine


_RetChar( ) API Library Routine

Sets the library return value to a null-terminated string.

void _RetChar(char FAR *string)
char FAR *string;            /* String. */

Remarks

If you need to return a string that might contain embedded null characters, use the _RetVal( ) function.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example makes two calls to _RetChar( ), demonstrating that control returns to the API routine from _RetChar( ) and that the last _RetChar( ) determines the value returned to Visual FoxPro.

Visual FoxPro Code

SET LIBRARY TO RETCHAR

C Code

#include <pro_ext.h>

void FAR chars(ParamBlk FAR *parm)
{
   char message[] = "Hello, world";
   _RetChar(message);
}
FoxInfo myFoxInfo[] = {
   {"CHARS", (FPFI) chars, 0, ""}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetCurrency( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetInt( ) | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetCurrency( ) API Library Routine

Sets the library return value to a currency value.

void _RetCurrency(CCY money, int width)
CCY money;         /* CCY - LARGE_INTEGER. */
int width;         /* Number of columns to display. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example converts a numeric type value to currency type value.

Visual FoxPro Code

SET LIBRARY TO RETCURR
? xntom(100.1)

C Code

#include <pro_ext.h>
#include <math.h>

void FAR retcurr(ParamBlk FAR *parm)
{
   CCY money;

   money.HighPart = (long) (parm->p[0].val.ev_real*10000 / pow(2,32));

   money.LowPart = (unsigned long) ((parm->p[0].val.ev_real - (double) (money.HighPart * pow(2,32)/10000.0)) *10000);

   _RetCurrency(money,25);
}

FoxInfo myFoxInfo[] = {
   {"XNTOM", (FPFI) retcurr, 1, "N"}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetInt( ) API Library Routine | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetDateStr( ) API Library Routine

Sets the library return value to a date.

void _RetDateStr(char FAR *string)
char FAR *string;            /* Date string. */

Remarks

Specify the date string in mm/dd/year format, in which the year may be either two or four digits.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example converts a character string into a date data type and returns it to Visual FoxPro.

Visual FoxPro Code

SET LIBRARY TO RETDATES
? DATES("02/16/95")  && returns date {02/16/95}

C Code

#include <pro_ext.h>

void FAR dates(ParamBlk FAR *parm)
{
   MHANDLE mh;
   char FAR *instring;

   if ((mh = _AllocHand(parm->p[0].val.ev_length + 1)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   instring = _HandToPtr(parm->p[0].val.ev_handle);
   instring[parm->p[0].val.ev_length] = '\0';
   _RetDateStr(instring);
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"DATES", (FPFI) dates, 1, "C"}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetInt( ) API Library Routine | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetDateTimeStr( ) API Library Routine

Sets the library return value to a datetime.

void _RetDateTimeStr(char FAR *string)
char FAR *string;            /* Datetime string. */

Remarks

Specify the datetime string in mm/dd/year hh:mm:ss format, in which the year may be either two or four digits. See CTOT( ) Function for a list of valid datetime formats for the datetime string.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example converts a date type value to datetime type value.

Visual FoxPro Code

SET LIBRARY TO RETDT
? xctot("2/16/95 12:07am")

C Code

#include <pro_ext.h>

void FAR datetime(ParamBlk FAR *parm)
{
  MHANDLE mh;
  char FAR *instring;

   if ((mh = _AllocHand(parm->p[0].val.ev_length + 1)) == 0) {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   instring = _HandToPtr(parm->p[0].val.ev_handle);
   instring[parm->p[0].val.ev_length] = '\0';
   _RetDateTimeStr(instring);
   _HUnLock(parm->p[0].val.ev_handle);
}
FoxInfo myFoxInfo[] = {
   {"XCTOT", (FPFI) datetime, 1, "C"}
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

CTOT( ) Function | _RetChar( ) API Library Routine | _RetCurrency( ) | _RetFloat( ) API Library Routine | _RetInt( ) API Library Routine | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetFloat( ) API Library Routine

Sets the library return value to a float value.

void _RetFloat(double flt, int width, int dec)
double flt;                  /* Double precision floating point
 value. */
int width;                     /* Number of columns for number
 display. */
int dec;                     /* Number of decimal places. */

Remarks

The width parameter specifies the number of columns Visual FoxPro uses when displaying the number, including a decimal point if one is needed. If you don't know the width, use 20. The dec parameter specifies the number of decimal places in the number. You must correctly set the number of decimal places to guarantee that Visual FoxPro correctly processes the number. If the number of decimal places isn't zero, the width must be at least two greater than dec.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _RetFloat( ) to return the floating point representation of a Visual FoxPro date parameter.

Visual FoxPro Code

SET LIBRARY TO RETFLOAT
? RETFLOAT({2/16/95})  && returns float representation of date {2/16/95}

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetFloat(parm->p[0].val.ev_real, 20, 4);
}

FoxInfo myFoxInfo[] = {
   {"RETFLOAT", (FPFI) Example, 1, "D"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetInt( ) API Library Routine | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetInt( ) API Library Routine

Sets the library return value to a numeric value.

void _RetInt(long ival, int width)
long ival;                     /* Long integer value. */
int width;                     /* Number of columns to display number. */

Remarks

The width parameter specifies the number of columns Visual FoxPro uses when displaying the number. If you don't know the width, use 10.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example performs some operations on the table open in the current work area. It displays the value returned by _RecCount( ).

Visual FoxPro Code

SET LIBRARY TO RETINT
? CTEST()

C Code

#include  <pro_ext.h>
#define nl _PutChr('\n')

long FAR CTest()
{
   long rc,rec;
   int workarea = -1;
   int flag = 0;
   int rn,recn;

   rc = _DBRewind(workarea);
   _PutStr("top");  nl;
   rc = _DBSkip(workarea, 5);
   _PutStr("skipped 5");  nl;

   rc = _DBAppend(workarea,flag);
   _PutStr("Appending"); nl;
   rc = _DBRewind(workarea);
   _PutStr("top");  nl;
   rn = _DBRecCount(workarea);
   _RetInt(rn, 10);
   rec = rn;
   return rn;
}

FoxInfo myFoxInfo[] = {
   {"CTEST", (FPFI) CTest,0 , ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *)0, sizeof(myFoxInfo) / sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetLogical( ) API Library Routine | _RetVal( ) API Library Routine


_RetLogical( ) API Library Routine

Sets the library return value to a logical value.

void _RetLogical(int flag)
int flag;                     /* Flag. */

Remarks

_RetLogical( ) considers zero to be False, and any non-zero value to be True.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example is a coin flip. It returns .T. or .F. based on the library function RAND( ).

Visual FoxPro Code

SET LIBRARY TO RETLOGIC
? RETLOGICAL()  && returns .T. or .F. pseudo-randomly

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   _RetLogical(rand() % 2);
}

FoxInfo myFoxInfo[] = {
   {"RETLOGICAL", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetInt( ) API Library Routine | _RetVal( ) API Library Routine


_RetVal( ) API Library Routine

Returns any Visual FoxPro data type, except Memo.

void _RetVal(Value FAR *val)
Value FAR *val;            /* Pointer to value structure. */

Remarks

_RetVal( ) passes a complete Visual FoxPro Value structure. You must call _RetVal( ) to return a string that contains embedded null characters.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _RetVal( ) to return its Character-type parameter converted to uppercase.

Visual FoxPro Code

SET LIBRARY TO RETVAL
? XUPPER("upper")  && returns "UPPER"

C Code

#include "pro_ext.h"

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1)) {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   char FAR *pString;
   int i;

   NullTerminate(&parm->p[0].val);
   pString = _HandToPtr(parm->p[0].val.ev_handle);
   for (i = 0; i < parm->p[0].val.ev_length; i++)
   {
      if ('a' <= *pString && *pString <= 'z')
      {
         *pString += ('A' - 'a');
      }
      pString++;
   }
   _RetVal(&parm->p[0].val);
}

FoxInfo myFoxInfo[] = {
   {"XUPPER", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_RetChar( ) API Library Routine | _RetCurrency( ) API Library Routine | _RetDateStr( ) API Library Routine | _RetDateTimeStr( ) API Library Routine | _RetFloat( ) API Library Routine | _RetInt( ) API Library Routine | _RetLogical( ) API Library Routine


_SetHandSize( ) API Library Routine

Changes the amount of memory allocated to the memory block handle hand.

unsigned short _SetHandSize(MHANDLE hand, unsigned long size)
MHANDLE hand;            /* Memory block handle. */
unsigned int size;            /* New number of bytes. */

Remarks

_SetHandSize( ) returns True (an integer other than 0) if the reallocation is successful, or False (0) if the reallocation fails. The data associated with the MHANDLE is preserved. If hand is a locked MHANDLE, _SetHandSize( ) fails.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _SetHandSize( ) to change the amount of memory allocated to an MHANDLE.

Visual FoxPro Code

SET LIBRARY TO SETHANDS
= HANDTOPTR("Hello, world.") && displays "Hello, world" on screen

C Code

#include <pro_ext.h>

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   NullTerminate(&parm->p[0].val);

   _HLock(parm->p[0].val.ev_handle);
   _PutStr(_HandToPtr(parm->p[0].val.ev_handle));
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"HANDTOPTR", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_AllocHand( ) API Library Routine | _FreeHand( ) API Library Routine | _GetHandSize( ) API Library Routine | _HandToPtr( ) API Library Routine | _HLock( ) API Library Routine | _HUnLock( ) API Library Routine | _MemAvail( ) API Library Routine


_SetItemCmdKey( ) API Library Routine

Sets both the keyboard shortcut for the specified menu item, and the displayed text for the keyboard shortcut.

void _SetItemCmdKey(MENUID menuid, ITEMID itemid, int key,
 char FAR *text)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */
int key;                     /* Shortcut key. */
char FAR *text;            /* Displayed text. */

Remarks

If you don't want to display a keyboard shortcut, pass text as a pointer to a null string. If you want the system to generate the default displayed text, pass (char FAR *)0.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example sets up a menu with three items and assigns a keyboard shortcut to each item.

Visual FoxPro Code

SET LIBRARY TO SETICMDK

C Code

#include <pro_ext.h>

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
   _DisposeMenu(menuId);
}

FAR SetItemCmdKeyEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x178, "Alt+1");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x179, "Alt+2");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");
   _SetItemCmdKey(menuId, itemId, altKey | 0x17a, "Alt+3");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _OnSelection(menuId, -1, onSelection);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) SetItemCmdKeyEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemCmdKey( ) API Library Routine | _GetItemId( ) API Library Routine | Accessing the Visual FoxPro API | _SetItemSubMenu( ) API Library Routine | _SetItemText( ) API Library Routine


_SetItemSubMenu( ) API Library Routine

Assigns a submenu to the specified menu item.

void _SetItemSubMenu(MENUID menuid, ITEMID itemid,
                        MENUID submenuid)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */
MENUID submenuid;         /* Submenu identifier. */

Remarks

You can use _SetItemSubMenu( ) to attach a menu to a menu title or to a submenu to a menu item.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example adds a menu title to the system menu. Using _SetItemSubMenu( ), it then attaches a menu with two items to this menu title.

Visual FoxPro Code

SET LIBRARY TO SETISUBM

C Code

#include <pro_ext.h>

MENUID SysMenuId;
MENUID PopupId;
ITEMID PadId;

void putLong(long n)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = 10;

   _PutValue(&val);
}

FAR onSelection(long menuId, long itemId)
{
   _PutStr("\nitemId = "); putLong(itemId);
}

void FAR StartUp()
{
      ITEMID Bar1Id;
      ITEMID Bar2Id;
      int Error;

   // Add new menu title to SYSMENU.
   SysMenuId = _MenuId(_SYSMENU);
   PadId = _GetNewItemId(SysMenuId);

   if (_NewItem(SysMenuId, PadId, _LASTITEM, "\\<Added menu title"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }

   // Define menu.
   PopupId = _GetNewMenuId();

   if (Error = _NewMenu(MPOPUP, PopupId))
   {
      _Error(-Error);
   }
   Bar1Id = _GetNewItemId(PopupId);

   // WARNING: Call _NewItem() before another _GetNewItemId().
   if (_NewItem(PopupId, Bar1Id, _LASTITEM, "\\<1st item"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }
   Bar2Id = _GetNewItemId(PopupId);

   if (_NewItem(PopupId, Bar2Id, _LASTITEM, "\\<2nd item"))
   {
      _Error(623); /* "Menu item cannot be defined." */
   }

   // Attach menu to menu title
   _SetItemSubMenu(SysMenuId, PadId, PopupId);

   // Set up selection action.
   _OnSelection(PopupId, -1, onSelection);
}

void FAR ShutDown()
{
   _DisposeItem(SysMenuId, PadId);
   _DisposeMenu(PopupId);
}

FoxInfo myFoxInfo[] = {
   {"STARTUP",    (FPFI) StartUp,   CALLONLOAD, ""},
   {"SHUTDOWN",   (FPFI) ShutDown, CALLONUNLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetNewMenuId( ) API Library Routine | _NewMenu( ) API Library Routine | _SetItemText( ) API Library Routine | _SetItemCmdKey( ) API Library Routine


_SetItemText( ) API Library Routine

Changes the displayed text for the specified menu item.

void _SetItemText(MENUID menuid, ITEMID itemid, char FAR *text)
MENUID menuid;            /* Menu identifier. */
ITEMID itemid;            /* Menu item identifier. */
char FAR *text;            /* Text. */

Remarks

The menu item can be either a menu title or a bar.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example builds a menu with three items. It then changes the item text using _SetItemText( ).

Visual FoxPro Code

SET LIBRARY TO SETITEXT

C Code

#include <pro_ext.h>

FAR SetItemTextEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);

   _ActivateMenu(menuId);
   _Execute("WAIT WINDOW 'Original item text'");

   _SetItemText(menuId, _GetItemId(menuId, 0),
      "This was the 1st item");
   _SetItemText(menuId, _GetItemId(menuId, 1),
      "This was the 2nd item");
   _SetItemText(menuId, _GetItemId(menuId, 2),
      "This was the 3rd item");

   _Execute("WAIT WINDOW 'New item text'");
   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) SetItemTextEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_GetItemId( ) API Library Routine | _GetItemText( ) API Library Routine | _SetItemCmdKey( ) API Library Routine | Accessing the Visual FoxPro API


_SetMenuPoint( ) API Library Routine

Specifies the screen position of the upper-left corner, loc, of a menu.

void _SetMenuPoint(MENUID menuid, Point loc)
MENUID menuid;            /* Menu identifier. */
Point loc;                  /* Position of upper-left corner
 of the menu. */

Remarks

Normally, a menu is automatically positioned based upon its size and how the user invoked it. This routine is provided to override automatic positioning.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

A menu is created and then activated at three different screen positions specified by _SetMenuPoint( ).

Visual FoxPro Code

SET LIBRARY TO SETMNPNT

C Code

#include <pro_ext.h>

FAR SetMenuPointEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 10; loc.h = 20;
   _SetMenuPoint(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   loc.v = 15; loc.h = 30;
   _SetMenuPoint(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   loc.v = 20; loc.h = 40;
   _SetMenuPoint(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) SetMenuPointEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_NewMenu( ) API Library Routine | Accessing the Visual FoxPro API | _SetItemCmdKey( ) API Library Routine | _SetMenuPointP( ) API Library Routine


_SetMenuPointP( ) API Library Routine

Specifies in pixels the screen position of the upper-left corner, loc, of a menu.

void _SetMenuPointP(MENUID menuid, Point loc)
MENUID menuid;            /* Menu identifier. */
Point loc;                  /* Position of upper left corner
 of the menu. */

Remarks

Normally, a menu is automatically positioned based upon its size and how the user invoked it. This routine is provided to override automatic positioning.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a menu and then activates it at three different screen positions specified by _SetMenuPointP( ).

Visual FoxPro Code

SET LIBRARY TO SETMNPTP

C Code

#include <pro_ext.h>

FAR SetMenuPointPEx(ParamBlk FAR *parm)
{
   MENUID menuId;
   ITEMID itemId;
   Point loc;

   menuId = _GetNewMenuId();
   _NewMenu(MPOPUP, menuId);

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<1st item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<2nd item");

   itemId = _GetNewItemId(menuId);
   _NewItem(menuId, itemId, -2, "\\<3rd item");

   loc.v = 40; loc.h = 80;
   _SetMenuPointP(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   loc.v = 80; loc.h = 160;
   _SetMenuPointP(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   loc.v = 160; loc.h = 320;
   _SetMenuPointP(menuId, loc);
   _MenuInteract(&menuId, &itemId);

   _DisposeMenu(menuId);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", SetMenuPointPEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_NewMenu( ) API Library Routine | Accessing the Visual FoxPro API | _SetMenuPoint( ) API Library Routine | _GetNewItemId( ) API Library Routine


_SetObjectProperty( ) API Library Routine

Sets a property for an object.

int _SetObjectProperty(Value FAR *objct, char FAR *prop, Value FAR *val,
   int fAdd)

Remarks

The first parameter *objct is an object reference; the second parameter *prop is the name of the property to set; the third parameter *val is the new property value.

The last parameter fAdd is either 0 or a non-zero value that specifies if the property is added to the object if the property does not exist. If fAdd is a non-zero value and property you specify does not exist for the object, the property is added to the object as a user-defined property, and contains the property value you specify with *val. If fAdd is 0 and the property you specify does not exist for the object, the property isn't added to the object.

_SetObjectProperty( ) returns 0 if it is successful; otherwise, the negative value of the corresponding Visual FoxPro error code is returned.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

See Also

_GetObjectProperty( ) API Library Routine | Accessing the Visual FoxPro API | Object Property | ReadObject Property


_Store( ) API Library Routine

Replaces the memory variable specified by loc with the value val.

int _Store(Locator FAR *loc, Value FAR *val)
Locator FAR *loc;            /* Memory variable locator. */
Value FAR *val;               /* Value to store. */

Remarks

Reference individual array elements by setting l_subs to the number of subscripts you specified and l_sub1 and l_sub2 to the actual subscripts. The first element of an array is numbered 1. If loc specifies an array and l_subs is 0, _Store( ) stores the value in val to all elements in the array.

_Store( ) returns 0 if it is successful. If it fails, _Store( ) returns a negative integer whose absolute value is a Visual FoxPro error number. If _Store( ) runs out of memory while storing to an array, some values of some array elements may have been set, and others may not have been.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example converts to uppercase a string argument passed by reference.

Visual FoxPro Code

SET LIBRARY TO STORE
x = "abc"
= XUPPER(@x)
? x

C Code

#include <pro_ext.h>

void FAR Upper(ParamBlk FAR *parm)
{
      char FAR *pString;
      Value val;
      int i;
//
//   _Load() and _Store are the functions of interest for pass-by-reference.
//
   _Load(&parm->p[0].loc, &val);
//
//   FoxPro doesn't check the type of pass-by-reference arguments, so we do.
//
   if (val.ev_type != 'C') {
      _Error(9); // "Data type mismatch"
   }
  pString = _HandToPtr(val.ev_handle);

   for (i = 0; i < val.ev_length; i++)  {
      if ('a' <= *pString && *pString <= 'z') {
         *pString += ('A' - 'a');
      }
      pString++;
   }
   _Store(&parm->p[0].loc, &val);
   //
   // We need to free the handle that we created with  _LOAD()
   //
   _FreeHand(val.ev_handle);

}
FoxInfo myFoxInfo[] = {
   {"XUPPER", (FPFI) Upper, 1, "R"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_ALen( ) API Library Routine | _FindVar( ) API Library Routine | _Load( ) API Library Routine | _NameTableIndex( ) API Library Routine | _NewVar( ) API Library Routine | _ObjectRelease( ) API Library Routine


_StrCmp( ) API Library Routine

Compares each byte in two null-terminated strings, starting with the leftmost byte.

int _StrCmp(char FAR *string1, char FAR *string2)
char FAR *string1;         /* First comparison string. */
char FAR *string2;         /* Second comparison string. */

Remarks

_StrCmp( ) returns 0 if string1 and string2 match, a positive number if the first unmatched byte in string1 is greater than the corresponding byte in string2, or a negative number if the first unmatched byte in string1 is less than the corresponding byte in string2.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _StrCmp( ) to compare two strings passed as parameters.

Visual FoxPro Code

SET LIBRARY TO STRCMP
? STRCMP("Hello, world.", "Hello, world.")  && matches; returns 0
? STRCMP("Hello, world.", "Hello, wurld.")  && no match; returns non-0

C Code

#include <pro_ext.h>

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1))
   {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   int RetValue;

   NullTerminate(&parm->p[0].val);
   NullTerminate(&parm->p[1].val);

   _HLock(parm->p[0].val.ev_handle);
   _HLock(parm->p[1].val.ev_handle);

   RetValue = _StrCmp(_HandToPtr(parm->p[0].val.ev_handle),
      _HandToPtr(parm->p[1].val.ev_handle));

   _RetInt(RetValue, 10); // does return control here

   _HUnLock(parm->p[0].val.ev_handle);
   _HUnLock(parm->p[1].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"STRCMP", (FPFI) Example, 2, "C,C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_StrCpy( ) API Library Routine | _StrLen( ) API Library Routine | _PutStr( ) API Library Routine | _WPutStr( ) API Library Routine | _SetHandSize( ) API Library Routine | String Manipulation Routines


_StrCpy( ) API Library Routine

Copies a null-terminated string from src to dest.

void _StrCpy(char FAR *dest, char FAR *src)
char FAR *dest;            /* Destination location. */
char FAR *src;               /* Source location. */

Remarks

_StrCpy( ) doesn't support overlapping moves. Overlapping moves are required when src and dest have some bytes in common. If overlapping moves are required, use _MemMove( ).

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example is passed a Visual FoxPro array of type Character. It then replaces the second element using _Store( ).

Before calling MYFUNC( ), the Visual FoxPro example code creates an array and initializes it to type Character. MYFUNC( ) passes this array by reference.

Visual FoxPro Code

SET LIBRARY TO STRCPY
? STRCPY("Hello", " world")   && returns "Hello world"

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
#define p0 (parm->p[0].val)
#define p1 (parm->p[1].val)

   if (!_SetHandSize(p0.ev_handle, p0.ev_length + p1.ev_length))
      _Error(182); // "Insufficient memory"
   _HLock(p0.ev_handle);
   _HLock(p1.ev_handle);
   ((char FAR *) _HandToPtr(p1.ev_handle))[p1.ev_length] = '\0';

   _StrCpy((char FAR *) _HandToPtr(p0.ev_handle) + p0.ev_length,
      _HandToPtr(p1.ev_handle));

   _RetChar(_HandToPtr(p0.ev_handle));
   _HUnLock(p0.ev_handle);
   _HUnLock(p1.ev_handle);
}
FoxInfo myFoxInfo[] = {
   {"STRCPY", (FPFI) Example, 2, "C,C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_StrCmp( ) API Library Routine | _StrLen( ) API Library Routine | String Manipulation Routines | _PutStr( ) API Library Routine | _WPutStr( ) API Library Routine


_StrLen( ) API Library Routine

Returns the length in bytes of the specified null-terminated string.

int _StrLen(char FAR *string)
char FAR *string;            /* String to be measured. */

Example

The following example is similar to the Visual FoxPro function LEN( ), but can't handle strings with embedded '\0'.

Visual FoxPro Code

SET LIBRARY TO STRLEN
? STRLEN("Hello") && returns 5

C Code

#include <pro_ext.h>

void NullTerminate(Value FAR *cVal)
{
   if (!_SetHandSize(cVal->ev_handle, cVal->ev_length + 1)) {
      _Error(182); // "Insufficient memory"
   }
   ((char FAR *) _HandToPtr(cVal->ev_handle))[cVal->ev_length] = '\0';
}

FAR Example(ParamBlk FAR *parm)
{
   NullTerminate(&parm->p[0].val);
   _HLock(parm->p[0].val.ev_handle);
   _RetInt(_StrLen(_HandToPtr(parm->p[0].val.ev_handle)), 10);
   _HUnLock(parm->p[0].val.ev_handle);
}

FoxInfo myFoxInfo[] = {
   {"STRLEN", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_StrCmp( ) API Library Routine | _StrCpy( ) API Library Routine | LEN( ) Function | String Manipulation Routines


_UserError( ) API Library Routine

Reports an error with the null-terminated text you specify in message.

void _UserError(char FAR *message)
char FAR *message;         /* Error message. */

Remarks

The Visual FoxPro internal code for this error is 98. The code returned by the Visual FoxPro ERROR( ) function is 1098. The Visual FoxPro MESSAGE( ) function returns to the user your specified message. Control is passed to the Visual FoxPro error handler and doesn't return.

Note Do not call _UserError( ) in a CALLUNLOAD routine: the library will not load, due to the _UserError( ) call, and no message will be displayed.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example calls _UserError( ), demonstrating that execution doesn't return to the API routine after _UserError( ).

Visual FoxPro Code

SET LIBRARY TO EXAMPLE
= EXAMPLE()

C Code

#include <pro_ext.h>

FAR UserErrorEx(ParamBlk FAR *parm)
{
   _UserError("This is a _UserError() example.");
   _PutStr("This should never be displayed.");
}

FoxInfo myFoxInfo[] = {
   {"EXAMPLE", (FPFI) UserErrorEx, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_Error( ) API Library Routine | _ErrorInfo( ) API Library Routine | ERROR( ) Function | MESSAGE( ) Function | Accessing the Visual FoxPro API


_WAttr( ) API Library Routine

Returns the attribute byte for the specified color index in the specified window's color scheme.

int _WAttr(WHANDLE wh, int color)
WHANDLE wh;            /* Window handle. */
int color;                     /* Color index. */

Example

The following example goes through each color of each color scheme, showing its attribute byte as returned by _WAttr( ).

Visual FoxPro Code

SET LIBRARY TO WATTR

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR WAttrEx(ParamBlk FAR *parm)
{
   int scheme;
   int color;
   WHANDLE wh;
   int attrib, savePen;

   for (scheme = 0; scheme <= 25; scheme++)
   {
      wh = _WOpen(2, 10, 23, 70, WEVENT, scheme, (Scheme FAR *) 0,
         WO_SYSTEMBORDER);

      for (color = WA_NORMAL; color <= WA_ISSHADOW; color++)
      {
         attrib  = _WAttr(wh, color);
         savePen = _WAttr(_WGetPort(), WA_PENCOLOR);

         _WSetAttr(_WGetPort(), WA_PENCOLOR, attrib);

         _PutStr("\nScheme:"); putLong(scheme, 5);
         _PutStr("; Color:"); putLong(color, 5);
         _PutStr("; Attribute byte:"); putLong(attrib, 5);

         _WSetAttr(_WGetPort(), WA_PENCOLOR, savePen);
      }
      _WClose(wh);
      _Execute("WAIT");
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WAttrEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSetAttr( ) API Library Routine | Change Font Attributes | Accessing the Visual FoxPro API


_WBottom( ) API Library Routine

Returns the row on the screen where the bottom of the specified window is located.

unsigned int _WBottom(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example displays the position of the active window.

Visual FoxPro Code

SET LIBRARY TO WBOTTOM
= WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTop(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeft(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottom(wh), 5);
   _PutStr("\nright  ="); putLong(_WRight(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WHeight( ) API Library Routine | _WLeft( ) API Library Routine | _WRight( ) API Library Routine | _WTop( ) API Library Routine | _WWidth( ) API Library Routine | _WBottomP( ) API Library Routine


_WBottomP( ) API Library Routine

Returns the position on the screen in pixels where the bottom of the specified window is located.

unsigned int _WBottomP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the position of the active window.

Visual FoxPro Code

SET LIBRARY TO WBOTTOM
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTopP(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeftP(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottomP(wh), 5);
   _PutStr("\nright  ="); putLong(_WRightP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WHeightP( ) API Library Routine | _WLeftP( ) API Library Routine | _WRightP( ) API Library Routine | _WTopP( ) API Library Routine | _WWidthP( ) API Library Routine | _WBottom( ) API Library Routine


_WClear( ) API Library Routine

Erases the contents of the specified window by changing the content area to the default background color.

void _WClear(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

The logical cursor position is unchanged.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and fills it with Xs. When the user presses a key in response to a Visual FoxPro WAIT command, _WClear( ) clears the window.

Visual FoxPro Code

SET LIBRARY TO WCLEAR

C Code

#include <pro_ext.h>

FAR WClearEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   int row, col;

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (row = 0; row < _WHeight(wh); row++)
   {
      for (col = 0; col < _WWidth(wh); col++)
      {
         _WPutChr(wh, 'X');
      }
      _WPutChr(wh, '\n');
   }
   _Execute("WAIT WINDOW 'Press any key to clear window'");
   _WClear(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WClearEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClearRect( ) API Library Routine | _WClearRectP( ) API Library Routine | Accessing the Visual FoxPro API | WAIT Command


_WClearRect( ) API Library Routine

Erases the specified rectangular area of the specified window by changing the area to the default background color.

void _WClearRect(WHANDLE wh, Rect r)
WHANDLE wh;            /* Window handle. */
Rect r;                     /* Rectangle to clear. */

Remarks

The output position is unchanged.

The area of the rectangle extends from the top left coordinate to, but not including, the bottom right coordinate. This means that you should declare the bottom and right coordinates to be one more than the intended size of the rectangle.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and fills it with Xs. After the user presses a key in response to a Visual FoxPro WAIT command, _WClearRect( ) clears a rectangular region of the window.

Visual FoxPro Code

SET LIBRARY TO WCLRECT

C Code

#include <pro_ext.h>

FAR WClearEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   int row, col;
   Rect r;

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (row = 0; row < _WHeight(wh); row++)
   {
      for (col = 0; col < _WWidth(wh); col++)
      {
         _WPutChr(wh, 'X');
      }
   }
   _Execute("WAIT WINDOW 'Press any key to clear window rectangle'");

   r.top    = 2;W
   r.left    = 2;
   r.bottom = 15;
   r.right  = 65;

   _WClearRect(wh, r);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WClearEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClear( ) API Library Routine | WAIT Command | _WClearRectP( ) API Library Routine | Accessing the Visual FoxPro API


_WClearRectP( ) API Library Routine

Erases the specified rectangular area of a window by changing it to the default background color.

void _WClearRectP(WHANDLE wh, Rect r)
WHANDLE wh;            /* Window handle. */
Rect r;                     /* Rectangle to clear. */

Remarks

The rectangular area is specified in pixels. The output position is unchanged.

The area of the rectangle extends from the top left position to, but not including, the bottom right position. This means that you should declare the bottom and right positions to be one pixel more than the intended size of the rectangle.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and fills it with Xs. After the user presses a key in response to the Visual FoxPro WAIT command, _WClearRectP( ) clears a rectangular region of the window.

Visual FoxPro Code

SET LIBRARY TO WCLRECTP

C Code

#include <pro_ext.h>

FAR WClearEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   int row, col;
   Rect r;

   wh = _WOpen(2, 2, 20, 70, CLOSE, WINDOW_SCHEME, (Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (row = 0; row < _WHeight(wh); row++)
   {
      for (col = 0; col < _WWidth(wh); col++)
      {
         _WPutChr(wh, 'X');
      }
   }
   _Execute("WAIT WINDOW 'Press any key to clear window rectangle'");

   r.top    = 20;
   r.left    = 20;
   r.bottom = 100;
   r.right  = 300;

   _WClearRectP(wh, r);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", WClearEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClear( ) API Library Routine | WAIT Command | _WClearRect( ) API Library Routine | Accessing the Visual FoxPro API


_WClose( ) API Library Routine

Closes the specified window and releases all memory associated with the window.

void _WClose(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

If the window is displayed on the screen, _WClose( ) removes it from the screen.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates and displays a window. After the user presses a key in response to a Visual FoxPro WAIT command, _WClose( ) closes the window.

Visual FoxPro Code

SET LIBRARY TO WCLOSE

C Code

#include <pro_ext.h>

FAR Ex(ParamBlk FAR *parm)
{
   WHANDLE wh;
   int row, col;
   Rect r;

   wh = _WOpen(2, 2, 20, 70, 0, WINDOW_SCHEME, (Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);
   _Execute("WAIT WINDOW 'Press any key to close window'");
   _WClose(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Ex, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WOpen( ) API Library Routine | WAIT Command | Accessing the Visual FoxPro API


_WFindTitle( ) API Library Routine

Returns the WHANDLE of the window with the specified title.

WHANDLE _WFindTitle(TEXT *title)
TEXT *title;               /* Window title. */

Example

The following example hides the window whose title is passed as an argument.

Visual FoxPro Code

SET LIBRARY TO WFINDTIT
CREATE TABLE X (X C(10))
BROWSE NOWAIT
SET LIBR TO WFINDTIT
= WHIDE("X")

C Code

#include <pro_ext.h>

void FAR WFindTitleEx(ParamBlk FAR *parm)
{
//   For readability:
#define pTITLE ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pTITLE[parm->p[0].val.ev_length] = '\0';
   wh = _WFindTitle(pTITLE);
   _HUnLock(parm->p[0].val.ev_handle);
   _WHide(wh);
}

FoxInfo myFoxInfo[] = {
   {"WHIDE", (FPFI) WFindTitleEx, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSetTitle( ) API Library Routine | _HUnLock( ) API Library Routine | _WHide( ) API Library Routine | _WTitle( ) API Library Routine


_WGetCursor( ) API Library Routine

Returns the current output position in the specified window.

Point _WGetCursor(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example creates a window and draws a diagonal pattern of Xs in this window. It positions the cursor before writing each X using _WPosCursor( ), and gets that same position using _WGetCursor( ).

Visual FoxPro Code

SET LIBRARY TO WGETCURS

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point putPos, getPos;

   wh = _WOpen(4,4,20,70,0,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (putPos.v = 2; putPos.v < 14; putPos.v++)
   {
      putPos.h = putPos.v;

      _WPosCursor(wh, putPos);
      getPos = _WGetCursor(wh);
      _WPutChr(wh, 'X');

      _PutStr("\nCursor position:");
      putLong(getPos.v, 5);
      putLong(getPos.h, 5);

      _Execute("WAIT WINDOW");
   }
   _WClose(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WPosCursor( ) | Accessing the Visual FoxPro API | _WGetCursorP( ) API Library Routine


_WGetCursorP( ) API Library Routine

Returns in pixels the current output position in the specified window.

Point _WGetCursorP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and draws a diagonal pattern of Xs in this window. It positions the cursor before writing each X using _WPosCursorP( ), and gets that same position using _WGetCursorP( ).

Visual FoxPro Code

SET LIBRARY TO WGETCURP

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point putPos, getPos;

   wh = _WOpen(4,4,20,70,0,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (putPos.v = 10; putPos.v < 100; putPos.v += 10)
   {
      putPos.h = putPos.v;

      _WPosCursorP(wh, putPos);
      _WPutChr(wh, 'X');

      getPos = _WGetCursorP(wh);

      _PutStr("\nCursor position:");
      putLong(getPos.v, 5);
      putLong(getPos.h, 5);

      _Execute("WAIT");
   }
   _WClose(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WPosCursor( ) API Library Routine | Accessing the Visual FoxPro API | SET CURSOR Command | _WGetCursor( ) API Library Routine | _WPosCursorP( ) API Library Routine


_WGetObjectClientWindow( ) API Library Routine

Returns the handle of the client window in which the specified object is contained.

WHANDLE _WGetObjectClientWindow(Value FAR *objct)

Remarks

Use the _WhToHwnd( ) API Library Routine function to convert the WHANDLE to a Windows HWND.

See Also

_WGetObjectWindow( ) API Library Routine | Accessing the Visual FoxPro API | _WGetPort( ) API Library Routine | _GetObjectProperty( ) API Library Routine | GETOBJECT( ) Function


_WGetObjectWindow( ) API Library Routine

Returns the handle of the frame window in which the specified object is contained.

WHANDLE _WGetObjectWindow(Value FAR *objct)

Remarks

Use the _WhToHwnd( ) API Library Routine function to convert the WHANDLE to a Windows HWND.

See Also

_WGetObjectClientWindow( ) API Library Routine | Accessing the Visual FoxPro API | _WGetPort( ) API Library Routine | _GetObjectProperty( ) API Library Routine | GETOBJECT( ) Function


_WGetPort( ) API Library Routine

Returns the WHANDLE of the window that is currently selected for user output.

WHANDLE _WGetPort(void any)
void any;                     /* Pointer. */

Example

The following example displays the window handle returned by _WGetPort( ) as the current output port is changed.

Visual FoxPro Code

SET LIBRARY TO WGETPORT

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{

   WHANDLE wh;
   WHANDLE oldPort;

   wh = _WOpen(2,10,23,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   _PutStr("\n1) _WGetPort() ="); putLong(_WGetPort(), 10);

   oldPort = _WSetPort(wh);
   _PutStr("\n2) _WSetPort(wh) ="); putLong(oldPort, 10);
   _PutStr("\n3) _WGetPort() ="); putLong(_WGetPort(), 10);

   oldPort = _WSetPort(oldPort);
   _PutStr("\n4) _WSetPort(oldPort) =");  putLong(oldPort, 10);

   _PutStr("\nShould be back where we started.");
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WhToHwnd( ) API Library Routine | _WGetObjectClientWindow( ) API Library Routine | _GetObjectProperty( ) API Library Routine | GETOBJECT( ) Function


_WHeight( ) API Library Routine

Returns the number of rows in the content area of the specified window.

unsigned int _WHeight(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example shows the height and width in rows and columns of the active window.

Visual FoxPro Code

SET LIBRARY TO WHEIGHT
=WDIMEN()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\nheight ="); putLong(_WHeight(wh), 5);
   _PutStr("\nwidth  ="); putLong(_WWidth(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WDIMEN", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WLeft( ) API Library Routine | _WRight( ) API Library Routine | _WTop( ) API Library Routine | _WWidth( ) API Library Routine


_WHeightP( ) API Library Routine

Returns the height in pixels of the content area of the specified window.

unsigned int _WHeightP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the height and width in pixels of the active window.

Visual FoxPro Code

SET LIBRARY TO WHEIGHTP
=WDIMEN()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\nheight ="); putLong(_WHeightP(wh), 5);
   _PutStr("\nwidth  ="); putLong(_WWidthP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WDIMEN", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottomP( ) API Library Routine | _WLeftP( ) API Library Routine | _WRightP( ) API Library Routine | _WTopP( ) API Library Routine | _WWidthP( ) API Library Routine


_WHide( ) API Library Routine

Removes a window from the screen, but keeps track of its contents so you can display it again.

void _WHide(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example hides the window whose title is passed as an argument.

Visual FoxPro Code

SET LIBRARY TO WHIDE
CREATE TABLE X (X C(10))
BROWSE NOWAIT
WAIT WINDOW "Press A Key To Hide Window"
SET LIBR TO WFINDTIT
= WHIDE("X")
WAIT WINDOW "Window Is Hidden"

C Code

#include <pro_ext.h>

void FAR Example(ParamBlk FAR *parm)
{
//   For readability---
#define pTITLE ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle))

   WHANDLE wh;

   if (!_SetHandSize(parm->p[0].val.ev_handle,
      parm->p[0].val.ev_length+ 1))
   {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   pTITLE[parm->p[0].val.ev_length] = '\0';
   wh = _WFindTitle(pTITLE);
   _HUnLock(parm->p[0].val.ev_handle);
   _WHide(wh);
}
FoxInfo myFoxInfo[] = {
   {"WHIDE", (FPFI) Example, 1, "C"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WShow( ) API Library Routine | HIDE WINDOW Command | SHOW WINDOW Command


_WhToHwnd( ) API Library Routine

Returns the Windows HWND of the specified WHANDLE.

HWND_WhToHwnd(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and then obtains the Windows HWND for the window with the callback _WhToHwnd( ). Then, to verify the value returned by _WhToHwnd( ), the example uses the HWND as an argument to a Windows function.

Visual FoxPro Code

SET LIBRARY TO WHTOHWND

C Code

#include <windows.h>
#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR WhToHwndEx(ParamBlk FAR *parm)
{
   RECT Rect;
   HWND hwnd;
   WHANDLE wh;
   Value val;

   wh = _WOpenP(10,10,120,240,CLOSE,WINDOW_SCHEME, (Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

//   Get Windows window handle and use as a parameter
//   to a Windows function
   hwnd = _WhToHwnd(wh);
   GetWindowRect(hwnd, &Rect); // Windows function

   _PutStr("\ntop   ="); putLong(Rect.top, 5);
   _PutStr("\nleft ="); putLong(Rect.left, 5);
   _PutStr("\nbottom ="); putLong(Rect.bottom, 5);
   _PutStr("\nright  ="); putLong(Rect.right, 5);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", WhToHwndEx, CALLONLOAD,  ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WFindTitle( ) API Library Routine | _WOpen( ) API Library Routine | Accessing the Visual FoxPro API


_WLeft( ) API Library Routine

Returns the column on the screen where the left edge of the specified window is located.

unsigned int _WLeft(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example shows the position of the active window.

Visual FoxPro Code

SET LIBRARY TO WLEFT
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTop(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeft(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottom(wh), 5);
   _PutStr("\nright  ="); putLong(_WRight(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WHeight( ) API Library Routine | _WRight( ) API Library Routine | _WTop( ) API Library Routine | _WWidth( ) API Library Routine


_WLeftP( ) API Library Routine

Returns the position on the screen in pixels where the left edge of the window is located.

unsigned int _WLeftP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example shows the position in pixels of the active window.

Visual FoxPro Code

SET LIBRARY TO WLEFTP
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTopP(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeftP(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottomP(wh), 5);
   _PutStr("\nright  ="); putLong(_WRightP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottomP( ) API Library Routine | _WHeightP( ) API Library Routine | _WRightP( ) API Library Routine | _WTopP( ) API Library Routine | _WWidthP( ) API Library Routine


_WMainWindow( ) API Library Routine

Returns the WHANDLE of the main Visual FoxPro window.

WHANDLE _WMainWindow(void any)
void any;                     /* Pointer. */

Remarks

Use the _WhToHwnd( ) API Library Routine function to convert the WHANDLE to a Windows HWND.

Example

The following example writes a message to the main Visual FoxPro window.

Visual FoxPro Code

SET LIBRARY TO WMAIN
= EXWMAIN()

C Code

#include <pro_ext.h>

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WMainWindow();
   _WPutStr(wh, "\nThis is the FoxPro main window or desktop.");
}

FoxInfo myFoxInfo[] = {
   {"EXWMAIN", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WhToHwnd( ) API Library Routine | Hiding the Main Visual FoxPro Window


_WMove( ) API Library Routine

Moves the specified window to the new location specified by pt.

void _WMove(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* New location. */

Remarks

The pt parameter specifies the position of the upper-left corner of the window in rows and columns. The new position can place the window partially or completely off the screen.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example moves the active window diagonally 10 rows down and 10 columns to the right.

Visual FoxPro Code

SET LIBRARY TO WMOVE
=WMOVE()

C Code

#include <pro_ext.h>

void FAR WMoveEx(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();
   Point newPos;

   newPos.v = _WTop(wh)  + 10;
   newPos.h = _WLeft(wh) + 10;

   _WMove(wh, newPos);
}

FoxInfo myFoxInfo[] = {
   {"WMOVE", (FPFI) WMoveEx, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSize( ) API Library Routine | _WMoveP( ) API Library Routine | _MemMove( ) API Library Routine | MOVE WINDOW Command | Accessing the Visual FoxPro API


_WMoveP( ) API Library Routine

Moves the specified window to a new location specified by pt.

void _WMoveP(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* New location. */

Remarks

The pt parameter specifies the location of the upper-left corner of the window in pixels. The new position can place the window partially or completely off the screen.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example moves the active window diagonally 40 pixels down and 40 pixels to the right.

Visual FoxPro Code

SET LIBRARY TO WMOVEP
=WMOVEP()

C Code

#include <pro_ext.h>

void FAR WMovePEx(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();
   Point newPos;

   newPos.v = _WTopP(wh)  + 40;
   newPos.h = _WLeftP(wh) + 40;

   _WMoveP(wh, newPos);
}

FoxInfo myFoxInfo[] = {
   {"WMOVEP", WMovePEx, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSizeP( ) API Library Routine | Accessing the Visual FoxPro API | _MemMove( ) API Library Routine | MOVE WINDOW Command | Accessing the Visual FoxPro API


_WOnTop( ) API Library Routine

Returns the WHANDLE of the active window.

WHANDLE _WOnTop(void any)
void any;                     /* Pointer. */

Remarks

Normally, keystrokes belong to the active window. Handler routines need to act appropriately.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays position information about the active window.

Visual FoxPro Code

SET LIBRARY TO WONTOP
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}
void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTop(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeft(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottom(wh), 5);
   _PutStr("\nright  ="); putLong(_WRight(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSendBehind( ) API Library Routine | _WShow( ) API Library Routine | _WTop( ) API Library Routine | Accessing the Visual FoxPro API


_WOpen( ) API Library Routine

Creates a new window at the coordinates specified by the top, left, bottom, and right parameters.

WHANDLE _WOpen(int top, int left, int bottom, int right, int flag,
         int scheme_num, Scheme FAR *scheme, char FAR *bord)
int top;                     /* Row of top coordinate. */
int left;                     /* Column of left coordinate. */
int bottom;                  /* Row of bottom coordinate.  */
int right;                     /* Column of right coordinate. */
int flag;                     /* Attributes. */
int scheme_num;            /* Color scheme. */
Scheme FAR *scheme;      /* Points to color scheme to use. */
char FAR *bord;            /* Border type. */

Remarks

The window coordinates may be off the screen, but the height can't exceed 120 and the width can't exceed 264. Additional memory is allocated to hold the off-screen image of this window.

The flag parameter determines the attributes for this window. The flag may be one or more of the following flag values. You can combine multiple flag values using the C-language | or + operator. Typical window borders are defined in PRO_EXT.H.

flag Value | Window attribute
WCURSOR | The insertion point may be displayed in this window.
ZOOM | The user may zoom the window.
ADJ | The user may adjust the size of the window.
CLOSE | The user may close the window.
MOVE | The user may move the window.
AUTOSCROLL | The window scrolls when output rolls off the bottom line.
WEVENT | The window receives, activates, and deactivates events.
SHADOW | The window casts a shadow.
WMODAL | The user can't send this window to the back.
WMINIMIZE | The user can minimize this window.

The scheme_num may be any valid color scheme number, or – 1 to indicate that the scheme parameter points to the color scheme to use.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates windows using a number of different color schemes and borders. In particular, note the custom color scheme.

Visual FoxPro Code

SET LIBRARY TO WOPEN

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;

   Scheme customScheme =
   {
      (char) (BLACK_ON      | WHITE),
      (char) (RED_ON      | BLACK      | BLINK),
      (char) (WHITE_ON      | WHITE      | BRIGHT),
      (char) (CYAN_ON      | BLUE      | BRIGHT),
      (char) (GREEN_ON      | BROWN),
      (char) (BROWN_ON      | BROWN      | BRIGHT),
      (char) (MAGENTA_ON   | MAGENTA   | BRIGHT),
      (char) (RED_ON      | MAGENTA   | BRIGHT | BLINK),
      (char) (BROWN_ON      | GREEN      | BRIGHT),
      (char) (BLACK_ON      | CYAN),
      (char) (BLUE_ON      | CYAN),
   };

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in WINDOW_SCHEME with WO_DOUBLEBOX border'");

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_DOUBLEBOX);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in ALERT_SCHEME with WO_SINGLEBOX border'");
   _WClose(wh);

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,ALERT_SCHEME, (Scheme FAR *) 0,
      WO_SINGLEBOX);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in WINDOW_SCHEME with WO_PANELBORDER border'");
   _WClose(wh);

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_PANELBORDER);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in a custom scheme with WO_SYSTEMBORDER border'");
   _WClose(wh);

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,-1,(Scheme FAR *) customScheme,
      WO_SYSTEMBORDER);
   _WShow(wh);

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClose( ) API Library Routine | _WSelect( ) API Library Routine | _WSetTitle( ) API Library Routine | _WShow( ) API Library Routine | Accessing the Visual FoxPro API API Library Routine


_WOpenP( ) API Library Routine

Creates a new window at the positions specified by the top, left, bottom, and right parameters.

WHANDLE _WOpenP(int top, int left, int bottom, int right, int flag,
         int scheme_num, Scheme FAR *scheme, char FAR *bord)
int top;                     /* Top coordinate in pixels. */
int left;                     /* Left coordinate in pixels. */
int bottom;                  /* Bottom coordinate in pixels. */
int right;                     /* Right coordinate in pixels. */
int flag;                     /* Attributes. */
int scheme_num;            /* Color scheme. */
Scheme FAR *scheme;      /* Points to color scheme to use. */
char FAR *bord;            /* Border type. */

Remarks

The window positions may be off the screen. Additional memory is allocated to hold the off-screen image of this window.

The flag parameter determines the attributes for this window. The flag may be one or more of the flag values in the table below. You can combine multiple flag values using the C | or + operator. Typical window borders are defined in PRO_EXT.H.

flag Value | Window attribute
WCURSOR | The insertion point may be displayed in this window.
ZOOM | The user may zoom the window.
ADJ | The user may adjust the size of the window.
CLOSE | The user may close the window.
MOVE | The user may move the window.
AUTOSCROLL | The window scrolls when output rolls off the bottom line.
WEVENT | The window receives, activates, and deactivates events.
SHADOW | The window casts a shadow.
WMODAL | The user can't send this window to the back.
WMINIMIZE | The user can minimize this window.

The scheme_num may be any valid color scheme number, or – 1 to indicate that the scheme parameter points to the color scheme to use.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates windows using a number of different color schemes and borders. In particular, note the custom color scheme.

Visual FoxPro Code

SET LIBRARY TO WOPENP

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;

   char customScheme[12] =
   {
      BLACK_ON      | WHITE,
      RED_ON      | BLACK      | BLINK,
      WHITE_ON      | WHITE      | BRIGHT,
      CYAN_ON      | BLUE      | BRIGHT,
      GREEN_ON      | BROWN,
      BROWN_ON      | BROWN      | BRIGHT,
      MAGENTA_ON   | MAGENTA   | BRIGHT,
      RED_ON      | MAGENTA   | BRIGHT | BLINK,
      BROWN_ON      | GREEN      | BRIGHT,
      BLACK_ON      | CYAN,
      BLUE_ON      | CYAN,
   };

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in WINDOW_SCHEME with WO_DOUBLEBOX border'");

   wh = _WOpenP(10, 10, 160, 320, WEVENT | CLOSE, WINDOW_SCHEME,
      (Scheme FAR *)0, WO_DOUBLEBOX);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in ALERT_SCHEME with WO_SINGLEBOX border'");
   _WClose(wh);

   wh = _WOpenP(10, 10, 160, 320, WEVENT | CLOSE, ALERT_SCHEME,
      (Scheme FAR *)0, WO_SINGLEBOX);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in WINDOW_SCHEME with WO_PANELBORDER border'");
   _WClose(wh);

   wh = _WOpenP(10, 10, 160, 320, WEVENT | CLOSE, WINDOW_SCHEME,
      (Scheme FAR *)0, WO_PANELBORDER);
   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to see a window \
      in a custom scheme with WO_SYSTEMBORDER border'");
   _WClose(wh);

   wh = _WOpenP(10,10,160,320,WEVENT | CLOSE,-1,customScheme,
      WO_SYSTEMBORDER);
   _WShow(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClose( ) API Library Routine | _WSelect( ) API Library Routine | _WSetTitle( ) API Library Routine | _WShow( ) API Library Routine | Accessing the Visual FoxPro API


_WPosCursor( ) API Library Routine

Positions the output position in the specified window at the location specified in rows and columns by pt.

void _WPosCursor(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* Location for the output position. */

Remarks

_WPosCursor( ) doesn't make the insertion point appear. Normally, the insertion point is visible only when Visual FoxPro is waiting for input.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and draws a diagonal pattern of Xs in this window. It positions the cursor before writing each X using _WPosCursor( ), and gets that same position using _WGetCursor( ).

Visual FoxPro Code

SET LIBRARY TO WPOSCUR

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point putPos, getPos;

   wh = _WOpen(4,4,20,70,0,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (putPos.v = 2; putPos.v < 14; putPos.v++)
   {
      putPos.h = putPos.v;

      _WPosCursor(wh, putPos);
      _WPutChr(wh, 'X');

      getPos = _WGetCursor(wh);

      _PutStr("\nCursor position:");
      putLong(getPos.v, 5);
      putLong(getPos.h, 5);

      _Execute("WAIT");
   }
   _WClose(wh);
}
FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WGetCursor( ) | Accessing the Visual FoxPro API | _WPosCursorP( ) API Library Routine | _WPutChr( ) API Library Routine | _WPutStr( ) API Library Routine


_WPosCursorP( ) API Library Routine

Positions the output position of the specified window at the location specified in pixels by pt.

void _WPosCursorP(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* Location for output position. */

Remarks

_WPosCursor( ) doesn't make the insertion point appear. Normally, the insertion point is visible only when Visual FoxPro is waiting for input.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and draws a diagonal pattern of Xs in this window. It positions the cursor before writing each X using _WPosCursorP( ), and gets that same position using _WGetCursorP( ).

Visual FoxPro Code

SET LIBRARY TO WPOSCURP

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}
FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point putPos, getPos;

   wh = _WOpen(4,4,20,70,0,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (putPos.v = 10; putPos.v < 100; putPos.v += 10)
   {
      putPos.h = putPos.v;

      _WPosCursorP(wh, putPos);
      _WPutChr(wh, 'X');

      getPos = _WGetCursorP(wh);

      _PutStr("\nCursor position:");
      putLong(getPos.v, 5);
      putLong(getPos.h, 5);

      _Execute("WAIT");
   }
   _WClose(wh);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WGetCursorP( ) API Library Routine | Accessing the Visual FoxPro API | _WPosCursor( ) API Library Routine | _WPutChr( ) API Library Routine | _WPutStr( ) API Library Routine


_WPutChr( ) API Library Routine

Displays one character char at the output position in the specified window and in the current color.

void _WPutChr(WHANDLE wh, int char)
WHANDLE wh;            /* Window handle. */
int char;                     /* Character to display. */

Remarks

Special characters such as newline, carriage return, and bell are treated as control characters and aren't displayed on the screen.

To show the character that corresponds to one of these control characters, add 256 to the value of the character.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _WPutChr( ) to display all 8-bit values in a new window.

Visual FoxPro Code

SET LIBRARY TO WPUTCHR

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int i;
   WHANDLE wh;

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (i = 0; i < 256; i++)
      _WPutChr(wh, i);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WPutStr( ) API Library Routine | _WGetCursorP( ) API Library Routine | Accessing the Visual FoxPro API | _WPosCursor( ) API Library Routine


_WPutStr( ) API Library Routine

Displays a null-terminated string at the output position in the specified window and in the current color.

void _WPutStr(WHANDLE wh, char FAR *theStr)
WHANDLE wh;            /* Window handle. */
char FAR *theStr;               /* String to display. */

Remarks

Output that normally causes the window to scroll produces undefined results in windows that don't have the AUTOSCROLL attribute set.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example uses _WPutStr( ) to display a string containing all 8-bit values (except '\0') in a new window.

Visual FoxPro Code

SET LIBRARY TO WPUTSTR

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   int i;
   WHANDLE wh;
   char String[256];

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   for (i = 0; i < 255; i++)
      String[i] = i + 1;
   String[255] = '\0';
   _WPutStr(wh, String);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WPutChr( ) | _WGetCursorP( ) API Library Routine | Accessing the Visual FoxPro API | _WPosCursor( ) API Library Routine


_WRight( ) API Library Routine

Returns the column on the screen where the right edge of the specified window is located.

unsigned int _WRight(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example shows the position of the active window.

Visual FoxPro Code

SET LIBRARY TO WRIGHT
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTop(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeft(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottom(wh), 5);
   _PutStr("\nright  ="); putLong(_WRight(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WHeight( ) API Library Routine | _WLeft( ) API Library Routine | _WTop( ) API Library Routine | _WWidth( ) API Library Routine


_WRightP( ) API Library Routine

Returns the position on the screen in pixels where the right edge of the specified window is located.

unsigned int _WRightP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the position of the active window.

Visual FoxPro Code

SET LIBRARY TO WRIGHTP
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTopP(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeftP(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottomP(wh), 5);
   _PutStr("\nright  ="); putLong(_WRightP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottomP( ) API Library Routine | _WHeightP( ) API Library Routine | _WLeftP( ) API Library Routine | _WTopP( ) API Library Routine | _WWidthP( ) API Library Routine


_WScroll( ) API Library Routine

Scrolls a portion of the contents of a window left or right and up or down.

void _WScroll(WHANDLE wh, Rect r, int dv, int dh)
WHANDLE wh;            /* Window handle. */
Rect r;                     /* Portion to scroll. */
int dv;                        /* Left or right. */
int dh;                     /* Up or down. */

Remarks

  • The r parameter describes the portion of the window to be scrolled.
  • The dv parameter describes the number of characters to scroll the window left or right. If dv is negative, the window contents scroll to the left. If dv is positive, the window contents scroll to the right.
  • The dh parameter describes the number of characters to scroll the window up or down. If dh is negative, the window contents scroll up. If dh is positive, the window contents scroll down.

If both dv and dh are 0, _WScroll( ) clears the characters inside the rectangle.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens a window and draws a rectangular pattern of Xs. This rectangle is also the scroll rectangle. First, the example scrolls the rectangle up two positions and to the left two positions. Next, it scrolls the rectangle down by four positions and to the right four positions.

Visual FoxPro Code

SET LIBRARY TO WSCROLL

C Code

#include <pro_ext.h>

FAR WScrollEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point pos;
   Rect rect;

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   rect.top   = 6;
   rect.left   = 6;
   rect.bottom = 12;
   rect.right   = 12;

   for (pos.v = rect.top; pos.v < rect.bottom; pos.v++)
   {
      for (pos.h = rect.left; pos.h < rect.right; pos.h++)
      {
         _WPosCursor(wh, pos);
         _WPutChr(wh, 'X');
      }
   }
   _Execute("WAIT WINDOW 'Press any key to _WScroll(wh,rect,-2,-2)'");
   _WScroll(wh, rect, -2, -2);
   _Execute("WAIT WINDOW 'Press any key to _WScroll(wh,rect,+4,+4)'");
   _WScroll(wh, rect, +4, +4);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WScrollEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClear( ) API Library Routine | Accessing the Visual FoxPro API | _WScrollP( ) API Library Routine | _WPosCursor( ) API Library Routine | _WPutChr( ) API Library Routine


_WScrollP( ) API Library Routine

Scrolls a portion of the contents of a window left or right and up or down.

void _WScrollP(WHANDLE wh, Rect r, int dv, int dh)
WHANDLE wh;            /* Window handle. */
Rect r;                     /* Portion to scroll. */
int dv;                        /* Left or right. */
int dh;                     /* Up or down. */

Remarks

  • The r parameter describes the portion of the window to be scrolled.
  • The dv parameter describes the number of pixels to scroll the window left or right. If dv is negative, the window contents scroll to the left. If dv is positive, the window contents scroll to the right.
  • The dh parameter describes the number of pixels to scroll the window up or down. If dh is negative, the window contents scroll up. If dh is positive, the window contents scroll down.

If both dv and dh are 0, _WScrollP( ) clears the characters inside the rectangle.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example opens a window and draws a rectangular pattern of Xs. This rectangle is also the scroll rectangle. First, _WScrollP( ) scrolls the rectangle up and left. Next, it scrolls the rectangle down and right.

Visual FoxPro Code

SET LIBRARY TO WSCROLLP

C Code

#include <pro_ext.h>

FAR WScrollEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point pos;
   Rect rect;

   wh = _WOpenP(2, 2, 160, 320, WEVENT | CLOSE, WINDOW_SCHEME,
      (char *) 0, WO_SYSTEMBORDER);

  _WShow(wh);

   rect.top   = 40;
   rect.left   = 40;
   rect.bottom = 100;
   rect.right   = 100;

   for (pos.v = rect.top; pos.v < rect.bottom; pos.v += 6)
   {
      for (pos.h = rect.left; pos.h < rect.right; pos.h +=6)
      {
         _WPosCursorP(wh, pos);
    _WPutChr(wh, 'X');
      }
   }
   _Execute("WAIT 'Press any key to _WScroll(wh, rect, -20, -20)'");
   _WScrollP(wh, rect, -20, -20);
   _Execute("WAIT 'Press any key to _WScroll(wh, rect, +40, +40)'");
   _WScrollP(wh, rect, +40, +40);
}

FoxInfo myFoxInfo[] =
{
   {"ONLOAD", WScrollEx, CALLONLOAD, ""},
};

FoxTable _FoxTable =
{
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClear( ) API Library Routine | Accessing the Visual FoxPro API | _WPosCursor( ) API Library Routine | _WPutChr( ) API Library Routine


_WSelect( ) API Library Routine

Brings the specified window to the active position on the screen.

void _WSelect(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example creates five overlapping windows. The windows are each moved to the active position using _WSelect( ), starting with the first window created.

Visual FoxPro Code

SET LIBRARY TO WSELECT

C Code

#include <pro_ext.h>

FAR WSelectEx(ParamBlk FAR *parm)
{
   WHANDLE wh[5];
   int i;

   for (i = 0; i < 5; i++)
   {
      wh[i] = _WOpen(4 + 2*i,4 + 2*i,12 + 2*i,40 + 2*i,WEVENT | CLOSE,
         WINDOW_SCHEME, (Scheme FAR *) 0, WO_SYSTEMBORDER);
      _WShow(wh[i]);
   }
   for (i = 0; i < 5; i++)
   {
      _Execute("WAIT WINDOW 'Press key to _WSelect() next window'");
      _WSelect(wh[i]);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WSelectEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WOnTop( ) API Library Routine | _WShow( ) API Library Routine | _WOpen( ) API Library Routine | _Execute( ) API Library Routine


_WSendBehind( ) API Library Routine

Sends the specified window to the backmost position on the screen.

void _WSendBehind(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example creates five overlapping windows. _WSendBehind( ) sends each window to the backmost position, starting with the last window created.

Visual FoxPro Code

SET LIBRARY TO WSENDBEH

C Code

#include <pro_ext.h>

FAR WSendBehindEx(ParamBlk FAR *parm)
{
   WHANDLE wh[5];
   int i;

   for (i = 0; i < 5; i++)
   {
      wh[i] = _WOpen(4 + 2*i,4 + 2*i,12 + 2*i,40 + 2*i,WEVENT | CLOSE,
         WINDOW_SCHEME, (Scheme FAR *) 0, WO_SYSTEMBORDER);
      _WShow(wh[i]);
   }
   for (i = 4; i >= 0; i--)
   {
      _Execute("WAIT WINDOW 'Press key to _WSendBehind() next window'");
      _WSendBehind(wh[i]);
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WSendBehindEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WOnTop( ) API Library Routine | _WSelect( ) API Library Routine | _WShow( ) API Library Routine | _Execute( ) API Library Routine


_WSetAttr( ) API Library Routine

Changes the attribute for the specified color scheme index in the indicated window's color scheme to the new attribute attr.

void _WSetAttr(WHANDLE wh, int color, int attr)
WHANDLE wh;            /* Window handle. */
int color;                     /* Color scheme. */
int attr;                     /* Attribute. */

Example

The following example goes through each color of each scheme, using _WSetAttr( ) to set the pen color, and then displaying some text in each color.

Visual FoxPro Code

SET LIBRARY TO WSETATTR

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR WAttrEx(ParamBlk FAR *parm)
{
   int scheme;
   int color;
   WHANDLE wh;
   int attrib, savePen;

   for (scheme = 0; scheme <= 25; scheme++)
   {
      wh = _WOpen(2,10,23,70,WEVENT,scheme,(Scheme FAR *)0,
         WO_SYSTEMBORDER);

      for (color = WA_NORMAL; color <= WA_ISSHADOW; color++)
      {
         attrib  = _WAttr(wh, color);
         savePen = _WAttr(_WGetPort(), WA_PENCOLOR);

         _WSetAttr(_WGetPort(), WA_PENCOLOR, attrib);

         _PutStr("\nScheme:"); putLong(scheme, 5);
         _PutStr("; Color:"); putLong(color, 5);
         _PutStr("; Attribute byte:"); putLong(attrib, 5);

         _WSetAttr(_WGetPort(), WA_PENCOLOR, savePen);
      }
      _WClose(wh);
      _Execute("WAIT");
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WAttrEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WClear( ) API Library Routine | _WClearRect( ) API Library Routine | _WAttr( ) API Library Routine | _PutStr( ) API Library Routine


_WSetPort( ) API Library Routine

Changes the user output window to be the specified window.

WHANDLE _WSetPort(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

_WSetPort( ) returns the handle of the previous user output window.

Note If your routine changes the user output window, be sure to restore the user output window before returning to Visual FoxPro.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and makes this the output port. It writes some text to this window before switching back to the original output port.

Visual FoxPro Code

SET LIBRARY TO WSETPORT

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

FAR Example(ParamBlk FAR *parm)
{

   WHANDLE wh;
   WHANDLE oldPort;

   wh = _WOpen(2,10,23,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   _PutStr("\n1) _WGetPort() ="); putLong(_WGetPort(), 10);

   oldPort = _WSetPort(wh);
   _PutStr("\n2) _WSetPort(wh) ="); putLong(oldPort, 10);

   _PutStr("\n3) _WGetPort() ="); putLong(_WGetPort(), 10);

   oldPort = _WSetPort(oldPort);
   _PutStr("\n4) _WSetPort(oldPort) =");  putLong(oldPort, 10);

   _PutStr("\nShould be back where we started.");
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WGetPort( ) API Library Routine | _PutStr( ) API Library Routine | _WShow( ) API Library Routine | Input and Output


_WSetTitle( ) API Library Routine

Changes the title of the specified window to title.

void _WSetTitle(WHANDLE wh, char FAR *title)
WHANDLE wh;            /* Window handle. */
char FAR *title;            /* Window title. */

Remarks

To remove a title from a window, pass (char FAR *)0 as the new title.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window and defines its title text with _WSetTitle( ).

Visual FoxPro Code

SET LIBRARY TO WSETTITL

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   char FAR *buffer;

   wh = _WOpen(4,4,20,70,CLOSE | WEVENT,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);

   _WSetTitle(wh, "This is a window title");

   _WShow(wh);

   if ((buffer = _Alloca(128)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _WTitle(wh, buffer);

   _PutStr("\nThe window title is \"");
   _PutStr(buffer);
   _PutChr('"');

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WFindTitle( ) API Library Routine | _WTitle( ) API Library Routine | _WShow( ) API Library Routine | Accessing the Visual FoxPro API


_WShow( ) API Library Routine

Displays a hidden window on the screen.

void _WShow(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

When you create a window, it is hidden by default until you use _WShow( ) to make it visible.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example contains two API routines. WINOPEN( ) opens a window but doesn't call _WShow( ), illustrating that the window is hidden until _WShow( ) displays it on the screen.

Visual FoxPro Code

SET LIBRARY TO WSHOW
wh = WOPEN()
= WSHOW(wh)

C Code

#include <pro_ext.h>

FAR WOpen(ParamBlk FAR *parm)
{
   _RetInt(_WOpen(2, 2, 20, 70, WEVENT | CLOSE, WINDOW_SCHEME,
      (Scheme FAR *) 0, WO_SYSTEMBORDER), 10);
}

FAR WShow(ParamBlk FAR *parm)
{
   _WShow(parm->p[0].val.ev_long);
}

FoxInfo myFoxInfo[] = {
   {"WOPEN", (FPFI) WOpen, 0, ""},
   {"WSHOW", (FPFI) WShow, 1, "I"},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WHide( ) API Library Routine | _WOpen( ) API Library Routine | _WSelect( ) API Library Routine | Accessing the Visual FoxPro API | _WOpen( ) API Library Routine


_WSize( ) API Library Routine

Sets new dimensions of the specified window to the height and width specified by h and v in the pt parameter.

void _WSize(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* Position. */

Example

The following example creates a window, and then expands its width and height.

Visual FoxPro Code

SET LIBRARY TO WSIZE

C Code

#include <pro_ext.h>

FAR WSizeEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point dim;

   wh = _WOpen(2,2,10,10,CLOSE | WEVENT,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   dim.v = 8;

//   Grow in width
   for (dim.h = 8; dim.h < 60; dim.h += 4)
   {
      _WSize(wh, dim);
      _Execute("WAIT WINDOW 'Press Any Key To Change Size'");
   }

//   Grow in height
   for (dim.v = 8; dim.v < 20; dim.v += 2)
   {
      _WSize(wh, dim);
      _Execute("WAIT WINDOW 'Press Any Key To Change Size'");
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) WSizeEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WMove( ) API Library Routine | _WSizeP( ) API Library Routine | _WShow( ) API Library Routine | _Execute( ) API Library Routine


_WSizeP( ) API Library Routine

Sets the new dimensions of the window to the height and width specified in pixels by h and v in the pt parameter.

void _WSizeP(WHANDLE wh, Point pt)
WHANDLE wh;            /* Window handle. */
Point pt;                     /* Position. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates a window, and expands its width and then its height.

Visual FoxPro Code

SET LIBRARY TO WSIZEP

C Code

#include <pro_ext.h>

FAR WSizeEx(ParamBlk FAR *parm)
{
   WHANDLE wh;
   Point dim;

   wh = _WOpenP(6,6,20,20,CLOSE | WEVENT,WINDOW_SCHEME,(Scheme FAR *)0,
      WO_SYSTEMBORDER);
   _WShow(wh);

   dim.v = 14;

//   Grow in width
   for (dim.h = 14; dim.h < 480; dim.h += 40)
   {
      _WSizeP(wh, dim);
      _Execute("WAIT");
   }

//   Grow in height
   for (dim.v = 14; dim.v < 240; dim.v += 40)
   {
      _WSizeP(wh, dim);
      _Execute("WAIT WINDOW 'Press Any Key To Change Window Size'");
   }
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", WSizeEx, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottomP( ) API Library Routine | _WLeftP( ) API Library Routine | _WRightP( ) API Library Routine | _WTopP( ) API Library Routine | _WSize( ) API Library Routine


_WTitle( ) API Library Routine

Puts the null-terminated title of the window wh in title.

void _WTitle(WHANDLE wh, char FAR *title)
WHANDLE wh;            /* Window handle. */
char FAR *title;            /* Window title. */

Example

The following example creates and shows a window with both a title and a footer. _WTitle( ) retrieves the title text, which is then displayed on the screen.

Visual FoxPro Code

SET LIBRARY TO WTITLE

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   char FAR *buffer;

   wh = _WOpen(4,4,20,70,CLOSE | WEVENT,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);

   _WSetTitle(wh, "This is a window title");

   _WShow(wh);

   if ((buffer = _Alloca(128)) == 0)
   {
      _Error(182); // "Insufficient memory"
   }
   _WTitle(wh, buffer);

   _PutStr("\nThe window title is \"");
   _PutStr(buffer);
   _PutChr('"');
}
FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WSetTitle( ) API Library Routine | _PutStr( ) API Library Routine | _WShow( ) API Library Routine


_WTop( ) API Library Routine

Returns the row on the screen where the top of the window is located.

unsigned int _WTop(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example displays the row position of the active window.

Visual FoxPro Code

SET LIBRARY TO WTOP
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTop(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeft(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottom(wh), 5);
   _PutStr("\nright  ="); putLong(_WRight(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WHeight( ) API Library Routine | _WLeft( ) API Library Routine | _WRight( ) API Library Routine | _WWidth( ) API Library Routine | _WTopP( ) API Library Routine


_WTopP( ) API Library Routine

Returns the position on the screen in pixels where the top of the window is located.

unsigned int _WTopP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the position of the active window in pixels.

Visual FoxPro Code

SET LIBRARY TO WTOPP
=WPOSITION()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\ntop   ="); putLong(_WTopP(wh), 5);
   _PutStr("\nleft ="); putLong(_WLeftP(wh), 5);
   _PutStr("\nbottom ="); putLong(_WBottomP(wh), 5);
   _PutStr("\nright  ="); putLong(_WRightP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WPOSITION", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottomP( ) API Library Routine | _WHeightP( ) API Library Routine | _WLeftP( ) API Library Routine | _WRightP( ) API Library Routine | _WWidthP( ) API Library Routine | _WTop( ) API Library Routine


_WWidth( ) API Library Routine

Returns the number of columns in the content area of the specified window.

unsigned int _WWidth(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Example

The following example shows the height and width in rows and columns of the active window.

Visual FoxPro Code

SET LIBRARY TO WWIDTH
=WDIMEN()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\nheight ="); putLong(_WHeight(wh), 5);
   _PutStr("\nwidth  ="); putLong(_WWidth(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WDIMEN", (FPFI) Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WHeight( ) API Library Routine | _WLeft( ) API Library Routine | _WRight( ) API Library Routine | _WTop( ) API Library Routine | _WWidthP( ) API Library Routine


_WWidthP( ) API Library Routine

Returns the width in pixels of the content area of the specified window.

unsigned int _WWidthP(WHANDLE wh)
WHANDLE wh;            /* Window handle. */

Remarks

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example displays the height and width in pixels of the active window.

Visual FoxPro Code

SET LIBRARY TO WWIDTHP
=WDIMEN()

C Code

#include <pro_ext.h>

void putLong(long n, int width)
{
   Value val;

   val.ev_type = 'I';
   val.ev_long = n;
   val.ev_width = width;

   _PutValue(&val);
}

void FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh = _WOnTop();

   _PutStr("\nheight ="); putLong(_WHeightP(wh), 5);
   _PutStr("\nwidth  ="); putLong(_WWidthP(wh), 5);
}

FoxInfo myFoxInfo[] = {
   {"WDIMEN", Example, 0, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WBottom( ) API Library Routine | _WHeightP( ) API Library Routine | _WLeftP( ) API Library Routine | _WRightP( ) API Library Routine | _WTopP( ) API Library Routine


_WZoom( ) API Library Routine

Minimizes or maximizes the specified window, or returns it to normal.

void _WZoom(WHANDLE wh, int newstate)
WHANDLE wh;            /* Window handle. */
int newstate;                  /* State of window after zoom. */

Remarks

You can specify the newstate parameter as WZ_MINIMIZE, WZ_NORMAL, or WZ_MAXIMIZE, which are defined in the PRO_EXT.H file.

For more information on how to create an API library and integrate it with Visual FoxPro, see Accessing the Visual FoxPro API.

Example

The following example creates and displays a window. It then calls _WZoom( ) for this window with each possible parameter.

Visual FoxPro Code

SET LIBRARY TO WZOOM

C Code

#include <pro_ext.h>

FAR Example(ParamBlk FAR *parm)
{
   WHANDLE wh;
   int row, col;

   wh = _WOpen(2,2,20,70,WEVENT | CLOSE,WINDOW_SCHEME,(Scheme FAR *) 0,
      WO_SYSTEMBORDER);

   _WShow(wh);

   _Execute("WAIT WINDOW 'Press any key to minimize window'");
   _WZoom(wh, WZ_MINIMIZED);

   _Execute("WAIT WINDOW 'Press any key to normalize window'");
   _WZoom(wh, WZ_NORMAL);

   _Execute("WAIT WINDOW 'Press any key to maximize window'");
   _WZoom(wh, WZ_MAXIMIZED);

   _Execute("WAIT WINDOW 'Press any key to normalize window'");
   _WZoom(wh, WZ_NORMAL);
}

FoxInfo myFoxInfo[] = {
   {"ONLOAD", (FPFI) Example, CALLONLOAD, ""},
};
FoxTable _FoxTable = {
   (FoxTable FAR *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

_WMove( ) API Library Routine | _WSize( ) API Library Routine | _WShow( ) API Library Routine | Accessing the Visual FoxPro API | ZOOM WINDOW Command


API Library Routines by Category

Debugging Routines

Environment Routines

Error Handling Routines

Event Handling Routines

File Input and Output Routines

Memory Management Routines

Variable and Array Routines

Memo Field Input and Output Routines

Menu Routines

Object Routines

Routines to Return Results to Visual FoxPro

Statement and Expression Routines

String Manipulation Routines

Table Input and Output Routines

Text Editor and Clipboard Manipulation Routines

Window Manipulation Routines


Debugging Routines

These API routines allow you to debug your API libraries.

_BreakPoint( )

A macro that generates the debugger breakpoint instruction, INT 3. This can be helpful for debugging external routines


Environment Routines

These API routines allow you to return information about the Visual FoxPro environment.

_GetAPIHandle( )

Returns the handle of the current FLL.


Error Handling Routines

These API routines allow you to determine the cause of an error and the error type.

_Error( )

Signals the error specified by the value in code to the Visual FoxPro runtime.

_ErrorInfo( )

Returns the external error number that reflects the internal error number specified by code.

_UserError( )

Reports an error with the null-terminated text specified in the message.


Event Handling Routines

These API routines allow you to create event handlers and process Visual FoxPro events.

_ActivateHandler( )

Adds a function handler to the end of the list of event handlers.

_ActivateIdle( )

Adds a routine to the list of routines called when Visual FoxPro is waiting for user input or for an event to time out.

_DeActivateHandler( )

Removes the specified handler from the event processor list.

_DeActivateIdle( )

Removes the specified routine from the idle loop.

_DefaultProcess( )

Provides the default event processing for an event returned by _GetNextEvent( ) when the event doesn't need special handling.

_GetNextEvent( )

Reads the next event into the EventRec and returns the event type.

_InKey( )

Returns the next key typed during the timeout period. The timeout period is specified as a number of MS-DOS timer ticks.

_MousePos( )

Fills in pt with the current position of the mouse.

_MousePosP( )

Fills in pt with the current position of the mouse in pixels.


File Input and Output Routines

These API routines allow you to directly create and manipulate files.

_FCHSize( )

Sets the file size on disk to the specified length. The specified length may extend or truncate the file.

_FClose( )

Terminates access to a file. Any buffers that have been modified while the buffer is open are automatically flushed to disk.

_FCopy( )

Attempts to copy len bytes from position spos in file sc to position dpos in file dc.

_FCreate( )

Assigns a Visual FoxPro channel to a new file.

_FEOF( )

Returns True if the file is currently at the end of file; otherwise, returns False.

_FError( )

Returns the last file operation error recorded for any channel.

_FFlush( )

Ensures that all modified buffers in memory have been flushed out to disk.

_FGets( )

Reads a single line of maxlen length, delimited with a carriage return, from a file.

_FOpen( )

Assigns a Visual FoxPro channel to an existing file.

_FPuts( )

Writes a null-terminated string to a file, followed by a carriage return/line feed pair.

_FRead( )

Reads exactly length bytes from a file into buffer.

_FSeek( )

Moves the file pointer to a new location as specified by position and mode.

_FWrite( )

Writes exactly length bytes from your buffer to a file. No terminator is added to the file.


Memo Field Input and Output Routines

These API routines allow you to manipulate memo fields in a Visual FoxPro table.

_AllocMemo( )

Allocates size bytes of space in the memo file for a field and inserts the new block number in the associated record in the table.

_FindMemo( )

Returns the location in the memo file to begin reading to access a memo field directly.

_MemoChan( )

Returns the Visual FoxPro channel of the memo file associated with the specified workarea.

_MemoSize( )

Returns the length of the memo field in the memo file.


Memory Management Routines

These API routines allow you to manipulate and allocate memory for your API functions.

_Alloca( )

Allocates a block of stack space for the calling routine. Memory is automatically freed when the routine exits.

_AllocHand( )

Returns a new MHANDLE of size hsize. A value of zero is returned when there is insufficient memory to fulfill the request. Memory allocated with _AllocHand( ) isn't initialized.

_FreeHand( )

Releases an MHANDLE previously allocated by means such as _AllocHand( ).

_GetHandSize( )

Returns the usable number of bytes associated with an MHANDLE.

_HandToPtr( )

Translates an MHANDLE to a FAR (32-bit) pointer, which points to the memory allocated to this MHANDLE.

_HLock( )

Locks an MHANDLE to prevent it from moving if Visual FoxPro requires memory reorganization.

_HUnLock( )

Unlocks an MHANDLE, allowing it to participate in Visual FoxPro memory reorganization.

_MemAvail( )

Returns True if a request to allocate a handle of size bytes will succeed. Otherwise, _MemAvail( ) returns False.

_MemCmp( )

Compares two length byte memory areas.

_MemFill( )

Fills an area of memory starting at the location pointed to by ptr with length copies of the byte in character.

_MemMove( )

Copies length bytes from src to dest.

_SetHandSize( )

Changes the amount of memory allocated to an MHANDLE. The routine returns True if the reallocation is successful or False if the reallocation fails.


Menu Routines

These API routines allow you to create, manipulate, and release menus.

_ActivateMenu( )

Displays the specified menu on the screen and immediately returns control to the calling routine.

_CountItems( )

Returns the number of menu titles or bars on the specified menu.

_DeActivateMenu( )

Removes a menu from the screen.

_DisposeItem( )

Releases the specified menu item and frees all storage associated with this item.

_DisposeMenu( )

Releases the specified menu and all its items and frees all storage associated with this menu.

_GetItemCmdKey( )

Copies the displayed keyboard shortcut string for the specified menu item to the buffer pointed to by the text parameter.

_GetItemId( )

Returns the item identifier of the index item in the specified menu.

_GetItemSubMenu( )

Returns the menu item identifier or a submenu assigned to a menu item.

_GetItemText( )

Copies the text of a menu bar or menu title to the buffer pointed to by text.

_GetNewItemId( )

Returns an identifier that is currently available for use as an item identifier in the specified menu.

_GetNewMenuId( )

Returns an identifier that's available for use as a menu identifier.

_MenuId( )

Returns the actual menu identifier that corresponds to the system-defined literal for the system menu title or menu.

_MenuInteract( )

Sets the itemid and the menuid to indicate which menu item was selected, if any.

_NewItem( )

Adds an item with the specified itemid to the menu specified by menuid.

_NewMenu( )

Creates a new menu of the specified menu type.

_OnSelection( )

Specifies a routine to execute when the specified menu and item are selected.

_SetItemCmdKey( )

Sets the keyboard shortcut for the specified menu item, as well as the displayed text for the keyboard shortcut.

_SetItemSubMenu( )

Assigns a submenu to a menu item. This can be used to attach a menu to a title, or a submenu to a menu item.

_SetItemText( )

Changes the displayed text for a menu item. The item may either be a pad or a bar.

_SetMenuPoint( )

Specifies the upper left corner, loc, of a menu.

_SetMenuPointP( )

Specifies in pixels the screen position of the upper left corner, loc, of a menu.


Object Routines

These API routines allow you to manipulate Visual FoxPro objects and controls.

_FreeObject( )

Releases an object from the Visual FoxPro API data pool.

_GetObjectProperty( )

Returns a property value for an object.

_ObjectCmp( )

Compares the properties of two objects and returns 0 if their properties and property values are identical.

_ObjectReference( )

Increments the reference count of an object.

_ObjectRelease( )

Decrements the reference count of an object.

_SetObjectProperty( )

Sets a property for an object.

_WGetObjectClientWindow( )

Returns the handle of the client window in which the specified object is contained.

_WGetObjectWindow( )

Returns the handle of the frame window in which the specified object is contained.


Routines to Return Results to Visual FoxPro

These API routines allow you to return results to Visual FoxPro as a specified data type.

_RetChar( )

Sets the function return value to a null-terminated string.

_RetCurrency( )

Sets the library return value to a currency value.

_RetDateStr( )

Sets the function return value to a date. The date is specified in mm/dd/year format, where the year may be either two or four digits.

_RetDateTimeStr( )

Sets the library return value to a datetime.

_RetFloat( )

Sets the function return value to a float value.

_RetInt( )

Sets the function return value to a numeric value.

_RetLogical( )

Sets the function return value to a logical value. Zero is considered False. Any non-zero value is considered True.

_RetVal( )

Passes a complete Visual FoxPro Value structure, so it can return any Visual FoxPro data type except for memo. You must call _RetVal( ) to return a string that contains embedded null characters.


Statement and Expression Routines

These API routines allow you to compile and execute Visual FoxPro commands.

_Evaluate( )

Compiles and executes a Visual FoxPro expression contained in expr, placing the result in res.

_Execute( )

Compiles and executes the null-terminated statement in stmt.


String Manipulation Routines

These API routines allow you to manipulate strings.

_StrCmp( )

Compares two null-terminated strings.

_StrCpy( )

Copies a null-terminated string from src to dest.

_StrLen( )

Returns the length in bytes of a null-terminated string.


Table Input and Output Routines

These API routines allow you manipulate Visual FoxPro tables.

_DBAppend( )

Attempts to append a new record to the table in the specified workarea.

_DBLock( )

Attempts to lock the current table record or file in a work area specified by workarea.

_DBRead( )

Moves the current record pointer to the specified record in the specified workarea.

_DBRecCount( )

Returns the total number of records in the table open in the specified workarea.

_DBRecNo( )

Returns the number of the current record in the table in the specified workarea.

_DBReplace( )

Places a new value in a field.

_DBRewind( )

Performs a GOTO TOP in the specified workarea and returns the resultant record number.

_DBSeek( )

Searches an indexed table in the current work area for the first record whose index key matches the value val.

_DBSkip( )

Performs a SKIP in the specified workarea of the distance specified.

_DBStatus( )

Returns status flags for the specified workarea.

_DBUnlock( )

Releases all user-obtained locks on records or the file in the work area specified by workarea.

_DBUnwind( )

Performs a GOTO BOTTOM in the specified workarea and returns the resultant record number.

_DBWrite( )

Writes to disk the current record in the specified workarea and updates any affected indexes.


Text Editor and Clipboard Manipulation Routines

These API routines allow you to manipulate the Visual FoxPro text editor, the file open in the text editor, and the clipboard.

_EdActive( )

Hides or shows the selection range or insertion point.

_EdCloseFile( )

Closes the specified file while saving without asking, prompting before saving, or saving as another file.

_EdCopy( )

Copies selected area to the clipboard.

_EdCut( )

Copies selected area to the clipboard and deletes it from the editor.

_EdDelete( )

Deletes the selected area. If there is no selection, deletes character at current pos.

_EdGetChar( )

Gets the character at EDPOS.

_EdGetEnv( )

Reads various editor settings.

_EdGetLineNum( )

Returns the line number for the position EDPOS.

_EdGetLinePos( )

Returns the EDPOS for the beginning of the line EDLINE.

_EdGetPos( )

Returns current editor POS, or returns anchor point if there's a selection.

_EdGetStr( )

Gets the text between EDPOS and EDPOS inclusive, and places it in TEXT.

_EdIndent( )

Indents the selected text by int tab stops. Int can be negative in order to format a hanging indent.

_EdInsert( )

Inserts BYTES of TEXT.

_EdLastError( )

Returns the error number of the last editor error.

_EdOpenFile( )

Starts an editor session on this file.

_EdPaste( )

Copies clipboard text into the editor at current position.

_EdPosInView( )

Returns TRUE if the editor position is visible.

_EdRedo( )

Redoes the most recent undo.

_EdRevert( )

Reverts to a saved file.

_EdSave( )

Saves the file without closing the editing window.

_EdScrollToPos( )

Makes sure that EDPOS passed is on the screen, but doesn't move insertion point. BOOL means center EDPOS vertically.

_EdScrollToSel( )

Makes sure the selection anchor point is on the screen. BOOL means center anchor point vertically.

_EdSelect( )

Selects the range from EDPOS to EDPOS. To move the insertion point, set both EDPOSes the same.

_EdSendKey( )

Simulates key press given by int.

_EdSetEnv( )

Sets various editor settings.

_EdSetPos( )

Moves insertion point, and has side affect of unselecting anything currently selected.

_EdSkipLines( )

Moves insertion point from EDPOS to beginning of line int.

_EdUndo( )

Undoes the most recent changes.

_EdUndoOn( )

Groups the actions performed after _EdUndoOn( ) is passed until it is passed again as a single action for undo purposes.


Variable and Array Routines

These API routines allow you to manipulate memory variables and memory variable arrays.

_ALen( )

Returns information about the dimensions of the array whose name table index is nti.

_FindVar( )

Provides a way to initialize a Locator so you can use _Store( ) to place data in an existing memory variable.

_Load( )

Fetches the value of the memory variable or table variable specified by loc and places it into val.

_NameTableIndex( )

Returns the name table index that corresponds to a given name, or -1 if that name isn't in the name table.

_NewVar( )

Creates a variable or an array.

_Release( )

Frees a memory variable or an array.

_Store( )

Replaces the memory variable specified by loc with the value val.


Window Manipulation Routines

These API routines allow you to create, manipulate, and release windows, and manipulate the main Visual FoxPro window.

_Dialog( )

Presents the user with a dialog that is the specified color scheme number scheme and contains the specified body text and button text.

_FindWindow( )

Places the WHANDLE of the window that the point pt belongs to on the screen into wh.

_FindWindowP( )

Places the handle of the window that the point pt belongs to on the screen into wh.

_GlobalToLocal( )

Translates a point in screen-relative coordinates to window-relative coordinates.

_GlobalToLocalP( )

Translates a point in screen-relative coordinates to window-relative pixel coordinates.

_PutChr( )

Writes one character char to the current output window in its normal attribute (color 0).

_PutStr( )

Writes a null-terminated string to the current output window in its normal attribute (color 0).

_PutValue( )

Formats the value val and writes it to the current output window.

_WAttr( )

Returns the attribute byte for the color index in the specified window's scheme.

_WBottom( )

Returns the row on the screen where the bottom of the window is located.

_WBottomP( )

Returns the position on the screen in pixels where the bottom of the specified window is located.

_WClear( )

Erases the contents of the specified window by changing the content area to the default background color.

_WClearRect( )

Erases a rectangular area of a window by changing it to the default background color.

_WClearRectP( )

Erases the specified rectangular portion of a window by changing it to the default background color.

_WClose( )

Closes a window and releases all memory associated with that window.

_WFindTitle( )

Passes the title of a window, and returns the WHANDLE.

_WGetCursor( )

Returns the position of the logical cursor in the specified window.

_WGetCursorP( )

Returns in pixels the current output position in the specified window.

_WGetPort( )

Returns the WHANDLE of the window that's currently selected for user output.

_WHeight( )

Returns the number of rows in the content area of a window.

_WHeightP( )

Returns the height in pixels of the content area of the specified window.

_WHide( )

Removes a window from the screen but keeps track of its contents so that it can be displayed again if desired.

_WLeft( )

Returns the column on the screen where the left edge of the window is located.

_WLeftP( )

Returns the position on the screen in pixels where the left edge of the window is located.

_WMainWindow( )

Returns the WHANDLE of the main Visual FoxPro window.

_WMove( )

Moves the specified window to a new location specified by pt.

_WMoveP( )

Moves the specified window to a new location specified by pt.

_WhToHwnd( )

Passes the WHANDLE, and returns the Windows HWND.

_WOnTop( )

Returns the WHANDLE of the frontmost window.

_WOpen( )

Creates a new window at the coordinates specified by top, left, bottom and right.

_WOpenP( )

Creates a new window at the coordinates specified by top, left, bottom and right.

_WPosCursor( )

Positions the logical cursor of the specified window at the location specified by pt.

_WPosCursorP( )

Positions the logical cursor of the specified window at the location specified in pixels by pt.

_WPutChr( )

Writes one character char to the specified window in the current color.

_WPutStr( )

Writes a null-terminated string to the specified window in the current color.

_WRight( )

Returns the column on the screen where the right edge of the window is located.

_WRightP( )

Returns the position on the screen in pixels where the right edge of the window is located.

_WScroll( )

Scrolls a portion of the contents of a window left or right and up or down.

_WScrollP( )

Scrolls a portion of the contents of a window left or right and up or down.

_WSetAttr( )

Changes the attribute for the specified color scheme index in the indicated window's color scheme to the new attribute attr.

_WSelect( )

Brings the specified window to the frontmost position on the screen.

_WSendBehind( )

Sends the specified window to the rearmost position on the screen.

_WSetPort( )

Changes the user output window to be the specified window.

_WSetTitle( )

Changes the title of a window.

_WShow( )

Redisplays a hidden window on the screen.

_WSize( )

Sets the new dimensions of the window to the height and width specified by h and v in pt.

_WSizeP( )

Sets the new dimensions of the window to the height and width specified by h and v in pt.

_WTitle( )

Puts the null-terminated title of the window wh in title.

_WTop( )

Returns the row on the screen where the top of the window is located.

_WTopP( )

Returns the position on the screen in pixels where the top of the window is located.

_WWidth( )

Returns the number of columns in the content area of a window.

_WWidthP( )

Returns the width in pixels of the content area of the specified window.

_WZoom( )

Zooms a window to a new state.


Visual FoxPro System Events (API Library Construction)

In this table, each Visual FoxPro event is listed along with the layout of its event record fields and a description of when the event occurs.

Event | EventRec Fields | Description
nullEvent | what = nullEvent where.h = horizontal mouse location where.v = vertical mouse location when = ticks since startup | Occurs when no other events are pending. This is the most frequently occurring event and, for performance reasons, should be used sparingly.
mouseDownEvent | what = mouseDownEvent where.h = horizontal mouse location where.v = vertical mouse location mbState = left mouse button when = ticks since startup | Occurs whenever the left mouse button is pressed. Trap for the mouseDownEvent and use this in combination with the where point and _FindWindow function to see if the user clicked on the close menu box or on other parts of a window. (A closeEvent is not generated when you click on the close menu box of a window.)
keyDownEvent | what = keyDownEvent where.h = horizontal mouse location where.v = vertical mouse location message = key code (see Appendix A) modifier = modifier key when = ticks since startup | Occurs whenever a key is pressed on the keyboard or whenever the keyboard buffer is played.
deactivateEvent | what = deactivateEvent where.h = horizontal mouse location where.v = vertical mouse location message = WHANDLE to window when = ticks since startup | Occurs whenever a window becomes deactivated by clicking on the close menu box, activating another window or using the DEACTIVATE WINDOW command. A deactivateEvent is usually followed by an activateEvent.
activateEvent | what = activateEvent where.h = horizontal mouse location where.v = vertical mouse location message = WHANDLE to window when = ticks since startup | Occurs whenever a window is activated. This includes system and user windows as well as dialogs, so it is suggested that whenever you receive this type of event, you check to see if it pertains to your window. An activateEvent is usually preceded by a deactivateEvent.
menuHitEvent | what = menuHitEvent misc = MENUID misc2 = BAR # when = ticks since startup modifier = modifier key | Occurs when a user makes a selection from a menu-type item. Menu-type items include menus, popups and scrollable lists. Because menuHitEvents occur very often, it is best to use the _OnSelection function to do a certain task upon a menu selection so you can eliminate a lot of extra event checking.
closeEvent | what = closeEvent message = WHANDLE to window when = ticks since startup | Occurs when a window is removed from memory with the RELEASE WINDOW command or by exiting Visual FoxPro. To check if a user closed a window by clicking on the close menu box, check for a mouseDownEvent.
hideEvent | what = hideEvent when = ticks since startup | Occurs when a window is hidden with the HIDE WINDOW command.
showEvent | what = showEvent when = ticks since startup | Occurs when a window is shown with the SHOW WINDOW command.
hotkeyEvent | what = hotkeyEvent where.h = horizontal mouse location where.v = vertical mouse location message = key code (see FoxPro Key Codes chapter) modifier = modifier key when = ticks since startup | Occurs when the user presses a key that has actions assigned to it with the ON KEY LABEL command.
sizeEvent | what = sizeEvent when = ticks since startup | Occurs only when a ZOOM WINDOW or SIZE WINDOW command is issued. To check for an instance of a user clicking on the size control of a window, check for a mouseDownEvent.
zoomEvent | what = zoomEvent when = ticks since startup | Occurs only when the ZOOM WINDOW command is executed. To check for the instance of a user clicking on the zoom control, check for a mouseDownEvent.

See Also

External API Library Routines A-Z | External API Library Routines by Category | Visual FoxPro Key Codes (API Library Construction) | Activate Event


Visual FoxPro Key Codes (API Library Construction)

Most keyboard keys have a constant value even when combined with different modifier keys (SHIFT, CTRL and ALT). All regular keys on the keyboard (alphabet and special characters) have a key code of their ASCII value.

Key code and key modifier values are returned in the EventRec structure. The key code can be found in EventRec.message and the key modifiers can be found in EventRec.modifiers.

Visual FoxPro interprets some keys as having a different value depending on the modifier with which they are combined. For example, if SHIFT+F10 is pressed, the corresponding fields in the EventRec would be:

  • EventRec.message = 15D (Hex)
  • EventRec.modifier = 1000 (Hex)

Similarly, if CTRL+F10 is pressed, the EventRec values would be:

  • EventRec.message = 167 (Hex)
  • EventRec.modifiers = 2000 (Hex)

When more than one modifier is used with a key, the modifier values are added together. For example, if you press CTRL+SHIFT+F10, the following values are returned:

  • EventRec.message = 167 (Hex)
  • EventRec.modifiers = 3000 (Hex)

The EventRec.modifiers value in the preceding example is 0x3000 because both the CTRL and SHIFT modifiers were included in the key press. Thus, the SHIFT key modifier (0x1000) was added to the CTRL key modifier (0x2000) to produce a value of 0x3000.

Note The manner in which Visual FoxPro interprets keys (specifically keys with modifiers) is inherent to Visual FoxPro. Other programs may interpret keys differently. If a key is pressed in combination with one or multiple modifier keys (SHIFT, CTRL and ALT), the uppermost nibble represents the modifiers that were used.

The following table demonstrates that the F8 key has a different key code depending on the modifier used.

Keys pressed | Modifier | Key value of F8
F8 | None | \x142
SHIFT+F8 | SHIFT | \x15B
CTRL+F8 | CTRL | \x165
ALT+F8 | ALT | \x16F

Each special key that can be combined with modifiers has a unique value when combined with each modifier. If a special key is combined with multiple modifiers, the unique value assigned to the key is its value for one of the modifiers according to the following rules:

  1. First check to see if the key combination pressed includes the ALT key because the main key will be assigned its ALT key value.
  2. If the key combination does not include ALT, check to see if the CTRL key modifier was used because the main key will be assigned its CTRL key value.
  3. If no ALT or CTRL key modifier is used, check to see if the SHIFT key modifier was used because the main key will be assigned its SHIFT key value.
  4. Finally, if no modifiers were used, the main key is assigned its value based on no modifiers.

Special Key Codes

The following table lists the key values assigned by Visual FoxPro to special keys on the keyboard.

Key | Key code (Hex) | Key modifier
LEFTMOUSE | 100 | None
F1 | 13B | None
F2 | 13C | None
F3 | 13D | None
F4 | 13E | None
F5 | 13F | None
F6 | 140 | None
F7 | 141 | None
F8 | 142 | None
F9 | 143 | None
F10 | 144 | None
HOME | 147 | None
UPARROW | 148 | None
PGUP | 149 | None
LEFTARROW | 14B | None
RIGHTARROW | 14D | None
END | 14F | None
DNARROW | 150 | None
PGDN | 151 | None
INS | 152 | None
DEL | 153 | None
F11 | 185 | None
F12 | 186 | None
BACKTAB | 10F | shiftKey
SHIFT+F1 | 154 | shiftKey
SHIFT+F2 | 155 | shiftKey
SHIFT+F3 | 156 | shiftKey
SHIFT+F4 | 157 | shiftKey
SHIFT+F5 | 158 | shiftKey
SHIFT+F6 | 159 | shiftKey
SHIFT+F7 | 15A | shiftKey
SHIFT+F8 | 15B | shiftKey
SHIFT+F9 | 15C | shiftKey
SHIFT+F10 | 15D | shiftKey
SHIFT+F11 | 187 | shiftKey
SHIFT+F12 | 188 | shiftKey
CTRL+A | 001 | ctrlKey
CTRL+B | 002 | ctrlKey
CTRL+C | 003 | ctrlKey
CTRL+D | 004 | ctrlKey
CTRL+E | 005 | ctrlKey
CTRL+F | 006 | ctrlKey
CTRL+G | 007 | ctrlKey
CTRL+H | 008 | ctrlKey
CTRL+I | 009 | ctrlKey
CTRL+ENTER | 00A | ctrlKey
CTRL+J | 00A | ctrlKey
CTRL+K | 00B | ctrlKey
CTRL+L | 00C | ctrlKey
CTRL+M | 00D | ctrlKey
CTRL+N | 00E | ctrlKey
CTRL+O | 00F | ctrlKey
CTRL+P | 010 | ctrlKey
CTRL+Q | 011 | ctrlKey
CTRL+R | 012 | ctrlKey
CTRL+S | 013 | ctrlKey
CTRL+T | 014 | ctrlKey
CTRL+U | 015 | ctrlKey
CTRL+V | 016 | ctrlKey
CTRL+W | 017 | ctrlKey
CTRL+X | 018 | ctrlKey
CTRL+Y | 019 | ctrlKey
CTRL+Z | 01A | ctrlKey
CTRL+LBRACKET | 01B | ctrlKey
CTRL+BACKSLASH | 01C | ctrlKey
CTRL+RBRACKET | 01D | ctrlKey
CTRL+CARET | 01E | ctrlKey+shiftKey
CTRL+HYPHEN | 01F | ctrlKey
CTRL+SPACEBAR | 020 | ctrlKey
CTRL+F1 | 15E | ctrlKey
CTRL+F2 | 15F | ctrlKey
CTRL+F3 | 160 | ctrlKey
CTRL+F4 | 161 | ctrlKey
CTRL+F5 | 162 | ctrlKey
CTRL+F6 | 163 | ctrlKey
CTRL+F7 | 164 | ctrlKey
CTRL+F8 | 165 | ctrlKey
CTRL+F9 | 166 | ctrlKey
CTRL+F10 | 167 | ctrlKey
CTRL+LEFTARROW | 173 | ctrlKey
CTRL+RIGHTARROW | 174 | ctrlKey
CTRL+END | 175 | ctrlKey
CTRL+PGDN | 176 | ctrlKey
CTRL+HOME | 177 | ctrlKey
CTRL+PGUP | 184 | ctrlKey
CTRL+F11 | 189 | ctrlKey
CTRL+F12 | 18A | ctrlKey
CTRL+UPARROW | 18D | ctrlKey
CTRL+DNARROW | 191 | ctrlKey
CTRL+INS | 192 | ctrlKey
CTRL+DEL | 193 | ctrlKey
CTRL+TAB | 194 | ctrlKey
ALT+Q | 110 | altKey
ALT+W | 111 | altKey
ALT+E | 112 | altKey
ALT+R | 113 | altKey
ALT+T | 114 | altKey
ALT+Y | 115 | altKey
ALT+U | 116 | altKey
ALT+I | 117 | altKey
ALT+O | 118 | altKey
ALT+P | 119 | altKey
ALT+A | 11E | altKey
ALT+S | 11F | altKey
ALT+D | 120 | altKey
ALT+F | 121 | altKey
ALT+G | 122 | altKey
ALT+H | 123 | altKey
ALT+J | 124 | altKey
ALT+K | 125 | altKey
ALT+L | 126 | altKey
ALT+Z | 12C | altKey
ALT+X | 12D | altKey
ALT+C | 12E | altKey
ALT+V | 12F | altKey
ALT+B | 130 | altKey
ALT+N | 131 | altKey
ALT+M | 132 | altKey
ALT+F1 | 168 | altKey
ALT+F2 | 169 | altKey
ALT+F3 | 16A | altKey
ALT+F4 | 16B | altKey
ALT+F5 | 16C | altKey
ALT+F6 | 16D | altKey
ALT+F7 | 16E | altKey
ALT+F8 | 16F | altKey
ALT+F9 | 170 | altKey
ALT+F10 | 171 | altKey
ALT+1 | 178 | altKey
ALT+2 | 179 | altKey
ALT+3 | 17A | altKey
ALT+4 | 17B | altKey
ALT+5 | 17C | altKey
ALT+6 | 17D | altKey
ALT+7 | 17E | altKey
ALT+8 | 17F | altKey
ALT+9 | 180 | altKey
ALT+0 | 181 | altKey
ALT+F11 | 18B | altKey
ALT+F12 | 18C | altKey
ALT+HOME | 197 | altKey
ALT+UPARROW | 198 | altKey
ALT+PGUP | 199 | altKey
ALT+LEFTARROW | 19B | altKey
ALT+RIGHTARROW | 19D | altKey
ALT+END | 19F | altKey
ALT+DNARROW | 1A0 | altKey
ALT+PGDN | 1A1 | altKey
ALT+INS | 1A2 | altKey
ALT+DEL | 1A3 | altKey

Example

FAR EventHandler(WHandle theWindow, EventRec FAR *ev)
{
switch(ev->what)
{
case keyDownEvent:                  /* Check the keyDownEvent */
if (ev->modifiers & shiftCodeMask)      /* A modifier was pressed. */
{
if (ev->modifiers & altKey)            /* Check for the ALT Key */
_PutStr("ALT Key Code should be used.\n");
else
if (ev->modifiers & ctrlKey)         /* CTRL Key */
_PutStr("CTRL Key Code should be used.\n");
else
if (ev->modifiers & shiftKey)         /* SHIFT Key */
_PutStr("SHIFT Key Code should be used.\n");
}
else
_PutStr("Regular Key Code should be used.\n");
return NO;                        /* Let Visual FoxPro have Key also */
break;
default:
return NO;
}
}

Note shiftCodeMask, altKey, ctrlKey, and shiftKey are all defined in PRO_EXT.H and PRO_EXT.INC as follows:

  • #define shiftCodeMask 0xf000
  • #define shiftKey 0x1000
  • #define ctrlKey 0x2000
  • #define altKey 0x4000

See Also

External Routines A-Z | External Routines by Category | _PutStr( ) API Library Routine | _ASCIICOLS System Variable | _ASCIIROWS System Variable | Visual FoxPro System Events (API Library Construction) | KeyPress Event


SQL Commands and Functions

Visual FoxPro supports Structured Query Language (SQL) commands and functions. Visual FoxPro's SQL commands make use of Rushmore Query Optimization technology to optimize performance, and a single SQL command can be used to replace multiple Visual FoxPro commands.

Visual FoxPro supports the following:

ALTER TABLE - SQL Command
Modifies an existing table. You can modify the name, type, precision, scale, null value support, and referential integrity rules for each field in the table.
CREATE CURSOR - SQL Command
Creates a temporary table. Each field in the temporary table is defined with a name, type, precision, scale, null value support, and referential integrity rules. These definitions can be obtained from the command itself or from an array.
CREATE SQL VIEW Command
Displays the View Designer, allowing you to create an SQL view.
CREATE TABLE -SQL Command
Creates a table. Each new table field is defined with a name, type, precision, scale, null value support, and referential integrity rules. These definitions can be obtained from the command itself or from an array.
DELETE - SQL Command
Marks records in a table for deletion using SQL syntax.
INSERT - SQL Command
Appends a new record to the end of an existing table. The new record contains data listed in the INSERT command or from an array.
SELECT - SQL Command
Specifies the criteria on which a query is based and issues the query. Visual FoxPro interprets the query and retrieves the specified data from the table(s). The SELECT command is built into Visual FoxPro like any other Visual FoxPro command. You can create a SELECT command query in these areas:
  • In the Command window.
  • In a Visual FoxPro program (like any other Visual FoxPro command).
  • In the Query Designer.
SQL Pass-Through Foundation Class
Makes it possible for you to execute stored procedures on a host database such as Microsoft SQL Server.
SQLCANCEL( ) Function
Requests cancellation of an executing SQL statement
SQLCOLUMNS( ) Function
Stores a list of column names and information about each column for the specified data source table to a Visual FoxPro cursor.
SQLCOMMIT( ) Function
Commits a transaction.
SQLCONNECT( ) Function
Establishes a connection to a data source.
SQLDISCONNECT( ) Function
Terminates a connection to a data source.
SQLEXEC( ) Function
Sends an SQL statement to the data source, where the statement is processed.
SQLGETPROP( ) Function
Returns current or default settings for an active connection.
SQLMORERESULTS( ) Function
Copies another result set to a Visual FoxPro cursor if more result sets are available.
SQLPREPARE( ) Function
Prepares an SQL statement for remote execution by SQLEXEC( ).
SQLROLLBACK( ) Function
Cancels any changes made during the current transaction.
SQLSETPROP( ) Function
Specifies settings for an active connection.
SQLSTRINGCONNECT( ) Function
Establishes a connection to a data source through a connection string.
SQLTABLES( ) Function
Stores the names of tables in a data source to a Visual FoxPro cursor.
UPDATE - SQL Command
Updates records in a table. The records can be updated based on the results of a SELECT - SQL statement.

See Also

CREATE QUERY | MODIFY QUERY | Language Reference


Language Reference for OLE DB Development

The Visual FoxPro OLE DB Provider supports the native Visual FoxPro language syntax for the following commands:

CREATE TABLE - SQL Command
Creates a table having the specified fields.
DELETE - SQL Command
Marks records for deletion.
DROP TABLE Command
Removes a table from the database specified with the data source and deletes it from disk.
INSERT - SQL Command
Appends a record to the end of a table that contains the specified field values.
SELECT - SQL Command
Retrieves data from one or more tables.
UPDATE - SQL Command
Updates records in a table with new values.

The Visual FoxPro Language Reference contains detailed information about the following supported commands:

ALTER TABLE - SQL Command
Programmatically modifies the structure of a table.
CREATE TABLE - SQL Command
Creates a table having the specified fields.
DELETE - SQL Command
Marks records for deletion.
DELETE TAG Command
Removes a tag or tags from a compound index (.cdx) file.
DROP TABLE Command
Removes a table from the database specified with the data source and deletes it from disk.
INDEX Command
Creates an index file to display and access table records in a logical order.
INSERT - SQL Command
Appends a record to the end of a table that contains the specified field values.
SELECT - SQL Command
Retrieves data from one or more tables.

The Visual FoxPro OLE DB Provider supports the native Visual FoxPro language syntax for this command.

SET ANSI Command
Determines how comparisons between strings of different lengths are made with the = operator in Visual FoxPro SQL commands.
SET BLOCKSIZE Command
Specifies how disk space is allocated for the storage of memo fields.
SET COLLATE Command
Specifies a collation sequence for character fields in subsequent indexing and sorting operations.
SET DELETED Command
Specifies whether records marked for deletion are processed and whether they are available for use in other commands.
SET EXACT Command
Specifies the rules for comparing two strings of different lengths.
SET EXCLUSIVE Command
Specifies whether table files are opened for exclusive or shared use on a network.
SET NULL Command
Determines how null values are supported by the ALTER TABLE - SQL, CREATE TABLE - SQL, and INSERT - SQL commands.
SET PATH Command
Specifies a path for file searches.
SET REPROCESS Command
Specifies how many times or for how long to lock a file or record after an unsuccessful locking attempt.
SET UNIQUE Command
Specifies whether records with duplicate index key values are maintained in an index file.
UPDATE - SQL Command
Updates records in a table with new values.

See Also

Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro SET Commands | Supported Visual FoxPro Commands and Functions | Unsupported Visual FoxPro Commands and Functions | Mapping Visual FoxPro ODBC driver functions to OLE DB methods | Supported OLE DB Objects | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Visual FoxPro OLE DB Provider Data Support

The following table describes the types and other file and code characteristics of data supported by the Visual FoxPro OLE DB Provider.

Data type | Indicator | Size | Range | OLE DB type
Character | C | 1 byte per char to 254 | Any Characters | DBTYPE_STR
Character (binary) | C NOCPTRANS | 1 byte per char to 254 | Any Characters | DBTYPE_BYTES
Date | D | 8 bytes | 0001-01-01 to 9999-12-31 | DBTYPE_DATE
DateTime | T | 8 bytes | 0001-01-01 to 9999-12-31; 00:00:00 a.m. to 11:59:59 p.m. | DBTYPE_DBTIMESTAMP
Numeric | N | 1 to 20 bytes | - .9999999999E+19 to .9999999999E+20 | DBTYPE_DECIMAL
Float | F | 1 to 20 bytes | - .9999999999E+19 to .9999999999E+20 | DBTYPE_DECIMAL
Integer | I | 4 bytes | 2147483647 to 2147483647 | DBTYPE_I4
Double | B | 8 bytes | +/-4.94065645841247E-324 to +/-8.9884656743115E307 | DBTYPE_R8
Currency | Y | 8 bytes | - 922337203685477.5807 to 922337203685477.5807 | DBTYPE_CY
Logical | L |  | .T./.F. | DBTYPE_BOOL
Memo | M | 4 bytes in table | Available memory | DBTYPE_BYTES
Memo (binary) | M NOCPTRANS | 4 bytes in table | Available memory | DBTYPE_BYTES
General (blob) | G | 4 bytes in table | Available memory | DBTYPE_BYTES

The following table describes the mapping of Visual FoxPro OLE DB types to Visual Studio types:

Indicator | OLE DB type | Visual Studio type
C | DBTYPE_STR | System.String
C NOCPTRANS | DBTYPE_BYTES | System.String
D | DBTYPE_DATE | System.DateTime
T | DBTYPE_DBTIMESTAMP | System.DateTime
N | DBTYPE_NUMERIC | System.Decimal
F | DBTYPE_NUMERIC | System.Decimal
I | DBTYPE_I4 | System.Int32
B | DBTYPE_R8 | System.Double
Y | DBTYPE_CY | System.Decimal
M | DBTYPE_STR | System.String
M NOCPTRANS | DBTYPE_BYTES | System.Byte
G | DBTYPE_BYTES | System.Byte

See Also

Language Reference for OLE DB Development | Supported Visual FoxPro SET Commands | Supported Visual FoxPro Commands and Functions | Unsupported Visual FoxPro Commands and Functions | Supported OLE DB Objects | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Supported Visual FoxPro Commands and Functions in OLE DB Provider

The following commands and functions are supported in rules, triggers, default values and stored procedures.

$ Operator | % Operator | & Command
&& Command | * Command | = Command

A

ABS( ) Function | ACOPY( ) Function | ACOS( ) Function
ADATABASES( ) Function | ADBOBJECTS( ) Function | ADD TABLE Command
ADEL( ) Function | AELEMENT( ) Function | AERROR( ) Function
AFIELDS( ) Function | AINS( ) Function | ALEN( ) Function
ALIAS( ) Function | ALLTRIM( ) Function | ALTER TABLE - SQL Command
AND Operator | APPEND Command | APPEND FROM ARRAY Command
APPEND GENERAL Command | APPEND GENERAL Command | APPEND MEMO Command
APPEND PROCEDURES Command | ASC( ) Function | ASCAN( ) Function
ASIN( ) Function | ASORT( ) Function | ASUBSCRIPT( ) Function
AT( ) Function | AT_C( ) Function | ATAN( ) Function
ATC( ) Function | ATCC( ) Function | ATCLINE( ) Function
ATLINE( ) Function | ATN2( ) Function | AUSED( ) Function
AVERAGE Command |  |

B

BEGIN TRANSACTION Command | BETWEEN( ) Function | BITAND( ) Function
BITCLEAR( ) Function | BITLSHIFT( ) Function | BITNOT( ) Function
BITOR( ) Function | BITRSHIFT( ) Function | BITSET( ) Function
BITTEST( ) Function | BITXOR( ) Function | BLANK Command
BOF( ) Function |  |

C

CALCULATE Command | CANDIDATE( ) Function | CDX( ) Function
CEILING( ) Function | CHR( ) Function | CHRTRAN( ) Function
CHRTRANC( ) Function | CLOSE Commands | CMONTH( ) Function
CONTINUE Command | COPY INDEXES Command | COPY PROCEDURES Command
COPY STRUCTURE Command | COPY STRUCTURE EXTENDED Command | COPY TO Command
CALCULATE Command | CANDIDATE( ) Function | CDX( ) Function
CEILING( ) Function | CHR( ) Function | CHRTRAN( ) Function
CHRTRANC( ) Function | CLOSE Commands | CMONTH( ) Function
CONTINUE Command | COPY INDEXES Command | COPY PROCEDURES Command
COPY STRUCTURE Command | COPY STRUCTURE EXTENDED Command | CURSORGETPROP("AutoIncError") Function

D

DATE( ) Function | DATETIME( ) Function | DAY( ) Function
DBC( ) Function | DBF( ) Function | DBUSED( ) Function
DELETE - SQL Command | DELETE Command | DELETE TAG Command
DELETED( ) Function | DESCENDING( ) Function | DIFFERENCE( ) Function
DIMENSION Command | DISKSPACE( ) Function | DMY( ) Function
DO CASE ... ENDCASE Command | DO Command | DO WHILE ... ENDDO Command
DOW( ) Function | DTOC( ) Function | DTOR( ) Function
DTOS( ) Function | DTOT( ) Function |

E

EMPTY( ) Function | END TRANSACTION Command | EOF( ) Function
ERROR( ) Function | EVALUATE( ) Function | EXIT Command
EXP( ) Function |  |

F

FCOUNT( ) Function | FDATE( ) Function | FIELD( ) Function
FILE( ) Function | FILTER( ) Function | FLDLIST( ) Function
FLOCK( ) Function | FLOOR( ) Function | FLUSH Command
FOR ... ENDFOR Command | FOR( ) Function | FOUND( ) Function
FREE TABLE Command | FSIZE( ) Function | FTIME( ) Function
FULLPATH( ) Function | FUNCTION Command | FV( ) Function

G

GATHER Command | GETCP( ) Function | GETFLDSTATE( ) Function
GETNEXTMODIFIED( ) Function | GO | GOTO Command | GOMONTH( ) Function

H

HEADER( ) Function HOUR( ) Function

I

IDXCOLLATE( ) Function | IF ... ENDIF Command | IIF( ) Function
INDBC( ) Function | INDEX Command | INLIST( ) Function
INSERT - SQL Command | INT( ) Function | ISALPHA( ) Function
ISBLANK( ) Function | ISDIGIT( ) Function | ISEXCLUSIVE( ) Function
ISLEADBYTE( ) Function | ISLOWER( ) Function | ISLOWER( ) Function
ISREADONLY( ) Function | ISUPPER( ) Function |

K

KEY( ) Function KEYMATCH( ) Function

L

LEFT( ) Function | LEFTC( ) Function | LEN( ) Function
LENC( ) Function | LIKE( ) Function | LIKEC( ) Function
LOCAL Command | LOCATE Command | LOCK( ) Function
LOG( ) Function | LOG10( ) Function | LOOKUP( ) Function
LOWER( ) Function | LPARAMETERS Command | LTRIM( ) Function
LUPDATE( ) Function |  |

M

_MLINE System Variable | MAX( ) Function | MDX( ) Function
MDY( ) Function | MEMLINES( ) Function | MESSAGE( ) Function
MIN( ) Function | MINUTE( ) Function | MLINE( ) Function
MOD( ) Function | MONTH( ) Function | MTON( ) Function

N

NDX( ) Function | NORMALIZE( ) Function | NOT Operator
NOTE Command | NTOM( ) Function | NVL( ) Function

O

OCCURS( ) Function | OLDVAL( ) Function | ON ERROR Command
ON KEY Command | ON( ) Function | OPEN DATABASE Command
OR Operator | ORDER( ) Function | OS( ) Function

P

PACK Command | PADL( ) | PADR( ) | PADC( ) Functions | PARAMETERS Command
PARAMETERS( ) Function | PAYMENT( ) Function | PI( ) Function
PRIMARY( ) Function | PRIVATE Command | PROCEDURE Command
PROGRAM( ) Function | PROPER( ) Function | PUBLIC Command
PV( ) Function |  |

R

RAND( ) Function | RAT( ) Function | RATC( ) Function
RATLINE( ) Function | RECALL Command | RECCOUNT( ) Function
RECNO( ) Function | RECSIZE( ) Function | RELATION( ) Function
REMOVE TABLE Command | REPLACE Command | REPLACE FROM ARRAY Command
REPLICATE( ) Function | RETRY Command | RETURN Command
RIGHT( ) Function | RIGHTC( ) Function | RLOCK( ) Function
ROLLBACK Command | ROUND( ) Function | RTOD( ) Function
RTRIM( ) Function |  |

S

SCAN ... ENDSCAN Command | SCATTER Command | SEC( ) Function
SECONDS( ) Function | SEEK Command | SEEK( ) Function
SELECT - SQL Command | SELECT Command | SELECT( ) Function
SET AUTOINCERROR Command | SET BLOCKSIZE Command | SET COLLATE Command
SET DATABASE Command | SET DEFAULT Command | SET DELETED Command
SET ENGINEBEHAVIOR Command | SET EXACT Command | SET EXCLUSIVE Command
SET FDOW Command | SET FIELDS Command | SET FILTER Command
SET FIXED Command | SET FULLPATH Command | SET FWEEK Command
SET HOURS Command | SET INDEX Command | SET LOCK Command
SET MULTILOCKS Command | SET NEAR Command | SET NOCPTRANS Command
SET NOTIFY Command | SET NULL Command | SET OPTIMIZE Command
SET ORDER Command | SET PATH Command | SET PROCEDURE Command
SET RELATION Command | SET RELATION OFF Command | SET REPROCESS Command
SET SKIP Command | SET UDFPARMS Command | SET UNIQUE Command
SET VOLUME Command | SET( ) Function | SETFLDSTATE( ) Function
SIGN( ) Function | SIN( ) Function | SKIP Command
SORT Command | SPACE( ) Function | SQRT( ) Function
STORE Command | STR( ) Function | STRCONV( ) Function
STRTRAN( ) Function | STUFF( ) Function | STUFFC( ) Function
SUBSTR( ) Function | SUBSTRC( ) Function | SUM Command
SYS(0) - Network Machine Information | SYS(1) - Julian System Date | SYS(2) - Seconds Since Midnight
SYS(3) - Legal File Name | SYS(5) - Default Drive | SYS(10) - String from Julian Day Number
SYS(11) - Julian Day Number | SYS(12) - Available Memory in Bytes | SYS(2001) – SET ... Command Status
SYS(2003) – Current Directory | SYS(2004) – Visual FoxPro Start Directory | SYS(2007) - Checksum Value
SYS(2011) - Current Lock Status | SYS(2015) - Unique Procedure Name | SYS(2029) - Table Type

T

_TALLY System Variable | _TRIGGERLEVEL System Variable | TABLEREVERT( ) Function
TABLEUPDATE( ) Function | TAG( ) Function | TAGCOUNT( ) Function
TAGNO( ) Function | TAN( ) Function | TARGET( ) Function
TIME( ) Function | TOTAL Command | TRIM( ) Function
TTOC( ) Function | TTOD( ) Function | TXNLEVEL( ) Function
TYPE( ) Function |  |

U

UNIQUE( ) Function | UNLOCK Command | UPDATE - SQL Command
UPDATE Command | UPPER( ) Function | USE Command
USED( ) Function |  |

V

VAL( ) Function VERSION( ) Function

W

WEEK( ) Function

Y

YEAR( ) Function

Z

ZAP Command

See Also

Language Reference for OLE DB Development | Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro SET Commands | Unsupported Visual FoxPro Commands and Functions | Supported OLE DB Objects | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Supported Visual FoxPro SET Commands in OLE DB Provider

The Visual FoxPro OLE DB Provider supports the following SET commands.

SET ANSI Command

SET AUTOINCERROR Command

SET BLOCKSIZE Command

SET COLLATE Command

SET DELETED Command

SET ENGINEBEHAVIOR Command

SET EXACT Command

SET EXCLUSIVE Command

SET FULLPATH Command

SET MULTILOCKS

SET NULL Command

SET PATH Command

SET REPROCESS Command

Note You can determine the state of many SET commands, supported and unsupported except for SET ANSI, by querying the database. For example, the following returns the value for PATH in the resultant cursor.
   SELECT SET('PATH') FROM <sometable> WHERE RECNO()=1

See Also

Language Reference for OLE DB Development | Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro Commands and Functions | Unsupported Visual FoxPro Commands and Functions | Supported OLE DB Objects | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Unsupported Visual FoxPro Commands and Functions in OLE DB Provider

The following Visual FoxPro commands and functions are not supported by the OLE DB Provider:

#DEFINE ... #UNDEF | #IF ... #ENDIF Preprocessor Directive | #IFDEF | #IFNDEF
#INCLUDE Preprocessor Directive | :: Scope Resolution Operator | ! Command (see RUN | ! Command)
? | ?? Command | ??? Command | \ | \\ Command
@ ... BOX Command | @ ... CLASS Command | @ ... CLEAR Command
@ ... EDIT - Edit Boxes Command | @ ... FILL Command | @ ... GET
@ ... MENU Command | @ ... PROMPT Command | @ ... SAY Command
@ ... SCROLL Command | @ ... TO Command |

A

ACCEPT Command | ACLASS( ) Function | ACTIVATE MENU Command
ACTIVATE POPUP Command | ACTIVATE SCREEN Command | ACTIVATE WINDOW Command
ActivateCell Method | ADD CLASS Command | ADIR( ) Function
AFONT( ) Function | AINSTANCE( ) Function | _ALIGNMENT System Memory Variable
AMEMBERS( ) Function | ANSITOOEM( ) Function | APRINTERS( ) Function
ASELOBJ( ) Function | ASSIST Command |

B

BAR( ) Function | BARCOUNT( ) Function | BARPROMPT( ) Function
_BEAUTIFY System Memory Variable | _BOX System Memory Variable | BROWSE Command
_BROWSER System Memory Variable | BUILD APP Command | BUILD EXE Command
BUILD PROJECT Command | _BUILDER System Memory Variable |

C

_CALCVALUE System Memory Variable | _CLIPTEXT System Memory Variable | _CONVERTER System Memory Variable
_CUROBJ System Memory Variable | CALL Command | CANCEL Command
CAPSLOCK( ) Function | CD Command | CHANGE Command
CHDIR Command | CHRSAW( ) Function | CLOSE MEMO Command
CNTBAR( ) Function | CNTPAD( ) Function | COL( ) Function
COMPILE Command | COMPILE DATABASE Command | COMPILE FORM Command
COMPOBJ( ) Function | Container Object | Control Object
COPY FILE Command | COPY MEMO Command | CREATE CLASS Command
CREATE CLASSLIB Command | CREATE COLOR SET Command | CREATE Command
CREATE CONNECTION Command | CREATE DATABASE Command | CREATE FORM Command
CREATE FROM Command | CREATE LABEL Command | CREATE MENU Command
CREATE PROJECT Command | CREATE QUERY Command | CREATE REPORT Command
CREATE SCREEN Command | CREATE SQL VIEW Command | CREATE TRIGGER Command
CREATE VIEW Command | CREATEOBJECT( ) Function | CURDIR( ) Function
CURSORTOXML( ) Function |  |

D

_DBLCLICK System Memory Variable | _DIARYDATE System Memory Variable | DBSETPROP( ) Function
DDE Functions | DEACTIVATE MENU Command | DEACTIVATE POPUP Command
DEACTIVATE WINDOW Command | DECLARE - DLL Command | DECLARE Command
DEFINE BAR Command | DEFINE BOX Command | DEFINE CLASS Command
DEFINE MENU Command | DEFINE PAD Command | DEFINE POPUP Command
DEFINE WINDOW Command | DELETE CONNECTION Command | DELETE DATABASE Command
DELETE FILE Command | DELETE TRIGGER Command | DELETE VIEW Command
DIR Command | DIRECTORY Command | DISPLAY Command
DISPLAY CONNECTIONS Command | DISPLAY DATABASE Command | DISPLAY DLLS Command
DISPLAY FILES Command | DISPLAY MEMORY Command | DISPLAY OBJECTS Command
DISPLAY PROCEDURES Command | DISPLAY STATUS Command | DISPLAY STRUCTURE Command
DISPLAY TABLES Command | DISPLAY VIEWS Command | DO FORM Command

E

EDIT Command | ERROR Command |
ERASE Command | EXTERNAL Command | EXPORT Command
EJECT Command | EJECT PAGE Command |

F

_FOXDOC System Memory Variable | _FOXGRAPH System Memory Variable | FCHSIZE( ) Function
FCLOSE( ) Function | FCREATE( ) Function | FEOF( ) Function
FERROR( ) Function | FFLUSH( ) Function | FGETS( ) Function
FILER Command | FIND Command | FKLABEL( ) Function
FKMAX( ) Function | FONTMETRIC( ) Function | FOPEN( ) Function
FPUTS( ) Function | FREAD( ) Function | FSEEK( ) Function
FWRITE( ) Function |  |

G

_GENGRAPH System Memory Variable | _GENMENU System Memory Variable | _GENPD System Memory Variable
_GENSCRN System Memory Variable | _GENXTAB System Memory Variable | GETBAR( ) Function
GETCOLOR( ) Function | GETDIR( ) Function | GETENV( ) Function
GETEXPR Command | GETFILE( ) Function | GETFONT( ) Function
GETOBJECT( ) Function | GETPAD( ) Function | GETPICT( ) Function
GETPRINTER( ) Function |  |

H

HELP Command | HIDE MENU Command | HIDE POPUP Command
HIDE WINDOW Command | HOME( ) Function |

I

IMESTATUS( ) Function | IMPORT Command | INPUT Command
INDEX ON Command | INKEY( ) Function | ISCOLOR( ) Function
INSERT Command | INSMODE( ) Function |
ISMOUSE( ) Function | _INDENT System Memory Variable |

J

JOIN Command

K

KEYBOARD Command

L

_LMARGIN System Memory Variable | LABEL Command | LASTKEY( ) Function
LINENO( ) Function | LIST Commands | LIST CONNECTIONS Command
LOAD Command | LOCFILE( ) Function |

M

MCOL( ) Function | MD Command | MENU TO Command
MEMORY( ) Function | MENU Command | MKDIR Command
MENU( ) Function | MESSAGEBOX( ) Function | MODIFY CONNECTION Command
MODIFY CLASS Command | MODIFY COMMAND Command | MODIFY FORM Command
MODIFY DATABASE Command | MODIFY FILE Command | MODIFY MEMO Command
MODIFY GENERAL Command | MODIFY LABEL Command | MODIFY PROJECT Command
MODIFY MENU Command | MODIFY PROCEDURE Command | MODIFY SCREEN Command
MODIFY QUERY Command | MODIFY REPORT Command | MODIFY WINDOW Command
MODIFY STRUCTURE Command | MODIFY VIEW Command | MOVE WINDOW Command
MOUSE Command | MOVE POPUP Command | MROW( ) Function
MRKBAR( ) Function | MRKPAD( ) Function |
MWINDOW( ) Function | MDOWN( ) Function |

N

NEWOBJECT( ) Function NUMLOCK( ) Function

O

OBJNUM( ) Function | OBJTOCLIENT( ) Function | ON BAR Command
OEMTOANSI( ) Function | ON APLABOUT Command | ON EXIT MENU Command
ON ESCAPE Command | ON EXIT BAR Command | ON KEY = Command
ON EXIT PAD Command | ON EXIT POPUP Command | ON PAD Command
ON KEY LABEL Command | ON MACHELP Command | ON SELECTION BAR Command
ON PAGE Command | ON READERROR Command | ON SELECTION POPUP Command
ON SELECTION MENU Command | ON SELECTION PAD Command |
ON SHUTDOWN Command | OBJVAR( ) Function |

P

_PADVANCE System Memory Variable | _PAGENO System Memory Variable | _PBPAGE System Memory Variable
_PCOLNO System Memory Variable | _PCOPIES System Memory Variable | _PDRIVER System Memory Variable
_PDSETUP System Memory Variable | _PECODE System Memory Variable | _PEJECT System Memory Variable
_PEPAGE System Memory Variable | _PLENGTH System Memory Variable | _PLINENO System Memory Variable
_PLOFFSET System Memory Variable | _PPITCH System Memory Variable | _PQUALITY System Memory Variable
_PRETEXT System Memory Variable | _PSCODE System Memory Variable | _PSPACING System Memory Variable
_PWAIT System Memory Variable | PACK DATABASE Command | PAD( ) Function
PCOL( ) Function | PEMSTATUS( ) Function | PLAY MACRO Command
POP KEY Command | POP MENU Command | POP POPUP Command
POPUP( ) Function | PRINTJOB ... ENDPRINTJOB Command | PRINTSTATUS( ) Function
PRMBAR( ) Function | PRMPAD( ) Function | PROMPT( ) Function
PROW( ) Function | PRTINFO( ) Function | PUSH KEY Command
PUSH MENU Command | PUSH POPUP Command | PUTFILE( ) Function

Q

QUIT Command

R

_RMARGIN System Memory Variable | RD Command | READKEY( ) Function
READ Command | READ MENU Command | RELEASE BAR Command
REFRESH() Function | REINDEX Command | RELEASE LIBRARY Command
RELEASE CLASSLIB Command | RELEASE Command | RELEASE PAD Command
RELEASE MENUS Command | RELEASE MODULE Command | RELEASE WINDOWS Command
RELEASE POPUPS Command | RELEASE PROCEDURE Command | RENAME Command
REMOVE CLASS Command | RENAME CLASS Command | RENAME VIEW Command
RENAME CONNECTION Command | RENAME TABLE Command | RESTORE FROM Command
REPORT Command | REQUERY( ) Function | RESTORE WINDOW Command
RESTORE MACROS Command | RESTORE SCREEN Command | RGBSCHEME( ) Function
RESUME Command | RGB( ) Function | RUN | ! Command
RMDIR Command | ROW( ) Function |
RUNSCRIPT Command | RDLEVEL( ) Function |

S

SAVE MACROS Command | SAVE SCREEN Command | SAVE TO Command
SAVE WINDOWS Command | SCHEME( ) Function | SCOLS( ) Function
SCROLL Command | _SCREEN System Memory Variable | SET Command
SET ALTERNATE Command | SET APLABOUT Command | SET AUTOSAVE Command
SET BELL Command | SET BLINK Command | SET BORDER Command
SET BRSTATUS Command | SET CARRY Command | SET DATE Command
SET CLASSLIB Command | SET CLEAR Command | SET CLOCK Command
SET COLOR OF Command | SET COLOR OF SCHEME Command | SET COLOR SET Command
SET COLOR TO Command | SET COMPATIBLE Command | SET CONFIRM Command
SET CONSOLE Command | SET CPCOMPILE | SET CPDIALOG
SET CURRENCY Command | SET CURSOR Command | SET DATASESSION Command
SET DATE Command | SET DEBUG Command | SET DECIMALS Command
SET DELIMITERS Command | SET DEVELOPMENT Command | SET DEVICE Command
SET DISPLAY Command | SET DOHISTORY Command | SET ECHO Command
SET ESCAPE Command | SET FORMAT Command | SET FUNCTION Command
SET HEADINGS Command | SET HELP Command | SET HELPFILTER Command
SET INTENSITY Command | SET KEY Command | SET KEYCOMP Command
SET LOGERRORS Command | SET MACDESKTOP Command | SET MACHELP Command
SET MACKEY Command | SET MARGIN Command | SET MARK OF Command
SET MARK TO Command | SET MEMOWIDTH Command | SET MESSAGE Command
SET MOUSE Command | SET ODOMETER Command | SET OLEOBJECT Command
SET PALETTE Command | SET PDSETUP Command | SET POINT Command
SET PRINTER Command | SET READBORDER Command | SET REFRESH Command
SET RESOURCE Command | SET SAFETY Command | SET SCOREBOARD Command
SET SECONDS Command | SET SEPARATOR Command | SET SHADOWS Command
SET SKIP OF Command | SET SPACE Command | SET STATUS Command
SET STATUS BAR Command | SET STEP Command | SET STICKY Command
SET SYSFORMATS Command | SET SYSMENU Command | SET TALK Command
SET TEXTMERGE Command | SET TEXTMERGE DELIMITERS Command | SET TOPIC Command
SET TOPIC ID Command | SET TRBETWEEN Command | SET TYPEAHEAD Command
SET VIEW Command | SET WINDOW OF MEMO Command | SET XCMDFILE Command
_SHELL System Memory Variable | SHOW GET Command | SHOW GETS Command
SHOW MENU Command | SHOW OBJECT Command | SHOW POPUP Command
SHOW WINDOW Command | SIZE POPUP Command | SIZE WINDOW Command
SKPBAR( ) Function | SKPPAD( ) Function | SOUNDEX( ) Function
_SPELLCHK System Memory Variable | SQL functions | SROWS( ) Function
_STARTUP System Memory Variable | STRTOFILE( ) function | SUSPEND Command
SYSMETRIC( ) Function |  |

T

_TABS System Memory Variable | TEXT ... ENDTEXT Command | TXTWIDTH( ) Function
TRANSFORM( ) Function | _TRANSPORT System Memory Variable |
TYPE Command | _THROTTLE System Memory Variable |

U

UPDATED( ) Function USE Command

V

VALIDATE DATABASE Command VARREAD( ) Function VERSION( ) Function

W

_WINDOWS System Memory Variable | _WIZARD System Memory Variable | WCHILD( ) Function
WAIT Command | WBORDER( ) Function | WFONT( ) Function
WCOLS( ) Function | WEXIST( ) Function | WLROW( ) Function
WITH ... ENDWITH Command | WLAST( ) Function | WONTOP( ) Function
WMAXIMUM( ) Function | WLCOL( ) Function | WREAD( ) Function
WOUTPUT( ) Function | WMINIMUM( ) Function | WVISIBLE( ) Function
WPARENT( ) Function | WTITLE( ) Function |
WROWS( ) Function | _WRAP System Memory Variable |

X

XMLTOCURSOR( ) Function

Z

ZOOM WINDOW Command

See Also

Language Reference for OLE DB Development | Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro SET Commands | Supported Visual FoxPro Commands and Functions | Supported OLE DB Objects | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Mapping Visual FoxPro ODBC driver functions to OLE DB methods

OLE DB and ODBC are different interfaces. There is no one-to-one correspondence between the properties of one interface and the attributes of the other. OLE DB contains a rich definition of property sets and interface method parameters that provide services significantly different from those provided by ODBC. For more information, see the OLE DB documentation of schema rowsets, property sets, and methods. For a discussion on OLE DB relative to ODBC, see the MSDN article "OLE DB for the ODBC Programmer."

See Also

Language Reference for OLE DB Development | OLE DB Provider for Visual FoxPro


Supported OLE DB Objects

The Visual FoxPro OLE DB Provider supports the following OLE DB objects that are based on the OLE DB 2.1 Spec. Implementation.

Object | Description
Data Source Object | Establish a link to a data store.
Session Object | Provide methods for creating commands and rowsets and for creating and modifying tables and indexes.
Command Object | Provide collections, properties, and methods for issuing commands and returning rowsets.
Rowset Object | Expose data in a tabular form as rowsets, rows that each contain columns of data.
Error Object | Provides the ability to return multiple error records from a single call and the ability to return provider-specific error information.
ConnectionPage Object | Provides access to a Microsoft DataLink (UDL) Configuration dialog box.

See Also

Language Reference for OLE DB Development | Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro SET Commands | Supported Visual FoxPro Commands and Functions | Unsupported Visual FoxPro Commands and Functions | Standard and Custom OLE DB Properties | OLE DB Provider for Visual FoxPro


Standard and Custom OLE DB Properties

Following is an alphabetical list of OLE DB Properties supported by the Visual FoxPro OLE DB Provider and Visual FoxPro custom properties. Refer to the OLE DB Programmers Reference for detailed descriptions of these properties.

Property | Description
DBPROP_ABORTPRESERVE | Preserve on Abort
DBPROP_ACCESSORDER | Access Order
DBPROP_ACTIVESESSIONS | Active Sessions
DBPROP_ALTERCOLUMN | Alter Column Support
DBPROP_APPENDONLY | Append-Only Rowset
DBPROP_ASYNCTXNABORT | Asynchable Abort
DBPROP_ASYNCTXNCOMMIT | Asynchable Commit
DBPROP_AUTH_CACHE_AUTHINFO | Cache Authentication
DBPROP_AUTH_ENCRYPT_PASSWORD | Encrypt Password
DBPROP_AUTH_INTEGRATED | Integrated Security
DBPROP_AUTH_MASK_PASSWORD | Mask Password
DBPROP_AUTH_PASSWORD | Password
DBPROP_AUTH_PERSIST_ENCRYPTED | Persist Encrypted
DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO | Persist Security Info
DBPROP_AUTH_USERID | User ID
DBPROP_BLOCKINGSTORAGEOBJECTS | Blocking Storage Objects
DBPROP_BOOKMARKINFO | Bookmark Information
DBPROP_BOOKMARKS | Use Bookmarks
DBPROP_BOOKMARKSKIPPED | Skip Deleted Bookmarks
DBPROP_BOOKMARKTYPE | Bookmark Type
DBPROP_BYREFACCESSORS | Pass By Ref Accessors
DBPROP_CACHEDEFERRED | Cache Deferred Columns
DBPROP_CANFETCHBACKWARDS | Fetch Backwards
DBPROP_CANHOLDROWS | Hold Rows
DBPROP_CANSCROLLBACKWARDS | Scroll Backwards
DBPROP_CATALOGLOCATION | Catalog Location
DBPROP_CATALOGTERM | Catalog Term
DBPROP_CATALOGUSAGE | Catalog Usage
DBPROP_CHANGEINSERTEDROWS | Change Inserted Rows
DBPROP_COL_AUTOINCREMENT | Autoincrement
DBPROP_COL_DEFAULT | Default
DBPROP_COL_DESCRIPTION | Description
DBPROP_COL_FIXEDLENGTH | Fixed Length
DBPROP_COL_NULLABLE | Nullable
DBPROP_COL_PRIMARYKEY | Primary Key
DBPROP_COL_UNIQUE | Unique
DBPROP_COLUMNDEFINITION | Column Definition
DBPROP_COLUMNRESTRICT | Column Privileges
DBPROP_COMMANDTIMEOUT | Command Time Out
DBPROP_COMMITPRESERVE | Preserve on Commit
DBPROP_CONCATNULLBEHAVIOR | NULL Concatenation Behavior
DBPROP_CURRENTCATALOG | Current Catalog
DBPROP_DATASOURCENAME | Data Source Name
DBPROP_DATASOURCEREADONLY | Read-Only Data Source
DBPROP_DBMSNAME | DBMS Name
DBPROP_DBMSVER | DBMS Version
DBPROP_DEFERRED | Defer Column
DBPROP_DELAYSTORAGEOBJECTS | Delay Storage Object Updates
DBPROP_DSOTHREADMODEL | Data Source Object Threading Model
DBPROP_GROUPBY | GROUP BY Support
DBPROP_HETEROGENEOUSTABLES | Heterogeneous Table Support
DBPROP_IAccessor | IAccessor
DBPROP_IColumnsInfo | IColumnsInfo
DBPROP_IColumnsRowset | IColumnsRowset
DBPROP_IConnectionPointContainer | IConnectionPointContainer
DBPROP_IConvertType | IConvertType
DBPROP_IDENTIFIERCASE | Identifier Case Sensitivity
DBPROP_ILockBytes | ILockBytes
DBPROP_IMMOBILEROWS | Immobile Rows
DBPROP_INDEX_AUTOUPDATE | Auto-Update
DBPROP_INDEX_CLUSTERED | Clustered
DBPROP_INDEX_FILLFACTOR | Fill Factor
DBPROP_INDEX_INITIALSIZE | Initial Size
DBPROP_INDEX_NULLCOLLATION | NULL Collation
DBPROP_INDEX_NULLS | NULL Keys
DBPROP_INDEX_PRIMARYKEY | Primary Key
DBPROP_INDEX_SORTBOOKMARKS | Sort Bookmarks
DBPROP_INDEX_TEMPINDEX | Temporary Index
DBPROP_INDEX_TYPE | Index Type
DBPROP_INDEX_UNIQUE | Unique
DBPROP_INIT_CATALOG | Initial Catalog
DBPROP_INIT_DATASOURCE | Data Source
DBPROP_INIT_HWND | Window Handle
DBPROP_INIT_IMPERSONATION_LEVEL | Impersonation Level
DBPROP_INIT_LCID | Locale Identifier
DBPROP_INIT_LOCATION | Location
DBPROP_INIT_MODE | Mode
DBPROP_INIT_PROMPT | Prompt
DBPROP_INIT_PROTECTION_LEVEL | Protection Level
DBPROP_INIT_PROVIDERSTRING | Extended Properties
DBPROP_INIT_TIMEOUT | Connect Timeout
DBPROP_IProvideMoniker | IProvideMoniker
DBPROP_IRowset | IRowset
DBPROP_IRowsetChange | IRowsetChange
DBPROP_IRowsetCurrentIndex | IRowsetCurrentIndex
DBPROP_IRowsetFind | IRowsetFind
DBPROP_IRowsetIdentity | IRowsetIdentity
DBPROP_IRowsetIndex | IRowsetIndex
DBPROP_IRowsetInfo | IRowsetInfo
DBPROP_IRowsetLocate | IRowsetLocate
DBPROP_IRowsetRefresh | IRowsetRefresh
DBPROP_IRowsetResynch | IRowsetResynch
DBPROP_IRowsetScroll | IRowsetScroll
DBPROP_IRowsetUpdate | IRowsetUpdate
DBPROP_ISequentialStream | ISequentialStream
DBPROP_IStorage | IStorage
DBPROP_IStream | IStream
DBPROP_ISupportErrorInfo | ISupportErrorInfo
DBPROP_LITERALBOOKMARKS | Literal Bookmarks
DBPROP_LITERALIDENTITY | Literal Row Identity
DBPROP_LOCKMODE | Lock Mode
DBPROP_LOCKMODES | Lock Modes
DBPROP_MAXINDEXSIZE | Maximum Index Size
DBPROP_MAXOPENROWS | Maximum Open Rows
DBPROP_MAXPENDINGROWS | Maximum Pending Rows
DBPROP_MAXROWS | Maximum Rows
DBPROP_MAXROWSIZE | Maximum Row Size
DBPROP_MAXROWSIZEINCLUDESBLOB | Maximum Row Size Includes BLOB
DBPROP_MAXTABLESINSELECT | Maximum Tables in SELECT
DBPROP_MAYWRITECOLUMN | Column Writable
DBPROP_MEMORYUSAGE | Memory Usage
DBPROP_MULTIPLEPARAMSETS | Multiple Parameter Sets
DBPROP_MULTIPLERESULTS | Multiple Results
DBPROP_MULTIPLESTORAGEOBJECTS | Multiple Storage Objects
DBPROP_MULTITABLEUPDATE | Multi-Table Update
DBPROP_NOTIFICATIONGRANULARITY | Notification Granularity
DBPROP_NOTIFICATIONPHASES | Notification Phases
DBPROP_NOTIFYCOLUMNSET | Column Set Notification
DBPROP_NOTIFYROWDELETE | Row Delete Notification
DBPROP_NOTIFYROWFIRSTCHANGE | Row First Change Notification
DBPROP_NOTIFYROWINSERT | Row Insert Notification
DBPROP_NOTIFYROWRESYNCH | Row Resynchronization Notification
DBPROP_NOTIFYROWSETFETCHPOSITIONCHANGE | Rowset Fetch Position Change Notification
DBPROP_NOTIFYROWSETRELEASE | Rowset Release Notification
DBPROP_NOTIFYROWUNDOCHANGE | Row Undo Change Notification
DBPROP_NOTIFYROWUNDODELETE | Row Undo Delete Notification
DBPROP_NOTIFYROWUNDOINSERT | Row Undo Insert Notification
DBPROP_NOTIFYROWUPDATE | Row Update Notification
DBPROP_NULLCOLLATION | NULL Collation Order
DBPROP_OLEOBJECTS | OLE Object Support
DBPROP_OPENROWSETSUPPORT | Open Rowset Support
DBPROP_ORDERBYCOLUMNSINSELECT | ORDER BY Columns in Select List
DBPROP_ORDEREDBOOKMARKS | Bookmarks Ordered
DBPROP_OTHERINSERT | Others' Inserts Visible
DBPROP_OTHERUPDATEDELETE | Others' Changes Visible
DBPROP_OUTPUTPARAMETERAVAILABILITY | Output Parameter Availability
DBPROP_OWNINSERT | Own Inserts Visible
DBPROP_OWNUPDATEDELETE | Own Changes Visible
DBPROP_PERSISTENTIDTYPE | Persistent ID Type
DBPROP_PREPAREABORTBEHAVIOR | Prepare Abort Behavior
DBPROP_PREPARECOMMITBEHAVIOR | Prepare Commit Behavior
DBPROP_PROCEDURETERM | Procedure Term
DBPROP_PROVIDERFRIENDLYNAME | Provider Friendly Name
DBPROP_PROVIDERNAME | Provider Name
DBPROP_PROVIDEROLEDBVER | OLE DB Version
DBPROP_PROVIDERVER | Provider Version
DBPROP_QUICKRESTART | Quick Restart
DBPROP_QUOTEDIDENTIFIERCASE | Quoted Identifier Sensitivity
DBPROP_REENTRANTEVENTS | Reentrant Events
DBPROP_REMOVEDELETED | Remove Deleted Rows
DBPROP_REPORTMULTIPLECHANGES | Report Multiple Changes
DBPROP_RETURNPENDINGINSERTS | Return Pending Inserts
DBPROP_ROWRESTRICT | Row Privileges
DBPROP_ROWSETCONVERSIONSONCOMMAND | Rowset Conversions on Command
DBPROP_ROWTHREADMODEL | Row Threading Model
DBPROP_SCHEMATERM | Schema Term
DBPROP_SCHEMAUSAGE | Schema Usage
DBPROP_SERVERCURSOR | Server Cursor
DBPROP_SERVERDATAONINSERT | Server Data on Insert
DBPROP_SERVERNAME | Server Name
DBPROP_SESS_AUTOCOMMITISOLEVELS | Autocommit Isolation Levels
DBPROP_SQLSUPPORT | SQL Support
DBPROP_STRONGIDENTITY | Strong Row Identity
DBPROP_STRUCTUREDSTORAGE | Structured Storage
DBPROP_SUBQUERIES | Subquery Support
DBPROP_SUPPORTEDTXNDDL | Transaction DDL
DBPROP_SUPPORTEDTXNISOLEVELS | Isolation Levels
DBPROP_SUPPORTEDTXNISORETAIN | Isolation Retention
DBPROP_TABLETERM | Table Term
DBPROP_TBL_TEMPTABLE | Temporary Table
DBPROP_TRANSACTEDOBJECT | Objects Transacted
DBPROP_UPDATABILITY | Updatability
DBPROP_USERNAME | User Name
DBPROP_VFPOLEDB_ANSI | SET ANSI
DBPROP_VFPOLEDB_BLOCKSIZE | SET BLOCKSIZE
DBPROP_VFPOLEDB_COLLATE | SET COLLATE setting
DBPROP_VFPOLEDB_Column_Caption | Column Caption
DBPROP_VFPOLEDB_Column_Comment | Column Comment
DBPROP_VFPOLEDB_Column_Default | Default Value
DBPROP_VFPOLEDB_Column_Error |
DBPROP_VFPOLEDB_Column_Format | Format
DBPROP_VFPOLEDB_Column_FormDisplay | DisplayClass
DBPROP_VFPOLEDB_Column_FormPath | DisplayClassLibrary
DBPROP_VFPOLEDB_Column_InputMask | InputMask
DBPROP_VFPOLEDB_Column_RuleExpression | RuleExpression
DBPROP_VFPOLEDB_Column_RuleText | RuleText
DBPROP_VFPOLEDB_DELETED | SET DELETED
DBPROP_VFPOLEDB_EXACT | SET EXACT
DBPROP_VFPOLEDB_INDEX | SET INDEX
DBPROP_VFPOLEDB_INIT_COLLATE | Collating Sequence
DBPROP_VFPOLEDB_NULL | SET NULL
DBPROP_VFPOLEDB_ORDER | SET ORDER
DBPROP_VFPOLEDB_PATH | SET PATH
DBPROP_VFPOLEDB_REPROCESS | SET REPROCESS
DBPROP_VFPOLEDB_Rowset_SP | Stored Procedure
DBPROP_VFPOLEDB_SESS_ID | Internal Session ID
DBPROP_VFPOLEDB_SETDEBUGOUTTO | Debug Output File
DBPROP_VFPOLEDB_SETDEFAULTTO | Default Drive and Folder
DBPROP_VFPOLEDB_SETFULLPATH | Set Fullpath ON/OFF
DBPROP_VFPOLEDB_Table_Comment | Comment
DBPROP_VFPOLEDB_Table_DeleteTrigger | DeleteTrigger
DBPROP_VFPOLEDB_Table_InsertTrigger | InsertTrigger
DBPROP_VFPOLEDB_Table_Path | Path
DBPROP_VFPOLEDB_Table_PrimaryKey | PrimaryKey
DBPROP_VFPOLEDB_Table_RuleExpression | RuleExpression
DBPROP_VFPOLEDB_Table_RuleText | RuleText
DBPROP_VFPOLEDB_Table_UpdateTrigger | UpdateTrigger
DBPROP_VFPOLEDB_UNIQUE | SET UNIQUE

See Also

Language Reference for OLE DB Development | Visual FoxPro OLE DB Provider Data Support | Supported Visual FoxPro SET Commands | Supported Visual FoxPro Commands and Functions | Unsupported Visual FoxPro Commands and Functions | Supported OLE DB Objects | OLE DB Provider for Visual FoxPro


Backward-Compatible Language Elements

The following language elements are included for backward compatibility with previous versions of FoxPro.

@ ... BOX Command

@ ... EDIT - Edit Boxes Command

@ ... GET - Check Boxes Command

@ ... GET - Combo Boxes Command

@ ... GET - Command Buttons Command

@ ... GET - List Boxes Command

@ ... GET - Option Buttons Command

@ ... GET - Spinners Command

@ ... GET - Text Boxes Command

@ ... GET - Transparent Buttons Command

@ ... MENU Command

@ ... PROMPT Command

@ ... SAY - Pictures & OLE Objects Command

@ ... SAY Command

@ ... TO Command

_ALIGNMENT System Variable

_ASSIST System Variable

_BOX System Variable

_CUROBJ System Variable

_FOXDOC System Variable

_GENGRAPH System Variable

_GENPD System Variable

_GENSCRN System Variable

_GENXTAB System Variable

_INDENT System Variable

_LMARGIN System Variable

_PADVANCE System Variable

_PBPAGE System Variable

_PCOLNO System Variable

_PCOPIES System Variable

_PDRIVER System Variable

_PDSETUP System Variable

_PECODE System Variable

_PEJECT System Variable

_PEPAGE System Variable

_PLENGTH System Variable

_PLINENO System Variable

_PLOFFSET System Variable

_PPITCH System Variable

_PQUALITY System Variable

_PSCODE System Variable

_PSPACING System Variable

_PWAIT System Variable

_RMARGIN System Variable

_TABS System Variable

_TRANSPORT System Variable

_WRAP System Variable

ACCEPT Command

ANSITOOEM( ) Function

ASSIST Command

CALL Command

CLEAR READ Command

COL( ) Function

ColorScheme Property

CREATE SCREEN - Quick Screen Command

CREATE SCREEN Command

DEFINE BOX Command

ErrorMessage Event

FIND Command

INPUT Command

INSERT Command

JOIN Command

LOAD Command

MDOWN( ) Function

MemoWindow Property

MENU Command

MENU TO Command

Message Event

MODIFY SCREEN Command

OBJNUM( ) Function

OBJVAR( ) Function

OEMTOANSI( ) Function

ON KEY = Command

ON KEY Command

ON READERROR Command

RDLEVEL( ) Function

READ Command

READ MENU Command

ReadActivate Event

ReadBackColor Property

ReadCycle Property

ReadDeactivate Event

ReadForeColor Property

READKEY( ) Function

ReadLock Property

ReadMouse Property

ReadObject Property

ReadSave Property

ReadShow Event

ReadTimeout Property

ReadValid Event

ReadWhen Event

ROW( ) Function

SET BORDER Command

SET BRSTATUS Command

SET CLEAR Command

SET COLOR OF Command

SET COLOR TO Command

SET DEBUG Command

SET DELIMITERS Command

SET DISPLAY Command

SET DOHISTORY Command

SET FORMAT Command

SET INTENSITY Command

SET VOLUME Command

SET WINDOW OF MEMO Command

SHOW GET Command

SHOW GETS Command

SHOW OBJECT Command

SizeBox Property

SYS(100) - Console Setting

SYS(101) - Device Setting

SYS(102) - Printer Setting

SYS(103) - Talk Setting

SYS(15) - Character Translation

SYS(18) - Current Control

SYS(20) - Transform German Text

SYS(2016) - SHOW GETS WINDOW Name

SYS(23)

SYS(24)

UPDATE Command

UPDATED( ) Function

VARREAD( ) Function

WREAD( ) Function

ZoomBox Property


Controls and Objects Created in Earlier Versions

This topic describes support for controls and objects created in earlier FoxPro versions and new controls added to Visual FoxPro.

The easiest way to create controls and objects is by using the Form Designer. For more information about creating controls with the Form Designer, see Creating Forms.

You can also create controls and objects programmatically. See DEFINE CLASS for more information about creating controls programmatically from the Visual FoxPro base classes, and Object-Oriented Programming.

Some controls behave slightly differently depending on whether you are using Visual FoxPro for Windows or Visual FoxPro for Macintosh; by default, controls in Visual FoxPro for Macintosh follow user interface conventions common to Macintosh applications. For example, by default the CheckBox, ComboBox, and OptionButton controls cannot receive the focus in Visual FoxPro for Macintosh. For more details about differences in control behavior, see the topic for the SET KEYCOMP command.

In Visual FoxPro, a NAME clause has been added to each of the controls created in previous FoxPro versions. The NAME clause creates an object reference for controls created with @ ... GET and @ ... EDIT, allowing you to manipulate the controls with Visual FoxPro properties, events, and methods. The NAME clause provides an intermediate step to upgrade your applications using Visual FoxPro object-oriented programming techniques.

Compatibility with FoxPro 2.x Controls

The following table lists the controls available in earlier FoxPro versions and the base class you can use to programmatically create the same control in Visual FoxPro.

FoxPro 2.x controls | Equivalent VisualFoxPro controls | Visual FoxProbase class names
@ ... GET - Check Boxes | CheckBox Control | CheckBox
@ ... GET - Lists | ListBox Control | ListBox
@ ... GET - Popups | ComboBox Control | ComboBox
@ ... GET - Push Buttons | CommandButton Control | CommandButton
@ ... GET - Radio Buttons | OptionButton Control | OptionButton
@ ... GET - Spinners | Spinner Control | Spinner
@ ... GET - Text Boxes | TextBox Control | TextBox
@ ... EDIT - Text Edit Regions | EditBox Control | EditBox

Visual FoxPro Base Classes

In addition, the following controls and objects are new to Visual FoxPro and can be created programmatically only from their Visual FoxPro base classes.

Controls and objects | Base class names | Description
Column Object | Column | Creates a column in a grid.
CommandGroup Control | CommandGroup | Creates a group of command buttons.
Container Object | Container | Creates an object that can contain other objects.
Control Object | Control | Creates a control object that can contain other protected objects.
Cursor Object | Cursor | Created when a table or view is added to the data environment for a form, form set, or report.
Custom Object | Custom | Creates a custom, user-defined object.
DataEnvironment Object | DataEnvironment | Created when a form, form set, or report is opened.
Form Object | Form | Creates a form.
FormSet Object | FormSet | Creates a form set.
Grid Control | Grid | Creates a Grid control.
Header Object | Header | Creates a Header for a Column in a Grid.
Hyperlink Object | HyperLink | Creates a hyperlink object, allowing you to jump to a URL (Uniform Resource Locator).
Image Control | Image | Creates an Image control that displays a .bmp or PICT picture.
Label Control | Label | Creates a Label control that displays text.
Line Control | Line | Creates a Line control that displays a horizontal, vertical, or diagonal line.
OLE Container Control | OLEControl | Creates an OLE Container control.
OLE Bound Control | OLEBoundControl | Creates an OLE Bound control.
OptionGroup Control | OptionGroup | Creates a group of option buttons.
Page Object | Page | Creates a page in a page frame.
PageFrame Control | PageFrame | Creates a page frame to contain pages.
ProjectHook Object | ProjectHook | Instantiated whenever a project is opened, providing programmatic access to project events.
Relation Object | Relation | Created when you establish relationships from within the Data Environment Designer for a form, form set, or report.
Separator Object | Separator | Creates a Separator object that places space between controls in a toolbar.
Session Object | Session | Creates a custom, user-defined object that manages its own data session.
Shape Control | Shape | Creates a Shape control that displays a box, circle, or ellipse.
Timer Control | Timer | Creates a Timer control that can execute code at regular intervals.
ToolBar Object | Toolbar | Creates a toolbar on which controls can be placed.

See Also

CREATE CLASS | CREATE FORM | DEFINE CLASS


@ ... BOX Command

Included for backward compatibility. Use the Shape control instead.


@ ... EDIT - Edit Boxes Command

Included for backward compatibility. Use the EditBox Control instead.


@ ... GET - Check Boxes Command

Included for backward compatibility. Use the CheckBox Control instead.


@ ... GET - Combo Boxes Command

Included for backward compatibility. Use the ComboBox Control instead.


@ ... GET - Command Buttons Command

Included for backward compatibility. Use the CommandButton Control instead.


@ ... GET - List Boxes Command

Included for backward compatibility. Use the ListBox Control instead.


@ ... GET - Option Buttons Command

Included for backward compatibility. Use the OptionGroup Control instead.


@ ... GET - Spinners Command

Included for backward compatibility. Use the Spinner Control instead.


@ ... GET - Text Boxes Command

Included for backward compatibility. Use the TextBox Control instead.


@ ... GET - Transparent Buttons Command

Included for backward compatibility. Use the CommandButton Control instead.


@ ... MENU Command

Included for backward compatibility. Use the Menu and Shortcut Designers and CREATE MENU Command instead.


@ ... PROMPT Command

Included for backward compatibility. Use the Menu and Shortcut Designer and CREATE MENU Command instead.


@ ... SAY - Pictures & OLE Objects Command

Included for backward compatibility. Use the Image Control, OLE Bound, and OLE Container Control instead.


@ ... SAY Command

Included for backward compatibility. Use the Label Control to display text and the TextBox Control to display the contents of fields and variables.


@ ... TO Command

Included for backward compatibility. Use the Shape Control instead.


_ALIGNMENT System Variable

Included for backward compatibility. Use the Report Designer instead.


_ASSIST System Variable

Included for backward compatibility. Use the DO Command instead.


_BOX System Variable

Included for backward compatibility. Use the Report Designer instead.


_CUROBJ System Variable

Included for backward compatibility. Use the ActiveControl Property for new forms instead.


_FOXDOC System Variable

Included for backward compatibility. Use the Documenting Wizard instead.


_GENGRAPH System Variable

Included for backward compatibility. Use the Graph Wizard instead.


_GENPD System Variable

Included for backward compatibility. Use the TO FILE ASCII argument in REPORT.


_GENSCRN System Variable

Included for backward compatibility. Use the Form Designer instead.


_GENXTAB System Variable

Included for backward compatibility. Use the Cross-tab Wizard instead.


_INDENT System Variable

Included for backward compatibility. Use the Report Designer instead.

See Also

System Variables A-Z | System Variables Overview


_LMARGIN System Variable

Included for backward compatibility. Use the Report Designer instead.


_PADVANCE System Variable

Included for backward compatibility. Use the Report Designer instead.


_PBPAGE System Variable

Included for backward compatibility. Use the Report Designer instead.


_PCOLNO System Variable

Included for backward compatibility. Use the Report Designer instead.


_PCOPIES System Variable

Included for backward compatibility. Use the Report Designer instead.


_PDRIVER System Variable

Included for backward compatibility. Use the TO FILE ASCII argument in REPORT.


_PDSETUP System Variable

Included for backward compatibility. Use the TO FILE ASCII argument in REPORT.


_PECODE System Variable

Included for backward compatibility. Use the Report Designer instead.


_PEJECT System Variable

Included for backward compatibility. Use the Report Designer instead.


_PEPAGE System Variable

Included for backward compatibility. Use the Report Designer instead.


_PLENGTH System Variable

Included for backward compatibility. Use the Report Designer instead.


_PLINENO System Variable

Included for backward compatibility. Use the Report Designer instead.


_PLOFFSET System Variable

Included for backward compatibility. Use the Report Designer instead.


_PPITCH System Variable

Included for backward compatibility. Use the Report Designer instead.


_PQUALITY System Variable

Included for backward compatibility. Use the Report Designer instead.


_PSCODE System Variable

Included for backward compatibility. Use the Report Designer instead.


_PSPACING System Variable

Included for backward compatibility. Use the Report Designer instead.


_PWAIT System Variable

Included for backward compatibility. Use the Report Designer instead.


_RMARGIN System Variable

Included for backward compatibility. Use the Report Designer instead.


_TABS System Variable

Included for backward compatibility. Use the Report Designer instead.


_TRANSPORT System Variable

Included for backward compatibility.


_WRAP System Variable

Included for backward compatibility. Use the Report Designer instead.


ACCEPT Command

Included for backward compatibility. Use the TextBox Control instead.


ASSIST Command

Included for backward compatibility. Use the DO Command instead.


CALL Command

Included for backward compatibility. Use SET LIBRARY instead.


CREATE SCREEN – Quick Screen Command

Included for backward compatibility. Use the Form Designer instead.

See Also

Form Designer


CREATE SCREEN Command

Included for backward compatibility. Use CREATE FORM instead.

See Also

CREATE FORM


DEFINE BOX Command

Included for backward compatibility. Use the Report Designer instead.


FIND Command

Included for backward compatibility. Use SEEK instead.


INPUT Command

Included for backward compatibility. Use the TextBox control instead.


INSERT Command

Included for backward compatibility. Use APPEND or INSERT - SQL instead.


JOIN Command

Included for backward compatibility. Use SELECT - SQL instead.


LOAD Command

No longer available. Use SET LIBRARY instead.


MENU TO Command

Included for backward compatibility. Use the Visual FoxPro Menu Designer instead.


MODIFY SCREEN Command

Included for backward compatibility. Use MODIFY FORM instead.


ON KEY = Command

Included for backward compatibility. Use ON KEY LABEL instead.


ON KEY Command

Included for backward compatibility. Use ON KEY LABEL instead.


ON READERROR Command

Included for backward compatibility. Use the Valid event instead.


READ MENU Command

Included for backward compatibility. Use the Menu Designer to create menus.


SET BORDER Command

Included for backward compatibility. Use the BorderStyle Property instead.


SET BRSTATUS Command

Included for backward compatibility. Use the StatusBarText Property instead.


SET CLEAR Command

Included for backward compatibility. Use the Refresh Method instead.


SET COLOR OF Command

Included for backward compatibility. Use SET COLOR OF SCHEME instead.


SET COLOR TO Command

Included for backward compatibility. Use SET COLOR OF SCHEME instead.


SET DEBUG Command

Included for backward compatibility. Makes the Debug and Trace windows either available or unavailable from the Visual FoxPro menu system in versions prior to 5.0.

SET DEBUG ON | OFF

Parameters

ON
(Default) Makes the Debug and Trace windows either available or unavailable from the Visual FoxPro menu system.
OFF
Makes the Debug and Trace windows unavailable from the Visual FoxPro system menu. However, when SET DEBUG is set to OFF, you can open the Debug window with SET ECHO ON or ACTIVATE WINDOW DEBUG, and you can open the Trace window with SET STEP ON or ACTIVATE WINDOW TRACE.

Remarks

For more information on using the Trace and Debug windows, see Testing and Debugging Applications.

See Also

CLEAR DEBUG | DEBUG | SET_ECHO


SET DELIMITERS Command

Included for backward compatibility. Use the Format Property instead.


SET DISPLAY Command

Included for backward compatibility. Use the font properties of the _SCREEN System Variable instead.


SET DOHISTORY Command

Included for backward compatibility. Use the Trace Window instead.


SET FORMAT Command

Included for backward compatibility. Use the Format Property instead.


SET INTENSITY Command

Included for backward compatibility. Use SET COLOR OF SCHEME instead.


SET VOLUME Command

Included for backward compatibility. Maps MS-DOS drive designators (A:, B:, C:, and so on) to volumes or folders in FoxPro for Macintosh.

SET VOLUME cMS-DOSDrive TO [cMacintoshPath]

Parameters

cMS-DOSDrive
Specifies an MS-DOS drive designator, and can be any letter from A through Z. The drive delimiter colon, as in A: or C:, is optional.
cMacintoshPath
Specifies a volume name, a volume name with a folder name, a nested folder, or Macintosh shorthand notation (: or ::) or MS-DOS shorthand notation (\ or ..).

If cMacintoshPath includes a volume or folder name that contains a space, cMacintoshPath must be enclosed in quotation marks. If you include a path in cMacintoshPath that is not fully qualified, the path is relative to the current default folder.

Remarks

Most effective in FoxPro for Macintosh.

SET VOLUME helps move applications created in FoxPro for MS-DOS and Visual FoxPro to FoxPro for Macintosh. For every occurrence of a specified MS-DOS drive designator, FoxPro for Macintosh internally substitutes the Macintosh volume or folder you designate.

When you start FoxPro for Macintosh, there is no default volume or folder designation. However, you can specify a default volume or folder in your Visual FoxPro configuration file with the VOLUME configuration item.

Use DISPLAY STATUS to display the current volume or folder mapping.

Example

The following commands map every occurrence of an MS-DOS C drive to a Macintosh volume named MacHD or Mac HD:

SET VOLUME C: TO MacHD:
SET VOLUME C: TO 'Mac HD:'
SET VOLUME C TO 'Mac HD:'

You can also specify a folder with a Macintosh volume:

SET VOLUME C: TO MacHD:FolderOne
SET VOLUME C TO 'MacHD:Folder One'

You can use MS-DOS and Macintosh shorthand notation as well. To map every occurrence of an MS-DOS C drive to the current Macintosh volume, issue the following command:

SET VOLUME C TO \

To map every occurrence of an MS-DOS C drive to the FoxPro for Macintosh startup volume, issue SET VOLUME without cMacintoshPath:

SET VOLUME C TO

See Also

SYS(5) – Default Drive | SYS(2003) – Current Directory


SET WINDOW OF MEMO Command

Included for backward compatibility. Use the TextBox Control instead.


SHOW GET Command

Included for backward compatibility. Use the Refresh method to redisplay a control after changing the control's properties.


SHOW GETS Command

Included for backward compatibility. Use the Refresh method to redisplay all controls on a form or formset after changing the control's properties.


SHOW OBJECT Command

Included for backward compatibility. Use the Refresh method to redisplay a control after changing the control's properties.


SYS(100) - Console Setting

Included for backward compatibility. Use SET("CONSOLE") instead.

SYS(100)

Return Values

Character

Example

IF SYS(100) != 'ON'
   SET CONSOLE ON
ENDIF

See Also

SET CONSOLE Command | SYS( ) Functions Overview | PREVIEW clause is not allowed with OFF/NOCONSOLE or TO PRINT/FILE (Error 1681) | SET( ) Function


SYS(101) - Device Setting

Included for backward compatibility. Use SET("DEVICE") instead.

SYS(101)

Return Values

Character

Example

IF SYS(101) != 'SCREEN'
   SET DEVICE TO SCREEN
ENDIF

See Also

SET DEVICE | SYS( ) Functions Overview | SYS(100) - Console Setting | SYS(102) - Printer Setting | SET( ) Function


SYS(102) - Printer Setting

Included for backward compatibility. Use SET("PRINTER") instead.

SYS(102)

Return Values

Character

Example

IF SYS(102) != 'OFF'
   SET PRINTER OFF
ENDIF

See Also

SET PRINTER | SYS( ) Functions Overview | GETPRINTER( ) | SET( ) Function


SYS(103) - Talk Setting

Included for backward compatibility. Use SET("TALK") instead.

SYS(103)

Return Values

Character

Example

IF SYS(103) != 'ON'
   SET TALK ON
ENDIF

See Also

SET TALK | SYS( ) Functions Overview | SET( ) Function


UPDATE Command

Included for backward compatibility. Use UPDATE - SQL instead.


User Interface Reference

User interface (UI) reference topics explain the options that appear on various dialog boxes, windows, and other user interface elements. These topics generally appear when you press F1 in a dialog box or window.

In This Section

Builders
Describes the builders included in Visual FoxPro and how you can use them for controls, forms, and for creating referential integrity between database tables.
Designers
Discusses designers, which make it possible for you to design the windows, dialog boxes, and components in your application visually.
Task Pane Manager
Describes the Task Pane Manager, which contains information and exposes essential tasks for easy use. Individual panes can contain static or dynamic information, gather content from the Internet, expose wizards to accomplish routine tasks, display Help, and present samples. You can create customized panes that can be shared with other users.
Toolbox
Describes the Visual FoxPro Toolbox, which displays items used in the creation of applications. Items are displayed in toolsets (collections of tools) by category.
Wizards
Discusses the Visual FoxPro wizards, which are interactive programs that help you quickly accomplish common tasks such as creating forms, formatting reports, setting up queries, importing and upsizing data, publishing in HTML, and so on.
Windows
Describes the options that appear on various dialog boxes, windows, and other user interfaces.
Dialog Boxes
Explains the options that appear on various Visual FoxPro dialog boxes.

Related Sections

Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
General Reference
Includes Visual FoxPro related technical information, including file types, file structures, and other reference information about Visual FoxPro elements.
Error Messages
Provides information about some of the more common error messages in Visual FoxPro.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks.
Programming in Visual FoxPro
Discusses how you can access the full power of Visual FoxPro by creating applications. Understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity.


Builders

Builders are tools that aid in setting properties of controls on a form. Unlike wizards, builders are reentrant, so you can reopen a builder on a particular control repeatedly.

Visual FoxPro includes a number of generic builders for many of the common form controls including grids, list boxes, combo boxes, check boxes, command groups, and option groups.

Visual FoxPro offers a wide selection of builders. For details, consult the list below.

You can use builders for some controls, for forms, for formatting controls, and for creating referential integrity between database tables.

To build a control

  • From the Form Controls toolbar, choose the Builder Lock button. Each time you add a new control to a form, Visual FoxPro displays the appropriate builder.

    -or-

  • Select a control on the form, and choose the Builder button in the Properties window.

To use the Form Builder

  • From the Form menu, choose Quick Form.

When you have several controls on a form, you can format them all at the same time with the AutoFormat Builder.

To format several controls

  1. In the Form Designer, select controls.
  2. From the Form Designer Toolbar, choose the AutoFormat button.

When a builder is displayed, select the options for each tab and then choose OK to register the changes.

In This Section

Application Builder
Displays a tabbed dialog box to simplify creating and modifying forms, complex controls, and other optional elements of effective and satisfying applications.
AutoFormat Builder
Allows you to apply a set of styles to selected controls of the same type.
Combo Box Builder
Makes it easy for you to set properties for a Combo Box control.
Command Group Builder
Makes it easy for you to set properties for a Command Group control.
CursorAdapter Builder
Makes it easy for you to build CursorAdapter objects more quickly.
DataEnvironment Builder
Makes it easy for you to build DataEnvironment objects that use the capabilities of CursorAdapter objects.
Edit Box Builder
Makes it easy for you to set properties for an Edit Box control.
Form Builder
Makes it easy for you to add fields as new controls to a form.
Grid Builder
Makes it possible for you to set properties for a Grid control.
List Box Builder
Makes it easy for you to set properties for a List Box control.
Option Group Builder
Makes it easy for you to set properties for an Option Group control.
Referential Integrity Builder
Helps you to ensure referential integrity by setting up triggers to control how records are inserted, updated, or deleted in related tables.
Text Box Builder
Makes it easy for you to set properties for a Text Box control.
XML Web Service Builder
Makes it possible for you to bind an XML Web service to a control on a Visual FoxPro form or to an object, such as a cursor adapter in the form's data environment, without writing code.

Related Sections

User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application Builder.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.


Application Builder

The Application builder tabbed dialog box simplifies creating and modifying forms, complex controls, and other optional, elements of effective and satisfying applications.

To use the Application builder

  1. On the Tools menu, point to Wizards, and then click All Wizards. The Wizard Selection dialog box appears.
  2. In the Wizard Selection dialog box, choose Application Builder.

The Application builder integrates with the application framework files created by the Application Wizard so you can build a complete application without having to write code. You also can do the following:

  • Add, edit, or remove such application-specific components as tables, forms, and reports.
  • Specify visual styles for forms and reports.
  • Add common application elements including a splash screen, an About dialog box, a Favorites menu, a User Login dialog box, and a standard toolbar.
  • Specify production credits and version information for the application.
  • View table files in a database from the Data tab.

As in all Visual FoxPro builders, the Application builder is reentrant, meaning that you can close it and then reopen it to modify any settings the builder makes. You can reopen the Application builder by right-clicking the project and selecting Builder.

Note Additional changes made by means of the builder will not appear in the application until the application is rebuilt.

For more information, see Creating Applications with the Application Framework.

Builder Tabs

General

Specifies the application name and other optional features such as splash screen, startup form, and the type of application.

Credits

Specifies application production credits such as author, company, version, copyright, and trademark.

Data

Specifies the data source and the format for forms and reports you include in your application.

Forms

Specifies menu types, the menu from which a form is called, toolbars, and whether a form can be instanced multiple times.

Reports

Specifies friendly names for reports in your application.

Advanced

Specifies the Help file name and the default directory for your application. You can also specify the inclusion of a standard toolbar and a Favorites menu in your application.

See Also

Builders | Application Framework Files | Application Wizard | Advanced Tab, Application Builder | Credits Tab, Application Builder | Data Tab, Application Builder | Forms Tab, Application Builder | General Tab, Application Builder | Reports Tab, Application Builder


General Tab, Application Builder

On this tab of the Application builder, you specify the application name and such other optional features as splash screen, startup form, and the type of application.

Name
Specifies the friendly name of your application used in the application title bar, About dialog box, and throughout your application.
Image
Specifies the file name and the location of the image used in the splash screen and the About dialog box of your application. You can use icon (.ico) files shipped in your Visual FoxPro \Graphics\ICO folder or such other graphic files as .bmp, .gif, or .jpg files.

Application Type

The following option buttons enable you to specify the way your application runs:

Normal
Application will run in the main Visual FoxPro window, taking over the entire Visual FoxPro environment including the system menu.
Module
Application is added to an existing project or called from another application. The application adds a single menu pad and menu to the existing system menu, and therefore functions as a component of another application.
Note Because modules do not issue READ EVENTS or alter existing Visual FoxPro environment settings, they function well when called by other applications or at design time in the Visual FoxPro development environment. For more information, see READ EVENTS Command.
Top-Level
Application will run on the Microsoft Windows-based desktop. With top-level applications, the Visual FoxPro-based desktop is not necessarily visible. Provides a Windows multiple-document interface (MDI) with more flexibility than _SCREEN because you can subclass it. For more information, see _SCREEN System Variable.

Common Dialogs

The following check boxes let you include certain dialog boxes in your application:

Splash Screen
Specifies whether the application starts by displaying the image file designated in the Image field and credits in an opening screen.
Quick Start form
Specifies whether to use a Quick Start form that provides access to application documents and other disk files. You might use this to route users through the application.
About dialog
Specifies whether an About dialog box appears in the application.
User Logins
Specifies whether the application prompts for user password login and maintains preference information for multiple users, such as Options dialog box settings and Favorites menu contents.
Icon
Specifies the graphic that appears in the main desktop (_SCREEN) of typical applications, in the top form frame of top-level applications, and in the title bar of forms to which you have not assigned a specific icon.

If you choose OK, the builder closes, applying the property settings from all tabs.

See Also

Application Builder | Creating Applications with the Application Framework


Credits Tab, Application Builder

On this tab of the Application builder, you can specify application production credits such as author, company, version, copyright, and trademark. This information will appear in the splash screen and the About dialog box.

Author
Specifies the name of the application author.
Company
Specifies the name of the company writing or using the application.
Version
Specifies the build edition of the application.
Copyright
Specifies any copyright information.
Trademark
Specifies any trade or service mark.

Because these entries are retained as text, you can enter any information you want — up to 50 characters — and not only information prompted by the tab option labels.

If you choose OK, the builder closes, applying the property settings from every tab.

See Also

Application Builder | Creating Applications with the Application Framework


Data Tab, Application Builder

On this tab of the Application builder, you can specify the data source and the format for forms and reports you include in your application. The grid displays the tables you select for your application.

Database Wizard
Makes it possible to create a new database for your application using the Database wizard. When the wizard closes, the tables and views in the new database are listed in the grid.
Table Wizard
Makes it possible to create a new table for your application using the Table wizard. When the wizard closes, the tables and views in the new database are listed in the grid.
Select
Makes it possible to select an existing database, table, or view to use in your application.
Clear
Removes all tables from the grid.
Generate
Generates new reports or forms from the selected table, for all checked forms or reports, in the specified form style or report style.
Form Style
Makes it possible to select a form style to use for one or more tables listed in the grid.
Report Style
Makes it possible to select a report style for one or more tables listed in the grid.

To use different styles for each form or report, select the forms or reports and the styles, and then generate the reports. Repeat this procedure for as many different styles as you want in your application.

If you choose OK, the builder closes, applying the property settings from all tabs.

See Also

Application Builder | Creating Applications with the Application Framework


Forms Tab, Application Builder

On this tab of the Application builder, you can specify menu types, the menu from which a form is called, toolbars, and whether a form can be instanced multiple times.

For each form listed, check the options you want to apply.

Name
Makes it possible to specify the friendly name for the selected form.
Add
Makes it possible to select a form to add to your application. When you select a form to add, the check box options are enabled. Application Builder automatically creates a list of all the forms you generated in the Application Builder Data tab.
Edit
Makes it possible to modify the selected form in the Form designer. You might want to do this to modify the size or shape of images in a form. For more information, see Form Designer.
Remove
Removes a form from your application.
Single Instance
Specifies whether you can open only a single instance of a form in the application. If you do not check this box, you can open the same form on different records in order to make comparisons.
Use Navigation Toolbar
Specifies that the builder include a navigation toolbar for the selected form.
Use Navigation Menu
Specifies that the builder include a navigation menu for the selected form.
Appear in File New dialog
Specifies that the form name appears in the built application's New dialog box.
Appear in File Open dialog
Specifies that the form name appears in the built application's Open dialog box.

If you choose OK, the builder closes, applying the property settings from all tabs.

See Also

Application Builder | Creating Applications with the Application Framework


Reports Tab, Application Builder

On this tab of the Application builder, you can specify friendly names for reports in your application.

Name
Makes it possible to specify the friendly name for the selected report.
Appear in Print Reports dialog
Specifies whether the friendly name of the selected report appears in the Print Reports dialog box of your application.
Add
Makes it possible to add an existing report to your application.
Edit
Makes it possible to edit the selected report in the Report designer. For more information, see Report Designer.
Remove
Removes the selected report from your application.

If you choose OK, the builder closes, applying the property settings from all tabs.

See Also

Application Builder | Creating Applications with the Application Framework


Advanced Tab, Application Builder

On this tab of the Application builder, you can specify the Help file name and the default directory for your application. You can also specify the inclusion of a standard toolbar and a Favorites menu in your application.

Help file
Makes it possible to specify the name and path to the Help file for your application.
Default data directory
Makes it possible to specify the default directory for the data files of your application. If you specify this directory before you select your data source, it can make it easier to specify multiple tables.

Menus

Standard toolbar
Specifies whether the standard toolbar appears in your application.
Favorites menu
Specifies whether the Favorites menu is available from your application.
Cleanup
Runs a routine to reconcile any changes that have been made in the Application Builder with the active project.

If you choose OK, the builder closes, applying the property settings from all tabs.

See Also

Application Builder | Creating Applications with the Application Framework


AutoFormat Builder

The AutoFormat builder of the Form designer applies a set of styles to selected controls of the same type. For example, you can select two or more text box controls on the form and use the AutoFormat builder to apply the same styles; or you can specify whether the styles apply to all or just some of the controls' borders, colors, fonts, layout, or 3D effect.

To use the AutoFormat builder

  • From the New menu, choose Form, and then click New file. At this point, you can manually build your form or you can immediately use the Autoformat Builder shortcut.

To start by manually building your form

  1. Using the Form Controls toolbar, place multiple controls of the same kind on the form.
  2. Select and right-click all the controls you want to format, and then choose Builder from the Form Designer shortcut menu.

    A dialog box appropriate to the selected control appears.

  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes and applies the selected configuration.

To start with the Autoformat builder

  1. In the open Form designer, on the Form Designer toolbar, select the Autoformat icon.
  2. When the Autoformat builder opens, choose a style from the listed options, and clear any items you want to leave unformatted.
  3. Click OK.

You can specify whether to use Embossed, Standard, or Professional style. When you click a style, the display to the left is updated to show you how the style looks. You can apply Style to the following:

Borders
Applies the selected style to the control borders. This option corresponds to the BorderStyle property.
Colors
Applies the selected style to the control colors. This option corresponds to the BackColor and ForeColor properties, the BackStyle property, and the BorderColor property.
Fonts
Applies the selected style to the control fonts.
Layout
Applies the selected style to the control alignment.
3D Effect
Applies the selected style to the control 3D effect.
Apply Now
Applies the style to the selected controls without leaving the AutoFormat Builder.

See Also

Builders | BackColor, ForeColor Properties | BackStyle Property | BorderColor Property | BorderStyle Property


CursorAdapter Builder

The CursorAdapter Builder makes it possible for you to build CursorAdapter objects more quickly. You can open the CursorAdapter Builder from the Form Designer or Class Designer.

To open the CursorAdapter Builder

  1. Create a new form or open an existing form.
  2. In the Form Designer, right-click the form, and click DataEnvironment.

    For a form with an empty DataEnvironment object, the Open dialog box appears.

  3. In the Open dialog box, click Cancel.
  4. Right-click the Data Environment surface, and click Builder.
  5. In the DataEnvironment Builder, click the Cursors tab to make it visible.
  6. To create a new CursorAdapter object, click New.

You can now set properties for the CursorAdapter object you created, add a CursorAdapter object from a class library, or edit an existing CursorAdapter object.

You can also open the CursorAdapter Builder by right-clicking a new or existing CursorAdapter class in the Class Designer and selecting Builder, or you can open the builder by right-clicking an existing CursorAdapter object in the form's Data Environment and clicking Builder.

Builder Tabs

Properties
Specifies the properties of the CursorAdapter object.
Data Access
Specifies how the CursorAdapter object retrieves data from the data source.
Auto-Update
Specifies how the CursorAdapter object updates records automatically in the data source.

See Also

Builders | CursorAdapter Class | Form Designer | Class Designer | DataEnvironment Builder


Properties Tab, CursorAdapter Builder

Displays the name and properties of the CursorAdapter class and specifies whether to use the Data Environment data source and use connection settings only in the builder.

Class
Displays the name of the class the CursorAdapter object is based on. The class can be the base class, the CursorAdapter object, or a class in a class library or program file, in which case, the file name and path are also displayed.
Name
Specifies the name assigned to the CursorAdapter object by the builder. You can change this name.
Alias
Specifies the alias assigned to the CursorAdapter object by the builder. The default name is the same as the one that appears in the Name box. You can change this name.
Note Make sure that the alias is unique at run time. The CursorAdapter CursorFill method fails if a table or cursor using the same alias name is already open. For more information, see CursorFill Method.
Use DataEnvironment data source
Specifies whether you want to use the data source of the DataEnvironment object. When the CursorAdapter DataSourceType property is "ADO", you should not select this check box unless the DataEnvironment object contains only one CursorAdapter that uses this data source.
Use connection settings in builder only
Specifies whether you want to use connection settings only in the builder. If you select this option, you need to add code to set up a custom connection environment at run time. Selecting this option makes it possible to have a connection open at design time so that you can select tables, build queries, and so forth.
Data source type
Specifies a data source type. Depending on the data source type selected, you can select or build one of the following data sources:
  • ADO

    Specifies one of the following ways to establish an ActiveX Data Objects (ADO) connection.

    Use existing ADO Recordset Specify a reference to a valid ADO RecordSet object. This reference must be valid at design time if the CursorAdapter Builder is to use this RecordSet.

    Use DSN Specifies a data source name (DSN) from the Data source list and values in the User ID and Password boxes, if applicable.

    In most cases, selecting a DSN for an ADO connection results in using the Open Database Connectivity (ODBC) driver specified by the DSN through the MSDASQL OLE DB Provider for ODBC. Certain OLE DB providers can map the ODBC DSN settings to the corresponding settings in the corresponding OLE DB provider.

    Note You should not use a DSN name if the OLE DB provider cannot map ODBC DSN settings. You can use an ODBC driver for a data source that does not have an OLE DB provider.

    Use connection string Specifies a valid connection string. This is the same type of connection string that you enter for the ADO ConnectionString property.

    Alternatively, you can display the Data Link Properties dialog box by clicking Build. You can then select the appropriate OLE DB Provider and other necessary connection string parameters.

  • Native

    Specifies a valid database name and path in the Database box. You can select a database to use by clicking the ellipsis (...) button to display the Select Database dialog box.

  • ODBC

    Specifies one of the following ways to establish a database connection.

    Use existing connection handle Specifies a property, memory variable, value, or expression that evaluates to a valid connection handle at run time.

    Use DSN Specifies a data source name (DSN) from the Data source list and values in the User ID and Password boxes, if applicable.

    Use connection string Specifies a valid connection string. This is the same type of connection string that you enter for the SQLSTRINGCONNECT( ) function. For more information, see SQLSTRINGCONNECT( ) Function.

  • XML

    Specifies XML as the data source.

See Also

CursorAdapter Builder | Data Access Tab, CursorAdapter Builder | Auto-Update Tab, CursorAdapter Builder


Data Access Tab, CursorAdapter Builder

Sets the Select command and CursorAdapter object schema values and other data access properties.

Select command
Type or construct an appropriate Select command.

When the data source type is XML, type the Select command. In this case, the Select command should be an expression that resolves to a valid and well-formed XML string.

When the data source type is Native, ODBC, or ADO, the Build button is available. Clicking the Build button opens the Select Command Builder dialog box.

Select Command Builder Specifies tables and fields to include in the Select command.

  • Table Specifies a table you want to use. The tables in the list correspond to the tables in the selected data source.
  • Add table Available when the data source type is Native and can be used to add tables not in the current database to the table list.
  • Available fields list Specifies fields to include in the Select command after selecting a table, or view, if appropriate. This list appears on the left side of the Select Command Builder dialog box.
  • Add single/Add all/Remove single/Remove all Adds a single field or all fields to the selected fields list or removes a single or all fields from the selected fields list.
  • Selected fields list Displays selected fields, which can be reorganized by clicking and dragging the mover buttons that appear along the left side of the selected fields list. This list appears on the right side of the Select Command Builder dialog box.
Schema
Type the schema for the CursorAdapter object, if needed. The schema is generated automatically when the Select command is constructed using the Select Command Builder.

If you typed the Select command, you can click the Build button, and the builder attempts to construct the schema by matching the table and column names with the available tables.

When the data source type is XML, you cannot build a Select command, and no schema is automatically generated. When you click the Build button, the Open dialog box appears, and you can specify an XML file from which to build the schema. This XML file must be a valid XML Schema Definition (XSD) schema, a valid XML with inline XSD schema, or a valid XML with reference to a valid external XSD schema.

Data fetching
Specifies properties relating to how to retrieve remote data when using the Open Database Connectivity (ODBC) data source type. The following settings are available:
  • Number of records to fetch at a time Retrieve all or a number of records at a time. For more information, see FetchSize Property.
  • Maximum number of records to fetch Retrieve all or a maximum number of records. For more information, see MaxRecords Property.
  • Use memo when character field length >= Use memo field size when character field length exceeds the specified value. For more information, see UseMemoSize Property.
  • Fetch remote data as needed Retrieve data only when needed. For more information, see FetchAsNeeded Property.
  • Precompile SQL on backend server Specifies whether to prepare SQL statements for subsequent REQUERY( ) function calls. For more information, see Prepared Property and REQUERY( ) Function.
  • Fetch memo fields Specifies whether to retrieve memo fields. For more information, see FetchMemo Property.
  • Allow simultaneous fetch Specifies whether to permit simultaneous data retrieval. For more information, see AllowSimultaneousFetch Property.
Buffer mode override
Specifies a buffer mode.

Optimistic row buffering Allows edits to a single record and locks the record only when written to disk. This is the default setting.

Optimistic table buffering Allows edits to all records and does not lock them until written to disk.

Break on error
Specifies whether to permit errors to break program execution at the location where they occurred or send them to the CursorAdapter object. For more information, see BreakOnError Property.
XML flags
Specifies the flag settings to pass to the XMLUPDATEGRAM( ) function, which is called when the data source type is XML and updating occurs. For more information about automatic updating, see Data Access Management Using CursorAdapters and XMLUPDATEGRAM( ) Function.

See Also

CursorAdapter Builder | Auto-Update Tab, CursorAdapter Builder | Properties Tab, CursorAdapter Builder


Auto-Update Tab, CursorAdapter Builder

Specifies how the CursorAdapter object automatically updates records in the data source. For more information about CursorAdapter objects, see CursorAdapter Class.

Send updates
Specifies whether the CursorAdapter object is available for updating. Send updates is selected by default.
Auto-update
Specifies whether to enable automatic updating capability for the CursorAdapter object.
Advanced
Displays the Advanced Update Properties dialog box, which contains three tabs: Update, Delete, and Insert. Each tab allows you to specify the following information:
  • Allow (update/delete/insert)

    Specifies whether to permit the update, delete, or insert operation. This option is selected by default.

  • Update/Delete/Insert command

    Specifies a custom update/delete/insert command text. These commands can be SQL UPDATE/ DELETE/INSERT statements, stored procedure names, calls to custom methods or procedures, and so forth.

  • Update data source type

    Specifies an appropriate data source type if you need a different data source type for your Update/Insert/Delete commands.

    Note When you select ADO or ODBC, you must also enter data source information as specified on the Properties tab.
Tables
Specifies a comma-delimited list of tables for updating. The builder usually supplies the table list.
Key field column (key symbol)
Displays check boxes for selecting primary key fields. This column is available only when Auto-update is selected.
Automatic updating column (pencil symbol)
Displays check boxes for selecting fields for automatic updating. This column is available only when Auto-update is selected.
Cursor field
Displays the fields available for automatic updating. This column is available only when Auto-update is selected.
Update name
Specifies the field names, as tableName.FieldName, used for automatic updating. This column is available only when Auto-update is selected. For more information, see UpdateNameList Property.
Update all fields
Specifies that all fields are selected and updated automatically. You must still specify a key field.
Update using
Specifies the preferred update method: SQL UPDATE or SQL DELETE then INSERT. For more information, see UPDATE - SQL Command, DELETE - SQL Command, and INSERT - SQL Command.
SQL WHERE clause includes
Specifies the type of WHERE clause used for updating: key fields only, key and updatable fields, key and modified fields, or key and timestamp. For more information, see the WhereType property.
Batch update count
Sets the BatchUpdateCount property value. For more information, see BatchUpdateCount Property.
Compare memo
Sets the CompareMemo property value to either on or off. For more information, see CompareMemo Property.
Conversion functions
Specifies a comma-delimited list of field name and function name pairs separated by spaces. For details, see the ConversionFunc Property.

See Also

CursorAdapter Builder | Properties Tab, CursorAdapter Builder | Data Access Tab, CursorAdapter Builder


DataEnvironment Builder

The DataEnvironment Builder makes it possible for you to build DataEnvironment objects that use the capabilities of CursorAdapter objects. You can open the DataEnvironment Builder in the Form Designer or Class Designer.

To open the DataEnvironment Builder

  1. Create a new form or open an existing form.
  2. In the Form Designer, right-click the form, and click DataEnvironment.

    For a form with an empty DataEnvironment object, the Open dialog box appears.

  3. In the Open dialog box, click Cancel.
  4. Right-click the Data Environment surface, and click Builder.

You can now use the builder to create DataEnvironment objects.

You can also open the DataEnvironment Builder by right-clicking a new or existing DataEnvironment class in the Class Designer and selecting Builder.

Builder Tabs

Data Source Tab, DataEnvironment Builder

Specifies the data source type and data source for the DataEnvironment object.

Cursors Tab, DataEnvironment Builder

Adds, creates, or removes CursorAdapter objects from the DataEnvironment object. You can also open the CursorAdapter Builder to edit existing CursorAdapter objects.

See Also

Builders | DataEnvironment Object | Form Designer | Class Designer | CursorAdapter Builder


Data Source Tab, DataEnvironment Builder

Specifies the data source type and data source to use, if needed.

Note When accessing tables in Microsoft Access, particularly tables that have spaces in column names, you should use the Microsoft OLE DB Provider for Access instead of the Microsoft Access ODBC driver and specify ADO as the data source type. To choose the OLE DB Provider for Access, on the Data Source tab, select ADO in the Data source type box. Click Use connection string, then the Build button to continue constructing the connection string to the Access database.
Data source type
Specifies the data source type. Depending on the data source type selected, you can select or build one of the following data sources:
  • ADO

    Specifies one of the following ways to establish an ActiveX Data Objects (ADO) connection.

    Use existing ADO Recordset Specify a reference to a valid ADO RecordSet object. This reference must be valid at design time if the CursorAdapter Builder is to use this RecordSet.

    Use DSN Specifies a data source name (DSN) from the Data source list and values in the User ID and Password boxes, if applicable.

    In most cases, selecting a DSN for an ADO connection results in using the Open Database Connectivity (ODBC) driver specified by the DSN through the MSDASQL OLE DB Provider for ODBC. Certain OLE DB providers can map the ODBC DSN settings to the corresponding settings in the corresponding OLE DB provider.

    Note You should not use a DSN name if the OLE DB provider cannot map ODBC DSN settings. You can use an ODBC driver for a data source that does not have an OLE DB provider.

    Use connection string Specifies a valid connection string. This is the same type of connection string that you enter for the ADO ConnectionString property.

    Alternatively, you can select the Build button to display the Data Link Properties dialog box. You can then select the appropriate OLE DB Provider and other necessary connection string parameters.

  • Native

    Specifies a valid database name and path in the Database box. You can browse for and select a database to use by clicking the ellipsis (...) button to display the Select Database dialog box.

  • ODBC

    Specifies one of the following ways to establish a database connection.

    Use existing connection handle Specifies a property, memory variable, value, or expression that evaluates to a valid connection handle at run time.

    Use DSN Specify a data source name (DSN) from the Data source list and values in the User ID and Password boxes, if applicable.

    Use connection string Specifies a valid connection string. This is the same type of connection string that you enter for the SQLSTRINGCONNECT( ) function. For more information, see SQLSTRINGCONNECT( ) Function.

  • XML

    Specifies XML as the data source.

See Also

DataEnvironment Builder | Cursors Tab, DataEnvironment Builder


Cursors Tab, DataEnvironment Builder

Use to create new CursorAdapter objects, add CursorAdapter objects from a class library, remove CursorAdapter objects, or open the CursorAdapter Builder for an existing CursorAdapter object.

Add
Displays the Open dialog box so that you can select an existing CursorAdapter class from a class library or program file.
New
Displays the CursorAdapter Builder so that you can create and configure a new CursorAdapter object.
Remove
Removes the currently selected CursorAdapter object. You can also select a different CursorAdapter object from the list appearing on the Cursors tab.
Builder
Opens the CursorAdapter Builder for the currently selected CursorAdapter object.
Class
Read-only. Displays the class name for the currently selected CursorAdapter object.
Name
Read/write. Displays the name of the currently selected CursorAdapter object. The default name is Cursor<CursorNumber>.

See Also

DataEnvironment Builder | Data Source Tab, DataEnvironment Builder


Combo Box Builder

The Combo Box builder of the Form designer makes it easy to set properties for a combo box control. You set properties by choosing options from the Combo Box Builder dialog box.

To use the Combo Box builder

  1. From the New menu, choose Form, and then click New file.
  2. Using the Form Controls toolbar, place one or more combo box controls on the form.
  3. Select and right-click all the combo box controls you want to format, and then choose Builder from the Form Designer shortcut menu.
  4. Choose the options on each tab of the dialog box that appears, and then choose OK.

    When you choose OK, the builder closes, applying the property settings to the control.

Builder Tabs

List Items
Specifies items from a table, an array, or manual selection to appear in the combo box.
Style
Specifies Style and SpecialEffect properties of the control, including 3D or plain style, drop-down combo or list, and single-key or incremental searching.
Layout
Specifies the control width and column widths properties.
Value
Specifies which column returns a value and where to store it.

See Also

Builders | ComboBox Control | Layout Tab, Combo Box Builder | List Items Tab, Combo Box Builder | Style Tab, Combo Box Builder | Value Tab, Combo Box Builder


List Items Tab, Combo Box Builder

This tab in the Combo Box builder specifies items that go into the combo box.

Fill the List With
Specifies the kind of data with which to fill the combo box list. The selection you make here determines which choices appear on this tab. Choose Fields From a Table or View, Data Entered by Hand, or Values From an Array.
Fields From a Table or View
Allows you to select free tables or tables and views from a database to use in the combo box.
Databases and Tables
Lists the available databases and gives the option to select Free Tables. To find a database or table, click the dialog button, which displays the Open dialog box. This option appears when you have selected Fields From a Table or View in the Fill the List With drop-down list.
List of Tables
Displays tables and views in the selected database, or free tables. This option appears when you have selected Fields From a Table or View in the Fill the List With drop-down list.
Available Fields
Shows all fields in the selected table or view. Select the fields whose data you want in your combo box. This option appears when you have selected Fields From a Table or View in the Fill the List With drop-down list.
Arrow Buttons
Adds fields to and removes fields from the Selected Fields box. This option appears when you have selected Fields From a Table or View in the Fill the List With drop-down list.

You also can double-click an item to move it between lists.

Selected Fields
Displays the fields that will be used to fill the combo box list. The order of the fields selected will correspond to the order of the columns in the combo box. This option appears when you have selected Fields From a Table or View in the Fill the List With drop-down list.
Data Entered By Hand
Allows you to select the number of columns to be displayed in the combo box and enter the information to be displayed.
Columns
Specifies the number of columns in the combo box list. This option appears when you have selected Data Entered By Hand in the Fill the List With drop-down list.
Column Grid
Displays the columns in which to enter data. Type the data in the column cells. You can size the columns by dragging the lines between them with the mouse. This option appears when you have selected Data Entered By Hand in the Fill the List With drop-down list.
Values From An Array
Allows you to use data from an array within the combo box.
Array Name
Specifies the name of an array. This option appears when you have selected Values From An Array in the Fill the List With drop-down list.
Entire Array
Specifies that the entire array will fill the combo box list. This option appears when you have selected Values From An Array in the Fill the List With drop-down list.
Range Of The Array
Specifies that a part of the array will fill the combo box list based on the column and row settings. This option appears when you have selected Values From An Array in the Fill the List With drop-down list.
Column and Row Range
Specifies the starting and ending column and row as the array range. These options are only available when you select Range of the Array. This option appears when you have selected Values From An Array in the Fill the List With drop-down list.

See Also

Combo Box Builder | ControlSource Property | Layout Tab, Combo Box Builder | Open Dialog Box | RowSource Property | RowSourceType Property | Style Tab, Combo Box Builder | Value Tab, Combo Box Builder


Style Tab, Combo Box Builder

This tab in the Combo Box builder specifies special effects, drop-down combo, drop-down list, and incremental searching support for the combo box.

Three-dimensional
Specifies a left and top edge highlight and a right and lower edge shadow for the combo box.
Plain
Specifies that the combo box is an unshadowed box on the form. Three-dimensional and Plain determine the value of the SpecialEffect property.
Drop-down Combo
Specifies that the combo box will be a drop-down combo, where the user can click the drop-down arrow to see a list of choices or enter a new item directly in the text box. This option corresponds to setting the Style property to 0.
Drop-down List
Specifies that the combo box will be a drop-down list, where the user may select only from the list. This option corresponds to setting the Style property to 2.
Yes, Enable Incremental Searching
Specifies whether the control tries to match an item in the list as the user types each letter. This option corresponds to setting the IncrementalSearch property.
No, Don't Enable Incremental Searching
Disables incremental searching so that each keystroke initiates a search for a beginning character.

See Also

Combo Box Builder | IncrementalSearch Property | List Items Tab, Combo Box Builder | Layout Tab, Combo Box Builder | Style Property | Value Tab, Combo Box Builder


Layout Tab, Combo Box Builder

This tab in the Combo Box builder controls column width and display.

Adjust the Width of the Combo Box to Display All Columns
Specifies that all selected columns will display even if the open combo box must extend beyond the form boundary. This controls the Width property of the combo box.
Column Grid
Controls the values in the ColumnWidths property. You can adjust the column width by dragging the right edge of a column heading with the mouse. Double-click a column heading to hide the column.

The grid shows actual data if it is available. If no data is available, the grid displays a message to that effect.

To change column order, return to the List Items tab, remove the fields, and add them back in the desired order.

See Also

Combo Box Builder | List Items Tab, Combo Box Builder | Style Tab, Combo Box Builder | Value Tab, Combo Box Builder


Value Tab, Combo Box Builder

This tab in the Combo Box builder specifies where to get return values and where to store them.

Return the Value From
Specifies the column whose value is stored to a table field when the user selects a combo box item. This option corresponds to the BoundColumn property.
Field Name
Specifies a table or view field in which to store the value specified in the Return the Value From box. By default, the list includes fields from tables in the data environment. Choose the dialog button to display the Open dialog box so you can select another table. This option corresponds to the ControlSource property.

For example, if you fill the combo box with a list of 50 states, when the user chooses a state, you could write it to the STATE field of an address table.

See Also

BoundColumn Property | Combo Box Builder | ControlSource Property | Layout Tab, Combo Box Builder | List Items Tab, Combo Box Builder | Open Dialog Box | Style Tab, Combo Box Builder


Command Group Builder

The Command Group builder makes it easy to set properties for a command group control. You set properties by selecting options in the Command Group Builder dialog box.

To use the Command Group builder

  1. Using the Form Controls toolbar, place a command group control on a form.
  2. Select and right-click the command group control, and then choose Builder from the Form Designer shortcut menu.

    A dialog box appropriate to the selected control appears.

  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

Buttons
Specifies the number of buttons and the Caption and Picture properties of each.
Layout
Specifies button layout (vertical or horizontal), spacing, and border style by controlling the Height and Width properties of the command group.
Note Command buttons may have captions, or graphics, or both. You can also specify graphics to be displayed when the button is disabled and when it is pressed, but you must do so programmatically or in the Properties window. For more details, see the DisabledPicture and DownPicture properties.

See Also

Builders | Buttons Tab, Command Group Builder | CommandButton Control | CommandGroup Control | Layout Tab, Command Group Builder | Properties Window


Buttons Tab, Command Group Builder

This tab in the Command Group builder specifies the number of buttons and their captions and graphics.

Number of Buttons
Specifies the number of buttons the command group will have. This option corresponds to the ButtonCount property. Range is from 0 to 100.
Caption Column
Specifies the caption to go on the button. Type the caption in the grid cell. This option corresponds to the Caption property.
Graphic Column
Specifies the path and file name of the bitmap to display on the button. Type the path and file name in the box, or click the dialog button to display the Open dialog box so you can select a file. This picture will be displayed on the command button all the time, regardless of the button's state. This option corresponds to the Picture property.

Buttons automatically resize to accommodate new captions and pictures. The group container also automatically resizes, and neighboring buttons are repositioned, if necessary, to preserve desired spacing.

See Also

ButtonCount Property | Caption Property | Command Group Builder | DisabledPicture Property | DownPicture Property | Layout Tab, Command Group Builder | Picture Property | Properties Window


Layout Tab, Command Group Builder

This tab in the Command Group builder specifies button layout (vertical or horizontal), spacing, and border style.

Button Layout
Specifies vertical or horizontal layout of command group buttons. You can also customize the location of buttons within a Command Group by selecting Edit from the shortcut menu and dragging buttons within the Command Group boundary. Return to Command Group editing by first clicking outside the Command Group boundary.

If you have customized the button layout, neither Vertical nor Horizontal is selected. If you then select Vertical or Horizontal, the buttons snap into alignment and you lose the custom pattern. Choose Cancel to retrieve the custom pattern.

Spacing Between Buttons
Specifies spacing between buttons. If you have customized the button spacing, this option is disabled. If you snap the buttons into horizontal or vertical alignment, this option is enabled.
Border Style
Specifies a single-line border or no border around the command group.

See Also

Buttons Tab, Command Group Builder | Command Group Builder | Edit Box Builder | Combo Box Builder


Edit Box Builder

The Edit Box builder makes it easy to set properties for an edit box control. Edit boxes are commonly used to display long Character fields or Memo fields and allow the user to edit text. An edit box can also display text from a text file or from the clipboard. You set properties for the edit box control by selecting options in the Edit Box Builder dialog box.

To use the Edit Box builder

  1. Using the Form Controls toolbar, place an edit box control on a form.
  2. Select and right-click the edit box control, and then choose Builder from the Form Designer shortcut menu.

    A dialog box appropriate to the selected control appears.

  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

Format
Specifies miscellaneous format options for the edit box.
Style
Specifies edit box visual effect, border, and alignment.
Value
Specifies a field in which to store the edit box's value.

See Also

Builders | EditBox Control | Format Tab, Edit Box Builder | Style Tab, Edit Box Builder | Value Tab, Edit Box Builder | Properties Window


Format Tab, Edit Box Builder

This tab in the Edit Box builder specifies miscellaneous format options for the edit box, such as adding vertical scrollbars and making the box read-only.

Allow User to Insert Tabs
Permits inserting of tabs in the edit box. This prevents the focus from moving to the next control when the TAB key is pressed. Press CTRL+TAB to move to the next control. This option corresponds to the AllowTabs property.
Add Vertical Scrollbars
Adds vertical scrollbars to the edit box. This option corresponds to the ScrollBars property.
Select on Entry
Specifies that the text in the edit box be selected when the edit box has the focus. This adds the setting "K" to the Format property.
Use Current SET DATE
Adds the setting "D" to the Format property so that date entries will conform to the current SET DATE or Date Format of the International tab of the Options dialog box.
Hide Selection
Specifies whether or not selected text in the edit box remain visibly selected when the edit box doesn't have the focus. This option corresponds to the HideSelection property.
Enable at Run time
Specifies whether or not the edit box is enabled when the form is run. This option corresponds to the Enabled property.
Make Read-Only
Prevents the user from changing the text in the edit box. This option corresponds to the ReadOnly property.
British Date
Adds the setting "E" to the Format property so date entries will conform to British formatting of SET DATE or of the Date Format of the International tab of the Options dialog box.

See Also

AllowTabs Property | Edit Box Builder | Enabled Property | Format Property | HideSelection Property | ReadOnly Property | ScrollBars Property | Style Tab, Edit Box Builder | Value Tab, Edit Box Builder


Style Tab, Edit Box Builder

This tab in the Edit Box builder specifies edit box visual effect, border, and alignment.

Special Effect

3D
Specifies a left and top edge highlight and a right and lower edge shadow for the combo box. This option corresponds to the 3D setting of the SpecialEffect property.
Plain
Specifies that the combo box is an unshadowed box on the form. This option corresponds to the Plain setting of the SpecialEffect property.

Border

Single
Specifies a single line around the edit box. This option corresponds to the Fixed-Single setting of the BorderStyle property.
None
Specifies no line around the edit box. This option corresponds to the None setting of the BorderStyle property.

Character Alignment

Left
Specifies that text in the edit box will be left-aligned. This option corresponds to the Left setting of the Alignment property.
Right
Specifies that text in the edit box will be right-aligned. This option corresponds to the Right setting of the Alignment property.
Center
Specifies that text in the edit box will be centered. This option corresponds to the Center setting of the Alignment property.

See Also

Edit Box Builder | Format Tab, Edit Box Builder | Value Tab, Edit Box Builder | Alignment Property | BorderStyle Property | SpecialEffect Property


Value Tab, Edit Box Builder

This tab in the Edit Box builder specifies a field in which to store the edit box's value.

Field Name
Specifies a table or view field in which to store the edit box's value. Type the field name, or click the dialog button to display the Open dialog box, where you can select another table or view. In the Edit Box builder, click the drop-down arrow next to the Field Name list box to select a field.

The default contents of this tab are all the fields in the data environment. This option corresponds to the ControlSource property.

For more information, see Creating Forms.

See Also

Edit Box Builder | Format Tab, Edit Box Builder | Open Dialog Box | Style Tab, Edit Box Builder | ControlSource Property


Form Builder

The Form builder makes it easy to add fields as new controls to a form. You add controls and specify style by selecting options displayed in the Form Builder dialog box.

To use the Form builder

  • Right-click on a new or existing form in the Form designer.

    -or-

  • Choose Quick Form from the Form menu.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

Field Selection
Specifies fields to be added as form controls.
Style
Offers several style choices for your controls and the option to enlarge the form if necessary. The form size will only enlarge to fit the size of the Maximum Design Area as set in the Forms tab of the Options dialog box.

The styles correspond to those offered by the Form wizards. If you created a form with a wizard, and then wish to add a new control of the same style, use the Form builder. You may also add new controls with a different style. The style chosen in the Form builder does not affect existing controls on a form. To format them, use the AutoFormat builder.

See Also

Builders | AutoFormat Builder | Field Selection Tab, Form Builder | Forms Tab, Options Dialog Box | Style Tab, Form Builder


Field Selection Tab, Form Builder

This tab in the Form builder specifies fields to be added as form controls.

Databases and Tables
Lists the available databases or lets you select free tables. To find a database or table, click the dialog button, which displays the Open dialog box.
List of Tables
Displays tables and views in the selected database, or free tables.
Available Fields
Shows all fields in the selected table or view. Select the fields whose data you want on your form.
Arrow Buttons
Adds fields to and removes fields from the Selected Fields box.
Selected Fields
Displays the fields that will appear on your form as controls.

See Also

Form Builder | Style Tab, Form Builder | Open Dialog Box | Grid Builder


Style Tab, Form Builder

This tab in the Form builder offers several style choices for your controls and the option to enlarge the form to accommodate data. The form size will only enlarge to fit the size of the Maximum Design Area as set in the Forms tab of the Options dialog box.

Style
Specifies the style of the form controls, which is determined by the class of the control. Select a form style to see a preview of what the style will look like.
Enlarge Form as Needed check box
Specifies that the builder enlarge the form to accommodate the selected fields; up to the maximum size determined by the design area of the form, if necessary.

See Also

Form Builder | Field Selection Tab, Form Builder | Forms Tab, Options Dialog Box | Edit Box Builder


Grid Builder

The Grid builder makes it easy to set properties for a grid control. The grid control allows you to present and manipulate rows and columns of data in a form or page. You set grid properties by selecting options displayed in the Grid Builder dialog box.

To use the Grid builder

  1. Using the Form Controls toolbar, place a grid control on a form.
  2. Select and right-click the grid control, and then choose Builder from the Form Designer shortcut menu.
  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

    Note Before running your form, make sure you have sized the grid control to adequately display your data.

Builder Tabs

Grid Items
Specifies fields to be displayed in the grid.
Style
Specifies a style for the grid display.
Layout
Specifies column captions and control types.
Relationship
Specifies relationships between grid fields and table fields.

See Also

Builders | Grid Control | Grid Items Tab, Grid Builder | Layout Tab, Grid Builder | RecordSource Property | RecordSourceType Property | Relationship Tab, Grid Builder | Style Tab, Grid Builder


Grid Items Tab, Grid Builder

This tab in the Grid builder specifies fields to be displayed in the grid.

Note In the Grid builder, you can select fields from a single table only. To set a relationship between Grids, you must use the Grid builder on each Grid separately, and then use the Relationship tab of one Grid builder to establish the relationship.

Databases and Tables Lists the available databases and gives the option to select free tables. To find a database or table, click the dialog button, which displays the Open dialog box.

List of Tables
Displays tables and views in the selected database, or free tables.
Available Fields
Shows all fields in the selected table. You may select fields from only one table.
Arrow Buttons
Add fields to and remove fields from the Selected Fields list.
Selected Fields
Displays the fields that will appear in the grid. Each field displays in one column in the grid.

See Also

Grid Builder | Layout Tab, Grid Builder | Open Dialog Box | Relationship Tab, Grid Builder | Style Tab, Grid Builder


Style Tab, Grid Builder

This tab in the Grid builder specifies a style for the grid display.

Style
Specifies the Professional, Standard, Embossed, or Ledger style for the grid display. You can choose to preserve the current style.

See Also

Grid Builder | Grid Items Tab, Grid Builder | Layout Tab, Grid Builder | Relationship Tab, Grid Builder


Layout Tab, Grid Builder

This tab in the Grid builder specifies column captions and the type of control you can add to the Grid.

Note You must select a column before you can change its heading.
Caption
Specifies the caption for the selected column. Type a caption in the box. If you do not specify a caption, the field names will be the column headings.
Control Type
Specifies the type of control to add to the selected column. Text or edit boxes are available for character data, text or check boxes are available for logical data, and text boxes or spinners are available for numeric data.
Grid Display
Shows the grid columns as currently specified. The display automatically updates according to your Caption and Control Type selections. You can set the columns to the desired width by dragging the right edge of a heading.

See Also

Grid Builder | Grid Items Tab, Grid Builder | Style Tab, Grid Builder | Relationship Tab, Grid Builder


Relationship Tab, Grid Builder

This tab in the Grid builder specifies a relationship between grid fields and table fields.

Key Field in Parent Table
Specifies the key field of the controlling table in a relationship. This option corresponds to the LinkMaster property. To find a table, click the dialog button, which displays the Open dialog box.
Related Index in Child Table
Specifies the index tag name of the controlled table in a relationship. This option corresponds to the ChildOrder property.

See Also

ChildOrder Property | Grid Builder | Grid Items Tab, Grid Builder | Style Tab, Grid Builder | Layout Tab, Grid Builder | LinkMaster Property


List Box Builder

The List Box builder makes it easy to set properties for a list box control. List boxes provide the user with a scrollable list that contains a number of options or pieces of information. In a list box, multiple items can be visible at all times. You set list box properties by selecting options displayed in the List Box Builder dialog box.

To use the List Box builder

  1. Using the Form Controls toolbar, place a list box control on a form.
  2. Select and right-click the list box control, and then choose Builder from the Form Designer shortcut menu.
  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

List Items
Specifies items to fill the list box and the sources of that data.
Style
Specifies style (3D or plain) and number of rows, and enables or disables incremental searching.
Layout
Controls column width and display.
Value
Specifies from which column to get return values and which field to store them in.

See Also

Builders | Layout Tab, List Box Builder | ListBox Control | List Items Tab, List Box Builder | Properties Window | Style Tab, List Box Builder | Value Tab, List Box Builder


List Items Tab, List Box Builder

This tab in the List Box builder specifies items to fill the list box.

In the Fill the List With box, you specify the kind of data with which to fill the list. The selection you make here determines which options appear on this tab. The options are Fields from a Table or View, Data Entered by Hand, and Values from an Array.

Fields from a Table or View

Databases and Tables
Lists the available databases and the option to select free tables. To find a database or table, click the dialog button, which displays the Open dialog box.
List of Tables
Displays tables and views in the selected database or free tables.
Available Fields
Shows all fields in the selected table or view. Select the fields whose data you want in your list box.
Arrow Buttons
Adds fields to and removes fields from the Selected Fields list.
Selected Fields
Displays the fields that will be used to fill the list. This option corresponds to the RowSource property.
Note You must choose this option in order to hide the column from the Layout tab.

Data Entered by Hand

Columns
Specifies the number of columns in the list. This option corresponds to the ColumnCount property.
Column Grid
Displays the columns in which to enter data. Type the data in the grid cells. You can size the columns by dragging the lines between the column headers with the mouse. Use the arrow keys to move through the columns. This option corresponds to the RowSource property.

Values from an Array

Array Name
Specifies the name of an array. This option corresponds to the RowSource property.
Entire Array
Specifies that the entire array will fill the list.
Range of the Array
Specifies that a part of the array will fill the list.
Column and Row Range
Specifies the starting and ending column and row as the array range. These options are available when you select Range of the Array. This option corresponds to the FirstElement property, NumberOfElements property, and ColumnCount property.

For more information, see Creating Forms.

See Also

Layout Tab, List Box Builder | List Box Builder | Open Dialog Box | RowSource Property | RowSourceType Property | Style Tab, List Box Builder | Value Tab, List Box Builder


Style Tab, List Box Builder

This tab in the List Box builder specifies style, number of rows to display, and incremental searching.

Three-dimensional
Specifies a three-dimensional look for the list box. This option corresponds to the SpecialEffect property.
Plain
Specifies a plain look for the list box. This option corresponds to the SpecialEffect property.
Rows to Display
Sets the Height property of the list box so it displays only the specified number of rows at a time.
Yes, Enable Incremental Searching
Specifies whether the control tries to match an item in the list as the user types each letter. This option corresponds to setting the IncrementalSearch property to .T.
No, Don't Enable Incremental Searching
Disables incremental searching. This option corresponds to setting the IncrementalSearch property to .F.

See Also

Height Property | IncrementalSearch Property | Layout Tab, List Box Builder | List Box Builder | List Items Tab, List Box Builder | SpecialEffect Property | Value Tab, List Box Builder


Layout Tab, List Box Builder

This tab in the List Box builder controls column width and display.

Adjust the Width of the List Box to Display All Columns
Specifies that all columns will be displayed, and the list box will be automatically sized as required. This option corresponds to the Width property.
Column Grid
Shows the columns defined on the List Items tab. You can adjust the column width by dragging the right edge of a column heading with the mouse.

You can hide a column by double-clicking a column heading if you have chosen "Fill the list with fields from a table or view" in the List Items tab. This option corresponds to the ColumnWidths property.

See Also

ColumnWidths Property | List Box Builder | List Items Tab, List Box Builder | Style Tab, List Box Builder | Value Tab, List Box Builder | Width Property


Value Tab, List Box Builder

This tab in the List Box builder specifies where to get return values and where to store them.

Return the Value From
Specifies the column or field from which to get a value when the user selects a list box item. This option corresponds to the BoundColumn property.
Field Name
Specifies a table or view field in which to store the value specified in the Return the Value From box. By default, the list includes fields from a table or view selected on the List Items tab. Choose the dialog button to display the Open dialog box so you can select another file. This option corresponds to the ControlSource property.

See Also

BoundColumn Property | ControlSource Property | Layout Tab, List Box Builder | List Box Builder | List Items Tab, List Box Builder | Open Dialog Box | Style Tab, List Box Builder


Option Group Builder

The Option Group builder makes it easy to set properties for an option group control. Option buttons allow users to choose one of several mutually exclusive options. You set properties by selecting options displayed in the Option Group Builder dialog box.

To use the Option Group builder

  1. Using the Form Controls toolbar, place an option group control on a form.
  2. Select and right-click the option group control, and then choose Builder from the Form Designer shortcut menu.
  3. Choose the options you want from the dialog, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

Buttons
Specifies number of buttons, captions, and graphics.
Layout
Specifies option button layout (vertical or horizontal), spacing, and border style.
Value
Specifies a table or view field in which to store the option group's value.

See Also

Builders | Buttons Tab, Option Group Builder | Layout Tab, Option Group Builder | OptionGroup Control | Value Tab, Option Group Builder


Buttons Tab, Option Group Builder

This tab in the Option Group builder specifies the number of buttons, captions, and graphics.

Number of Buttons
Specifies the number of buttons the option group will have. This option corresponds to the ButtonCount property.
Standard
Specifies radio-style option buttons. The Graphic column is disabled when Standard is selected.
Graphical
Specifies rectangular option buttons. You can specify both caption and graphic in the columns when this is selected.
Caption Column
Specifies the caption to display next to the button. Type the caption in the box, or leave it blank if you don't want a caption. This option corresponds to the Caption property.
Graphic Column
Specifies the path and file name of the bitmap to display on the button. Type the path and file name in the box, or click the dialog button to display the Open dialog box so you can select a file. This option corresponds to the Picture property of the Option button.
Note Option buttons may have both captions and graphics. You can also specify graphics to be displayed when the button is disabled and when it is pressed, but you must do so programmatically or in the Properties window.

See Also

ButtonCount | Caption Property | DisabledPicture Property | DownPicture Property | Layout Tab, Option Group Builder | Option Group Builder | Picture Property | Properties Window | Value Tab, Option Group Builder


Layout Tab, Option Group Builder

This tab in the Option Group builder specifies button layout (vertical or horizontal), spacing, and border style.

Button Layout
Specifies vertical or horizontal layout of option group buttons by adjusting the Width property.
Spacing Between Buttons
Specifies spacing between buttons by adjusting the Width property or the Height property.
Border Style
Specifies a single-line border around the option group, or no border. This option corresponds to the BorderStyle property.

See Also

BorderStyle Property | Buttons Tab, Option Group Builder | Option Group Builder | Value Tab, Option Group Builder


Value Tab, Option Group Builder

This tab in the Option Group builder specifies a table or view field in which to place the option group's value.

Field Name
Specifies a table or view field in which to store the option group's value. By default, the list includes fields from a table. Choose the dialog button to display the Open dialog box so you can select another file. This option corresponds to the ControlSource property.

See Also

Buttons Tab, Option Group Builder | ControlSource Property | Layout Tab, Option Group Builder | Open Dialog Box | Option Group Builder


Referential Integrity Builder

The Referential Integrity (RI) builder helps you ensure referential integrity by setting up triggers to control how records are inserted, updated, or deleted in related tables.

The RI Builder is displayed when you:

  • Double-click a relationship line between two tables in the Database designer and choose the Referential Integrity button in the Edit Relationship dialog box.
  • Choose Edit Referential Integrity from the Database Designer shortcut menu.
  • Choose Edit Referential Integrity from the Database menu.

Builder Tabs

Rules for Updating
Specifies rules to apply when the key value in the parent table is modified.
Rules for Deleting
Specifies rules to apply when a record in the parent table is deleted.
Rules for Inserting
Specifies rules to apply when a new record is inserted or an existing record is updated in the child table.

For more information, see Developing Databases, Trigger Usage, and Working with Tables.

See Also

Builders | Database Designer | Edit Relationship Dialog Box | Rules for Deleting Tab | Rules for Inserting Tab | Rules for Updating Tab | Building Referential Integrity


Rules for Updating Tab, RI Builder

This tab in the Referential Integrity (RI) builder specifies rules to apply when the key value in the parent table is modified.

Cascade
Specifies that changes in the fields of the Primary or Candidate key of the parent table are reflected in related child tables. If you select this option, any time you change any of those fields in the parent table, Microsoft Visual FoxPro automatically changes the corresponding values in all related child table records.
Restrict
Prevents modification of values in fields of the Primary or Candidate key of the parent table so there are no orphaned records in the child table.
Ignore
Makes it possible for you to update records in the parent table, even if there are related records in the child table.
Referential Integrity Grid
Parent Table displays the name of the table in the database relation containing the primary or candidate index.

Child Table displays the name of the child table in the database relation.

Update displays the update rules for referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Delete displays the delete rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Insert displays the insert rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Parent Tag grid column displays the tag name of the index in the Primary or Candidate in the Parent table.

Child Tag grid column displays the tag name of the index in the child table.

See Also

Referential Integrity Builder | Rules for Deleting Tab | Rules for Inserting Tab


Rules for Deleting Tab, RI Builder

This tab in the Referential Integrity (RI) builder specifies rules to apply when a record in the parent table is deleted.

Cascade
Specifies that deletions in the parent table are reflected in the related child tables. If you select Cascade Delete for a relationship, whenever you delete records in the parent table, records in the related child table are automatically deleted.
Restrict
Prevents you from deleting records in the parent table that have related records in the child table. If you select Restrict Delete for a relationship, an attempt to delete records in the parent table generates an error if there are related records in the child table.
Ignore
Makes it possible for you to delete records in the parent table, even if there are related records in the child table.
Referential Integrity Grid
Parent Table displays the name of the table in the database relation containing the primary or candidate index.

Child Table displays the name of the child table in the database relation.

Update displays the update rules for referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Delete displays the delete rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Insert displays the insert rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Parent Tag grid column displays tag name of the index in the Primary or Candidate in the Parent table.

Child Tag grid column displays the tag name of the index in the child table.

See Also

Referential Integrity Builder | Rules for Inserting Tab | Rules for Updating Tab


Rules for Inserting Tab, RI Builder

This tab in the Referential Integrity (RI) builder specifies rules to apply when a new record is inserted or an existing record is updated in the child table.

Restrict
Prevents you from adding records in the child table for which there are no matching records in the parent table. If you select Restrict Insert for a relationship, an attempt to add records in the child table generates an error if there is no matching parent record.
Ignore
Makes it possible for you to insert records into the child table regardless of whether there is a matching record in the parent table.
Referential Integrity Grid
Parent Table displays the name of the table in the database relation containing the primary or candidate index.

Child Table displays the name of the child table in the database relation.

Update displays the update rules for referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Delete displays the delete rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Insert displays the insert rules for the referential integrity for the relation. Possible values are Cascade, Restrict, or Ignore. You can change the settings by selecting the field, which will present a drop-down list of the choices.

Parent Tag grid column displays tag name of the index in the Primary or Candidate in the Parent table.

Child Tag grid column displays the tag name of the index in the child table.

See Also

Referential Integrity Builder | Rules for Inserting Tab | Rules for Updating Tab


Text Box Builder

The Text Box builder makes it easy to set properties for a text box control. The text box is the basic control that allows users to add or edit data in a Character, Numeric, or Date field in a table. You set properties by selecting options displayed in the Text Box Builder dialog box.

To use the Text Box builder

  1. Using the Form Controls toolbar, place a text box control on a form.
  2. Select and right-click the text box control, and then choose Builder from the Form Designer shortcut menu.
  3. Choose the options you want from the dialog box, and then choose OK.

    When you choose OK, the builder closes, applying the property settings from every tab.

Builder Tabs

Format
Specifies miscellaneous format options for the text box and the type of input mask.
Style
Specifies text box visual effect, border, and character alignment.
Value
Specifies a field in which to store the text box's value.

See Also

Builders | Format Tab, Text Box Builder | Style Tab, Text Box Builder | Text Box Control | Value Tab, Text Box Builder


Format Tab, Text Box Builder

This tab in the Text Box builder specifies miscellaneous format options for the text box and the type of input mask.

Data Type
Specifies a Character, Date, Logical, or Numeric data type for your text box. If you choose a value in the Value tab, make sure it is the same data type as the value specified here.
Enable at Run Time
Specifies that the text box be enabled when the form is run. This option is available for all data types and is checked by default. This option corresponds to the Enabled property.
Alphabetic Characters Only
Specifies that only alphabetic characters be allowed in the text box (no numbers or symbols). This option is available for Character data type only. This option corresponds to the "A" setting of the Format property.
Make Read-Only
Prevents the user from changing the text in the text box. This option corresponds to the ReadOnly property and is available for all data types.
Select on Entry
Specifies that the text in the text box be selected when the text box has the focus. This option is available for the Character data type only. This option corresponds to the "K" setting of the Format property.
Hide Selection
Specifies whether or not selected text in the text box remains visibly selected when the text box doesn't have the focus. This option corresponds to the HideSelection property and is available for all data types.
Display Leading Zeros
Specifies that zeros to the left of the decimal point be displayed. This is available for the Numeric data type only. This option corresponds to the "L" setting of the Format property.
Use Current SET DATE
Adds the setting "D" to the Format property so that date entries will conform to the current SET DATE or Date Format of the Regional tab of the Options dialog box. This option appears when you select Date in the Data Type drop-down box.
British Date
Adds the setting "E" to the Format property so that date entries will conform to British formatting of SET DATE or of the Date Format of the Regional tab of the Options dialog box. This option appears when you select Date in the Data Type drop-down box.
Input Mask
Specifies format of user input for Numeric, Character, and Logical fields. Several options are available from the drop-down list; an example of the selected input mask appears to the right of the drop-down list. For example, an input mask for a Numeric data type is North American phone number format:
(###) ###-####.

See Also

Enabled Property | Format Property | HideSelection Property | InputMask Property | ReadOnly Property | Style Tab, Text Box Builder | Text Box Builder | Value Tab, Text Box Builder


Style Tab, Text Box Builder

This tab in the Text Box builder specifies text box visual effect, border, and character alignment.

Visual Effect

3D
Specifies a bold left and top edge for the text box. This option corresponds to the 3D setting of the SpecialEffect property.
Plain
Specifies that the text box is an unshadowed box on the form. This option corresponds to the Plain setting of the SpecialEffect property.

Border

Single
Specifies a single line around the text box. This option corresponds to the Fixed-Single setting of the BorderStyle property.
None
Specifies no line around the text box. This option corresponds to the None setting of the BorderStyle property.

Character Alignment

Left
Specifies that text in the text box will be left-aligned. This option corresponds to the Left setting of the Alignment property.
Right
Specifies that text in the text box will be right-aligned. This option corresponds to the Right setting of the Alignment property.
Center
Specifies that text in the text box will be centered. This option corresponds to the Center setting of the Alignment property.
Automatic
Specifies that text in the text box will be aligned according to the data type of the control source. This option corresponds to the Automatic (Default) setting of the Alignment property.
Size Text Box to Fit
Automatically sizes the text box. If an input mask is specified, the input mask settings are used to fit the text box. If not, then the ControlSource property field length is used to fit the text box.
Note If you specified an input mask on Format tab of the Text Box builder, the text box will enlarge to fit the length of the input mask. If you did not specify an input mask, the text box will enlarge to fit the field length.

See Also

BorderStyle Property | ControlSource Property | Format Tab, Text Box Builder | SpecialEffect Property | Text Box Builder | Value Tab, Text Box Builder


Value Tab, Text Box Builder

This tab in the Text Box builder specifies a field in which to store the text box's value.

Field Name
Specifies a table or view field in which to store the text box's value. Choose the dialog button to display the Open dialog box so you can select a file. This option corresponds to the ControlSource property.

See Also

ControlSource Property | Format Tab, Text Box Builder | Open Dialog Box | Style Tab, Text Box Builder | Text Box Builder


XML Web Service Builder

Makes it possible for you to bind an XML Web service to a control on a Visual FoxPro form or to an object, such as a cursor adapter in the form's data environment, without writing code.

You can open the XML Web Service Builder from the Form Designer or Class Designer.

To open the XML Web Service Builder

  1. Create a new or open an existing form.
  2. From the Tools menu, click Toolbox.
  3. From My XML Web Services in the Toolbox, drag and drop the Generic Handler control or a registered XML Web service to a form.

You can also open the XML Web Service Builder for an existing XML Web service by registering the XML Web service in the Toolbox, dragging the XML Web service from the Toolbox and dropping it on a form, right-clicking the XML Web service, and, from the shortcut menu, right-click Builder.

Note As with other Visual FoxPro builders, you can use the XML Web Service Builder to modify the XML Web service again. Not only does the builder set properties for a control, it writes information to the custome SetupOperations method.

Builder Tabs

Services Tab, XML Web Service Builder
Specifies an XML Web service to use for a form or class.
Operations Tab, XML Web Service Builder
Specifies the XML Web service operations to use and their bindings between the controls or objects on a form or class.

See Also

Builders | Accessing XML Web Services


Services Tab, XML Web Service Builder

Specifies the XML Web service to use in your application. You can also view the operations, or method calls, available for the XML Web service.

Select an XML Web service
Specifies the XML Web service that you want to bind to controls or objects on the form and displays other XML Web services that are available in the Toolbox.
Refresh
Updates the selected XML Web service so it can be registered properly on your computer. This option is available only when all registered XML Web services are listed.
Add a new XML Web service
Makes it possible for you to register and add a new XML Web service. This option is available only when all registered XML Web services are listed.
Change XML Web service
Lists all registered XML Web services. This option appears if an XML Web service is selected when opening the builder.
Note Changing the XML Web service removes all settings from the Operations tab for that XML Web service.
View operations
Displays the operations, or method calls, available for the selected XML Web service.
Note The selected operation appears in the View operations box only for informational purposes. You can set bindings for the operation on the Operations tab. For more information, see Operations Tab, XML Web Service Builder.
View service description (WSDL)
Displays the WSDL description for the XML Web service.

See Also

XML Web Service Builder | Operations Tab, XML Web Service Builder


Operations Tab, XML Web Service Builder

Specifies the XML Web service operations, or method calls, you want to use in your form or class. You can supply parameter information for the operation calls in advance and specify a control, or client, to which you want to bind the results of the operation call.

Note Settings for the Operations and Clients tabs are stored in the custom SetupOperations method.
Operations
Lists all registered operations for the XML Web service. You can call these operations automatically when the form or class is instantiated or programmatically when needed. You can associate each operation with multiple clients.
  • Add Displays a dialog box with options for adding a new operation. For more information, see XML Web Service - Operation Detail Dialog Box.
  • Edit Displays a dialog box with options for editing the selected operation. For more information, see XML Web Service - Operation Detail Dialog Box.
  • Remove Removes the selected operation. If you remove an operation, you are prompted to remove any clients associated with the operation.
Clients
Lists all registered clients for the selected operation. Clients are controls or objects on a form or in a class that use the XML Web service operation. You can specify when binding occurs between the operation and client and to which property of the control operation results are assigned. For XML Web services that return ADO.NET DataSets, you can also specify complex type information such as table or field settings.
  • Add Displays a dialog box with options for adding a new client. For more information, see XML Web Service - Client Detail Dialog Box.
  • Edit Displays a dialog box with options for editing the selected client. For more information, see XML Web Service - Client Detail Dialog Box.
  • Remove Removes the selected client.

See Also

XML Web Service Builder | Services Tab, XML Web Service Builder


Designers

Designers make it possible for you to design the windows, dialog boxes, and components in your application visually.

In This Section

Class Designer
Allows you to create and modify classes visually.
Connection Designer
Allows you to create and modify named connections. Because connections are stored as part of a database, you only can use the Connection designer if you have a database open.
Data Environment Designer
Allows you to create and modify the data environment of forms, form sets, and reports visually.
Database Designer
Displays and allows you to create and modify tables, views, and relationships that are contained in a database.
Form Designer
Allows you to create and modify forms and form sets visually. A form set consists of one or more forms that can be manipulated as a unit.
Label Designer
Allows you to create and modify labels. When the Label designer window is active, Microsoft Visual FoxPro displays the Report menu and the Report Controls toolbar.
Menu and Shortcut Designers
Allows you to create menus, menu items, submenus of menu items, lines that separate groups of related menu items, and so on.
Query and View Designers
Allows you to create and modify queries and views. When the Query or View designer is active, Microsoft Visual FoxPro displays the Query menu and the Query toolbar or View designer toolbar.
Report Designer
Allows you to create and modify reports. When the Report designer window is active, Microsoft Visual FoxPro displays the Report menu and the Report Controls toolbar.
Table Designer
Allows you to create and modify database tables, free tables, fields, and indexes.

Related Sections

User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
Utility Programs
Describes tools that are provided with Microsoft Visual FoxPro to help speed the process of application development.


Class Designer

Use the Class Designer to create and modify classes visually. When the Class Designer window is active, Microsoft Visual FoxPro displays the Class Menu. The View Menu makes it possible for you to open complementary class design tools such as the Properties window, the Form Controls Toolbar, and the Layout Toolbar.

Classes are stored in class library (.vcx) files. To modify more than one class, you can open multiple class designers at the same time.

You can save classes by pressing CTRL+E while in the code snippet editor. When you reopen the class, the snippet editor reopens to the same location in the code.

For detailed information on designing classes, see Object-Oriented Programming, and the topics Creating Classes and Saving Forms.

The Class Designer window consists of the Class window, which displays a single class. The Class window is anchored to the top-left corner of the Class Designer and cannot be moved unless the window contains toolbar types.

See Also

Data Session Window | Form Designer | PageFrame Control | Connection Designer | Database Designer | Data Environment Designer


Connection Designer

Use the Connection Designer to create and modify named connections. Because connections are stored as part of a database, you only can use the Connection Designer if you have a database open.

For more information on creating connections, see "Defining a Connection" in Accessing Remote Data.

Specify Datasource

Data Source, Userid, Password
Specifies that Visual FoxPro display the following three boxes:
  • Data Source Makes it possible for you to choose a data source from the list of installed ODBC data sources.
  • Userid Makes it possible for you to enter a user name or ID if the data source requires one.
  • Password Makes it possible for you to enter a password if the data source requires one.
  • Database Makes it possible for you to choose a database for the selected data source to connect to.
Connection String
Specifies that Visual FoxPro display the Connect String textbox in which you type a connection string. Choosing the dialog button displays the Select Connection or Data Source Dialog Box, allowing you to select an existing file or machine data source.
Verify Connection
Makes it possible for you to check the connection you have just entered information for. If the connection was made successfully, a dialog box appears to indicate this. If the connection was not successful, an error message appears. If no information has been specified for the connection, the Select Database dialog box appears, which makes it possible for you to select a data source.
New Data Source
Displays the Data Sources dialog box, which makes it possible for you to add, delete, or configure data sources.

Display ODBC Login Prompts

When Login Info Is Not Specified
Specifies that Visual FoxPro prompt the user with the ODBC Data Source Login dialog box if the user ID and password are not stored in the named connection definition.
Always
Specifies that Visual FoxPro always prompt the user with the ODBC Data Source Login dialog box. This enables the user to use a different login ID and password from those stored in the named connection.
Never
Specifies that Visual FoxPro never prompt the user. This option ensures higher security.

Data Processing

These options correspond to connection properties that you can also set with the DBSETPROP( ) Function. For more information about these properties, see the connection properties in the DBGETPROP( ) Function.

Asynchronous Execution
Specifies an asynchronous connection. This option corresponds to the Asynchronous connection property.
Display Warnings
Specifies the display of non-trappable warnings. This option corresponds to the DispWarnings connection property.
Batch Processing
Specifies that the connection operate in batch mode. This option corresponds to the BatchMode connection property.
Automatic Transactions
Specifies that the transaction processing is automatically handled. This option corresponds to the Transactions connection property.
Packet Size
Makes it possible for you to specify the network packet size (in bytes) for information transmitted to and from the remote data site. Select a choice from the drop-down list, or type a value.

Timeout Intervals

These options set values for connection properties that you can also set with the DBSETPROP( ) function. For more information about these properties, see connection properties in the DBGETPROP( ) Function.

Connection (sec)
Specifies the connection timeout interval in seconds. This option corresponds to the ConnectTimeout connection property.
Query (sec)
Specifies the query timeout interval in seconds. This option corresponds to the QueryTimeout connection property.
Idle (min)
Specifies the idle timeout interval in minutes. Active connections are deactivated after the specified time interval. This option corresponds to the IdleTimeout connection property.
Wait Time (ms)
Specifies the amount of time in milliseconds that elapses before Visual FoxPro determines whether the SQL statement has completed executing. This option corresponds to the WaitTime connection property.

See Also

CREATE CONNECTION command | DBGETPROP( ) Function | DBSETPROP( ) Function | DELETE CONNECTION Command | DISPLAY CONNECTIONS Command | LIST CONNECTIONS Command | MODIFY CONNECTION Command | RENAME CONNECTION Command | SQLCONNECT( ) Function | SQLDISCONNECT( ) Function | SQLGETPROP( ) Function | SQLSETPROP( ) Function


Data Environment Designer

Use the Data Environment Designer to visually create and modify the data environment of forms, form sets, and reports. When the Data Environment Designer window is active, Visual FoxPro displays the Data Environment menu, which makes it possible for you to manipulate data environment objects. To display the Properties window and Code window, right-click to display the Data Environment shortcut menu, and then click Properties and Code.

A data environment defines the source for the data used in a form or report. This can include tables, views, and relationships. The data environment is saved with the form or report and can be modified whenever you are using the Report Designer or Form Designer.

When the data environment of a form or report is defined, Visual FoxPro automatically opens the tables or views when you open or run the file and closes them when the file is closed or released.

  • For forms, Visual FoxPro populates the ControlSource property list in the Properties window with all the fields in your data environment.
  • For reports, Visual FoxPro populates the data set your report needs based on associated tables and views.
  • For more information about using the Data Environment Designer with forms, see Creating Forms.

See Also

Code Window | ControlSource Property | Form Designer | Properties Window | Report Designer | Form Designer | Database Designer | Label Designer


Database Designer

The Database Designer displays all the tables, views, and relationships contained in a database. When the Database Designer window is active, Visual FoxPro displays the Database Menu and the Database Designer toolbar.

Each table is represented by a resizeable window that lists the table's fields and indexes, if any exist. The Database Designer shows persistent relationships by displaying lines between tables that connect the indexes.

You can position the tables and views by dragging them into place, or using the Arrange command on the Database menu. If you want to show or hide objects in the window, you can use the Properties command on the Database menu.

See Also

CREATE DATABASE Command | Table Designer | Table Wizard | Data Environment Designer | Form Designer | Connection Designer | Setting Temporary Relationships Between Tables | Adding Tables to a Database


Form Designer

Use the Form Designer to visually create and modify forms and form sets. A form set consists of one or more forms that can be manipulated as a unit. Forms and form sets are objects with their own properties, events, and methods.

When the Form Designer window is active, Visual FoxPro displays the Form menu, the Form Controls toolbar, the Form Designer toolbar, and the Properties window.

You can run the form by clicking the ! icon in the toolbar or by pressing Ctrl-E while in the code snippet editor. When reopening the Form designer, the code snippet editor reopens to the same location in the code.

For information about editing event and method code, see Creating Forms.

The Form Designer window consists of:

Form Window
Contains a single form on which you add and modify controls. More than one form window is displayed in the Form Designer when you modify a form set containing multiple forms. Form windows can be moved around within the Form Designer.

See Also

Class Designer | Forms Tab, Options Dialog Box | Form Wizard | PageFrame Control | Properties Window | Adding Visual FoxPro Controls to a Form


Label Designer

Use the Label Designer to create and modify labels. When the Label Designer window is active, Visual FoxPro displays the Report menu and the Report Controls toolbar.

The Label Designer is the same as the Report Designer, using the same menus and toolbars. The main difference is that the Label Designer automatically defines the page and its columns based on the size of label you select.

To quickly create a simple label layout, click Quick Report on the Report menu. Quick Report prompts you for input on the fields and layout you want for your label.

Bands

By default, the Label Designer displays five bands: Page Header, Column Header, Detail, Column Footer, and Page Footer.

You can add the following bands to your label.

Band | Printed | Typical Contents
Group Header | Once per report | Preface to following data
Group Footer | Once per report | Calculated values for group data
Title | Once per report | Title Date or page number Company logo Box around the title
Summary | Once per report | Grand totals Text such as Grand Totals

Ruler

The Label Designer has a vertical and horizontal ruler you use to more precisely position objects in the bands. Use the ruler in conjunction with the View menu's Show Position command to help you position objects.

To change the ruler scale

The ruler is set to the system default (inches). Change this to pixels as follows:

  1. On the Format menu, click Set Grid Scale. The Set Grid Scale Dialog Box is displayed.
  2. In the Set Grid Scale dialog box, select Pixels and click OK.

    The ruler scale is set to pixels, and the position indicator in the status bar (if Show Position is selected on the View menu) also displays positions in pixels.

See Also

Label Wizard | Quick Report Dialog Box | Set Grid Scale Dialog Box | CREATE LABEL Command | Menu and Shortcut Designers | Form Designer | Creating Reports and Labels | Controlling Report and Label Output


Menu and Shortcut Designers

You can create menus, menu items, submenus, lines that separate groups of related menu items, shortcut menus, and so on using the Menu Designer and the Shortcut Designer. By creating your own menus and shortcut menus, you can customize your copy of Visual FoxPro or design menus for applications you intend to distribute.

The Menu and Shortcut Designers contain the following elements and options:

Prompt
Specifies menu titles and menu items in menus or shortcut menus.
Mover Control
Appears as a double-headed arrow button to the left of the Prompt column when you insert at least one item. You can use the mover control to arrange the order of menu items at design time.
Result
Specify the action that occurs when you choose a menu title or menu item. For example, you can execute a command, open a submenu, or run a procedure.
Create
Appears when you select Submenu or Procedure in the Result column. You can use the Create button to specify a submenu or procedure for a menu title or menu item.
Edit
Appears only after you have created a submenu or procedure in the Result column for a menu item. Clicking the Edit button switches the Menu Designer to the submenu or procedure associated with a menu title or menu item.
Options
Opens the Prompt Options dialog box, which you can use to define keyboard shortcuts and other menu options.
Menu level
Specifies the menu, submenu, or shortcut you are editing.
Preview
Displays the menu you are creating.

Item Group

Insert
Inserts a new item in the Menu Designer window.
Insert Bar
Available only when an item is selected in the Shortcut Designer and opens the Insert System Menu Bar dialog box, which makes it possible for you to select and insert standard Visual FoxPro menu items.
Delete
Available only when an item is selected and deletes the selected row from the Menu Designer.
Move Item
Available only when an item is selected and opens the Move Item dialog box, which you can use to change the location of the menu item.

See Also

Dialog Boxes | Prompt Options Dialog Box | Creating Menus, Shortcut Menus, Menu Items, and Submenus | Insert System Menu Bar Dialog Box | Move Item Dialog Box | General Options Dialog Box | Menu Options Dialog Box


Query and View Designers

To create and modify queries and views, use the Query Designer and View Designer. When the Query or View Designer is active, the Query menu and the Query Designer or the View Designer toolbar are visible.

The top pane of the designer displays the tables in the query or view. A resizable window representing each table lists the fields and indexes in the table. The designer shows join conditions by displaying lines that connect fields between tables. You can drag indexed fields between tables to create join conditions. To display the Join Condition Dialog Box for editing the condition, double-click a line.

In This Section

Fields Tab, Query and View Designers
Specifies fields, aggregate functions, such as SUM Command or COUNT Command, or other expressions.
Join Tab, Query and View Designers
Specifies join expressions for matching records between two or more tables or views.
Filter Tab, Query and View Designers
Specifies conditions for selecting records, such as specific values in a field, or join conditions defining temporary relationships between tables.
Order By Tab, Query and View Designers
Specifies fields, aggregate functions, such as SUM Command or COUNT Command, or other expressions used to set the order of records retrieved in the query.
Group By Tab, Query and View Designers
Specifies fields, aggregate functions, such as SUM Command or COUNT Command, or other expressions used to combine records into a group based on identical values in those fields.
Update Criteria Tab, View Designer
Specifies fields to be updated and criteria for fields to be updated (View Designer only).
Miscellaneous Tab, Query and View Designers
Specifies if duplicates should be retrieved and limits on records, such as the top quantity or percentage.

Related Sections

Designers
Designers make it possible for you to design the windows, dialog boxes, and components in your application visually.
Class Designer
Use the Class designer to create and modify classes visually.
Connection Designer
Use the Connection designer to create and modify named connections. Because connections are stored as part of a database, you only can use the Connection designer if you have a database open.
Data Environment Designer
Use the Data Environment designer to create and modify the data environment of forms, form sets, and reports visually.
Database Designer
The Database designer displays all the tables, views, and relationships contained in a database.
Form Designer
Use the Form designer to create and modify forms and form sets visually. A form set consists of one or more forms that can be manipulated as a unit.
Label Designer
Use the Label designer to create and modify labels. When the Label designer window is active, Microsoft Visual FoxPro displays the Report menu and the Report Controls toolbar.
Menu and Shortcut Designers
Use the Menu designer and the Shortcut designer to create menus, menu items, submenus of menu items, lines that separate groups of related menu items, and so on.
Report Designer
Use the Report designer to create and modify reports. When the Report designer window is active, Microsoft Visual FoxPro displays the Report menu and the Report Controls toolbar.
Table Designer
Use the Table designer to create and modify database tables, free tables, fields, and indexes.


Fields Tab, Query and View Designers

Specifies fields, aggregate functions, and other expressions for query or view output. This tab appears in the Query and View Designers.

Available fields
Lists all the fields available in the tables of the query or view. You can select all available tables and their fields by choosing the asterisk (*), all fields in a particular table by choosing table.*, or individual fields for your query or view. Your selections appear in the SELECT statement in the SQL window when you click the SQL button or choose View SQL from the Query menu.

If you select a field in the Available Fields list, its name automatically appears in the Functions and expressions edit box and in the Expression edit box of the Expression Builder, which opens when you click the ellipsis (...) button.

Functions and expressions
Specifies a function or expression. You can either type an expression directly into the box or select a function from a list in the Expression Builder, which opens when you click the ellipsis (...) button.

After creating your expression, you can add it to the Selected fields box by clicking the Add button.

Selected fields
Lists the selected fields, aggregate functions, and other expressions that appear in the query or view results. You can rearrange the order of the output by dragging the vertical double arrow to the left of the fields.
Add
Adds the selected item from the Available fields box or the Functions and expressions box to the Selected fields box.
Add All
Adds all fields from the Available fields box to the Selected fields box.
Remove
Removes the selected item from the Selected fields box.
Remove All
Removes all items from the Selected fields box.
Properties
Displays the View Field Properties Dialog Box, which makes it possible for you to specify options for fields in a view just as you do for fields in database tables. This option is available only in the View Designer.

See Also

Filter Tab, Query and View Designer | Group By Tab, Query and View Designers | Order By Tab, Query and View Designers | Query and View Designers | Update Criteria Tab, View Designers | Join Tab, Query and View Designers


View Field Properties Dialog Box

Use to specify options for fields in a view just as you can for fields in database tables. You can define properties to determine the type of data the field stores, to control data entry for updateable views, and to control the display of the field.

This dialog box appears when you select a field and click the Properties button on the Fields tab of the Query and View Designers.

Field
Specifies the name of the selected field in the view. To set properties on other selected fields, you can choose from the drop-down list. The field appears with its sequential field number.

Field Validation Options

These options allow you to control the contents of the field.

Rule
Specifies the expression for the field-level rule that controls which values can be entered into the field.
Message
Specifies the error message displayed when the field-level rule is violated.
Default value
Specifies a quantity or string that is the content for a field when a new record is added. The default value remains in the field until you enter a new value.

Display Options

These options allow you to control how values are entered or displayed in the field.

Format
Specifies the expression for case, size, and style for display of the field in the Browse window, forms, or reports. Property settings within the form and report can override this expression.
Input Mask
Specifies the format for values as they are entered into the field. For example, telephone numbers might have a format of (999) 999-9999.
Caption
Specifies the label that appears for the field in the Browse window, forms, or reports. Property settings within the form or report can override this setting. To specify an expression for a field caption, include the equal sign (=) preceding the caption string. If an equal sign is not found, it is treated as a string literal. Expressions cannot exceed 254 characters. If the expression exceeds 254 characters, the caption defaults to the field name.
Note Support for using expressions as field captions should be used only with DBC tables in applications running on Visual FoxPro 8.0 or later. In earlier versions, the expression appears as a string literal.

Map Field Type to Classes Options

If you plan to use the view field in forms, these options allow you to specify a default control type that appears when you drop the field on a form.

Display library
Specifies the class library file (.vcx) containing the control class you want to associate with the field.
Display class
Specifies the type of control that is created when the field is dropped onto a form.

Data Mapping Options

By default, the view field has the same property settings as its associated field in a table. These options are only enabled for remote views.

Data type (remote views only)
Specifies the kind of data this field can hold.
Width (remote views only)
Specifies the number of characters this field can hold.
Decimal (remote views only)
For numeric data types, specifies the number of places to the right of the decimal point this field can hold.
Comment (remote views only)
Provides space for you to type a comment about the field.

See Also

Query and View Designers | Join Tab, Query and View Designers | Fields Tab, Query and View Designers | Creating Default Values for View Fields | Filter Tab, Query and View Designers


Join Tab, Query and View Designers

Specifies join conditions for matching and selecting records in one or more tables or views, for example, specific values in a field or join conditions that define temporary relationships between tables.

Settings in the Join tab determine the join conditions that appear in the FROM clause of the SELECT - SQL Command that is generated and that appears in the SQL window. The View Designer loads and generates any FROM clause with or without the JOIN option, using parentheses where needed in the ON clause.

Condition Button
Appears if two or more tables are joined in the query. Click the double-headed horizontal arrow to edit the selected condition or query criterion in the Join Condition Dialog Box, which will update entries in the other columns.
Left Table
Contains the alias of the left table in the join or "<Prev join>", which means the left table in the join is actually the previous subjoin.
Join type
Specifies the type of join condition. By default, the join type is Inner Join. When creating a new join condition, click the field to display a drop-down list of the join types.
  • Inner Join Specifies that only the records that match the join condition are included in the results. This type is the default and most commonly used type of join.
  • Left Outer Join Specifies that all the records in the left table, regardless whether they match the join condition, and only those records in the right table that match the join condition, are included with the results.
  • Right Outer Join Specifies that all the records in the right table, regardless whether they match the join condition, and only those records in the left table that match the join condition, are included with the results.
  • Full Join Specifies that both records that match and do not match the join condition are included in the results. The field must match the example text, character for character.
  • Cross Join Specifies that each record in the left table is matched with all records in an existing right table. When a WHERE clause does not exist, setting a cross join produces a Cartesian product result set.

    The Cross Join option makes it possible to modify the table sequence appearing in the FROM clause of the SQL SELECT statement in the SQL window for the query or view. Selecting Cross Join inserts a comma (,) that separates tables in the FROM clause.

    Note You can specify a cross join only for the left table, which cannot be a previous join (<Prev join>). You cannot specify a cross join when adding new tables to the query or view, so if you want to set a specific sequential position for the table, you must manually add the cross join for the table.
    Outside the Query and View designers, cross joins are not supported in Visual FoxPro SQL SELECT command syntax. Cross joins are supported only for modifying the sequence of tables in Query and View Designers.

    When parsing the SQL SELECT statement, Visual FoxPro puts every table from the FROM clause that is not involved in the join into the Join tab. A row with "<alias> Cross join" appears in the join list. The sequence of tables in the FROM clause of the SQL SELECT statement matches the sequence of joins in the Join tab. When generating queries, Visual FoxPro uses this information to place a table in the correct position as specified by the FROM clause. When changes are reloaded in the Query and View designers, they are updated in the Join tab.

    If a table is not referenced in the Join tab, Visual FoxPro places it at the beginning of the FROM clause. If several unreferenced tables exist, all such tables are placed randomly at the beginning of the FROM clause.

Pri. (Priority)
Specifies a number ranging from 0 to 99, which indicates a priority for the join operation. The number 0 specifies the highest priority, while the number 99 specifies the lowest priority.

Setting priorities for join operations determines the order in which joins are performed and uses parentheses (()) to group operations. For example, suppose you specify a priority of 0 for a join operation, a priority of 1 for a second join operation, and a priority of 0 for a third join operation. The first and third join operations, which have a priority of 0, are performed before the second join operation, which has a priority of 1.

Right Table
Contains the alias of the right table in the join or "<Next join>", which means the right table in the join is actually the next subjoin.
Field Name
Specifies the first field of the join condition. When creating a new join condition, click the field to display a drop-down list of the available fields. You can also specify an expression.
Not
Reverses the condition to exclude records matching the condition.
Criteria
Specifies a condition operator:
  • Equal (=) Specifies that field and the value in the Example field have the same value.
  • Like Specifies that the field must include characters that match characters in the text in the Example field.

    For example, Customer.state Like O matches records from Ohio, Oklahoma, and Oregon.

  • Exactly Like (==) Specifies that the field must match, character for character, the text in the Example field.
  • Greater Than (>) Specifies that the field must be more than the value in the Example field.
  • Less Than (<) Specifies that the field must be the same or less than the value in the Example field.
  • Greater Than or Equal To (>=) Specifies that the field must be the same or more than the value in the Example field.
  • Less Than or Equal To (<=) Specifies that the field must be the same or less than the value in the Example field.
  • Is NULL Specifies that the field must contain a null value.
  • Is True Specifies the left field or expression evaluates to True, assuming the field or expression evaluates to a logical value.
  • Between Specifies that the field must be greater than or equal to the lower value, and less than or equal to the higher value, in the condition appearing in the Example column. You must separate the two values in the Example field with the word AND. Visual FoxPro creates the query with the word BETWEEN.

    For example, Invoices.idate Between 05/10/97 AND 05/12/97 matches records for the 10th, 11th, and 12th of May, 1997.

  • In Specifies that the field must match one of several values in the comma-separated list appearing in the Example field.

    For example, Customer.name In Al,George,Mary matches records in which the customer's name is Al, George, or Mary.

Value
Specifies the other table and field in the join condition. You can also specify an expression.
Logical
Adds an AND or OR condition to the list of join conditions.
Pri. (Priority)
Specifies a number ranging from 0 to 99, which indicates the priority for logical operations. The number 0 indicates the highest priority, while the number 99 indicates the lowest priority.

Setting priorities for logical operations determines the order in which logical operations are performed and uses parentheses (()) for grouping operations. For example, suppose you specify a priority of 0 for a logical operation, a priority of 1 for a second logical operation, and a priority of 0 for a third logical operation. The first and third logical operations, which have a priority of 0, are performed before the second logical operation, which has a priority of 1.

Insert button
Inserts a blank join condition above the selected condition.
Remove button
Removes the selected condition from the query.

See Also

Query and View Designers | Fields Tab, Query and View Designers | Group By Tab, Query and View Designers | Join Condition Dialog Box | Order By Tab, Query and View Designers | SELECT - SQL Command | Update Criteria Tab, View Designer | Filter Tab, Query and View Designers | Querying Multiple Tables and Views


Filter Tab, Query and View Designers

Determines the conditions for selecting records as listed in the WHERE clause of the SELECT - SQL Command in the SQL window. You can load and save a query or view with a subquery in the WHERE clause.

Mover Box

Drag the mover box to move the selected item up or down within the grid.

Condition Button
Click the double-headed horizontal arrow to edit the selected filter.
Field Name
Specifies the first field of the filter condition. When creating a new filter condition, click the field to display a drop-down list of the available fields.
Not
Reverses the condition to exclude records matching the condition.
Criteria
Specifies a comparison operator:
  • Equal (=) Specifies that field and the value in the Example field have the same value.
  • Like Specifies that the field must include characters that match characters in the text in the Example field.

    For example, Customer.state Like O matches records from Ohio, Oklahoma, and Oregon.

  • Exactly Like (==) Specifies that the field must match, character for character, the text in the Example field.
  • Greater Than (>) Specifies that the field must be more than the value in the Example field.
  • Less Than (<) Specifies that the field must be the same or less than the value in the Example field.
  • Greater Than or Equal To (>=) Specifies that the field must be the same or more than the value in the Example field.
  • Less Than or Equal To (<=) Specifies that the field must be the same or less than the value in the Example field.
  • Is NULL Specifies that the field must contain a null value.
  • Is True Constructs a WHERE clause containing only the left field where the field or expression evaluates to True, assuming the field or expression evaluates to a logical value.
  • Between Specifies that the field must be greater than or equal to the lower value, and less than or equal to the higher value, in the condition appearing in the Example column. You must separate the two values in the Example field with the word AND. Visual FoxPro creates the query with the word BETWEEN.

    For example, Invoices.idate Between 05/10/97 AND 05/12/97 matches records for the 10th, 11th, and 12th of May, 1997.

  • In Specifies that the field must match one of several values in the comma-separated list appearing in the Example field.

    For example, Customer.name In Al,George,Mary matches records in which the customer's name is Al, George, or Mary.

  • Exists Specifies that the records returned contain the criterion in the Example field. When the filter condition specifies Exists, the filter condition evaluates to True (.T.) unless the subquery returns an empty set.

    In the following example, specifying Exists returns every customer that has an order:

    SELECT Customer.cust_id, Customer.company;
 FROM testdata!customer;
 WHERE Exists (select * from orders where customer.cust_id = ;
   orders.cust_id)
Example
Specifies the value or text with which you want to compare the field. To match the text casing of the example, use the UPPER( ), LOWER( ), and PROPER( ) functions.
Logical
Adds an AND or OR condition to the filter condition list.
Pri. (Priority)
Specifies a number ranging from 0 to 99, which indicates the priority for logical operations. The number 0 indicates the highest priority, while the number 99 indicates the lowest priority.

Setting priorities for logical operations assigns the order in which each logical operation is performed. In effect, the behavior is similar to using parentheses (()) to group operations. For example, suppose you specify a priority of 0 for a logical operation, a priority of 1 for a second logical operation, and a priority of 0 for a third logical operation. The first and third logical operations with priority 0 are performed before the logical operation with priority 1.

Insert button
Inserts a blank filter condition above the selected condition.
Remove button
Removes the selected condition from the query.

See Also

Fields Tab, Query and View Designers | Group By Tab, Query and View Designers | Join Condition Dialog Box | Order By Tab, Query and View Designers | Query and View Designers | SELECT - SQL Command | Update Criteria Tab, View Designer


Order By Tab, Query and View Designers

Specifies fields, aggregate functions such as SUM Command or COUNT Command, or other expressions used to set the order of records retrieved in the query.

You can select fields from the Order By tab that are not included in the SELECT list.

Selected Output
Lists the selected fields and expressions that will appear in the query results.
Ordering Criteria
Specifies the fields and expressions used in the query's sort order. The arrow that appears to the left of each field specifies an ascending (up) or descending (down) sort. A mover box appears to the left of the arrow for changing the order of the fields.

Order Options

Ascending
Sets the selected item in the Ordering Criteria box to sort in ascending order.
Descending
Sets the selected item in the Ordering Criteria box to sort in descending order.
Add
Adds the selected item in the Selected Output box to the Ordering Criteria box.
Remove
Removes the selected item from the Ordering Criteria box.

See Also

COUNT Command | Fields Tab, Query and View Designers | Filter Tab, Query and View Designers | Group By Tab, Query and View Designers | SELECT - SQL Command | SUM Command | Update Criteria Tab, View Designer


Group By Tab, Query and View Designers

Groups rows of query or view results. This tab appears in the Query and View Designers. For more information, see the GROUP BY clause in the SELECT - SQL Command.

Available Fields
Lists all the available fields in the tables of a query or view and other expressions.
Grouped Fields
Lists the fields, aggregate functions, and other expressions for determining the grouping of the query results. Fields are grouped in the order they appear in the list. You can change the field order and the grouping hierarchy by dragging the double-headed arrow to the left of each field.
Add
Adds the selected item in the Available Fields box to the Group By Fields box.
Remove
Removes the selected item from the Group By Fields box.
Having
Displays the Having Dialog Box for setting selection criteria on groups rather than on individual records.

See Also

Fields Tab, Query and View Designers | Filter Tab, Query and View Designers | Having Dialog Box | Order By Tab, Query and View Designers | Query and View Designers | SELECT - SQL Command | Update Criteria Tab, View Designer


Update Criteria Tab, View Designer

Specifies conditions for sending changes in the view to the original records in the tables used in the view. The Update Criteria tab appears only in the View Designer.

Table
Specifies which tables used in the view can accept changes. The list shows the tables that have fields in the Selected fields list of the Fields Tab, Query and View Designers.
Reset Key
Selects the primary key field from each table as the key fields for the view and places a check mark under the key symbol in the Field name list for each primary key field. Key fields are used for matching the changes in the view to the original record in the table.
Update All
Selects all fields other than the key fields for updating and places a check mark under the pencil symbol in the Field name list.
Send SQL Updates
Specifies whether changes to the records in the view are actually sent to the original tables.
Field Name Pane
Shows the fields that you have selected for output and, therefore, are available to update.
  • Key Field (marked with a key symbol) Specifies whether the field is a key field.
  • Updatable (marked with a pencil symbol) Specifies whether the field is updatable.
  • Field Name Displays the name of the output fields available to mark as key fields or updatable.

SQL WHERE Clause Includes

Controls which fields are added to the WHERE clause to detect update conflicts on the server when the changes to the view are sent to the original tables.

A conflict is based on a comparison between the old values in the view, OLDVAL( ), and the current values in the original table, CURVAL( ). If the values are equal, the original table is considered unchanged and no conflict exists. If they are not equal, a conflict exists and the data source returns an error.

The error returned for a conflict between the old value and the current value is Error 1585 "Record has been modified by another" or Error 1494 "Update conflict. Use TABLEUPDATE() to force the update or TABLEREVERT() to rollback".

Key Fields Only
Sets the WHERE clause to detect a conflict if a key field has been changed in the original table. Changes made by another user to any other field in the original record of the table are not compared.
Key and Updatable Fields
Sets the WHERE clause to detect a conflict if another user changed any of the fields that were updatable.
Key and Modified Fields
Sets the WHERE clause to detect a conflict if the key field or one of the modified fields in the record in the original table has changed since the view was first retrieved (default).
Key and Timestamp
Sets the WHERE clause to detect a conflict if the timestamp of the record on the original table has changed since it was first retrieved. This option is only available if the remote table has a timestamp column.

Update Using

Specifies how updates are performed on the back-end server.

SQL DELETE then INSERT
Deletes the record from the original table, and then creates a new record from the modified record in the view.
SQL UPDATE
Uses the changes in the fields of the view to modify the fields in the original table.

See Also

Fields Tab, Query and View Designers | Filter Tab, Query and View Designers | Group By Tab, Query and View Designers | Order By Tab, Query and View Designers | Query and View Designers


Miscellaneous Tab, Query and View Designers

Specifies other record selection conditions for the query or view.

Note It is possible to add multiple conflicting options by clicking the Cross tabulate, Report, and Label buttons multiple times. The Query Designer will attempt to warn you and provide the option to remove the previous command if it is the first conflict found. You should make sure that only the desired optional code appears in the query.
No duplicates
Eliminates duplicate records from the query or view results. Duplicate records are records in which every field matches.
Force join
Changes statement parsing or generation to support the FORCE option in the FROM clause, that is, to specify that tables are joined in the order in which they appear in the FROM clause. To enable the force join option, select Force join.
Top
Selects a quantity or percentage of records from the result set. When specifying a number or percentage, use the Order By Tab, Query and View Designers to choose which records are at the top of the result set.

All Specifies that all of the records selected by the query or view should be included in the results set.

Number of records Sets a quantity of records of the selected records to include in the results set.

Percent Changes the number in the box above to a percentage of records.

Cross tabulate (Queries only)
Sends the results of the query or view to Microsoft Graph, a report, or a table in cross-tabular format. You query must contain exactly three items that represent the X-axis, the Y-axis, and the cell value for the graph.

Visual FoxPro inserts the following example code:

INTO CURSOR SYS(2015)
* To execute the following command, result should have three columns.
DO (_GENXTAB) WITH 'T2 t1'
Note The INTO CURSOR clause is added only if the query does not already have such a clause.

For example, you could generate a report that shows the amount billed to clients by month. You would create a graph that displays clients down the left side of the page, the twelve months across the top of the page, and, within the graph, the amount billed to each client each month.

Report (Queries only)
Generates the appropriate REPORT FORM command and opens the Report dialog box that makes it possible for you to set report and certain option settings.

Visual FoxPro inserts following example code:

INTO CURSOR SYS(2015)
REPORT FORM tbl2.frx TO PRINTER PLAIN
Note The INTO CURSOR clause is added only if the query does not already have such a clause.
Note An existing REPORT command in the Query window is not parsed, and its settings are not reflected in the dialog box. You must re-enter the desired dialog box options. After clicking OK, you will be prompted to replace the existing command. You will be presented with this option only if the REPORT command is the first item after the query. If you insert any code before the REPORT command, a new REPORT command is placed immediately after the SQL statement.
Label (Queries only)
Generates the appropriate LABEL FORM command and opens the Label dialog box that makes it possible for you to set label and certain option settings.

Visual FoxPro inserts the following example code:

INTO CURSOR SYS(2015)
LABEL FORM tbl2.lbx TO PRINTER
Note The INTO CURSOR clause is added only if the query does not already have such a clause.
Note An existing LABEL command in the Query window is not parsed, and its settings are not reflected in this dialog box. You must re-enter the desired dialog box options. After clicking OK, you will be prompted to replace the existing command. You will be presented with this option only if the LABEL command is the first item after the query. If you insert any code before the LABEL command, a new LABEL command is placed immediately after the SQL statement.

See Also

Fields Tab, Query and View Designers | Filter Tab, Query and View Designers | Group By Tab, Query and View Designers | Order By Tab, Query and View Designers | Query and View Designers | Report Dialog Box | Label Dialog Box


Report Designer

Use the Report Designer to create and modify reports. When the Report Designer window is active, Visual FoxPro displays the Report menu and the Report Controls toolbar.

To quickly create a simple report layout, click Quick Report on the Report menu. Quick Report prompts you for input on the fields and layout you want for your report.

When the Report Designer is open, you can manage foreground and background colors of report elements through additions to the Format menu, according to the following table:

Control | Foreground Color | Background Color
Label | Enabled | Disabled
Field | Enabled | Enabled
Line | Enabled | Enabled
Rectangle | Enabled | Enabled
Rounded Rectangle | Enabled | Enabled
Picture / Activex Bound | Disabled | Disabled

For detailed information on using the Report Designer, see "Formatting Options for Report Controls" in Formatting Field Controls in a Report.

The Report Designer uses bands and controls to manage the layout of data in a form.

Bands

By default, the Report Designer displays three bands; Page Header, Detail, and Page Footer. A separator bar is located at the bottom of each band. The name of the band type appears on the bar next to a blue arrow, which indicates that the band is above, not below, the bar.

Bands are added to the list of bands in the Bands option of the Report menu as you add them to your report by selecting Report menu options.

Band | Printed | Typical Contents
Column Header | Once per column | Column title
Column Footer | Once per column | Summary, totals
Group Header | Once per group | Preface to following data
Group Footer | Once per group | Calculated values for group data
Title | Once per report | Title Date or page number Company logo Box around the title
Summary | Once per report | Grand totals Text such as Grand Totals

Insert Control

This menu option displays controls of associated Report Controls Toolbar. When you select from this palette, Visual FoxPro places the report in tab mode and adds the control to the upper left corner of the report. Then, you can move or resize the control and tab from one control to the next. Use CTRL+tab to unselect the control, Use Alt+Enter to open the Properties window.

Ruler

The Report Designer has a vertical and horizontal ruler you use to more precisely position objects in the bands. Use the ruler in conjunction with the View menu Show Position command to help you position objects.

The scale for the ruler is determined by your system measurement settings. You can change from the system default scale (inches or centimeters) to pixels from within Visual FoxPro. If you want to change to the system default, change the measurement setting for your operating system.

To change the ruler scale to pixels

Change this to pixels as follows:

  1. On the Format menu, click Set Grid Scale. The Set Grid Scale dialog box is displayed.
  2. In the Set Grid Scale dialog box, select Pixels and click OK.

    The ruler scale is set to pixels, and the position indicator in the status bar, if Show Position is selected on the View menu, displays the position in pixels.

You can move easily between objects in the report while in Tab mode. To enter tab mode, press TAB to move to the next object or SHIFT+TAB to move to the previous object.

To edit labels, press CTRL+E to enter Edit mode. If you need specify high ASCII characters using the CTRL key, exit Edit mode by pressing the ESC key. Other Designer navigation keys apply.

To edit a report field, press ALT+ENTER to open the appropriate properties dialog box for that field.

For more information, see Keyboard Shortcuts.

See Also

Quick Report Dialog Box | Report Wizard | Set Grid Scale Dialog Box | Table Designer | Controlling Report and Label Output | Formatting Field Controls in a Report


Table Designer

Use the Table Designer to create and modify database tables, free tables, fields, and indexes. The Table Designer helps you implement advanced features, such as validation rules, default values, and default control classes.

In This Section

Fields Tab, Table Designer
Displays table fields in a scrollable grid.
Indexes Tab, Table Designer
Contains a scrollable grid for defining indexes.
Table Tab, Table Designer
Displays the information about the table and makes it possible for you to specify triggers and record-level rules.

Related Sections

Designers
Designers make it possible for you to design the windows, dialog boxes, and components in your application visually.
Class Designer
Use the Class designer to create and modify classes visually.
Connection Designer
Use the Connection designer to create and modify named connections. Because connections are stored as part of a database, you only can use the Connection designer if you have a database open.
Data Environment Designer
Use the Data Environment designer to create and modify the data environment of forms, form sets, and reports visually.
Database Designer
The Database designer displays all the tables, views, and relationships contained in a database.
Form Designer
Use the Form designer to create and modify forms and form sets visually. A form set consists of one or more forms that can be manipulated as a unit.
Label Designer
Use the Label designer to create and modify labels. When the Label designer window is active, Microsoft® Visual FoxPro® displays the Report menu and the Report Controls toolbar.
Menu and Shortcut Designers
Use the Menu designer and the Shortcut designer to create menus, menu items, submenus of menu items, lines that separate groups of related menu items, and so on.
Query and View Designers
Use the Query designer and the View designer to create and modify queries and views. When the Query or View designer is active, Microsoft® Visual FoxPro® displays the Query menu and the Query toolbar or View designer toolbar.
Report Designer
Use the Report designer to create and modify reports. When the Report designer window is active, Microsoft® Visual FoxPro® displays the Report menu and the Report Controls toolbar.


Fields Tab, Table Designer

The Fields tab displays slightly different information depending on whether you open a database table or a free table. If you are creating a database table, the Fields tab includes options for setting validation rules. If you are creating a free table, the Fields tab contains only basic field name, type, and formatting options.

The Fields tab displays table fields in a scrollable grid. Each row contains the field's name, data type, character width, decimal width, and support for null values. Click a cell in the grid to modify a field.

Mover Button
This is the double-headed arrow button at the extreme left of the row. Once you have entered two or more rows, use the mover button to move a row up or down in the list.
Name
Specifies the name of the field. Spaces are not accepted. For database tables, the length of the name can be up to 128 characters. For more information, see Visual FoxPro Name Creation.
Type
Specifies the field's data type. Click the drop-down arrow to select a data type from the list.
Width
Specifies the number of characters or digits the field can store.
Decimal
Specifies the number of digits to the right of the decimal point. The Decimal column applies to numeric and double data types.
Index
Specifies a regular index on the field for ordering the data.
NULL
When checked, specifies that the field can accept a null value.
Insert Button
Inserts a new field above the selected field.
Delete Button
Deletes the selected field from the table.
Display
Specifies the format properties for entering and displaying the field.

Format Specifies the expression for case, size, and style for display of the field in the Browse window, forms, or reports. Property settings within the form and report can override this expression.

Input mask Specifies the format for values as they are entered into the field. For example, telephone numbers might have a format of (999) 999-9999.

Caption Specifies the label that appears for the field in the Browse window, forms, or reports. Property settings within the form or report can override this setting. To specify an expression for a field caption, include an equal sign (=) preceding the caption string. Expressions cannot exceed 254 characters. If the expression exceeds 254 characters, the caption defaults to the field name.

Note Support for using expressions as field captions should be used only with DBC tables in applications running on Visual FoxPro 8.0 or later. In earlier versions, the expression appears as a string literal.
Field validation
If you are modifying a database table, the Field Properties option group appears below the scrollable grid.

Properties settings for the selected field are specified in this area. Choose the dialog button to the right of each property setting to display the Expression Builder Dialog Box, or just type the expression directly. Entries for these options are not required.

Rule Specifies the field-level rule for enforcing data validation.

Message Specifies the error message to be displayed if an entry violates the field-level validation rule.

Default value Specifies the default value for the field.

Map field type to classes
To specify a default control class, set the library and class you want to create when you drag the field onto a form.

Display library Specifies the path and file name for the class library. To browse for a file, use the dialog button.

Display class Specifies the default control class for the field.

AutoIncrement
To set the start and increment values after enabling autoincrementing for a field, select values from the Next Value and Step spin boxes. For more information about autoincrementing, see Autoincrementing Field Values in Tables.

Next Value Specifies the start value for a field using autoincrementing. You can select a positive or a negative integer value from 2,147,483,647 to -2,147,483,647. The default value is 1.

Step Specifies the increment value for a field using autoincrementing. You can select a positive, nonzero integer value from 1 to 255. The default value is 1.

Field comment
Provides a space to enter notes about the field.

See Also

Expression Builder Dialog Box | Indexes Tab, Table Designer | Table Wizard | Visual FoxPro Name Creation | Table Designer


Indexes Tab, Table Designer

The Indexes tab appears in the Table Designer. It contains a scrollable grid for defining indexes. The grid has four columns.

Mover button
This is the double-headed arrow button at the extreme left of the row. Once you have entered two or more rows, use the mover button to move a row up or down in the list.
Order
Specifies the sort order for the index. An up arrow indicates an ascending sort; a down arrow, descending.
Name
Specifies the index tag name for the index. The arrow button to the left of the index name specifies ascending or descending order. Select the index, and then click on the arrow button to change the order.
Type
Specifies the type of index: Primary (only if the table is contained in a database), Candidate, or Regular (the default). When you click a cell in this column, a list appears from which you can select a type. An entry is not required in this field.

Only one index in a table can be set as Primary in the Type column.

Note If a table contains a unique index tag, the Table Designer will list that type, but the designer no longer provides this tag option.
Expression
Specifies the index expression, such as a field name. Click the button to create or edit an expression in the Expression Builder Dialog Box. An expression can be up to 240 characters.
Filter
Specifies the filter expression. Click the button to create or edit an expression in the Expression Builder dialog box.
Collate
Specifies a collating sequence for the index tag. Click the arrow to select a Visual FoxPro collating sequence from the drop-down list. The default setting is "Machine".
Insert Button
Inserts a new index above the selected index in the grid.
Delete button
Deletes the selected index from the grid.

See Also

Expression Builder Dialog Box | FOR( ) Function | INDEX Command | SYS(14) - Index Expression | SYS(2021) - Filtered Index Expression | Table Designer | Table Tab, Table Designer | Table Wizard


Table Tab, Table Designer

The Table tab appears in the Table Designer. It contains read-only information about the table and areas for setting the record-level rule and validation error text, triggers, and comments.

Note If you are modifying a free table, only the read-only statistics for the table are displayed on this tab. Free tables cannot have associated rules, triggers, or comments.
Name
Specifies the name of the table being created or modified.

For database tables, the table name appears in the Project Manager; it is not the file name. Long names up to 128 characters are supported.

Database
Displays the name of the database to which the table belongs if the table is not a free table. This box is read-only.

Statistics

Displays read-only about the table.

Table file
Displays the path and file name for the table.
Records
Displays the quantity of rows currently stored in the table.
Fields
Displays the quantity of columns defined in the table structure.
Length
Displays the length of the table.

Record Validation

Sets the row-level rule, validation error text, and a comment for the table. The button to the right of each setting displays the Expression Builder Dialog Box.

Validation Rule
Specifies a record-level rule for enforcing data validation.
Validation Text
Specifies the error message to be displayed if an entry fails to conform to the record-level validation rule.

Triggers

Specifies rules for updates, inserts, and deletes.

INSERT Trigger
Specifies a rule to be triggered every time a record is inserted or appended to the table. Click the dialog button to display the Expression Builder Dialog Box.
UPDATE Trigger
Specifies a rule to be triggered every time a record is updated in the table. Click the dialog button to display the Expression Builder Dialog Box.
DELETE Trigger
Specifies a rule to be triggered every time a record is deleted from the table. Click the dialog button to display the Expression Builder Dialog Box.
Table Comment
Provides space for you to type a comment about the table. Whatever you type here appears as the description at the bottom of the Project Manager when this table is selected.

See Also

Expression Builder Dialog Box | FOR( ) Function | INDEX Command | SYS(14) - Index Expression | SYS(2021) - Filtered Index Expression | Table Tab, Table Designer | Table Wizard | Table Designer


Dialog Boxes

This section explains the options that appear on various dialog boxes.

In This Section

About Microsoft Visual FoxPro Dialog Box
Displays the Visual FoxPro copyright, licensing, and version information, as well as your product identification number.
Add Files to Source Control Dialog Box
Adds a file or selected files in your project to source code control.
Add Table or View Dialog Box
Allows you to select one or more existing tables or views on which to base your new query or local view.
Advanced Options Dialog Box
Makes it possible for you to fine-tune how records are retrieved in a view or how updates are made to the server or source tables.
Append From Dialog Box
Makes it possible for you to add records to the current table or view from another table, a spreadsheet, or text file.
Append From Options Dialog Box
Specifies fields to append and allows you to build an expression that must be met by records that are to be appended.
Arrange Tables and Views Dialog Box
Allows you to change the layout of tables and views in your database.
Beautify Options Dialog Box
Makes it possible for you to specify capitalization and indentation styles for editing window text.
Breakpoints Dialog Box
Allows you to specify options for breakpoints.
Build Options Dialog Box
Allows you to create a custom application or refresh an existing project.
Calculate Field Dialog Box
Makes it possible for you to select a mathematical operation to create a computed field.
Change Icon Dialog Box
Specifies an icon to be used for a linked or embedded object on a form or in a General field of a table.
Check In Files Dialog Box
Checks in changes made in your development environment working directory to your source code control database.
Check Out Files Dialog Box
Checks out a copy of the selected files from your source code control provider and places a writable copy in the corresponding development environment working directory.
Choose Field/Variable Dialog Box
Specifies a table field or variable.
Class Info Dialog Box
Shows various attributes of class members, their design-time appearance, and whether or not they are protected.
Code Page Dialog Box
Allows you to assign a code page to a .dbf file or text file that does not have one.
Column Footer Dialog Box
Sets height and other options for the Column Footer band in a label or multiple-column report.
Column Header Dialog Box
Sets height and other options for the Column Header band in a label or multiple-column report.
Comment Dialog Box
Allows you to enter notes or comments to identify the query or view and its purpose.
Compile Dialog Box
Allows you to compile program, menu, or query files.
Connections Dialog Box
Allows you to create and maintain database connections.
Coverage Dialog Box
Makes it possible for you to specify options for logging program execution.
Create Dialog Box
Allows you to specify the directory, name, and type of the new file.
Create One-To-Many Relationships Dialog Box
Establishes a one-to-many relationship, in which the child table can contain multiple records that correspond to one record in the parent table.
Data Grouping Dialog Box
Makes it possible for you to create group bands for separating groups of records visually, and displaying summary data for each group.
Database Properties Dialog Box
Allows you to choose the types of database objects that are displayed in the Database Designer.
Define Window Layout Dialog Box
Allows you to name and save window and toolbar configurations for reuse.
Delete (Records) Dialog Box
Makes it possible to mark records for deletion.
Description Dialog Box
Provides a text box where you can type a brief description identifying a file.
Detail Dialog Box
Sets height and other options for the Detail band in a report or label.
Do Dialog Box
Allows you to specify a program or form file to run.
Edit Bands Dialog Box
Displays a list of available bands so you can directly modify height, as well as entry and exit actions.
Edit Links Dialog Box
Makes it possible for you to change or break an object link.
Edit Properties Dialog Box
Allows you to set editing options for the current editing window or set color and font options for all editing sessions.
Edit Property/Method Dialog Box
Allows you to add new properties and methods or edit existing ones.
Edit Relationship Dialog Box
Allows you to alter a persistent relationship between tables.
Event Tracking Dialog Box
Makes it possible for you to see when each event occurs in relation to other events.
EXE Version Dialog Box
Displays information about the build number as well as other information that you supply.
Execution Throttle Dialog Box
Makes it possible for you to specify the delay in seconds between the execution of each line of code located in the Trace Window.
Export Dialog Box
Allows you to export data from Visual FoxPro tables to a text file, spreadsheet, or common table format.
Export Options Dialog Box
Specifies which records and fields to export.
Expression Builder Dialog Box
Makes it possible for you to create and edit expressions. An expression can be as simple as a field name or as complex as a calculation involving immediate IF functions, concatenations, and data type conversions.
Expression Builder Options Dialog Box
Sets preferences for the items displayed in the Expression Builder.
File Finder Dialog Box
Enables searches based on specified criteria.
Find Dialog Box
Makes it possible to search for text.
Find Table or View Dialog Box
Allows you to select a table or views you cannot locate in the database schema displayed in the Database Designer.
Font Dialog Box
Controls the type, style, and size of fonts in a text file, field, or label control in a report, label, or in the Command window.
Format (Field) Dialog Box
Specifies the value of an expression in a field control.
General Options Dialog Box
Allows you to specify code for an entire menu system.
Generate Menu Dialog Box
Lets you specify a name for the generated menu program and then generate the program.
Get Latest Version of Files Dialog Box
Gets the latest files from the source code control provider and places a local copy in the Project Manager.
Go To Line Dialog Box
Makes it possible for you to move the insertion point to the designated line in a text or program file or in the Command window.
Go To Record Dialog Box
Specifies which record to move the record pointer to.
Group Footer Dialog Box
Sets height options and band expressions for the Group Footer band in a report or label.
Group Header Dialog Box
Sets height options and band expressions for the Group Header band in a report or label.
Having Dialog Box
Specifies the conditions for selecting the groups of records to include in query output.
Import Dialog Box
Allows you to import data to a table from a spreadsheet or another table format.
Include File Dialog Box
Allows you to specify an include file containing predefined compile-time constants for a user-defined class, form, or form set.
Insert Object Dialog Box
Lists the OLE objects you can link or embed in your application for forms or General fields in tables.
Insert Object Reference Dialog Box
Makes it possible for you to see the name of all objects in the designer and insert a fully qualified reference to the object in your code.
Insert System Menu Bar Dialog Box
Allows you to add menus and menu options to the Menu Designer window.
Join Condition Dialog Box
Specifies a join condition between tables.
Locate Database Dialog Box
Makes it possible for you to locate or ignore a missing table or view.
Locate File Dialog Box
Makes it possible for you to locate or ignore a missing file or group of files.
Locate Record Dialog Box
Searches for a record in the active table or view that matches specified conditions.
Look Up Reference Dialog Box
Makes it possible for you to search for and replace code references or text in your projects or folders.
Look Up Reference Dialog Box, Options Dialog Box
Sets additional options for a code reference search.
Macros Dialog Box
Makes it possible for you to define key combinations using the CTRL key, ALT key, or function keys to perform a series of keystrokes.
Menu Options Dialog Box
Allows you to specify code for a specific menu.
More Windows Dialog Box
Displays a list of active windows from which you can choose.
Move Item Dialog Box
Makes it possible for you to change the location of a menu or menu item.
New Class Dialog Box
Specifies information for a new class, which is then used by the Class Designer.
New Dialog Box
Allows you to create new files using designers and wizards.
New File Dialog Box
Lets you create a new form, report, label, or query, depending on the type of file currently selected in the Project Designer.
New Label Dialog Box
Displays predefined Avery label types.
New Local View Dialog Box
Lets you create a view of local tables or other views in a database using either the Local View wizard or View designer.
New Method Dialog Box
Allows you to create a new method and specify the description and visibility of the method.
New Property Dialog Box
Allows you to create a new property and specify the description and visibility of the property.
New Remote View Dialog Box
Allows you to create a new remote view using the View designer or the Remote View wizard.
New Table Dialog Box
Allows you to create a new table in the database using the Table designer or the Table wizard.
Open Dialog Box
Allows you to open an existing file or create a new file.
Open Picture Dialog Box
Allows you to open an existing graphics file.
Options Dialog Box
Makes it possible for you to set different categories of options.
Page Footer Dialog Box
Sets height and other options for the Page Footer band in a report or label.
Page Header Dialog Box
Sets height and other options for the Page Header band in a report or label.
Page Setup Dialog Box
Makes it possible for you to adjust column width and page layout for reports and labels.
Pane Customization Dialog Box
Used to create, modify, and delete panes in the Task Pane Manager.
Paste Special Dialog Box
Makes it possible for you to link or embed an OLE object from the Clipboard.
Print Dialog Box
Lets you print a text file, report, label, or the contents of the Command window or the Clipboard.
Print File Dialog Box
Allows you to search a drive or directory for a file to print.
Print Options Dialog Box
Lets you print a text file, report, label, or the contents of the Command window or the Clipboard.
Print Setup Dialog Box
Allows you to select a printer, printer path, and paper setting.
Print When Dialog Box
Enables the conditional printing of an object based on the value of an expression and controls how objects print when bands are continued.
Project Information Dialog Box
Makes it possible for you to view and edit information about the project and its files.
Prompt Options Dialog Box
Lets you specify options for prompts in a customized menu system.
Query Destination Dialog Box
Makes it possible for you to send the results of your query to seven different outputs. This command is available only for queries.
Quick Report Dialog Box
Makes it possible for you to select fields and a field layout for a report.
Recall Records Dialog Box
Lets you unmark records that are marked for deletion.
Rectangle/Line Dialog Box
Specifies position and printing options for rectangle and line controls.
Remove Files from Source Control Dialog Box
Removes selected files in your project from source code control.
Rename File Dialog Box
Allows you to rename the selected file.
Replace Dialog Box
Makes it possible for you to search for and replace specified text in the current file.
Replace Field Dialog Box
Changes values stored in one record or in a range of records.
Report and Label Print Options Dialog Box
Allows you to specify how much to print and create expressions that the selected records must meet in order to print.
Report Designer Band Dialog Boxes
Include options for column, group, and page headers and footers, titles, and so on.
Report Expression Dialog Box
Defines the contents of a field control in a report.
Report Picture Dialog Box
Makes it possible for you to include bitmaps, icons, or other information from a General table field in your report or label.
Report Variables Dialog Box
Makes it possible for you to create variables within a report.
Round Rectangle Dialog Box
Specifies the exact shape, position, and printing options for round rectangle controls.
Save As Class Dialog Box
Lets you save a form, or selected controls on a form, as a class definition.
Save As Dialog Box
Saves a new file or saves an existing file with a different name.
Save As HTML Dialog Box
Enables you to create a new HTML version of the current form, menu, report, or table.
Scope Dialog Box
Specifies the records that Visual FoxPro acts on in the current table or view.
Select Connection or Data Source Dialog Box
Allows you to select a data source or an existing connection to a data source to create a new remote view.
Select Dialog Box
Makes it possible for you to select an XML Web service and insert code for it in a program or code editing window.
Set Grid Scale Dialog Box
Lets you define horizontal and vertical increments of the grid in pixels and specifies whether the ruler displays in system units or pixels.
Set Index Order Dialog Box
Sets the index order for a child table.
Spelling Dialog Box
Makes it possible for you to check spelling in a text file or memo field.
Summary Dialog Box
Sets height and other options for the Summary band in a report or label.
Tab Order Dialog Box
Adjusts the order in which objects are accessed in the form when you use the keyboard.
Task Pane Options Dialog Box
Customizes the Task Pane Manager and the individual panes that it contains.
Title Dialog Box
Sets height and other options in the Title band in a report or label.
Title/Summary Dialog Box
Makes it possible for you to specify whether a Title or Summary band is included in a report.
Toolbars Dialog Box
Makes it possible for you to create, edit, hide, and customize toolbars.
Undo Check Out of Files Dialog Box
Overwrites your changes to a file and copies the latest checked-in version to your development-environment working directory.
Update Project List Dialog Box
Displays the results of a project list update.
View Parameters Dialog Box
Sets up views that prompt for a value entry to complete the view.
Visual FoxPro Converter Dialog Box
Makes it possible for you to open files created in an earlier version of Visual FoxPro.
Visual FoxPro Transporter Dialog Box
Makes it possible to transport forms, labels, and reports across different Visual FoxPro platforms and versions.
Visual FoxPro XML Web Service Location Dialog Box
Specifies a local Uniform Resource Locator (URL) or virtual directory for publishing an XML Web service.
Visual FoxPro XML Web Services Publisher Dialog Box
Specifies information for publishing Visual FoxPro COM (.dll) Servers as XML Web services that can be accessed on the Web.
Visual FoxPro XML Web Services Registration Dialog Box
Specifies information for registering an XML Web service so you can use it in your applications.
Wizard Selection Dialog Box
Displays a list of wizards from which you can choose.
Work Area Properties Dialog Box
Makes it possible for you to modify the structure of a table, select index files and fields, and define data filters. This dialog box appears when you choose Properties from the Table Menu.
XML Web Service - Client Detail Dialog Box
Makes it possible for you to specify the control, or client, to which you want to bind the results of the XML Web service operation.
XML Web Service - Complex Types Dialog Box
Makes it possible for you to specify information for complex types such as table and field names for XML Web service operations that return ADO.NET DataSets or property names for a returned object.
XML Web Service - Operation Detail Dialog Box
Makes it possible for you to choose specific XML Web service operations, or methods, you want to call from your application. You can also specify parameter values for these operations.
XML Web Service - Parameter Values Dialog Box
Makes it possible for you to set parameter values or specify a control and its property as a parameter source for a selected XML Web service operation.
Zoom <property> Dialog Box
Displays the text value of the selected property.

Related Sections

User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.
Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
Utility Programs
Describes how these tools that are provided with Microsoft Visual FoxPro help speed the process of application development.


About Microsoft Visual FoxPro Dialog Box

Displays the Visual FoxPro copyright, licensing, and version information, as well as your product identification number.

To display this dialog box

  • From the Help menu, choose About Microsoft Visual FoxPro.
System Info
Displays the Microsoft System Information tool which contains your system configuration information. To access help information about Microsoft System Information, press F1 or, choose Help Topics from the Microsoft System Information Help menu.

See Also

SET HELP TO | HELP Command | HTML Help | WinHelp 4.0


Add Files to Source Control Dialog Box

Adds a file or selected files in your project to source code control.

Files to add
Lists all the files you can add to source control.
Keep Checked out
Updates the source code control database with your changes but keeps the file checked out to you.
Comment
Displays comment associated with a file, or allows you to add or change one.

See Also

Undo Check Out of Files Dialog Box | Remove Files from Source Control Dialog Box | Compiling Source Code


Add Table or View Dialog Box

Appears when you select Query or Local View in the New dialog box and then choose New File. In this dialog box, you select one or more existing tables or views on which to base your new query or local view.

Database
Displays the current database by default and lets you select another database.
Tables/Views in database
Displays the tables or views from the current database, depending on whether you select the Tables or Views option.
Alias
Specify an alias instead of the automatically generated alias to use for the table or view you select.
Add
Adds the table or view.
Other
Displays the Open dialog box, from which you can select a free table to add to the query.
Tables
Displays the tables from the current database in the Tables in database box.
Views
Displays the views from the current database in the Views in database box.

See Also

Add Table or View Dialog Box | Join Condition Dialog Box | Arrange Tables and Views Dialog Box | Querying Multiple Tables and Views | New Dialog Box | Open Dialog Box


Advanced Options Dialog Box

Makes it possible for you to fine-tune how records are retrieved in a view or how updates are made to the server or source tables. This command is available with views only.

Connection Information

Connection Name/Datasource
Displays the name of the connection or data source being used to access the data in the view.
Share Connection
Specifies that Visual FoxPro is to use the same connection for new views you create. This option applies only to remote (ODBC) data. If you currently have a connection set up, you can set this option to Uses Current Connection for new views.

Data Fetching

Number of Records to Fetch at a Time
Controls how many records are returned at a time from the ODBC server or remote data source. For example, if you run a query that returns 1000 records, and you set this option to 100, the first 100 records will be displayed when you run the view, and the remaining records will be fetched in blocks of 100 as you continue to browse the results. Clicking All sets this value to –1, indicating that all records should be returned in the first fetch operation.
Maximum Number of Records to Fetch
Limits total number of records returned by a view. Clicking All sets this value to indicate that all records should be returned.
Use Memo When Character Field Length >=
Determines when long character fields should be converted to Memo fields in the output of your view.

Performance

Number of Records to Batch Update
Specifies number of records to update with a single command. For more information, see the REPLACE command and Scope Clauses.
Fetch Memo
Fetches Memo fields from the data source only when a memo field is activated in the view output.
Include Memo Fields in WHERE Clause
Specifies that when Visual FoxPro compares a record held locally to one on the server, it check for changes; memo fields should be included in this comparison. Some data sources don't support this option; in this case, including a memo field can cause the server to report changes, even if the records are the same.
Precompile SQL on Back-end Server
Specifies that Visual FoxPro pass the SQL query to the server to be compiled before being executed. If the server supports this option, queries can be executed substantially faster than if they are not compiled.

See Also

View Parameters Dialog Box | Comment Dialog Box | Query and View Designers | REPLACE Command | Scope Clauses | Query Destination Dialog Box


Append From Dialog Box

Lets you add records to the current table or view from another table, a spreadsheet, or text file. This dialog displays when you select Append Records from the Table menu.

Type
Specifies the file type from which to append records.
From
Provides space for you to type the name of the file from which to append records. If you do not know the name, choose the dialog button to display the OpenDialog Box and select the desired file.
To
Displays the path and file name of the table or view to which the records will be appended.
Options
Displays the Append From Options Dialog Box, in which you specify fields to append, and build an expression, which records to be appended must meet.

For more information, see The Process of Appending Data in Importing and Exporting Data.

See Also

Append From Options Dialog Box | APPEND FROM Command | Browse Window | Open Dialog Box | Adding Records | APPEND Command


Append From Options Dialog Box

Specifies fields to append and allows you to build an expression that must be met by records to be appended. This dialog box appears when you choose Options in the Append From Dialog Box.

Criteria

Fields
Displays the Field Picker Dialog Box, where you select fields to append.
For
Displays the Expression Builder Dialog Box, where you create a For expression that every record must meet to be appended.

See Also

Append From Dialog Box | Expression Builder Dialog Box | Field Picker Dialog Box | Delete (Records) Dialog Box | APPEND FROM Command | APPEND Command


Arrange Tables and Views Dialog Box

This dialog box allows you to change the layout of tables and views in your database. Use it to arrange, align, or resize the tables and views in your database layout.

This dialog box appears when you select Arrange from the Database menu.

Arrange

These options allow you to order the contents of the database layout.

By Name
Orders the tables and views by name.
By Type
Orders the tables together and the views together.

Align Objects

These options allow you to position the contents of the database layout in a line.

Vertically
Positions the objects in a line vertically in the Database Designer window.
Horizontally
Positions the objects in a line horizontally in the Database Designer window.
Resize objects to default height and width
By default, the objects in the database show five of the fields. If you changed the size of the objects to view more of the contents of the object, you can return to the default size.

See Also

Connections Dialog Box | Database Properties Dialog Box | Adding Tables to a Database | Updating Multiple Tables in a View | New Local View Dialog Box | Find Table or View Dialog Box | Database Designer


Beautify Options Dialog Box

Makes it possible for you to specify capitalization and indentation styles for program code appearing in an editing window. When a program file is open in the editing window, selecting the Beautify command from the Tools menu opens the Beautify Options dialog box.

Capitalization

Keywords
Provides ways to format keywords: UPPERCASE, lowercase, Mixed Case, or No change
Symbols
Provides ways to represent symbols: UPPERCASE, lowercase, Match with first occurrence, or No change.

Match with first occurrence only affects the symbols available within the current editing window.

Indentation

Types of indent
Provides ways to indent text using Tabs, Spaces, or No Change.

When selecting Spaces, type or select the number of spaces used to indent the text.

Text to indent
Makes it possible for you to specify what types of text should be indented.

Comment Indents all text lines beginning with the comment identifier (*).

Continuation lines Indents lines following the semicolon (;), which indicates the first line continuation mark. The indentation for Continuation lines continues at the same level until a new command line is entered.

Extra indent beneath
Provides extra indentation for the lines following the beginning of procedures and DO CASE control structures.

See Also

Editing Window | _BEAUTIFY System Variable | Macros Dialog Box


Breakpoints Dialog Box

Makes it possible for you to specify options for breakpoints.

This dialog box appears when you choose Breakpoints from the Tools Menu, Debugger Window.

Type
The type of breakpoint. Choose one of the following settings:
Setting | Description
Break at location | Stops execution at a line of code.
Break at location if expression is true | Stops execution at a line of code when an expression becomes true.
Break when expression is true | Stops execution when an expression becomes true.
Break when expression has changed | Stops execution when the value of an expression changes.
Location
Where to suspend execution. The location can be a program, a procedure, or a specific method or event. You can suspend program execution at a particular line in the location by including the line number after the location and a comma.
Tip To display line numbers in the Trace Window, choose Show line numbers in the Debug Tab, Options Dialog Box.
File
The file that the location is in. The file can be a program, form, or class file. If you don't specify a file name, the breakpoint is evaluated for any method or procedure with the same name as the method or procedure in the Location box.
Pass Count
Number of times the line of code in the Location box must execute before program execution suspends.
Tip Use Pass Count with loops that encounter problems only after a certain number of iterations.
Expression
Any valid Visual FoxPro expression. When you choose Break when expression is true or Break at location if expression is true from the Type list, specify the expression here.
Breakpoints
Lists all breakpoints you have added. Enabled breakpoints are marked with a check and are toggled with the Enable and Disable buttons.

All breakpoints listed in the Breakpoints list are saved to a debug configuration file when you choose Save Configuration from the File menu in the Debugger window.

Add
Adds the breakpoint specified by the Type, Location, File, Pass Count, and Expression boxes to the Breakpoints list. Only added breakpoints are saved when you exit the dialog box.
Remove
Removes the selected breakpoint from the Breakpoints list.
Disable
Clears the check mark beside the selected breakpoint in the Breakpoints list. When you disable a breakpoint, program execution is not suspended at the location or condition specified by the breakpoint.
Enable
Sets the check mark beside the selected breakpoint in the Breakpoints list and activates the breakpoint.
Clear All
Removes all the breakpoints from the Breakpoints list.
Display Breakpoint Messages
Makes it possible for you to toggle whether breakpoint message boxes display when a breakpoint is encountered. Breakpoint messages do not display when the break at location breakpoint is encountered.

See Also

Debug Tab, Options Dialog Box | Trace Window | Debugger Window | Debugger Keyboard Shortcuts and Menus


Build Options Dialog Box

Lets you create a custom application or refresh an existing project.

This dialog box appears when you select Build from the Project Menu.

Action

Rebuild Project
Creates and builds a project file. This option corresponds to the BUILD PROJECT command.
Application (.app)
Builds the project, compiles files that are out of date, and creates a single .app file. This option corresponds to the BUILD APP command.
Win32 executable / COM Server (.exe)
Creates an executable file from a project. This option corresponds to the BUILD EXE command.
Single-threaded COM server (.dll)
Creates a dynamic-link library with a .dll file name extension using class information from the project file. This option corresponds to the BUILD DLL command that points to the vfp8r.dll run-time library.
Multi-threaded COM server (.dll)
Creates a multithreaded dynamic-link library (DLL) with a .dll file name extension using class information from a project file. This option corresponds to the BUILD MTDLL command that points to the vfp8t.dll. run-time library.

Options

Recompile All Files
Recompiles all files in the project and creates an object file for each source file.
Display Errors
Displays compile-time errors in an editing window after the build is complete.
Run After Build
Allows you to specify if you want the application to run after it has been built.
Regenerate Automation server IDs
Installs and registers Automation servers contained in the project. When marked, this option specifies that new GUIDs (Globally Unique Identifiers) are generated when you build a program. Only those classes marked OLE Public in the Class Info dialog box of the Class menu will be created and registered. This option is enabled when you have marked Build OLE DLL or Build Executable and have already built a program containing the OLEPublic keyword.
Version
Displays the EXE Version dialog box, which allows you to specify information for the version number and the type of version. This button is enabled when you select Build Executable or Build OLE DLL in the Build Options dialog box.

See Also

BUILD APP Command | BUILD EXE Command | BUILD PROJECT Command | Editing Window | Project Manager | Project Information Dialog Box | BUILD DLL Command | BUILD MTDLL Command | Class Info Dialog Box | EXE Version Dialog Box


Calculate Field Dialog Box

Makes it possible for you to select a mathematical operation to create a computed field. This dialog box is displayed when you choose Calculations in the Report Expression dialog box.

Reset
Makes it possible for you to specify the point at which the expression is reset to its initial value. By default, End of Report is displayed in the list box. You can also select End of Page or End of Column. If you have specified groups in a report in the Data Grouping dialog box, the Reset box displays an item for each group in the report.

Calculate

These options make it possible for you to specify a calculation performed on the report expression.

Nothing
Specifies that no calculations be made on this expression. (Default)
Count
Counts the number of times a variable is printed per group, page, column, or report (depending on your selection in the Reset list). The calculation is based on the number of times the variable occurs, not on the variable's value.
Sum
Computes the additive sum of the expression's values. This option keeps a running total of the expression values for a group, page, column, or report (depending on your selection in the Reset box).
Average
Computes the arithmetic mean (average) of the expression values within a group, page, column, or report (depending on your selection in the Reset box).
Lowest
Displays the lowest value that occurred in that expression for a group, page, column, or report (depending on your selection in the Reset list). Initially sets the expression's value equal to the value of the first record. When a lower value is encountered, the variable's value changes accordingly.
Highest
Displays the highest value that occurred in that expression for a group, page, column, or report (depending on your selection in the Reset box). Initially sets the expression's value equal to the value of the first record. When a higher value is encountered, the expression's value changes accordingly.
Standard deviation
Returns the square root of the variance for the expression values within a group, page, column, or report (depending on your selection in the Reset box).
Variance
Measures the degree to which individual field values vary from the average of all the values in the group, page, column, or report (depending on your selection in the Reset box).

See Also

Data Grouping Dialog Box | Report Designer | Report Expression Dialog Box | Report Designer Band Dialog Boxes


Change Icon Dialog Box

This dialog box specifies an icon to be used for a linked or embedded object on a form or in a General field of a Visual FoxPro table. This dialog box is displayed when you select Display as Icon in the Insert Object dialog box or the Paste Special dialog box and choose Change Icon.

Icon
Current Specifies that the current icon be used.

Default Specifies that the default icon be used.

From File Specifies the file from which the new icon is to be obtained. Type the path and file name in the box, and then click OK to show all available icons. Scroll through the icons, select the icon you want to use, and then click OK.

Label
Specifies the label that will be displayed beneath the icon. Type the desired label in the box.
Browse
Displays the Browse dialog box so you can select a file containing the icon you want.

See Also

Insert Object Dialog Box | Edit Links Dialog Box | General Field Window | Editing OLE Objects in Forms and Tables | Icon Property | Paste Special Dialog Box | Paste Special Dialog Box


Check In Files Dialog Box

Checks in changes made in your development-environment working directory to your source code control database.

Files To Be Checked In
Lists the files available for check in. Click the files you want to check in, or click Select All to select all the files listed.
Comment
Type an optional comment.
Keep Checked Out
Updates the source code control database with your changes but keeps the file checked out to you.

See Also

Get Latest Version of Files Dialog Box | Check Out Files Dialog Box | Compiling Source Code


Check Out Files Dialog Box

Checks out a copy of the selected files from your source code control provider and places a writable copy in the corresponding development-environment working directory.

Files to be Checked Out
Lists the files available for check out. Click the files you want to check out, or click Select All to select all files listed.
Comment
Type a brief description of the reason for the check out.
Select All
Selects all files listed.
Advanced
Displays the source code control provider's Advanced Check Out Options dialog box.

See Also

Check In Files Dialog Box | Undo Check Out of Files Dialog Box | Compiling Source Code


Choose Field/Variable Dialog Box

Specifies a table field or variable.

Choose a Field or Variable
Enter the desired field or variable.
Fields
Displays fields in the table specified in the Field box of the Report Picture dialog box. Double-click the desired field to move the field to the Choose a Field or Variable box.
Variables
Displays available variables. Double-click the desired variable to move it to the Choose a Field or Variable text box.
Comment
Makes it possible for you to add comments. Comments are entirely for your reference and do not appear in the printed report or label.

See Also

Report Picture Dialog Box | Table Field Naming Conventions | Access to Visual FoxPro Variables and Fields | Variables | Round Rectangle Dialog Box


Class Info Dialog Box

This dialog box shows various attributes of class members, their design-time appearance, and whether or not they are protected.

The options are grouped onto the following tabs.

Tab | Description
ClassTab | General information about the class and its associated icons.
MembersTab | Information about individual members of the class.

See Also

Class Tab, Class Info Dialog Box | Members Tab, Class Info Dialog Box | Protection and Hiding of Class Members | Specifying Design-Time Appearance


Class Tab, Class Info Dialog Box

Gives general information about the class and its associated icons. The dialog box that contains this tab appears when you choose Class Info from the Class menu.

Toolbar Icon
Displays the name of the class toolbar icon. Choose the dialog button to select an icon for the class.

The class toolbar icon is displayed in the Form Controls toolbar in the Form Designer, and in the Class Designer when you populate the Form Controls toolbar with the classes in your class library. The class toolbar icon also appears in the Project container when the class is part of a project.

Container Icon
Displays the name of the class container toolbar icon. Choose the dialog button to select an icon for the class container.

The container icon is displayed only in the Class Browser window.

OLE Public
Specifies that when a program containing the OLEPublic keyword is built through the Project Manager, a custom Automation server is generated. A Globally Unique Identifier, or GUID, is also generated for the program.
Description
Displays comments about the selected class. You can type a new description in the box or edit an existing one.
Class Name
Displays the name of the class selected in the Class Designer.
Parent Class
Displays name of parent class.
Class Library
Displays path and file name of class library.

See Also

Class Info Dialog Box | Members Tab, Class Info Dialog Box | Class Browser Window | Class Designer | Form Designer | Project Manager Window


Members Tab, Class Info Dialog Box

Displays information about individual members of the class. The dialog box that contains this tab appears when you choose Class Info from the Class menu.

The Members tab consists of a list box with the following columns:

Class
Displays the class name.
Name
Displays the class property or method name. Access and Assign methods created for properties also appear in the Name column.
Visibility
Specifies whether the class member is protected, public, or hidden. If you select Protected from the Visibility drop-down list in the Edit Property/Method dialog box, access and changes to class properties are prevented from outside the class or subclass definition.
No Init
Specifies whether the Init method is executed when an object is added. When true (.T.), the Init method is not executed. This option only applies to subclasses of the class.
Modify
Opens the Edit Property/Method dialog box where you can edit an existing property or method.

See Also

Class Info Dialog Box | Class Tab, Class Info Dialog Box | Access and Assign Methods | Protection and Hiding of Class Members | Class Member Protection and Hiding | Edit Property/Method Dialog Box


Code Page Dialog Box

Allows you to assign a code page to a .dbf or text file that does not have one.

.Dbf and text files display properly only if they have the correct code pages. Visual FoxPro automatically assigns code pages to these files when you create them. However, .dbf and text files created in previous versions of FoxPro or in other products might not have code pages.

If you check Prompt for Code Page in the Data tab of the Options dialog box, Visual FoxPro prompts you to specify a code page when opening tables or text files that are not marked with a code page. You can also display the Code Page dialog box with the GETCP( ) function.

Platform
Refers to the type of operating system you are using. Your selection determines which code pages are displayed in the Code Page box.
  • All Displays code pages for all platforms.
  • Windows Displays only Windows code pages.
  • MS-DOS Displays only MS-DOS code pages.
  • Macintosh Displays only Macintosh code pages.
Code Page
Lists all the code pages for the selected platform.
Select
Designates the currently selected code page as the default.

See Also

Open Picture Dialog Box | Save As Dialog Box | Data Tab, Options Dialog Box | GETCP( ) Function | Open Dialog Box | Save As Dialog Box | Developing International Applications


Column Footer Dialog Box

Sets height and other options for the Column Footer band in a label or multiple-column report. This dialog box appears when you double-click the Column Footer band separator bar in the Report Designer.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before the contents of the column footer are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after the contents of the column footer are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Refining Page Layout | Report Layout Preparation


Column Header Dialog Box

Sets height and other options for the Column Header band in a label or multiple-column report. This dialog box appears when you double-click the Column Header band separator bar in the Report Designer.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before the contents of the column header are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after the contents of the column header are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Refining Page Layout | Report Layout Preparation


Comment Dialog Box

Allows you to enter notes or comments to identify the query or view and its purpose.

Add Comment
Allows you to type a comment or note about the query or view.

See Also

Query Destination Dialog Box | Advanced Options Dialog Box | Comment Property | Comments


Compile Dialog Box

Lets you compile program, menu, or query files.

Note If you have a program open in the Edit window, the Compile command compiles the current program without displaying any options.

This dialog box appears when you select Compile from the Program menu.

File Name
Specifies the file to compile. To compile, select the file name from the list and choose Compile, or double-click the file name. To choose multiple files, hold down the CTRL key while clicking file names.

The files displayed are those in the current directory that match the type specified in the List Files of Type box.

List Files Of Type
Lists the available file types. Program (.prg) is the default. If you have given your programs, forms, menus, or queries an extension different from the Visual FoxPro default, you can see them by choosing All Files.
Compile
Compiles the selected files.
Select All
Selects all file names in the File Name box for compiling.
Deselect All
Deselects all file names in the File Name box.
More
Expands the Compile dialog box so you can specify other options.

Options

Encrypt Compiled Files
Scrambles compiled files to protect your source code from being reconstructed by decompile programs.
Include Debugging Information
Specifies whether debugging information is included with the compiled file. If this is not checked, you cannot view program execution in the Trace window. Corresponds to the NODEBUG argument in the COMPILE command.
Compile Updated Files Only
Of the files selected, compiles only those that are new or have been updated since the last time they were compiled.

Error Location

ERR File
Stores error messages for each selected file in a separate file with the same base name as the original file. The .err file is stored in the same directory as the source file. If you uncheck this box, error messages for all selected files are stored together in a log file that you specify in the File box.
Append
Adds error messages for each selected file to an existing log file. This check box is enabled if you uncheck the .err File check box.
File
Stores error messages for all selected files in one log file. Type the log file name in the box, or choose the dialog button to find and specify an existing log file. This text box is enabled if you uncheck the .err File check box.

Location of Compiled Files

Directory
Specifies a path where compiled output files are stored. Type the path in the box, or choose the dialog button to find and specify a directory and file name.

See Also

COMPILE Command | Trace Window | Do Dialog Box | Testing and Debugging Applications | Compiling an Application


Connections Dialog Box

This dialog box allows you to create and maintain database connections. It appears when you select Connections from the Database menu.

Connections in <database>
Lists the connections associated with the database currently opened.
New
Opens the Connection designer, which allows you to create and modify named connections.
Modify
Opens the Connection designer, which allows you to modify the existing database connection.
Delete
Allows you to delete the connection from the database.

See Also

Connection Designer | Edit Relationship Dialog Box | Arrange Tables and Views Dialog Box | Managing Connections with SQL Pass-Through | Sharing Connections for Multiple Remote Views | Creating Databases | Database Designer


Coverage Dialog Box

Makes it possible for you to specify options for logging program execution. Use this dialog box to retrieve information on how many times each line of code was executed, which lines of code were not executed in your testing, and how long each line took to execute.

This dialog box appears when you choose Coverage Logging from the Tools Menu, Debugger Window.

File
Specifies the file to write the coverage log to. The dialog button displays the Open Dialog Box, which makes it possible for you to select a file to which to write the coverage log.
Append
Specifies that the coverage log is written after the current contents of an existing file, preserving the original contents.
Overwrite
Specifies that coverage log replaces the contents of the specified file.

See Also

Coverage Profiler Application | COVERAGE System Variable | Debugger Window | Debugger Keyboard Shortcuts and Menus | Open Dialog Box


Create Dialog Box

Appears when you select Project, Database, or Table in the New dialog box and then choose New File. Allows you to specify the directory, name, and type of the new file.

Code Page
Displays the Code Page dialog box so that you can specify the code page needed to view the file correctly. This command applies only to text files such as program (.prg), query (.qpr), and text (.txt) files.

See Also

New Dialog Box | Select Connection or Data Source Dialog Box | Code Page Dialog Box | Adding Files to a Project | Code Page Dialog Box | Wizards


Create One-To-Many Relationships Dialog Box

Establishes a one-to-many relationship, in which the child table can contain multiple records that correspond to one record in the parent table. Corresponds to the SET SKIP Command.

This dialog box appears when you choose the 1-To-Many button in the Data Session Window.

The 1-To-Many button is enabled when there is at least one relation originating from the selected table.

Child Aliases
Lists the child aliases of the parent alias, whose name is given at the top of the dialog box.
Selected Aliases
Lists aliases of all tables currently involved in a one-to-many relationship with the parent table.
Move
Copies the selected child aliases in the Child Aliases box to the Selected Aliases box. To enable this button, you must select an alias in the Child Aliases box.
All
Copies all the child aliases in the Child Aliases box to the Selected Aliases box.
Remove
Removes the selected aliases from the Selected Aliases box. To enable this button, you must select an alias in the Selected Aliases box.
Remove All
Removes all aliases from the Selected Aliases box.

See Also

Data Session Window | One-To-Many Form Wizard | SET RELATION Command | SET SKIP Command | Set Index Order Dialog Box | Table Creation


Customize Toolbox Dialog Box

Displays options to change settings for the Toolbox and to edit categories and items displayed in the Toolbox.

Selection Treeview
Displays the areas that you can modify and change settings for the Toolbox.

Options

Displays the general options for setting the Toolbox behavior.

Run associated builders
Specifies that builders are displayed automatically in the Forms Designer when you create a control that has a builder registered to it.
Display toolbox help text section
Specifies if the help text section in the Toolbox is displayed.
Show tooltips
Specifies whether ToolTips are displayed for category items.
Always on top
Specifies whether the Toolbox should appear in front of other windows.
Double-click to open an item
Specifies whether a hyperlink item in the Toolbox needs a double-click or a single-click to open it.
Set CurrentControl property when a control is dropped on a grid column
Specifies that Visual FoxPro should automatically change the value of the CurrentControl property when a control is dropped on a grid column from the Toolbox.
Prompt to remove Text1 control when dropping new control on a grid column
Specifies that Visual FoxPro should automatically remove the Text1 control from the grid column when a new control is dropped on a grid column from the Toolbox.
Allow toolbox to be minimized
Specifies if the Toolbox minimize control button should be displayed so that the Toolbox can be minimized.
Category scroll speed
Specifies the speed, in milliseconds, that a category will scroll when the mouse is over a scroll up or down widget in the Toolbox.
Toolbox table
Specifies the table for the Toolbox to save settings.
Font
Sets the font attributes used for the Toolbox.
Clean Up Toolbox
Removes deleted items from the Toobox table.
Restore to Default
Restores the Toolbox to its default state.

Class Items

Displays options for how classes are displayed and used from the Toolbox.

Default naming convention for classes added to Toolbox
Specifies the naming convention for how a class is displayed in the Toolbox.
Drag and drop text template
Specifies what text will be added when you drag and drop a class from the Toolbox.
CTRL+Drag and drop text template
Specifies the text to be added when you CTRL+Drag a class from the Toolbox.
Edit
Opens an editor, which has IntelliSense and color coding, to change the drag-and-drop or CTRL+Drag text.

Filters

Displays options for managing your filters for the Toolbox.

New Filter
Creates a new filter and selects it for editing.
Delete Filter
Prompts to delete the currently selected filter.
Apply Filter
Applies the currently selected filter to the Toolbox.
Clear Filter
Removes the effects of a filter from the Toolbox.
Filter Name
Specifies the name for the currently selected filter.
Update
Saves any changes made to the filter name that were made in the filter name field.
Defined Filters
Displays a list of filters that can be applied to the Toolbox.
Select toolbox categories that belong to this filter.
Displays a list of filter options that can be applied with a filter.

Categories

Displays options for managing the categories in the Toolbox.

Add Category
Displays a dialog box to add a new category to the Toolbox.
Remove Category
Prompts to delete the currently selected category.
Category Properties
Displays a dialog box that contains information on the properties for the currently selected category.
Refresh Category
Updates the Toolbox with any changes made to the currently selected category.
Refresh Toolbox
Updates the Toolbox with any changes made to all of the categories displayed in the Toolbox.
Select an item to view
Specifies the type of items that are shown in the item list for a specific category.
Show checked items only
Specifies that only items in the item list that are selected and show in the category are visible.
Add Item
Displays a dialog box used to add a new item to the currently selected category.
Remove Item
Prompts to remove an item from the currently selected category.
Item Properties
Displays a dialog box that contains information on the properties for the currently selected item.
Sort Alphabetically
Sorts the items in the item list to be displayed in alphabetical order.

See Also

Dialog Boxes | Toolbox


Data Grouping Dialog Box

Makes it possible for you to create group bands for separating groups of records visually, and displaying introductory and summary data for each group. These properties include printing text in headers and footers to identify specific groups, printing each group on a new page, and resetting page numbers when groups are printed on a new page.

Group Expressions

Displays group break expressions, such as a field name, for the current report and makes it possible for you to type new ones. If you want to build an expression, choose the dialog button to display the Expression Builder Dialog Box.

Group Properties

These options make it possible for you to specify options for page breaks.

Start Group On New Column
Starts a new column every time the group changes.
Start Each Group On a New Page
Starts a new page every time the group changes.
Reset Page Number to 1 for Each Group
Starts a new page and restarts page numbering every time the group changes.
Reprint Group Header On Each Page
Specifies that the group header follow the page header on all pages for the group when the group spans more than one page.
Start Group On New Page When Less Than
Sets the minimum distance from the page bottom that a group header is printed.
Insert
Inserts a blank text box in the Group Expressions box so you can define a new group expression.
Delete
Deletes the selected group expression from the Group Expressions box.

See Also

Title/Summary Dialog Box | Expression Builder Dialog Box | Report Variables Dialog Box | Adding Multiple Data Groupings | Data Grouping in Your Layout | Creating a Report Layout


Database Properties Dialog Box

This dialog box allows you to choose the type of database objects that are displayed in the Database designer. You can choose from tables, relations, local views, and remote views. You can also add a comment. Use this dialog box to show or hide database objects in your database schema.

This dialog box appears when you select Properties from the Database menu.

Event
Lists the available events.
Set Events On
Specifies whether DBC Events are enabled at design time and run time in the current Visual FoxPro session.
Events File
Enables you to specify an external file that contains DBC Event code.
Edit Code button
Opens the Visual FoxPro editor so you can add code to the currently selected DBC Event in the stored procedures file or in the specified external file.
Tables
Shows or hides the tables in the database schema.
Relations
Shows or hides the relationship lines between tables in the database schema.
Local Views
Shows or hides the views created on data stored in local tables.
Remote Views
Shows or hides the views created on data stored in a remote data source.
Comment
Provides space for you to type a comment about the database schema.

See Also

Connections Dialog Box | Arrange Tables and Views Dialog Box | Database Designer | New Local View Dialog Box | New Remote View Dialog Box | Edit Relationship Dialog Box | Find Table or View Dialog Box | Viewing and Setting Database Properties


Define Window Layout Dialog Box

Allows you to name and save window and toolbar configurations for reuse.

View Name
Specifies the name of the current window layout.
View
Lists the available window layouts.
Apply
Configures the current windows to the selected window layout.
Add
Adds the currently named layout to the list of available window layouts.
Delete
Deletes the currently select layout from the list of available window layouts.
Rename
Allows you to change the name of the current window layout.

See Also

General Options Dialog Box | DEFINE WINDOW Command | Configuring Visual FoxPro Toolbars | Menu Designer | Tab Order Dialog Box | Toolbars Dialog Box


Delete (Records) Dialog Box

Lets you mark records for deletion. Corresponds to the DELETE command.

This command does not physically delete records, but only marks them for deletion in the future. To permanently delete records from the hard disk, use Remove Deleted Records in the Table Menu.

Scope
Allows you to specify the records on which Visual FoxPro is to act. Choose Next, All, Record or Rest from the drop-down list. Choose a number from the spinner on the right when you select Next or Record from the Scope drop-down list.
For
Displays the Expression Builder Dialog Box, where you create the logical expression that every record must meet to be affected by the command. Every record in the table is tested using the For expression.
While
Displays the Expression Builder Dialog Box. The While expression specifies that the action affects records only as long as the logical expression is true. The first time the expression evaluates to false, the action ceases without considering remaining records.
Delete
Deletes records using the Scope, For, and While values.

See Also

DELETE Command | Expression Builder Dialog Box | Recall Records Dialog Box | Scope Dialog Box | Replace Field Dialog Box


Description Dialog Box

Provides a text box where you can type a brief description identifying a file. This dialog box appears when you select a file in the Project Manager and choose the Edit Description command on the Project menu.

Description
Displays the current description of a file, which can be replaced by typing a new description in the box.

See Also

Text Box Builder | Description Property | Modifying Class Icons and Descriptions | Rename File Dialog Box | New File Dialog Box


Detail Dialog Box

Sets height and other options for the Detail band in a report or label. This dialog box appears when you double-click the Detail band separator bar in the Report Designer.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before a record in the detail band is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after a record in the detail band is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Refining Page Layout | Creating Reports and Labels | Report Layout Preparation


Do Dialog Box

Lets you specify a program or form file to run.

This dialog box appears when you select Do from the Program menu.

Shortcut

CTRL+D

Do (text box)
Specifies the program or form file to run. To run the program or form, select a name from the list and choose Do, or double-click the file name.

The program files displayed are those in the current directory with the .app, .fxp, .mpr, .prg, .qpr, or .src extension that matches the type specified in the Files of Type box.

Do (button)
Sets the default folder to the one that contains the selected program or form and runs the program or form.

See Also

DO Command | Compiling an Application | Testing and Debugging Applications | DoCmd Method


Edit Bands Dialog Box

Displays a list of the available bands so you can directly modify height, and entry and exit actions. This dialog box appears when you click Bands on the Report menu or when you double-click a report band. The band editor provides the following options.

Height spinner
Enables you to modify the current height of the selected band.
Constant band height checkbox
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run expression

On entry edit box and expression builder
Lets you type an expression that will run when the cursor moves into the selected report band.
On exit edit box and expression builder
Lets you type an expression that will run when the cursor moves out of the selected report band.

See Also

Report Designer | expression builder | Report Designer Band Dialog Boxes | Changing a Group Band | Deleting a Group Band


Edit Links Dialog Box

This dialog box makes it possible for you to change or break an object link. This menu option is enabled when you open a general field that contains a linked OLE object you generated in a separate application.

Links
Displays the name and path of the linked file, the type of application, and the type of updating selected for the link.
Source
Displays the complete name and location of the object file selected in the Link box.
Type
Displays the object application or type of application to which the file selected in the Link box is linked.
Update
Specifies how you want to update information.
  • Select Automatic to have Visual FoxPro update the information whenever new information becomes available.
  • Select Manual to update the information only when you select a link and click Update Now.
Update Now
Updates the link selected in the Link box. If information has changed in the object document, the new information shows in your form or report.
Open Source
Opens the selected file in the object application for editing.
Change Source
Displays the Change Source dialog box, where you can specify a different object file for the selected link or change item information.
Break Link
Breaks the link selected in the Link box. This changes the object to a picture, which can no longer be edited by the OLE application that created it.

See Also

Edit Properties Dialog Box | General Field Window | Adding OLE Objects to Applications | Change Icon Dialog Box | Updating Table and Database Links | Dynamic Information Sharing


Edit Properties Dialog Box

This dialog box makes it possible for you to set editing options for the current editing window or set color and font options for all editing sessions.

This dialog box appears when you choose Properties from the shortcut menu of any editing window or when you click Properties on the Edit menu.

Behavior

The options in this area affect the current editing window only.

Drag-and-drop editing
Enables drag-and-drop text editing for manipulating text with the mouse.
Wordwrap
Wraps text lines within the window. Wordwrap is only available when the syntax coloring is set to OFF. For more information, see Editor Tab, Options Dialog Box.
Automatic indent
Automatically indents text according to the first line's indent. This does not affect how the text is saved.
Embedded hyperlinks
Makes it possible for you to specify whether hyperlinks can be included in the selected file type.

Appearance

Makes it possible for you to control the size, style, color and other text characteristics.

Alignment
Specifies left, center, or right alignment of text.
Font
Changes the font in the edit window. Click the ellipsis (...) button to open the Font dialog box.
Show line/column position
Enables the display of line number and column position in the status bar. The line number isn't displayed if wordwrap is enabled.
Syntax coloring
Toggles whether colors are shown for syntax elements. You can only select if wordwrap is set to OFF. For more information, see Editor Tab, Options Dialog Box.
Display white space
Specifies whether spaces, tabs, and paragraphs appear as characters in the currently active editor. This option is available when you work in the text editor. Paragraph markers (line feeds) appear only if the wordwrap option is enabled. To display white space, click View White Space on the Format menu.
Note The View White Space option is not supported on double-byte character set (DBCS) platforms.

Save Options

Makes it possible for you to manage characteristics of saved files. The available save options depend on the type of file you open.

Make backup copy
Specifies that Visual FoxPro create a backup copy each time you save a file. The backup copy is saved with the file name and a .bak extension in your Visual FoxPro Projects folder.
Save with line feeds
Saves the file with line feeds that have been entered into it. If this box is not selected, line feeds are removed when the file is saved. For more information, see AddLineFeeds Property.
Save with end-of-file marker
Places a CTRL+Z character at the end of a file when the file is saved. This extra character, when saved with the file, helps resolve the difference between normal editing activity and MODIFY MEMO activity. For more information, see MODIFY MEMO Command.
Compile before saving (Program editor)
Specifies that Visual FoxPro automatically compile the program and check for syntax errors when the file is saved.
Save preferences
Determines if the settings for an open file and all other windows of that same type are saved for the next time they are opened. If Save preferences is not selected, the preferences are only saved for the individual open window.
Apply to method code (Form or Class Designer)
Specifies the current settings as the default for all form or class methods.
Apply to menu code (Menu Designer)
Specifies the current settings as the default for all menu procedures.
Apply to .PRG or .TXT files (Program or text editor)
Specifies the current settings as the default for .prg or .txt files.
Apply to memos (Memo field editor)
Specifies the current settings as the default for memo fields.

Indentation

Makes it possible for you to specify the size and behavior of spaces and tabs.

Tab size
Specifies the width, in characters, of a tab for the currently selected file type. The range is 1 to 50. The default value is 4.
Indent size
Specifies the width, in characters, of a paragraph indent for the currently selected file type. If this is different from the tab size, extra tabs and/or spaces are used to create the specified value. The range is 1 to 50. The default value is 4.
Insert spaces
Specifies that spaces be inserted by the tab key for the currently selected file type. The default value is 4.
Keep tabs
Specifies that tabs be inserted by the tab key for the currently selected file type (default).

File Information (Program or text editor)

Makes it possible for you to specify the system characteristics of saved files.

File Name
Specifies the name and directory of the program or text file being edited.
Size
Specifies the size of the program or text file being edited.
Last Saved
The date and time the program or text file was last saved to disk.

See Also

MODIFY MEMO | Edit Links Dialog Box | Font Dialog Box | Change Icon Dialog Box | Viewing and Setting Database Properties | Edit Property/Method Dialog Box | EditorOptions Property |Setting Editor Options


Edit Property/Method Dialog Box

Allows you to add new properties and methods, or edit existing properties and methods. For forms and form sets, the property or method is scoped to the stand-alone form or form set, as applicable.

You can also create Access and Assign methods. An Access method allows you to execute code when the value of a property is queried. An Assign method allows you to execute code when you attempt to change the value of a property.

This dialog box appears when you select Edit Property/Method from the Class or Form menus.

Property/Method Information
Provides information about properties and methods added to a form, form set, or class. You can click on the heading of a column to sort the column in ascending or descending alphabetical order. The columns in this dialog are resizable by clicking and dragging between column headers.
Column | Description
Name | The name of each property and method.
Type | Property (P) or method (M).
Access | Indicates if a property has a corresponding Access method. Yes indicates the property has an Access method, No indicates the property doesn't have an Access method.
Assign | Indicates if a property has a corresponding Assign method. Yes indicates the property has an Assign method, No indicates the property doesn't have an Assign method.
Visibility Indicates the visibility of a property or method. For a form or form set, the visibility of properties and methods is always Public. For a class, the visibility can be Hidden, Protected, or Public.

Public properties and methods can be accessed from anywhere within an application. Protected properties and methods cannot be accessed by object instances, but can be accessed by subclasses. Hidden properties and methods cannot be accessed by either object instances or subclasses.

Note that in the Class Designer you can select multiple properties and methods so you can set the visibility to the same setting for all the selected properties and methods. All Public properties and methods appear in the type libraries created for in-process .dlls and out-of-process .exes; multiple selection allows you to set the visibility to Protected or Hidden so the selected properties and methods don't appear in the type libraries.
New Property
Displays the New Property dialog box, allowing you to create a new property.
New Method
Displays the New Method Dialog Box, allowing you to create a new method.
Remove
Removes the selected property or method.
Property/Method Name
Displays the name of the currently selected property or method.
Access Method
Specifies if a property has an Access method whose code is executed whenever the property is queried. Select this check box to create an Access method for a property. Clear the check box to remove an Access Method.
Assign Method
Specifies if a property has an Assign method whose code is executed whenever you attempt to change the value of the property. Select this check box to create an Assign method for a property. Clear the check box to remove an Assign Method.
Description
Contains the property or method description to be displayed at the bottom of the Properties Window in the Class Designer and, if the property is not protected, in the Form Designer.
Visibility (Classes Only)
Specifies whether the class is Public, Protected, or Hidden.
Apply
Applies changes made to a property or method.
Close
Closes the dialog box.

See Also

Access and Assign Methods | Class Designer | Form Designer | New Property Dialog Box | Properties Window | Adding Properties and Methods to a Form | New Method Dialog Box


Edit Relationship Dialog Box

After creating a persistent relationship between tables, use the Edit Relationship dialog box to alter the relation.

This dialog box appears when you select a relationship line in the Database designer and select Edit Relationship from the Database menu, or double-click the relationship line.

Table
Shows the name of the current parent table and allows you to select a different index tag.
Related Table
Shows the name of the current child table and allows you to select a different index tag.
Relationship Type
Shows the type of relationship between the parent and child tables.
Referential Integrity
Displays the Referential Integrity builder so you can set up rules to control how records are inserted, updated, or deleted in related tables.
Note If your tables are not already indexed, you need to open them in the Table designer and create indexes before you use the Referential Integrity builder.

See Also

Database Designer | Referential Integrity Builder | Table Designer | Connections Dialog Box | Find Table or View Dialog Box | Adding Tables to a Database | Creating One Index | Adding Tables to a Database | Creating Databases


Event Tracking Dialog Box

Makes it possible for you to see when each event occurs in relation to other events. Use this dialog box to determine the most efficient place to include your code.

This dialog box appears when you choose Event Tracking from the Tools Menu, Debugger Window.

Turn event tracking on
Toggles event tracking on or off.

When event tracking is enabled, every time a system event in the Events to track list occurs, the name of the event is displayed in the Debug Output window or written to a file.

Available events
Displays all available events that are not selected for tracking.
Tip If you are not specifically working with mouse movements, remove the MouseMove event from the Events to track list. MouseMove events typically occur very frequently.
Events to track
Displays all events that you want to track.

Send Output To

Debugger Output Window
Toggles whether tracked events are listed in the Debug Output window. If the Debug Output window is not open, events will not be listed, even if the Debug Output Window box is set.
File
Specifies a file for the tracked events to be written to. The dialog button makes it possible for you to select a file from the Open dialog box.
Append
Specifies that tracked events are written after the current contents of an existing file, preserving the original contents.
Overwrite
Specifies that tracked events replace the contents of the specified file.

See Also

Open Dialog Box | Debug Output Window | Debugger Window | Debugger Keyboard Shortcuts and Menus | Coverage Dialog Box | MouseMove Event


EXE Version Dialog Box

Displays the build number of a program, as well as other information that you can provide.

Version Number

Major
Displays a four-digit number that can be edited. This number corresponds to a major version.
Minor
Displays a four-digit number that can be edited. This number corresponds to a minor version.
Revision
Displays an editable four-digit number. This number corresponds to incremental updates.
Auto Increment
When checked, this option allows for automatic updates to the Revision number with every build of the program.

Version Information

Type
Lists seven categories of version information, which you can define. These categories are Comments, Company Name, File Description, Legal Copyright, Legal Trademarks, Product Name, and Language ID.
Value
Displays the information entered about a single category. Click a category in the Type list to display, enter, or edit the information.

See Also

Getting the Latest Versions of Files | GetLatestVersion Method | VersionNumber Property | VersionTrademarks Property | VersionCopyright Property | Build Options Dialog Box | Project Information Dialog Box


Execution Throttle Dialog Box

Makes it possible for you to specify the delay in seconds between the execution of each line of code located in the Trace Window. This dialog box appears when you select Throttle from the Debug Menu, Debugger Window.

Delay (seconds)
Makes it possible for you to set the delay of execution from 0.0 seconds to 5.0 seconds between each line of code.

See Also

Trace Window | Debugger Window | Debugger Keyboard Shortcuts and Menus


Export Dialog Box

Lets you export data from Visual FoxPro tables to a text file, spreadsheet, or common table format.

This dialog box appears when you select Export from the File menu.

Type
Specifies the type of file to export. Select a file type from the list.
To
Specifies the path and name of the destination file. Type the path and name, or click the dialog button to find the destination file.
Text delimiter
Allows you to delimit strings of text in the output file. The default text delimiter is the double-quote (") character. This option only appears if you choose Delimited Text from the Type drop-down list.
Field separator
Makes it possible for you to separate data fields in the output file. The default field separator is the comma (,) character. This option only appears if you choose Delimited Text from the Type drop-down list.
From
Specifies the path and name of the source file. Type the path and name, or click the dialog button to find the source file.
Options
Displays the Export Options dialog box, where you specify which records and fields to export.

The following table shows the file types you can export with this command, and their equivalents that you would type in the Command window.

File Types Command Equivalent
Data Interchange Format (DIF)
COPY TO FileName TYPE DIF
DBASE IV (DBF)
COPY TO FileName FOX2X
Delimited Text
COPY TO FileName TYPE DELIMITED
FoxBASE+ (DBF)
COPY TO FileName FOXPLUS
FoxPro for Windows 2.x (DBF)
COPY TO FileName FOX2X
Lotus 1-2-3 1-A (WKS)
COPY TO FileName TYPE WKS
Lotus 1-2-3 2.x (WK1)
COPY TO FileName TYPE WK1
Microsoft Excel 2.0, 3.0, and 4.0 (XLS)
COPY TO FileName TYPE XLS
MultiPlan 4.01 (MOD)
COPY TO FileName TYPE MOD
Symbolic Link Format
COPY TO FileName TYPE SYLK
Symphony 1.01 (WRK)
COPY TO FileName TYPE WRK
Symphony 1.10 (WR1)
COPY TO FileName TYPE WR1
System Data Format (SDF)
COPY TO FileName TYPE SDF
Visual FoxPro (DBF)
COPY TO FileName

See Also

Export Options Dialog Box | Command Window | COPY TO Command | Export Options | EXPORT Command | Import Dialog Box | The Process of Exporting Data


Export Options Dialog Box

Specifies which records and fields to export. This dialog box is displayed when you choose Options in the Export dialog box.

Criteria
These options control which records and fields export and the conditions under which they export.
  • Scope Displays the Scope dialog box, in which you specify how many records to export.
  • For Displays the Expression Builder dialog box, in which you create a logical expression which every record must meet to be exported.
  • While Displays the Expression Builder dialog box, in which you create a logical WHILE expression that must be true in order for records to be exported.
  • Fields Displays the Field Picker dialog box, where you choose fields to be exported.

See Also

Export Dialog Box | EXPORT Command | Expression Builder Dialog Box | Field Picker Dialog Box | Scope Dialog Box, | Page Setup Dialog Box | The Process of Exporting Data


Expression Builder Dialog Box

Makes it possible for you to create and edit expressions. An expression can be as simple as a field name or as complex as a calculation involving immediate IF functions, concatenations, and data type conversions. The main purpose of the Expression Builder is to facilitate the creation of expressions by providing you with lists of appropriate options each step of the way. This dialog box can be accessed from designers, windows, builders, and wizards.

To create an expression, you can type it directly into the expression box, or you can select items from the functions drop-down lists in the dialog box to have Visual FoxPro paste them into the expression box for you.

You might find some of the following functions useful when manipulating strings in expressions.

If you want to | Use this function
Remove leading and trailing blanks from character expressions | ALLTRIM( ) Function
Remove leading blanks | LTRIM( ) Function
Remove trailing blanks | RTRIM( ) Function
Add specified characters to the left, right, or both sides of a string | PADL( ) | PADR( ) | PADC( ) Functions
Work with parts of a character string for comparisons | SUBSTR( ) Function
Use a specified number of characters starting with the left of a string | LEFT( ) Function
Use a specified number of characters starting from the right of a string | RIGHT( ) Function
Change uppercase to lowercase, or lowercase to uppercase | UPPER( ) Function, LOWER( ) Function
Convert a string to initial capitals | PROPER( ) Function
Have a numeric field interpreted as a character string | STR( ) Function

Functions

Contains list boxes of four function types. When you select a function from one of the four types, Visual FoxPro automatically pastes it into the expression box. When you are building expressions for remote views, Visual FoxPro lists only the functions specific to the target back-end data.

String
Lists available character string functions.
Logical
Lists available logical functions.
Math
Lists available math functions.
Date
Lists available date and time functions.
Expression
Displays the expression that you are creating or editing.
Fields
Lists the fields in the current table or view.

To paste a field into the Expression box, either double-click the field or select the field and press ENTER.

To display fields from a different table, select a different table in the From Table box.

From Table
Lists tables and views that are open. Select a table or view to update the Fields box.
Variables
Lists system memory variables, arrays, and memory variables that you have created.

To paste a variable into the Expression box, either double-click the variable, or select the variable and press ENTER.

Verify
Validates the syntax of the expression in the expression box if the corresponding table is open. If the expression is valid, "Expression is valid" is displayed in the status bar. If it is not valid or if the corresponding table is not open, Visual FoxPro displays an error message. This option is not enabled for remote views.
Note If you include a user-defined function call in the expression, Verify will indicate an error, but there will not necessarily be an error when the expression is evaluated at run time.
Options
Displays the Expression Builder Options Dialog Box, in which you can set preferences for the Expression Builder.

For more information, see "Building Print Expressions" in Setting Each Control's Print Options.

See Also

ALLTRIM( ) Function | Expression Builder Options Dialog Box | IIF( ) Function | LEFT( ) Function | ISLOWER( ) Function | ALLTRIM( ) Function | PADL( ) | PADR( ) | PADC( ) Functions | PROPER( ) Function | RIGHT( ) Function | RTRIM( ) Function | SET ANSI Command | SET EXACT Command | STR( ) Function | SUBSTR( ) Function | UPPER( ) Function


Expression Builder Options Dialog Box

Sets preferences for the items displayed in the Expression Builder. This dialog box appears when you click Options in the Expression Builder Dialog Box.

Functions

Enables you to change what appears on the String, Math, Logical, and Date functions in the Expression Builder. You can choose to display all of these in the Expression Builder String box, or select only those you want. To select or deselect multiple items, press CTRL as you make your selections.

String
Displays all string functions in the box. All selected string functions will be displayed in the Expression Builder.
Math
Displays all math functions in the box. All selected math functions will be displayed in the Expression Builder.
Logical
Displays all logical functions in the box. All selected logical functions will be displayed in the Expression Builder.
Date
Displays all date functions in the box. All selected date functions will be displayed in the Expression Builder.
Note Select individual items by pressing CTRL+left mouse button. Select a consecutive group of items by left-clicking the first item and pressing SHIFT+left mouse button on the last item.
All
Selects all functions in the box so that they all appear as choices in the Expression Builder.
Clear
Deselects all functions in the box so that they don't appear as choices in the Expression Builder.

Field Aliases

These options specify whether and how table or view aliases appear in your expressions.

Always Add Alias
Specifies that the table or view name is always included with fields used in the expression.
Add Non-Selected Alias Only
Specifies that when more than one table or view is open, Visual FoxPro only includes the name of any table or view that is not selected in the Aliases list of the Data Session Window with any of its fields in the expression. Table or view names are not added for tables that are selected in the Aliases list.
Never Add Alias
Specifies that table or view names are not included with any field when you create the expression.
Show System Memory Variables
Specifies whether system memory variables are displayed in the Expression Builder. Turn this option off if you want to see only the system memory variables that have been defined.

See Also

Data Session Window | Expression Builder Dialog Box | Setting Each Control's Print Options | _TEXT System Variable


File Finder Dialog Box

Enables searches based on specified criteria.

Find Now
Performs a file search based on the options you specify on the Filer tabs.
Edit
Opens the files selected in the Search results list for editing.
New Search
Clears the options specified on the Text Search, Date Modified, and File Attributes tabs.
Search result
Displays the files located by the search. Double-click a file in the Search result list to open the file for editing. To open multiple files for editing, select the files and click the Edit button.

The Filer options are grouped onto the following tabs.

Tab | To access these features
Name and Location | Specify the names, extensions, and locations of the files you search for.
Text Search | Specify text strings to search for.
Date Modified | Specify the creation, modification, or access dates for the files you search for.
File Attributes | Specify the file size and file attributes of the files you search for.

Name and Location Tab

Named
Specifies the files you want to search for. Specify a file name and extension or any portion of a file name and extension that includes wildcard characters. Separate multiple file specifications with semicolons. For example, to display all .prg and .app files, use *.prg;*.app.

Click the down arrow to display a list of commonly used Visual FoxPro file extensions.

Look in
Specifies the folder in which the search occurs. Click the down arrow to display a list of folders you've specified during the current Filer session.
Browse
Displays the Select Directory dialog box, making it possible for you to select the folder in which the search occurs.
Include Subfolders
If checked, specifies that subfolders are also searched. Note that Filer ignores System folders.

Text Search Tab

Expression 1
A text string to search for in the files that match the file specification on the Name and Location tab.
Expression 2
An additional text string to search for. Ignored if Expression 1 is empty.
Expression 3
An additional text string to search for. Ignored if Expression 1 and Expression 2 are empty.
Contains any matching words
If chosen, specifies that any of the text in the text strings specified in Expression 1, Expression 2, and Expression 3 must match for the search to be successful.
Contains all matching words
If chosen, specifies that all the text in the text strings specified in Expression 1, Expression 2, and Expression 3 must match for the search to be successful.
Match case
If checked, specifies that the word case isn't ignored for text in the text strings specified in Expression 1, Expression 2, and Expression 3.
Match whole words
If checked, specifies that the text in the text strings specified in Expression 1, Expression 2, and Expression 3 must match whole words for the search to be successful.

Date Modified Tab

All Files
If chosen, specifies that the dates that files are created, modified, or accessed are ignored in the search.
Find all files created or modified
If chosen, includes in the search all files created or modified between or before the specified dates.
Find all files last accessed
If chosen, includes in the search all files accessed between or before the specified dates.
Between
Available when Find all files created or modified or Find all files last accessed is chosen. Includes in the search all files created, modified, or accessed between the two specified dates.
During the previous month(s)
Available when Find all files created or modified or Find all files last accessed is chosen. Includes in the search all files created, modified, or accessed during the specified number of months.
During the previous day(s)
Available when Find all files created or modified or Find all files last accessed is chosen. Includes in the search all files created, modified, or accessed during the specified number of days.

File Attributes Tab

Size is
Specifies that the files included in the search are at least or at most a specified size (in kilobytes).

Exclude files with these attributes

Read-only
Excludes files in the search that have the read-only file attribute set.
Archive
Excludes files in the search that have the archive file attribute set.
Hidden
Excludes files in the search that have the hidden file attribute set.
System
Excludes files in the search that have the system file attribute set.

See Also

Options Dialog Box | Debugger Window | Beautify Options Dialog Box | Macros Dialog Box | Spelling Dialog Box | Wizard Selection Dialog Box


Find Dialog Box

This dialog box contains options that make it possible for you to search for text. Visual FoxPro adds several ways to access the Find dialog box from the keyboard.

Keys | Description
CTRL+F | Find.
CTRL+L | Replace.
F3 | Find Again or open Find dialog box.
CTRL+F3 | Update Find with the word or selected characters at the cursor position.
CTRL+SHIFT+F3 | Update Find with the word or selected characters at the cursor position for a previous occurrence.
Look For
Specifies the text string for which to search.

To search for special characters, type the following C language representations in the text boxes in the Find dialog box.

To search for | Type
Enter | \r
Tab | \t
Backslash \\
New line (line feed) | \n

In Visual FoxPro, searches support wildcards.

Options
These options define the limits and direction of the search. If you specify text to search for and do not get the expected results, make sure you have the correct options selected.
  • Match Case Locates text that exactly matches the combination of uppercase and lowercase letters you type in the Look For box.
  • Wrap Around Searches the current file from the insertion point to the end of the file and then from the beginning of the file to the original insertion point.
  • Match Whole Word Locates distinct occurrences of words, not groups of characters inside words.
  • Search Backward Searches backwards from the current insertion point position to the beginning of the file.
  • Use wildcards Makes it possible for you to use wildcard characters in your search text.

    With Use wildcards cleared, a literal search is conducted for any characters. When Use wildcards is selected, the following rules apply:

    Character | Description | Usage
    ? Any single character Specified in place of the missing character.
    * Zero or more characters Specified in place of the missing character/s.
    # Any single digit Specified in place of the missing digit.
    < Beginning of a word Finds expression at beginning of a word.
    > End of a word Finds expression at end of a word. Must be placed after characters to search.
    [charlist] | Set of characters | Matches any one of the specified characters in the brackets. Set can be a range, separated by a dash (–) (for example, [a-d]).
    [!charlist] | Exclude characters | Matches any character except those following the exclamation mark in brackets.
    \ Escape Matches the character following the backslash (\). This makes it possible for you to find characters used in the regular expression notation, such as * and >.
Scope
Defines how extensive the search is. The Scope options are enabled when you are editing a procedure in a Code window.
  • Current Procedure Searches only the current procedure, which is displayed in the Code window.
  • Current Object Searches all procedures (event code) in the current (selected) object.
  • All Objects Searches all procedures (event code) in all objects in the current form or form set. If Wrap Around is selected, only the current method or event, will be searched.
Find Next
Finds the next occurrence of the string you typed in the Look For box.
Replace
Expands the dialog box by adding a Replace All button and the Replace With text entry box, in which you can specify replacement text.

See Also

Replace Dialog Box | Paste Special Dialog Box | Go To Line Dialog Box | Insert Object Dialog Box | Change Icon Dialog Box | Edit Links Dialog Box | Code window


Find Table or View Dialog Box

This dialog box allows you to select a table or views you can't locate in the database schema displayed in Database designer. Use this dialog box to find tables or views in the database schema.

This dialog box appears when you select Find Object from the Database menu.

Tables or Views
Shows a list of objects in your database layout that you can find. If the table or view you want does not appear in this list, it has not been added to the database.
Find button
Selects and displays the object in the database schema.

See Also

New Local View Dialog Box | Edit Relationship Dialog Box | New Remote View Dialog Box | Creating Views | Adding Tables to a Database | Table Creation | Creating a Database Table | Database Designer


Font Dialog Box

Controls the font type, style, and size.

You can change fonts in a text file, field or label control in a report or label, or the Command window. To change fonts in reports and labels, you must create a label control or field control and then select it.

Font
Displays the available fonts.
Font Style
Displays the styles (Regular, Bold, Italic, or Bold Italic) you can apply to the font or selected text.
Size
Displays a list of point sizes for the font.

Effects

  • Strikeout Strikes through text using a horizontal line. This option appears only when you are working with a report or label.
  • Underline Underlines the selected text. This option appears only when you are working with a report or label.
Color
Specifies text color of selected text. This option appears only when you are working with a report or label.
Sample
Displays a sample of the selected font's letter style for both uppercase and lowercase letters.
Script
Lists the available language scripts for a specific font. Pick the one appropriate for the language your computer is set up for.

See Also

Browse Window | Edit Window | Fonts Overview | FontBold, FontItalic, FontStrikethru, FontUnderline Properties | Creating Reports and Labels


Format (Field) Dialog Box

Specifies the value of an expression in a field control. This dialog box appears when you have a valid expression in the Expression box of the Report Expression dialog box and choose the dialog button for Format.

Format
Makes it possible for you to type the format expression instead of setting the options below, or type a format template.
Character
Specifies Character data type, and displays the appropriate editing options.
Numeric
Specifies Numeric data type, and displays the appropriate editing options.
Date
Specifies Date data type, and displays the appropriate editing options.

This group changes according to the data type (Character, Numeric, or Date). Selecting these options places a formatting code in the Format box.

To Upper Case (Character type)
Converts all characters to uppercase.
Ignore Input Mask
Displays, but does not store, nonformat characters.
Left Justify (Numeric and Character type)
Begins all numeric data at the leftmost position in the specified field.
Right Justify (Character type)
Prints data flush-right in field.
Center Justify (Character type)
Centers data in field.
Blank If Zero (Numeric type)
If field output is zero, does not print the zero.
(Negative) (Numeric type)
Places negative numbers in parentheses.
SET Date (all types)
Displays data as a date using the current SET DATE format.
British Date (all types)
Displays data as a European (BRITISH) date.
CR If Positive (Numeric type)
Displays CR (credit) after positive numbers.
DB If Negative (Numeric type)
Displays DB (debit) after negative numbers.
Leading Zeros (Numeric type)
Prints all leading zeros.
Currency (Numeric type)
Displays currency format as specified on the Regional tab in the Options dialog box.
Scientific (Numeric type)
Displays format in scientific notation (useful for very large or very small numbers).

See Also

Calculate Field Dialog Box | Regional Tab, Options Dialog Box | Report Designer | Report Expression Dialog Box | SET DATE | Formatting Field Controls | Creating a Report Layout


General Options Dialog Box

Allows you to specify code for an entire menu system. You can access this dialog box by selecting General Options from the View Menu in the Menu Designer.

Procedure
Creates menu procedure code. If code exceeds the displayed editing region, the scroll bar is activated.
Edit
Opens an editing window so you can create code there instead of in the General Options dialog box. To activate the editing window, click Edit, and then click OK in the General Options dialog box.

Location

Replace
Replaces the existing menu system with a new menu system.
Append
Adds a new menu system to the right of the active menu system.
Before
Inserts a new menu before the specified menu. This option displays a drop-down list containing the names in the active menu system. To insert the new menu, select the menu name you want the new menu to precede.
After
Insert a new menu after the specified menu. This option displays a drop-down list containing the names in the active menu system. To insert the new menu, select the menu name you want the new menu to follow.

Menu Code

Setup
Opens an editing window in which you can add setup code to a menu system. To make the editing window active, click OK in the General Options dialog box.
Cleanup
Opens an editing window in which you can add cleanup code to a menu system. To make the editing window active, click OK in the General Options dialog box.
Top-Level Form
If checked, allows the menu to be used in a top-level (SDI) form. If not checked, allows the menu to only be used on the Visual FoxPro frame.

For more information, see Designing Menus and Toolbars.

See Also

Menu Designer | Menu Options Dialog Box | Define Window Layout Dialog Box | Tab Order Dialog Box | Toolbars Dialog Box


Generate Menu Dialog Box

Lets you specify a name for the generated menu program and then generate the program. If you have not saved your menu, you are prompted to do so.

This dialog box appears when you select Generate from the Menu menu.

Output File
Specifies the path to the generated menu program. Choose the dialog button to select a directory and file name, or substitute a file name of your choice by typing over the name displayed.
Generate
Produces a menu program file, which has the .mpr extension.

See Also

Do Dialog Box | Menu Designer | Menu System Creation | Menu System Design Guidelines | Creating Menus, Shortcut Menus, Menu Items, and Submenus | CREATE MENU Command


Get Latest Version of Files Dialog Box

Gets the selected files from the source code control provider and places a local copy in the Project Manager.

File(s) to Get Latest Version
Lists available files in the source code control project.
Select All
Selects all available files.
Advanced
Displays the source code control provider's Advanced Get Options dialog box.

See Also

Check In Files Dialog Box | Check Out Files Dialog Box | Undo Check Out of Files Dialog Box | Project Manager Hooks


Go To Line Dialog Box

This dialog box makes it possible for you to move the insertion point to the designated line in a text or program file or in the Command window.

Line Number
Specifies the line number where you want the insertion point to appear.

See Also

Command Window | Find Dialog Box | Options Dialog Box | SYS(2002) - Turn Insertion Point On or Off | Insert Object Dialog Box | Replace Dialog Box


Go To Record Dialog Box

Specifies which record to move the record pointer to. Type the record number in the Record Number box, or use the up and down arrows as required until the desired number displays in the Record Number box. Choose OK to return to the Browse window with the record pointer on the specified record.

This dialog box appears when you choose the Record # command from the Go to Record submenu.

See Also

Browse Window | Locate Record Dialog Box | Scope Dialog Box | Field Picker Dialog Box | Working with Records | Adding Records | Filtering Data | Record Manipulation


Group Footer Dialog Box

Sets height options and band expressions for the Group Footer band in a report or label. This dialog box appears when you double-click the bar for the Group Footer band in the Report Designer. To create a Group Footer band, choose Data Grouping from the Report Menu, create a group expression, and then choose OK.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before the contents of the group footer are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after the contents of the group footer are printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Data Grouping Dialog Box | Expression Builder Dialog Box | Group Header Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Creating Reports and Labels | Refining Page Layout | Report Layout Preparation


Group Header Dialog Box

Sets height options and band expressions for the Group Header band in a report or label. This dialog box appears when you double-click the bar for the Group Header band in the Report Designer. To create a Group Header band, choose Data Grouping from the Report menu, create a group expression, and then choose OK.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before each new group header is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after each new page is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Data Grouping Dialog Box | Expression Builder Dialog Box | Group Footer Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Refining Page Layout | Report Layout Preparation


Having Dialog Box

Specifies conditions for selecting which groups of records to include in query output.

The Having dialog box appears when you choose Having in the Group By Tab, Query and View Designers.

Field Name
Specifies a function, field name, or other expression. When creating a Having clause, select the field to display a list of functions, a list of field names for each table, or use the expression command to display the Expression Builder dialog box. If you choose a function, a submenu displays a list of field names available to use with that function.
Not
Reverses the comparison criterion.
Comparison criterion
Specifies the operator for the selection criterion. The comparison criteria are as follows:
  • Equal (=) Specifies that field and the value in the Example field have the same value.
  • Like Specifies that the field must include characters that match characters in the text in the Example field.

    For example, Customer.state Like O matches records from Ohio, Oklahoma, and Oregon.

  • Exactly Like (==) Specifies that the field must match, character for character, the text in the Example field.
  • Greater Than (>) Specifies that the field must be more than the value in the Example field.
  • Less Than (<) Specifies that the field must be the same or less than the value in the Example field.
  • Greater Than or Equal To (>=) Specifies that the field must be the same or more than the value in the Example field.
  • Less Than or Equal To (<=) Specifies that the field must be the same or less than the value in the Example field.
  • Is NULL Specifies that the field must contain a null value.
  • Is True Specifies the left field or expression evaluates to True, assuming the field or expression evaluates to a logical value.
  • Between Specifies that the field must be greater than or equal to the lower value, and less than or equal to the higher value, in the condition appearing in the Example column. You must separate the two values in the Example column with the word AND. Visual FoxPro creates the query with the word BETWEEN.

    For example, Invoices.idate Between 05/10/97 AND 05/12/97 matches records for the 10th, 11th, and 12th of May, 1997.

  • In Specifies that the field must match one of several values in the comma-separated list appearing in the Example field.

    For example, Customer.name In Al,George,Mary matches records in which the customer's name is Al, George, or Mary.

Example
Specifies the value or text with which you want to compare the field. To match the text casing of the example, use the UPPER( ), LOWER( ), and PROPER( ) functions.
Logical
Adds an AND or OR condition to the list of conditions.
Pri. (Priority)
Specifies a number ranging from 0 to 99, which indicates the priority for logical operations. The number 0 indicates the highest priority, while the number 99 indicates the lowest priority.

Setting priorities for logical operations determines the order in which logical operations are performed and uses parentheses (()) for grouping operations. For example, suppose you specify a priority of 0 for a logical operation, a priority of 1 for a second logical operation, and a priority of 0 for a third logical operation. The first and third logical operations, which have a priority of 0, are performed before the second logical operation, which has a priority of 1.

Insert
Inserts a blank row above the selected condition.
Remove
Removes the selected row from the Field Name list.

See Also

Group By Tab, Query and View Designers | Query and View Designers | SELECT - SQL Command | CREATE QUERY Command | Creating a Query


Import Dialog Box

Lets you import data to a Visual FoxPro table from a spreadsheet or another table format. You can also use the Import Wizard to import files.

Note You cannot import text files with this menu command. To import text files, use the Import Wizard, or create a table and then append the text file to the new table.

This dialog box appears when you select Import from the File menu.

Type
Specifies the type of file to import. Select a file type from the list.
From
Specifies the path and name of the source file. Type the path and name, or click the dialog button to find the source file.
Sheet
Specifies a Microsoft Excel worksheet to import. This box appears only if you select Microsoft Excel in the Type box.
To
Displays the path, as defined in the File Locations tab, Options dialog box, and the file name of the imported file. The file name is that of the source file, but with a .dbf extension.
Import Wizard
Starts the Import Wizard, which prompts you with simple questions as you go through a brief series of steps. You must use the Import Wizard to import text files, or create a table and then append the text file to the new table.

The following table shows the file types you can import with this command, and their equivalents that you would type in the Command window.

File Types Command Equivalent
FrameWork II (FW2)
IMPORT FROM FileName TYPE FW2
Lotus 1-2-3 1-A (WKS)
IMPORT FROM FileName TYPE WKS
Lotus 1-2-3 2.x (WK1)
IMPORT FROM FileName TYPE WK1
Lotus 1-2-3 3.x (WK3)
IMPORT FROM FileName TYPE WK3
Microsoft Excel 2.0, 3.0, and 4.0 (XLS)
IMPORT FROM FileName TYPE XLS
MultiPlan 4.01 (MOD)
IMPORT FROM FileName TYPE MOD
Paradox 3.5, 4.0, 4.5 (DB)
IMPORT FROM FileName TYPE PDOX
RapidFile (RPD)
IMPORT FROM FileName TYPE RPD
Symphony 1.01 (WRK)
IMPORT FROM FileName TYPE WRK
Symphony 1.10 (WR1)
IMPORT FROM FileName TYPE WR1

See Also

Append From Dialog Box | Command Window | Export Dialog Box | Import Wizard | IMPORT Command | File Locations Tab, Options Dialog Box | Importing and Exporting Data


Include File Dialog Box

Allows you to specify an include file containing predefined compile-time constants for a user-defined class, form, or form set.

This dialog box appears when you select Include File from the Class or Form menus.

Include File
Specifies a header file of predefined compile-time constants for a user-defined class, form, or form set. Type the name of the include file in the box, or use the dialog button to select an existing include file.

See Also

#DEFINE | Edit Property/Method Dialog Box | New Method Dialog Box | New Property Dialog Box | Working with User-Defined Functions | Procedures and User-Defined Functions | Constants


Insert Object Dialog Box

This dialog box lists the OLE objects you can link or embed in your application for forms or General fields in Visual FoxPro tables.

In a browse window, double-click a General field to bring up an editing window and enable the Insert Object command.

For a form, select an OLE Container control while a form is displayed. This displays the Insert Object dialog box and the new object is stored in the field to which the control is bound.

Create New
Displays the Object Type box so you can choose an OLE application in which to create a new object.
Object Type
Appears when you select Create New, and displays the OLE applications installed on your computer. Select an application in which to create the object.
Create From File
Displays the File box so you can specify an existing object to insert.
File
Appears when you select Create From File. Type the object's file name and path, or click Browse to select the appropriate file.
Browse
Opens the Browse dialog box that makes it possible for you to select a table or view.
Link
Links the object. If you don't select this option, the object is embedded.
Display As Icon
Displays the inserted object as an icon. The icon comes from the application in which the object was created.
Results
Depending on the radio button selected, can display a description of action to be performed on the contents of the file after you click OK, a Unique Identifier, and a path to the Control or Object Type selection. You can alter the description displayed by choosing the Create New, Create from File, or Display As Icon options.
Change Icon
Displays the Change Icon dialog box, which makes it possible for you to select a different icon for the OLE object. Appears when you select the Display As Icon option.
Insert Control (forms only)
Displays the Control Type box so you can insert an ActiveX control.
Control Type (forms only)
Appears when Insert Control is selected, and lists the ActiveX controls you can insert.
Add Control (forms only)
Appears when Insert Control is selected, and displays the Browse dialog box so you can find and select an ActiveX control not listed under Control Type.

See Also

Controls Tab, Options Dialog Box | General Field Type | Properties Window | Change Icon Dialog Box | Dynamic Information Sharing


Insert Object Reference Dialog Box

Makes it possible for you to see the name of all objects in the designer and insert a fully qualified reference to the object in your code.

This dialog box appears when you choose Objects List from the shortcut menu of the Code Window in the Form Designer or Class Designer.

Objects list
All the objects contained in the highest-level container in the Form Designer or Class Designer. Contained objects are indented to indicate the container hierarchy.
Insert
Inserts a string with the full object reference at the cursor in the editing window.

See Also

Class Designer | Form Designer | Document View Window | Code Window | Insert Object Dialog Box


Insert System Menu Bar Dialog Box

Allows you to add menus and menu options to the Menu Designer window. This dialog box appears when you choose Insert Bar from the Menu menu or select the Insert Bar button on the Menu Designer window.

Menu List Box
Lists the available menu names and menu option names, depending on whether you have chosen Usage or Prompt in the Order by area.

Order By

Usage
Designates that the Menu List Box display the available menu items in the order that they would appear on their respective menu titles. For example, all of the File menu items are listed first, in the order that they appear on the actual File menu. Edit menu items appear next, and so on.
Prompt
Designates that the Menu List Box display the available menu items in alphabetical order.
Insert
Inserts the selected menu item on the designated row in the Menu Designer window.

See Also

Generate Menu Dialog Box | Menu Options | Menu Options Dialog Box | Menus and Menu Bars | Menu Designer


Join Condition Dialog Box

Specifies a join condition between tables. This dialog box appears when you add more than one table in your query or view, and those tables do not have a join condition already specified.

For more information about join conditions, see Join Conditions for Tables, Queries, and Views.

Right Field List
Shows the fields from the table you have added. Select a field from the list by which to join the tables.
Left Field List
Shows the fields from all of the tables previously added into the Query Designer. Select a field from the list by which to join the tables.

Type of Join

Inner Join
Creates a join that will list only the records from the Left Field List that match the records from the Right Field List for the fields selected.
Left Join
Creates a join that includes the Left Field List records and the matching Right Field List records for the fields selected.
Right Join
Creates a join that includes the Right Field List records and the matching Left Field List records for the fields selected.
Full Join
Creates a join that includes all the records from both list boxes for the fields selected in the list boxes.
Description
Specifies how the fields of each table will relate to each other when you select the different join options.

See Also

Add Table or View Dialog Box | SELECT - SQL Command | SET ANSI Command | Query Destination Dialog Box | Query Designer


Label Dialog Box

Displays the results of the query in an existing label. You must have previously set up the label file (.lbx) to accommodate the columns of output in the query. This command is available for queries only.

Open Label
Displays the Open dialog box for you to select a label file to use for your query. You can click the button or type a file name in the text box.
Wizard Icon
Displays the Label Wizard.
Page Preview
Displays the output in the Page Preview window.
Console On
Displays the output in the active output window.

Secondary Output

None
Specifies that the output not be sent to the printer or saved as a text file.
To Printer
Sends the results of the query to the printer.
To Text File
Saves the results of the query as a text file. Click the button to select an existing file that you want to overwrite, or type the name of a new file in the text box.

See Also

Miscellaneous Tab, Query and View Designers | Label Wizard | Label Designer | Creating a Mailing Label Layout


Locate Database Dialog Box

Makes it possible for you to locate or ignore a missing table or view.

This dialog box appears when you open or run a form and Visual FoxPro is unable to locate a table or view in the data environment of the form.

Locate
Displays the Open Dialog Box, so you can find the table or view.
Ignore
Visual FoxPro will continue to load the form without instantiating the cursor object in data environment. If there are controls bound to fields in the table or view, additional errors will be generated.
Cancel
Visual FoxPro will stop loading the form.
Help
Displays Help on the dialog box.

See Also

Open Dialog Box | LOCATE Command | Locate Record Dialog Box | Locate Button | Find Table or View Dialog Box | Add Table or View Dialog Box


Locate File Dialog Box

Makes it possible for you to locate or ignore a missing file or group of files. This dialog box appears when you run a program and Visual FoxPro is unable to locate a needed file to successfully run the program.

Locate
Displays the Open Dialog Box, so you can find the file.
Ignore
Visual FoxPro will continue to run the program without the required file.
Ignore all
Visual FoxPro will continue to run the program without the required group of files.
Cancel
Visual FoxPro will stop running the program.

See Also

Open Dialog Box | LOCATE Command | Locate Record Dialog Box | Locate Button | Find Table or View Dialog Box | Add Table or View Dialog Box | Locate Database Dialog Box


Locate Record Dialog Box

Searches for a record in the active table or view that matches specified conditions. Use this command when you want to search a table or view record-by-record on an indexed or unindexed field, or when you want to find more than one record in a table.

This dialog box appears when you choose the Locate command from the Go to Record Submenu.

Scope
Allows you to specify the records on which Visual FoxPro is to act. Choose All, Next, Record, or Rest from the drop-down list. Choose a number from the spinner on the right when you select Next or Record from the Scope drop-down list.
For
Displays the Expression Builder dialog box, in which you create the logical expression that every record must meet to be affected by the command.
While
Displays the Expression Builder Dialog Box. The While expression specifies that the action affects records only as long as the logical expression is true. The first time the expression evaluates to false, the action ceases without considering remaining records.
Locate
Carries out the command using the Scope, For, and While values.

See Also

Browse Window | CONTINUE Command | Expression Builder Dialog Box | LOCATE Command | Scope Dialog Box | Working with Records | Adding Records | Filtering Data | Record Manipulation


Look Up Reference Dialog Box

Provides a way for you to search for occurrences of a code reference in a project, specific folder or subfolder. You can filter your search by file type.

The Look Up Reference dialog box appears only in design mode when you select Code References on the Tools menu. You can also select Look Up Reference when you right-click inside the editing window for programs or open the Look Up Reference dialog box programmatically for the first time using the following code:

DO(_FOXREF)

For more information about calling the _FOXREF system variable, see _FOXREF System Variable.

Look for
Specifies the target search expression.

Visual FoxPro populates the Look for box with the expression selected in the Editing window. The Look for box contains any recently selected or previously searched expressions.

When you select the Use regular expressions check box, an arrow button next to the Look for box becomes available. Selecting the Use regular expressions check box allows for wildcard character searches. For more information, see "Use regular expressions" in this topic.

Scope
Specifies the range of the search and contains the following options:
  • Folder Search the current folder and optionally, subfolders.
  • Project Search the set of files in the selected project. Only opened projects appear in the drop-down list.
Look in
Specifies the current folder and contains a drop-down list with the history of previously selected folders when Folder is selected in the Scope box. To select a different folder, click the ellipsis (...) button to open the Select Directory dialog box.

The Look in box is not available when Project is selected in the Scope box.

Search subfolders
Includes subfolders of the selected folder in your search. The Search subfolders check box is available only when Folder is selected in the Scope box.
Limit search to project home directory and subfolders
Includes only those files in the project that are located within the project's home folder and subfolders. Shared files are excluded. This check box is available only when Project is selected in the Scope box.
Overwrite prior results
Controls whether results from an earlier search are included or overwritten in the new search. This option functions similarly to selecting Clear All Results from the context menu in the Code References window to replace all the content in the Search pane. The Overwrite prior results check box is available when Folder or Project scope is selected.
File Types
Specifies a set of file types for limiting your search. File types are separated by commas. The most recent value used in a search is used in the next search. You can add custom file types using the FoxRefAddin.dbf file. The FoxRefAddin table allows for specific file type extensions that are excluded when doing a wildcard file name (*.*) search. The following table lists all Visual FoxPro file types that are supported and how searches on a file type are conducted.
File extension | Behavior
.cdx | Search index expressions. Selecting this extension requires a table to be open to find the expression.
.dbc | Search stored procedures, remote view source, connections, and other .dbc data, excluding .dbf files and structures.
.dbf | Search field names and any extended .dbc file metadata such as trigger expressions but not table contents. Visual FoxPro might need to temporarily open or close tables if you select this extension.
.frx, .lbx | Search report and label expressions, label values, and data environment.
.mnx | Search menu names and associated code.
.prg | Search program files and display the line number for the reference if found.
.scx | Search all method code, data environment, and non-default property values.
.vcx | Search all method code and non-default property values.
Other file types | Treat search expressions as strict text.

The following table lists default file type groups appearing in the drop-down list in the File Types box.

File types | File extensions
All Files *.*
Common | *.scx, *.vcx, *.prg, *.frx, *.lbx, *.mnx, *.dbc, *.qpr, *.h
All Source | *.scx, *.vcx, *.prg, *.frx, *.lbx, *.mnx, *.dbc, *.dbf, *.cdx, *.qpr, *.h
Forms and Classes | *.scx, *.vcx, *.prg
Reports and Labels | *.frx, *.lbx
Menus | *.mnx
Programs | *.prg, *.h, *.qpr, *.mpr
Data Structures | *.dbc, *.dbf, *.cdx
Text | *.txt, *.xml, *.xsl, *.html, *.log, *.asp, *.aspx

Note The Common source file type group includes only .dbc files as a data source option by default. The default behavior is to search only stored procedures. You can change this behavior by clicking the Options button in the Look Up Reference dialog box.

Options
Opens the Options dialog box to set additional options for your search. For more information, see Look Up Reference Dialog Box, Options Dialog Box.

Options Group

The Options group box includes additional options you can specify to customize your search.

Match case
Specifies whether your search is sensitive to text casing.
Match whole word
Specifies whether your search must match entire words exactly.
Use regular expressions
Allows for wildcard character searches. Selecting the Use regular expressions check box enables the arrow button next to the Look for box. Clicking the arrow button opens a menu from which you can select a regular expression type to insert in the Look for box. For more information about regular expressions, see Regular Expressions and Operators.
Comments
Specifies whether to include code comments in your search. Comments begin with an asterisk (*), double ampersand (&&), or NOTE keyword. The Comments drop-down list includes the following options:
  • Include Comments Include comments in your search.
  • Ignore Comments Ignore comments in your search.
  • Comments Only Search comments only.

See Also

Dialog Boxes | Code References Window | Viewing Code Definitions | _FOXREF System Variable


Look Up Reference Dialog Box, Options Dialog Box

Sets additional options for a code reference search.

The Options Dialog Box appears when you click the Options button in the Look Up Reference Dialog Box or the Code References window. You can obtain descriptions of each option by clicking the option text.

Create symbol definition table during search
Specifies collecting code symbol definitions from processed files during a reference search. Otherwise, definitions are collected on demand when viewing code definitions. This option performs a full definition scan during a reference search and saves time when viewing code definitions. For more information, see Viewing Code Definitions.
Limit definition collection to project home directory and below
Specifies that a collection of code symbol definitions for a project include only those files that are in the project's home directory tree. This prevents including definitions from framework and other files that are not immediately relevant to the current project.
Search only source code and expressions
Specifies that searching is performed only on source code and expressions. Otherwise, values such as field names in tables, label values in reports, captions, and other text are included in the search.
Search form/class property names and values
Specifies that properties names and values of visual forms (.scx) and visual classes (.vcx) are included in a reference search.
Display number of references found per line in search results
Specifies that an indicator is displayed in the references window next to results that have more than one match per line.
Show history of file types searched
Specifies that a history of recently selected file types is displayed in the Look Up Reference window. Otherwise, only common file types and the most recent file type selected are displayed.
Backup Style
Specifies how files are named when backing them up during global code reference replacement.
Font
Displays the Font dialog box, which you can use to change the font of the Code References window.
Folder for code references tables
Specifies and contains the location for core code reference tables. To select a different folder, click the ellipsis (...) button to display the Select Directory dialog box.
Clean Up Source Tables
Cleans up Visual FoxPro reference tables by looking for old and outdated records. Specifically, this option performs the following actions:
  • Removes all Inactive and Error records from the RefFile.dbf file except where UniqueID="WINDOW", which always remains.
  • Removes all records that reference files that do not exist on the disk from the RefFile.dbf file and any corresponding records in the RefDef.dbf file.
  • Removes all Inactive records from the RefDef.dbf file.
  • Performs a PACK operation on the RefFile.dbf and RefDef.dbf files.

See Also

Dialog Boxes | Look Up Reference Dialog Box | Code References Window | PACK Command


Macros Dialog Box

Makes it possible for you to define key combinations using the CTRL key, ALT key, or function keys to perform a series of keystrokes. You can combine individual macros in sets and store them in files.

Individual Macro
Displays macros available for use.
Record
Displays the Record Macro Dialog Box, in which you can create a macro.
New
Displays the New Macro Dialog Box, in which you can manually create a macro.
Edit
Displays the Edit Macro Dialog Box, in which you can edit the selected macro.
Clear
Prompts you to erase or keep the selected macro.

Macro Set

Save
Displays the Save Macros dialog box, in which you can name and save individual macros or macro sets.
Restore
Displays the Restore Macros dialog box, in which you can add a saved macro set to the current macros (that is, those in the Individual macro box in the Macros dialog box).
Set Default
Prompts you to overwrite the default macro set with a new macro set.
Clear All
Prompts you to erase all macros in the Individual Macro list.

See Also

APPEND Command | DIR or DIRECTORY Command | DISPLAY Command | DISPLAY MEMORY Command | DISPLAY STATUS Command | DISPLAY STRUCTURE Command | Edit Macro Dialog Box | LIST Commands | Macro File Format (.fky) | Macro Substitution | PLAY MACRO Command | SET Command Overview | Overwrite Macro Dialog Box | Stop Recording Macro Dialog Box


Record Macro Dialog Box

Automatically creates a macro by recording your keystrokes until you stop recording.

This dialog box appears when you choose Record in the Macros Dialog Box.

Defined Key
Displays the key combination you press that will run the macro. To assign your macro to a particular keystroke, put the cursor in this field, and then press the key or key combination. Visual FoxPro puts the name of the key or key combination you pressed into this field and assigns the macro you are about to record to that key or key combination.
Macro Name
Displays the default macro name, which is based on the defined key. For example, if the defined key is CTRL+D, the macro name will be CTRL_D. If you want to rename the macro, type the new name (up to 20 characters) in the box. The recording does not begin until you click OK, which puts the insertion point in the command window where you record the macro.

See Also

Overwrite Macro Dialog Box | SET FUNCTION Command | Stop Recording Macro Dialog Box | New Macro Dialog Box | Edit Macro Dialog Box | Macros Dialog Box


Stop Recording Macro Dialog Box

Interrupts the process of recording a macro. From this dialog box, you can choose OK to stop recording the macro as it is, or you can take advantage of some other options.

This dialog box appears when you select Macros from the Tools Menu while recording a macro.

Insert Literal
Records the literal meaning of the next keystroke, instead of a meaning currently assigned to the key with a macro. Use this when you want to circularly define two keys.
Insert Pause
Records a pause in the macro. Before you choose Insert Pause, choose either Key To Resume or Seconds to define how macro execution will resume.
Key to Resume
Prompts for a key that resumes execution of a macro that has been paused. This prompt appears only if you have implemented the SET MACKEY Command.
Seconds
Specifies how long the pause in macro execution lasts before it automatically resumes. In the spinner control, type or select a number.
Continue
Returns to the point before the Stop Recording Macro dialog box appeared so you can continue recording the macro.
Discard
Deletes the macro you are recording and puts your insertion point in the last entered text box.
OK
Confirms that the macro is completed and ready for use.

See Also

Macros Dialog Box | SET MACKEY Command | Overwrite Macro Dialog Box | New Macro Dialog Box | Edit Macro Dialog Box


Overwrite Macro Dialog Box

Replaces an existing macro with a new one of the same name. This dialog box appears when you define an already existing key combination in the Record Macro Dialog Box and click OK.

Overwrite
Replaces the existing macro definition with the new definition.
Append Keystrokes
Adds keystrokes to the end of the existing macro. The insertion point is placed in the last entered text box so you can type the keystrokes to append.

See Also

Record Macro Dialog Box | New Macro Dialog Box | Edit Macro Dialog Box | Stop Recording Macro Dialog Box | Macros Dialog Box


New Macro Dialog Box

Manually creates a macro instead of recording your keystrokes.

Defined Key
Displays the key combination you press that will launch the macro.
Macro Name
Displays the default macro name, which is based on the defined key. For example, if the defined key is CTRL+D, the macro name will be CTRL_D. If you want to rename the macro, type the new name (up to 20 characters) in the box.
Macro Contents
Provides space for you to type the keystrokes the macro executes. Use the key label assignments listed in the ON KEY LABEL Command topic and enclose them in braces to represent the desired keystrokes. Place all key combinations (such as CTRL+F2) in braces also. For example:
MODIFY{SPACEBAR}COMMAND{ENTER}
{HOME}{SHIFT+END}
Note The key combinations SHIFT+CTRL+\, CTRL+–, CTRL+^, and SHIFT+CTRL+ENTER are not supported in Visual FoxPro.

See Also

Edit Macro Dialog Box | ON KEY LABEL Command | Macros Dialog Box | Overwrite Macro Dialog Box | Stop Recording Macro Dialog Box | Record Macro Dialog Box


Edit Macro Dialog Box

Makes it possible for you to manually edit a preexisting macro.

Defined Key
Displays the key combination you press that will launch the macro.
Macro Name
Displays the default macro name, which is based on the defined key. For example, if the defined key is CTRL+D, the macro name will be CTRL_D. If you want to rename the macro, type the new name (up to 20 characters) in the box.
Macro Contents
Provides space for you to type the keystrokes the macro executes. Use the key label assignments listed in the ON KEY LABEL Command topic and enclose them in braces to represent the desired keystrokes. Place all key combinations (such as CTRL+F2) in braces also. For example:
MODIFY{SPACEBAR}COMMAND{ENTER}
{HOME}{SHIFT+END}
Note The key combinations SHIFT+CTRL+\, CTRL+–, CTRL+^, and SHIFT+CTRL+ENTER are not supported in Visual FoxPro.

See Also

ON KEY LABEL Command | Macros Dialog Box | Overwrite Macro Dialog Box | Stop Recording Macro Dialog Box | Record Macro Dialog Box


Menu Options Dialog Box

Allows you to specify code for a specific menu. You can access this dialog box by selecting Menu Options from the View Menu in the Menu Designer.

Name
Contains the name of the menu. By default, this is the same as the text in the Prompt column of the Menu Designer. Change it by typing a new name in the Prompt column.
Procedure
Provides space for menu procedure code, or displays existing code. If code exceeds the displayed editing region, the scroll bar is activated.
Edit
Opens an editing window so you can create code there instead of in the Menu Options dialog box. To activate the editing window, click OK in the Menu Options dialog box.

For more information, see Designing Menus and Toolbars.

See Also

General Options Dialog Box | Menu Designer | Define Window Layout Dialog Box | Tab Order Dialog Box | Toolbars Dialog Box


More Windows Dialog Box

Displays a list of active windows from which you can choose. This dialog box appears when you choose More Windows from the Windows menu. Choose one of the active window names listed in the Select window to view the active window.

See Also

HIDE WINDOW Command | MODIFY WINDOW Command | Command Window | Data Session Window | SHOW WINDOW Command


Move Item Dialog Box

Makes it possible for you to change the location of a menu or menu item.

The Move Item dialog box appears when you select a row in the Menu Designer or Shortcut Designer and click Move Item.

Move Group

Name
Displays the name of the menu or menu item.
Type
Displays the type of the menu or menu item.

To Location Group

To Location box
Displays a list of valid locations to which you can move a menu item.

See Also

Dialog Boxes | Menu and Shortcut Designers


New Class Dialog Box

Specifies information for a new class; this information is then used by the Class Designer.

This dialog box appears when you select Class in the New dialog box and then choose New File or type CREATE CLASS in the Command window.

Class Name
Specifies the name of the class definition to create.
Note The name that you specify is converted to lowercase when the class is saved.
Based On
Specifies the class on which the new class definition is based. Choose from the list, or click the dialog button to display a dialog box from which you can select a .vcx file. This list includes all Visual FoxPro classes by default.
From
Lists the path to the visual class library of the base class you specified in the Based On box.
Store In
Displays a File Save dialog box in which you can specify the name of the visual class library in which to save the new class.

See Also

Command Window | Class Designer | Class Property | Class Library Property | CREATE CLASS Command | Open Dialog Box | New Label Dialog Box | New Dialog Box | Creating, Copying, and Removing Class Library Files


New Dialog Box

Lets you create new files using designers and wizards.

Visual FoxPro provides a range of designers to help you create classes, connections, databases, forms, labels, menus, queries, local and remote views, reports, and tables. You may also use a Visual FoxPro wizard to create many of these files, including a variety of reports, forms, and queries. New program or text files are created by simply typing them in the Editing Window. The following table shows you the file types and how each can be created.

Shortcut

CTRL+N

The New dialog box appears when you select New from the File menu.

File Type
The following table lists the file types and the features available for creating them, depending on whether you click New File or Wizards.
File Type | Created With
Project | Project Manager
Database | Database Designer
Table | Table Designer, Table Wizard
Query | Query Designer, Cross-Tab Wizard, Query Wizard, Local View Wizard, Remote View Wizard, PivotTable Wizard
Connection* | Connection Designer
View* | View Designer, Local View Wizard
Remote View* | Remote View Wizard
Form | Form Designer, Form Wizard, One-to-Many Form Wizard
Report | Report Designer, Report Wizard, One-to-Many Report Wizard
Label | Label Designer, Label Wizard
Program | Editing Window
Class | Class Designer
Text File | Editing Window
Menu | Menu Designer

* You must have a database open to enable this option.

New File
Displays a dialog box, designer, or editing window so you can create the selected file type.
Wizard
Opens a wizard that creates the selected file type. If there is a group of wizards to choose from, Visual FoxPro will prompt you to select the wizard you want.

See Also

Create Dialog Box | Class Designer | Connection Designer | Database Designer | Editing Window | Form Designer | Label Designer | Menu Designer | Project Manager | Query Designer | Report Designer | Table Designer | View Designer


New File Dialog Box

Lets you create a new form, report, label, or query, depending on the type of file currently selected in the Project Manager.

If you check Prompt for Wizard in the Projects tab, Options dialog box, Visual FoxPro prompts you with the option of running a wizard if there is a wizard associated with the selected file type.

Note File names preceded by a slashed circle are excluded when the project is built. If there is no slashed circle by the file name, that file will be included in the build. The main program file name is in bold.

This dialog box appears when you select New File from the Project menu.

File Type Wizard
Opens a wizard that creates the selected file type. If there is a group of wizards to choose from, Visual FoxPro will prompt you to select the wizard you want. Displayed only if you check Prompt for Wizard in the Projects tab, Options dialog box.
New File Type
Displays a dialog box, designer, or editing window so you can create the selected file type.

See Also

New Dialog Box | Options Dialog Box | Project Manager Window | Projects Tab, Options Dialog Box | CREATE FORM Command | Creating Forms | CREATE REPORT Command | CREATE LABEL Command | Creating a New Form | Creating a Query | CREATE QUERY Command | Rename File Dialog Box | Description Dialog Box | Wizards


New Label Dialog Box

Displays predefined Avery label types. This dialog box appears when you select Label from the New dialog box and then choose New File. The type you select becomes the basis for the new label you create in the Label Designer. The Columns column refers to how many columns of that label type will fit on a page.

The following columns display information about the label (you cannot change these settings):

Avery No.
The manufacturer's identification number for a particular label type.
Height
The height in inches of an individual label.
Width
The width in inches of an individual label.
Columns
How many columns of that label type will fit on an 8 1/2 inch x 11 inch page.
Note You can add a new label size to the list using the ADDLABEL.APP application located in the Visual FoxPro ...\Tools directory.

See Also

CREATE LABEL Command | Label Designer | Select Connection or Data Source Dialog Box | Creating Reports and Labels | Addlabel.app | Report Layout Preparation | Label Wizard | New Dialog Box | ADDLABEL.APP


New Local View Dialog Box

This dialog box lets you create a view of local tables or other views in the database using either the Local View wizard or View designer. Local views can include native Visual FoxPro .dbf format tables, existing local or remote views, any tables in a .dbf format, and other tables stored on local servers.

The New Local View dialog box only displays the Local View Wizard option when you have selected Prompt for Wizards in the Projects tab of the Options dialog box.

View Wizard
Opens the Local View wizard, which creates a local view.
New View
Opens the View designer so you can create a local view.

See Also

Database Designer | Local View Wizard | Options Dialog Box | Projects Tab, Options Dialog Box | View Designer | New Remote View Dialog Box | Find Table or View Dialog Box | Combining Views | Updating Multiple Tables in a View | Creating a Local View | Creating Views


New Method Dialog Box

Allows you to create a new method and specify the description and visibility of the method.

This dialog box appears when you select New Method from the Class or Form menus.

Name
Specifies the name of the new method.
Visibility (Classes only)
Specifies whether the class property is protected. Protected properties cannot be accessed by object instances, but can be accessed by subclasses. Hidden properties cannot be accessed by either object instances or subclasses.
Description
Contains the method description to be displayed at the bottom of the Properties Window in the Class Designer and, if the property is not protected, in the Form Designer.

See Also

Class Designer | Edit Property/Method Dialog Box | Form Designer | New Property Dialog Box | Properties Window | Adding Properties and Methods to a Form


New Property Dialog Box

Allows you to create a new property and specify the description and visibility of the property.

This dialog box appears when you select New Property from the Class or Form menus.

Name
Specifies the name of the new property.
Visibility (Classes only)
Protected properties cannot be accessed by object instances, but can be accessed by subclasses. Hidden properties cannot be accessed by either object instances or subclasses.
Access Method
Specifies if an Access method is created for the new property. The code in an Access method is executed whenever the property is queried. Select this check box to create an Access method for a property.
Assign Method
Specifies if an Assign method is created for the new property. The code in an Assign method is executed whenever you attempt to change the value of the property. Select this check box to create an Assign method for a property.
Description
Contains the method description to be displayed at the bottom of the Properties window in the Class Designer and, if the property is not protected, in the Form Designer.

See Also

Access and Assign Methods | Class Designer | Edit Property/Method Dialog Box | Form Designer | New Class Dialog Box | New Method Dialog Box | Properties Window | Forms Property


New Remote View Dialog Box

This dialog box lets you create a new remote view using the View designer or the Remote View wizard. If the information you need is on a remote data source, you can create a remote view from it and incorporate that view into your database.

The New Remote View dialog box only displays the Remote View Wizard option when you have selected Prompt for Wizards in the Projects tab of the Options dialog box.

Note Before you can create a new remote view, you must establish a connection or ODBC data source. To establish a connection, use the Connection designer.
View Wizard
Opens the Remote View wizard, which creates a remote view.
New View
Opens the Select Connection Or Data Source dialog box so you can select a remote data source to use in your remote view.

See Also

Connection Designer | Database Designer | Projects Tab, Options Dialog Box | Options Dialog Box | Remote View Wizard | Select Connection or Data Source Dialog Box | View Designer | Accessing Remote Data


New Table Dialog Box

This dialog box lets you create a new table in the database using the Table designer or the Table wizard.

Table Wizard
Opens the Table wizard, which creates a table for you. The wizard provides sample fields that make it easy to create a table structure. The New Table dialog box only displays the Table wizard option when you have selected Prompt for Wizards in the Projects tab of the Options dialog box, which appears when you select New Table from the Database menu.
New Table
Opens the Table designer so you can create a table in the database.

See Also

ADD TABLE Command | Database Designer | Options Dialog Box | Projects Tab, Options Dialog Box | Table Designer | Table Wizard | Creating a Database Table | Copying and Editing Table Structure | New Remote View Dialog Box | New Local View Dialog Box | Adding Tables to a Database


Open Dialog Box

Use to open an existing file or create a new file. This dialog box appears when you select Open from the File menu.

Previously opened projects appear at the bottom of the File menu. You can open a previously opened project by choosing its name from the bottom of the File menu.

Note Files created with the Open command are not added to a project.

The GETFILE( ) function corresponds to the Open Dialog Box. For example, this dialog box appears when you type ? GETFILE( ) in the Command window.

Shortcut

CTRL+O

Look in
Displays a drop-down list of locations where you can look for your file. On Windows 2000 and Windows XP operating systems, the Places bar on the left side of the dialog box displays common locations such as My Documents and Desktop. Click one of these icons to make the corresponding location appear in the drop-down list.
File name
Displays the name of the currently selected file or allows you to specify the file you want to open.
Class Library
Specifies the name of the class library. This box appears only when opening a class library or when using AGETCLASS( ) or MODIFY CLASS.
Files of type
Displays a list of file types. You can select a file type from the drop-down list to display only files of a particular type. The following extensions are no longer used in this version of Visual FoxPro: .lbl, .fpc, .cat, and .frm.
Class Name
Displays classes stored in the class library displayed in the Class Name box. This list appears only when opening a class library or when using AGETCLASS( ) or MODIFY CLASS.
Open as read-only
Specifies that the file you open can be viewed but not modified.
Environment
Saves all environment settings with the file and opens the associated environment when you open the file.
Note The Environment check box appears only in versions prior to Visual FoxPro 8.0.

This option is available when you choose Form, Label, or Report from the List Files of Type list and is checked by default. To open a form, label, or report without opening an associated environment, clear the check box.

Open exclusive
Specfies that you can use a table (.dbf) or database (.dbc) file exclusively so that no other user can open the file. This option is available only when opening a table. Corresponds to the USE command.
Code Page
Displays the Code Page dialog box so you can specify the code page needed to view the file correctly. This command applies only to text files such as program (.prg), query (.qpr), and text (.txt) files.
Preview
Specifies that you can preview graphic files when they are selected in the files list. This check box appears only when you can open or select a graphics file. For example, this check box appears in the Open dialog when you add an Image control to a form and double-click the Picture property in the Properties window.
Note The Preview check box appears only when running Visual FoxPro on operating systems earlier than Windows 2000. You can preview images in Windows 2000 and later by clicking the View Menu icon near the top of the dialog box and then Thumbnails.

See Also

Open Picture Dialog Box | New Class Dialog Box | Code Page Dialog Box | GETFILE( ) Function | Open Picture Dialog Box | USE EXCLUSIVE Command | USE Command


Open Picture Dialog Box

Use to open an existing graphic file.

The GETPICT( ) function corresponds to the Open Picture dialog box. For example, this dialog box appears when you type ? GETPICT( ) in the Command window.

Look in
Displays a drop-down list of locations where you can look for your file. On Windows 2000 and Windows XP operating systems, the Places bar on the left side of the dialog box displays common locations such as My Documents and Desktop. Click one of these icons to make the corresponding location appear in the drop-down list.
File name
Displays the name of the currently selected file or allows you to specify the file you want to open.
Files of type
Displays a list of file types. You can select a file type from the drop-down list to display files of a particular type. The following extensions are no longer used in this version of Visual FoxPro: .lbl, .fpc, .cat, and .frm.
Picture
Displays a preview of the selected graphic file when the Preview check box is selected.
Note Picture appears only when running Visual FoxPro on operating systems earlier than Windows 2000. Otherwise, the Open Picture dialog box shows a thumbnail (smaller) version of the graphic file. Double-click the thumbnail to view a larger version of the file.
Preview
Allows you to preview the selected graphic file.
Note The Preview check box appears only when running Visual FoxPro on operating systems earlier than Windows 2000. You can preview images in Windows 2000 and later by clicking the View Menu icon near the top of the dialog box and then Thumbnails.

See Also

Open Dialog Box | Code Page Dialog Box | GETPICT( ) | Open Dialog Box | Command Window | Graphics Support in Visual FoxPro | Creating Graphical Help | Report Picture Dialog Box


Options Dialog Box

Makes it possible for you to set different categories of options. The Options dialog box appears when you select Options from the Tools menu.

When you click Set As Default, Visual FoxPro saves all the options on all tabs.

The following table describes tabs that appear in the Options dialog box.

Tab | Options available
Controls Tab, Options Dialog Box | Set options for the visual class libraries and ActiveX controls to make available from the View Classes button on the Form Controls toolbar.
Data Tab, Options Dialog Box | Set table options, such as whether to use Rushmore Query Optimization, enforce unique records in indexes, and specify the collating sequence, memo block size, record counter interval for searches, and locking/buffering options to use.
Debug Tab, Options Dialog Box | Set debugger display and trace options, such as windows, font, and colors.
Editor Tab, Options Dialog Box | Set font and color options for identifying program elements, such as comments and keywords in the Command window and in all editing windows, except those opened with the MODIFY FILE or MODIFY MEMO commands.
Field Mapping Tab, Options Dialog Box | Set options for the controls to create when dragging tables or fields to a form from the Data Environment Designer, Database Designer, or Project Manager Window.
File Locations Tab, Options Dialog Box | Set locations for the default Visual FoxPro directory, where Help is stored, and where auxiliary files are stored.
Forms Tab, Options Dialog Box | Set Form Designer options, such as the grid spacing, the scale units to use, the maximum design area, and what template classes to use.
General Tab, Options Dialog Box | Set data entry and programming options, such as specifying the warning sound, whether to log compilation errors, whether to automatically fill new records, what navigation keys to use, what color palette to use, and whether to warn before overwriting files.
IDE Tab, Options Dialog Box | Set formatting, appearance, and behavior settings for Visual FoxPro file types.
Projects Tab, Options Dialog Box | Set Project Manager options, such as whether to prompt for wizards, whether to run or modify files on double-click, and options for source control.
Regional Tab, Options Dialog Box | Set formats for dates, times, currency, and numbers.
Remote Data Tab, Options Dialog Box | Set remote data access options, such as connection timeout values, the number of records to fetch at once, and how to use SQL for updates.
Reports Tab, Options Dialog Box | Configure settings for the Report Designer when creating reports.
View Tab, Options Dialog Box | Set interface options, such as whether to display a status bar, clock, command results, system messages, or a recently used project list.

See Also

Dialog Boxes | Viewing and Changing Environment Settings | Visual FoxPro Environment Settings


Controls Tab, Options Dialog Box

Contains options to register visual class libraries for specifying template classes on the Forms Tab, Options Dialog Box. These options also specify what can be selected from the View Classes button on the Form Controls Toolbar to make adding custom controls to forms easy.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Visual class libraries
Specifies that class libraries (.vcx files) are displayed in the Selected list.
ActiveX controls
Specifies that ActiveX controls are displayed in the Selected list.
Selected
Lists files that you can add or remove to your Visual FoxPro environment. If you have chosen Visual class libraries, the list displays the .vcx files that you have already added, and specifies which libraries appear on the shortcut menu when you click the View Classes button on the Form Controls Toolbar.

If you have chosen ActiveX controls, the list displays the classes of objects and controls available on your system. ActiveX objects and controls that you have already added are checked, and appear on the shortcut menu when you click the View Classes button on the Form Controls toolbar.

Label
Appears when the Visual class libraries option is selected. Specifies the name for the class library. By default, Visual FoxPro uses the file name without the .vcx extension.
Library
Appears when the Visual class libraries option is selected. Displays the path and file name for of the .vcx files for the currently selected class library.
Show
Appears when the ActiveX is selected. Makes it possible for you to specify what types of ActiveX objects appear in the Selected list.
  • Insertable Objects Specifies that the Selected list displays classes of objects that you can insert as ActiveX objects into Visual FoxPro applications.
  • Controls Specifies that the Selected list displays ActiveX controls.
Add
Choose this button to display the Open Dialog Box so you can add libraries (.vcx files) or ActiveX controls to the Selected list. Adding an ActiveX control also registers it so it will be available in the list of controls in the Insert Object Dialog Box and in other applications.
Remove
Appears when the Visual class libraries option is selected. Choose this button to remove the selected library from the Selected box.

See Also

Forms Tab, Options Dialog Box | Insert Object Dialog Box | Open Dialog Box | Options Dialog Box


Data Tab, Options Dialog Box

Contains options for controlling data in tables.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves all the options on all tabs.

Open exclusive
Specifies whether Visual FoxPro opens tables and databases exclusively, so that no one else can view or modify them while you are working on them. Opening files exclusively can result in better performance. Use this option when processing large numbers of records under circumstances when other users do not need access to data (such as at night). This option corresponds to the SET EXCLUSIVE Command.
Show field names
Specifies whether Visual FoxPro displays a field name as a column heading above each field in the output of the AVERAGE Command, CALCULATE Command, DISPLAY Command, LIST Commands, and SUM Command. This option corresponds to the SET HEADINGS Command.
Prompt for code page
Specifies whether Visual FoxPro prompts you to attach a code page when you open tables that do not already have one attached. This option corresponds to the SET CPDIALOG Command.
Ignore deleted records
Specifies whether Visual FoxPro ignores records marked for deletion when executing commands that use a scope clause. If this option is cleared, Visual FoxPro includes the marked records. This option corresponds to the SET DELETED Command.
Rushmore Query Optimization
Specifies whether Visual FoxPro uses Rushmore optimization when executing commands that include a FOR clause. This option corresponds to the SET OPTIMIZE Command. For more information, see Optimizing Applications.
Unique records in indexes
Specifies whether Visual FoxPro allows records with duplicate index key values in an index file. If you choose this option, only the first record containing the original key index is indexed. This option corresponds to the SET UNIQUE Command.
Collating sequence
Specifies a collation sequence (sort order) for character fields in indexing and sorting operations. This option corresponds to the SET COLLATE Command.
Record counter interval
Specifies how many records should be processed during commands such as COPY TO before Visual FoxPro updates the record counter display in the status line. The range is from 1 to 32,767 records. The higher the number you specify, the longer the delay between updates, but the command can run faster. You must choose the Status Bar option on the View tab for this option to have effect. This option corresponds to the SET ODOMETER Command.
Memo block size (bytes)
Specifies the block size in which disk space for memo fields is allocated. The value you enter specifies the minimum disk space required for a memo field, and the size by which memo fields increase as data is added to them. If you specify a value between 1 and 32, Visual FoxPro multiplies your value by 512, and then allocates disk space in a block of that size. If you specify a value greater than 32, Visual FoxPro allocates blocks of only that size; specifying a number greater than 32 can therefore save disk space. This option corresponds to the SET BLOCKSIZE Command.
Browse refresh interval (sec)
Specifies how often Visual FoxPro updates the display of records in an active Browse window, which is useful in a multiuser environment. Possible values are 0 to 3600. Set this value to 0 to prevent updates. Set this value to a high number to update the Browse window less often, which can increase performance. This option corresponds to the SET REFRESH Command.
Table refresh interval (sec)
Specifies how often Visual FoxPro should update the display of an active table, which is useful in a multiuser environment. Possible values are 0 to 3600. Set this value to 0 to prevent updates; set this value to a high number to update the table less often, which can increase performance. This option corresponds to the SET REFRESH Command.

String comparisons

SET NEAR on
Specifies that Visual FoxPro positions the record pointer on the closest matching record after an unsuccessful FIND or SEEK command. This option corresponds to the SET NEAR Command.
SET EXACT on
Specifies that Visual FoxPro uses the full length of both string expressions (except for trailing blanks) when using the comparison operator (=). If you clear this option, Visual FoxPro stops comparing two strings when the end of the expression on the right side of the comparison operator (=) is reached. This option corresponds to the SET EXACT Command.
Note This setting has no effect on the results of the = operator.
SET ANSI on
Specifies whether Visual FoxPro pads strings when comparing them with the SQL = operator, which compares character by character until the shorter string is finished. If you choose this option, Visual FoxPro pads the shorter string with spaces, so a SQL comparison fails ("Tommy" is not equivalent to "Tom "). If you clear this option, the shorter string is not padded, so strings of unequal length can be equivalent ("Tommy" is equivalent to "Tom"). This option corresponds to the SET ANSI Command.

Locking and buffering

Automatic file locking
Specifies that Visual FoxPro automatically locks files for certain commands that do not change data including AVERAGE, COPY TO, INDEX, REPORT, SORT, and TOTAL. If you clear this option, the file is not locked during these commands, and other users can change records while your command is being executed. This option corresponds to the SET LOCK Command.
Multiple record locks
Specifies whether Visual FoxPro locks multiple records concurrently. If you clear this option, Visual FoxPro clears all current locks and makes it possible for you to lock only one record at a time; the current record is unlocked when you lock the next one. This option corresponds to the SET MULTILOCKS Command.
Buffering
Specifies for multiuser environments whether to buffer record changes locally, and if so, whether to do so optimistically or pessimistically. Buffering can improve performance and provide greater concurrency control. You must choose the Multiple Record Locks option for this option to have effect. It corresponds to the CURSORSETPROP( ) Function. Options are:
  • Off Changes are not buffered, and record updates are made immediately to disk. This mode is recommended only when working in a single-user environment.
  • Record (Pessimistic) The current record is locked when the user makes a change to it, and changes are buffered. Other users can read but not change the record on disk. When the record pointer moves to another record, the current record is written back automatically from the buffer to the source table, and then unlocked. Pessimistic record locking is useful for interactive editing in a table subject to many updates by other users.
  • Record (Optimistic) Changes for a single record are buffered but not locked when the user moves the record pointer to the record. Other users can read and change the record on disk. When the user moves the record pointer to another record, Visual FoxPro checks changes in the current record against the record on disk. If the record on disk has been changed, Visual FoxPro offers options to discard current changes or overwrite the record on disk. Optimistic record buffering is recommended primarily when updating tables in which there is little activity.
  • Table (Pessimistic) Record changes are buffered and locked when the user moves the record pointer to them, and remain so until TABLEUPDATE( ) Function is called. Pessimistic table buffering is the safest mode for updating multiple records in a table, but because it locks every changed record, it can limit other users' access to the data. It is therefore recommended only to help speed data entry when users will be entering new records in batches, or when it is essential for the application that all currently used records be held exclusively by the application.
    Note When using table buffering, you must issue TABLEUPDATE( ) to write buffered record changes to the disk. If you don't, the changed records are discarded when the user quits Visual FoxPro.
  • Table (Optimistic) Record changes are buffered, but not locked, when the user moves the record pointer to the record. Other users can read and change the records on disk. When TABLEUPDATE( ) is issued, Visual FoxPro checks for changes in each record as the record is written to disk; records that have changed are not written. Optimistic table buffering is useful for optimizing update performance in tables in which there is little activity. When using this option, issue TABLEUPDATE( ) often so that the chances of buffered records changing on disk is minimized.
    Note When using table buffering, you must issue TABLEUPDATE( ) to write buffered record changes to the disk. If you don't, the changed records are discarded when the user quits Visual FoxPro.
Reprocessing
Specifies how many times or for how long Visual FoxPro attempts to lock a record or table that is already locked by another user. This option corresponds to the SET REPROCESS Command. Choices are:
  • Attempt Lock (Default). Attempts to lock one time only.
  • Attempt Lock (Automatic). Continues to attempt the lock until successful or until the user cancels the attempt by pressing ESC. Equivalent to SET REPROCESS TO AUTO.
  • Wait for Lock. Continues to attempt a lock until the record becomes available. This option does not provide a way for the user to stop trying to lock the record. Equivalent to SET REPROCESS TO -1.
  • Retry Attempts. Attempts to lock the record or table the specified number of times. If the lock is still unsuccessful, an error message is displayed. SET REPROCESS TO n, where n is the number of retry attempts.
  • Retry Seconds. Attempts to lock the record or table for the specified number of seconds. If the lock is still unsuccessful, an error message is displayed. SET REPROCESS TO n SECONDS, where n is the number of seconds to retry.

See Also

Options Dialog Box


Debug Tab, Options Dialog Box

Makes it possible for you to set options to customize the Visual FoxPro debugger windows, including:

  • Font and colors.
  • Whether to trace Timer event code.
  • Whether line numbers are displayed.
  • Whether to log Debug Output window output to a file.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Environment
Specifies the debugging environment.
  • Debug frame All debugger windows appear in one big frame that is external to the Visual FoxPro main window, with their own menus and toolbars. This makes the debugger less intrusive on your application's run-time environment. If you choose this option, you can open the debugger by choosing Debugger on the Tools Menu.
  • FoxPro frame Debugger windows appear in the Visual FoxPro main window. The FoxPro environment is most useful if you want just a single window open, for example the Watch window. If you choose this option, Visual FoxPro replaces the Debugger command on the Tools Menu with commands to open individual debug windows, and toolbars for individual debug windows are tiled to the main Visual FoxPro window.
    Note You cannot change this option if the full debugger or any debugger window is open, or if the debug toolbar is open in the Visual FoxPro desktop.
Display timer events
Choose this option if you want Timer Control timer events displayed in the Trace Window when their interval value is reached. If you clear this option, the timer event still occurs, but is not displayed; it is treated as if you had specified Step Over for that event.

With this check box cleared, Visual FoxPro filters timer events even when you are stepping through a timer event currently. This is by design. Visual FoxPro steps inside a timer event in the following situations:

  • SET STEP is ON.
  • A breakpoint is set on a line of code.
  • A breakpoint is set on a value that is changed.
  • A new method or procedure is called.

Specify Window

Choose an option to specify which debugger window you want to set options for. The window you choose here affects the following available options.

Call Stack
Displays the following options for the window:
  • Show call stack order Displays a number beside each program listed in the Call Stack Window window, with the highest number indicating the currently executing program.
  • Show current line indicator Indicates whether the current line indicator is displayed in the Call Stack window.
  • Show Call Stack indicator Indicates whether an arrow is displayed in the Call Stack window to indicate the procedure displayed in the Trace Window window. If the current line and call stack procedures are the same, Visual FoxPro displays only the current line indicator.
Locals
No additional options are available for this window.
Output
Displays the Log debug output area, which contains the following options:
  • Log Debug Output Copies the values written in the Debug Output Window to a text file. If you choose to log output values, you need to specify a file to log them to. The default file extension for a log file is .log. Visual FoxPro will log output to a file only if the Output window is displayed. You can display information in the Output window (and send it to the log file) using the DEBUGOUT Command or SET PRINTER Command in a program.

    When you quit Visual FoxPro, this option is cleared, so that you do not inadvertently overwrite a log file the next time you start Visual FoxPro.

  • Append Specifies that the debug output is written after the current contents of an existing file, preserving the original contents.
  • Overwrite Specifies that the debug output replaces the contents of the specified file.
Trace
Displays the following options for the window:
  • Show line numbers Displays line numbers to the left of the lines of code in the Trace Window.
  • Trace between breakpoints Executes code between breakpoints at the throttle speed. The throttle speed indicates the pause in seconds between the execution of each line of code. If you clear this option, code between breakpoints is executed at normal speed, the default setting of _THROTTLE System Variable, which is 0. Equivalent to using the SET TRBETWEEN command.
  • Pause between line execution Sets the throttle, which is the delay in seconds between the execution of each line of code. This option makes it possible for you to slow program execution so you can watch the lines of code without having to step through each line individually. Trace between breakpoints must be on for this setting to have any effect. Equivalent to setting the _THROTTLE system memory variable.
Watch
No additional options are available for this window.
Font
Choose a font and style for the specified debugger window. For example, to set the font of the debugger's Trace window, choose Trace under Specify Window, and then choose Font to select the font, size, and style.

Colors

Area
Select the text element for which you want to specify a color. For example, to specify a color for the text used for changed values, select Changed Value. The choices in the Area list depend on what window has been specified under Specify Window.
Foreground
Choose a color for the text of the selected area. To use the default color established in the Windows control panel, select Automatic.
Background
Choose a background color for the selected area. For example, to show comments in yellow text on a blue background, select yellow in Foreground and blue in Background. To use the default color established in the Windows control panel, select Automatic.

For more information, see Testing and Debugging Applications.

See Also

Call Stack Window | Debug Output Window | Debugger Window | Trace Window | Watch Window | Options Dialog Box


Editor Tab, Options Dialog Box

Contains options to specify color and font to identify Visual FoxPro program elements, such as keywords and comments, in the command window and in all editing windows — except those opened with the MODIFY FILE Command or MODIFY MEMO Command.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Editor options

Makes it possible for you to specify functionality common to all Visual FoxPro editors.

Selection margin
Makes it possible for you to specify whether editors display a selection margin so you can highlight a line and specify breakpoints, or Bookmarks and Shortcuts.
Enable hyperlinks
Specifies whether editor windows recogize "http:/" as hyperlink and your entry as such.
Drag Drop between words
Specifies whether drag and drop behavior permits dragging into words or only between words.
Comment string
Specifies the character that identifies a comment in code. The default comment string is *!*
List display count
Specifies the maximum number of items in a dropdown list.
Highlight duration
Specifies the number of milliseconds to highlight statements in parenthetical or bracket delimiters. You can select one of the settings from the list, or type any specific duration into the box manually.

Syntax color settings

Makes it possible for you to specify characteristics of syntax coloring.

Area
Choose the type of program element to set font and color options for. When you make your selection, the other controls are updated with values for the selected area.
Font style
Choose a font style for the specified area. For example, to display all comments in your programs italic, select Comments in the Area box, then select Italic in the Font style box.
Foreground
Choose a color for the text of the selected area. To use the default color established in the Control Panel, select Automatic.
Background
Choose a background color for the selected area. For example, to show comments in yellow text on a blue background, choose Comments in the Area box, select yellow in Foreground, and then select blue in Background. To use the default color established in the Control Panel, select Automatic.

The sample area displays the effect of your settings.

Reset All
Choose this option to set syntax coloring to the Visual FoxPro default settings.

See Also

Edit Properties Dialog Box | MODIFY FILE Command | MODIFY MEMO Command | Options Dialog Box


Field Mapping Tab, Options Dialog Box

Makes it possible for you to specify what type of control Visual FoxPro creates when you drag a table or field to a form from the Data Environment Designer, Database Designer, or Project Manager Window. For example, you can specify that Visual FoxPro create an edit box when you drag a Character field onto a form.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database). Note that in this tab, choosing OK also saves the option settings in the registry.

Map fields to classes for drag-and-drop operations
Displays the current mappings between field types and classes (controls). The list includes:
  • Type All supported data types for database fields. The field type Multiple is used to specify the class that will be created if you drag an entire table or multiple fields onto a control at once. The field type Label is used to specify the class that will be created for the field captions.
  • Class Library The library containing the class definition to map to a field type. If this column is blank, the field type is mapped to a Visual FoxPro base class.
  • Class Name The class to which a field type is mapped, which specifies the type of control that will be created.
Modify
Choose this button to display the Modify Field Mapping Dialog Box, where you can specify a different mapping for the selected field type.

To modify field mappings

  1. In the Field Mapping tab of the Options dialog box, choose Modify.
  2. In the Modify Field Mapping dialog box, select a field type from the Type list.
  3. To set the class that is created whenever you drag a table or multiple fields, select Multiple.
  4. To select the class library (.vcx file) that contains the control you want to associate with the selected field type, choose Browse.
  5. Select a class name from the Name list. The class you specify here will be created any time a field of the selected type is dragged onto a form.
  6. Choose OK or Apply to accept the mapping.

Database options

Drag-and-drop field caption
Choose this option if you want Visual FoxPro to use the name of the field as the caption of the class being created. If you clear this option, Visual FoxPro will not create field captions.
Copy field comment
Choose this option to have Visual FoxPro copy the comment from a field (if any) to the Comment property of the new class when creating it.
Copy field input mask
Choose this option to have Visual FoxPro copy the input mask of a field (if any) to the InputMask property of the new class when creating it.
Copy field format
Choose this option to have Visual FoxPro copy the format specification from a field (if any) to the Format property of the new class when creating it.

See Also

Modify Field Mapping Dialog Box | Options Dialog Box | Data Environment Designer | Database Designer | Project Manager Window | Adding Visual FoxPro Controls to a Form | Adding Controls to a Form with the Component Gallery


Modify Field Mapping Dialog Box

Use this dialog box to change the mapping between a database field type and the type of class (control) that Visual FoxPro creates when you drag a table or field onto a form from the Data Environment Designer, Database Designer, or Project Manager Window.

This dialog box appears when you choose Modify in the Field Mapping Tab, Options Dialog Box.

Type
Select the database field type for which you want to change the mapping. By default, the field type is selected that was selected in the Field Type Mapping tab.

Class information

Library
Enter a class library that contains the class that you want to have Visual FoxPro create when a field of the specified type is dragged onto a form. If this box is blank, the field type is mapped to a Visual FoxPro base class.
Browse
Choose this to display the Open Dialog Box, from which you can select a class library.
Name
Select the name of a class to map to the specified field type. The list contains only the classes in the library you chose; to display the Visual FoxPro base classes in this box, clear the Library box. The base class and description of the selected class, if available, is displayed below the class name.
Apply
Choose this to create the mapping. Choose Apply if you want to change a mapping but keep the Field Type Mapping dialog box open to change another mapping. To change a single mapping, choose OK.

See Also

Field Mapping Tab, Options Dialog Box | Options Dialog Box | Data Environment Designer | Database Designer | Project Manager Window | Adding Visual FoxPro Controls to a Form


File Locations Tab, Options Dialog Box

Contains directory locations and names of files used by Visual FoxPro. You can type the path and file name directly into each box or click the dialog button to display a dialog box for setting the option.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Beautify
Specifies the file name of the application that is called when you choose Beautify in the Tools menu. The Beautify command appears on the Tools menu when you open a program or text file in an editing window. Contains Beautify.app by default. This option corresponds to the _BEAUTIFY System Variable.
Builders
Specifies the file name of the application that is called in the Form Designer when you choose Builder from the right-click menu. A builder consists of one or more dialog boxes that help you set properties for a specific control, or combine clauses to create a specific expression. This option corresponds to the _BUILDER System Variable. Builders can be displayed automatically if you choose the Builder lock option in the Forms Tab, Options Dialog Box.
Class Browser
Specifies the file name of the application that is called when you choose Class Browser in the Tools menu. This file corresponds to the _BROWSER System Variable and contains Browser.app by default.
Code References
Specifies the name of the application that is called when you choose Code References from the Tools menu, or when you select Look Up Reference or View Definition from the shortcut menu from the Editing window of a program. This file corresponds to the _FOXREF System Variable and contains FoxRef.app by default.
Component Gallery
Specifies the file name of the application that is called when you choose Component Gallery in the Tools menu. Contains Gallery.app by default. This option corresponds to the _GALLERY System Variable.
Converter
Specifies the file name of the application that is called when you open a form, report, or other application component created in an earlier version of FoxPro or Visual FoxPro. The specified application converts the component to the current file format. This option corresponds to the _CONVERTER System Variable.
Coverage Profiler
Specifies the file name of the application that creates the Debugger coverage and profiler output. Contains Coverage.app by default. This option corresponds to the _COVERAGE system variable.
Cross tab Generation
Specifies the name and location of the program that creates cross-tabs.
Default Directory
Specifies the default Visual FoxPro directory. If you check this box and choose Set As Default, the displayed directory is registered as the default for the current session and all future sessions. If you clear this option and choose Set As Default, the displayed directory is deleted from the registry. If you check this box and choose OK, this changes the default directory for the current session only. Finally, if you clear this option, you will not be able to change the current session's default directory. This option corresponds to the SET DEFAULT Command.
Default Include File
Specifies a default header file of predefined compile-time constants automatically included with user-defined classes, forms, or form sets. This option is empty by default, and corresponds to the _INCLUDE System Variable.
Expression Builder
Specifies the file name of the application that is executed when you issue the GETEXPR command or invoke the Expression Builder dialog box from within Visual FoxPro. This option is empty by default, and corresponds to the _GETEXPR System Variable.
FoxCode
Specifies the name and location of the table that provides IntelliSense functionality. This option corresponds to the FoxCode Property.
FoxTask
Specifies the name and location of the table that contains the tasklist records. This option corresponds to the _FoxTask System Variable.
Help File
Specifies whether Visual FoxPro displays Help, and if so, what file to use. If the file name's extension is .hlp, then graphical Help is used. If the file name's extension is .dbf, then .dbf-style Help is used. If no extension is specified, the default is graphical Help. This option corresponds to the SET HELP Command.
HTML Generator
Specifies the file name of the application that is called when you choose Save As HTML from the File menu. Contains Genhtml.prg by default. This option corresponds to the _GENHTML System Variable.
IntelliSense Manager
Specifies the name and location of the program that provides Visual FoxPro IntelliSense.
Menu Builder
Specifies the file name of the menu builder program. This option corresponds to the _GENMENU System Variable system variable.
Object Browser
Specifies the name and location of the Object Browser. This option corresponds to _ObjectBrowser System Variable.
Resource File
Specifies whether Visual FoxPro stores its current state (macros, size and location of windows, and so on) into a resource file, and if so, what file to use. If this option is not selected, Visual FoxPro resets the system state to its default each time you start the program. In addition, some options in the Options dialog box will be disabled.

This option corresponds to the SET RESOURCE Command.

Samples Directory
Specifies the directory containing the Visual FoxPro sample files. This option corresponds to the _SAMPLES System Variable.
Search Path
Specifies the directories that Visual FoxPro searches in for files if it does not find the files in the default directory. The directories must be separated by commas or semicolons. You can use the dialog button to automatically insert semicolons when specifying multiple directories. This option corresponds to the SET PATH Command.
Startup Program
Specifies the file name of the application that is called when you start Visual FoxPro. It contains Vfp8strt.app by default. This option corresponds to the _STARTUP System Variable.
Task List
Specifies the name and location of the program that manages the tasklist. This option corresponds to the _TASKLIST System Variable.
Temporary Files
Specifies the directory in which Visual FoxPro saves temporary files — for example, when sorting or indexing. Because temporary files can grow quite large, specify a directory with plenty of free space. For best performance, specify a fast drive; for example, in a multiuser environment, you might specify a local drive.
Wizards
Specifies the file name of the application that is called when you run a wizard. This option corresponds to the _WIZARD System Variable.

For more information, see Customizing the Visual FoxPro Environment in the Installation Guide.

See Also

_COVERAGE System Variable | _GALLERY System Variable | ADDLABEL.APP | _BUILDER System Variable | _CONVERTER System Variable | _GENMENU System Variable | Options Dialog Box | SET DEFAULT Command | SET HELP Command | SET PATH Command | SET RESOURCE Command | _WIZARD System Variable | _TASKLIST System Variable | _OBJECTBROWSER System Variable | _FoxTask System Variable


Forms Tab, Options Dialog Box

Contains options for the Form Designer.

When you choose Set As Default, which appears on every tab in the dialog box, Visual FoxPro saves the option settings in the registry (system Windows registration database).

Note If an instance of the Form Designer is already open when you change settings in the Forms tab of the Options dialog box, the Form Designer does not reflect the changes until you close that instance and reopen it.

Grid

Grid lines
Specifies that the Form Designer displays grid lines to help you align controls.
Note These are defaults for new forms only. Settings for existing forms are saved in the resource file.
Snap to grid
Specifies that when you draw new controls, their edges align with the nearest grid lines.
Note These are defaults for new forms only. Settings for existing forms are saved in the resource file.
Horizontal spacing (pixels)
Specifies the width of the space between horizontal grid lines. The width is based on the Scale units option on the Forms tab.
Note These are defaults for new forms only. Settings for existing forms are saved in the resource file.
Vertical spacing (pixels)
Specifies the height of the space between vertical grid lines. The height is based on the Scale Units option on the Forms tab.
Note These are defaults for new forms only. Settings for existing forms are saved in the resource file.
Show position
Specifies whether object position and dimensions are displayed on the status bar.
Tab ordering
Specifies how to set tab order in a form. To order controls by clicking on them, choose Interactive. To order controls using the Tab Order Dialog Box, choose By List.
Scale units
Specifies Pixels or Foxels, which sets the default scale mode for the Form Designer and Class Designer.
Maximum design area
Specifies the maximum size of the form at design time. The default setting is None, which prevents the form from appearing cropped inside the Form Designer. You cannot size a form that is bigger than the specified resolution. It is a good idea to specify the smallest resolution your users will want so that all users can see your forms.

Template classes

Specifies a class library and class to base your new forms and form sets on. The default is that Visual FoxPro uses its base class.

Form set
Displays the Form Set Template dialog box, where you select a form set template.
Form
Displays the Form Template dialog box, where you select a form template.
Builder lock
Specifies that builders are displayed automatically in the Form Designer when you create a control that has a builder registered to it.
Prompt to save changes before running form
Specifies that when you run a form from the Form Designer, you are prompted to save changes to the form made since the last time you saved it. If you clear this option, the Form Designer saves changes automatically before running the form.

See Also

Form Designer | Options Dialog Box | Tab Order Dialog Box | Form Set Template Dialog Box | Form Template Dialog Box


Form Set Template Dialog Box

Specifies a form set template to use for form sets.

Class
Specifies the file name of the form set template.
Class name
Lists classes in the currently selected class library.

See Also

Forms Tab, Options Dialog Box | Options Dialog Box | Form Designer | Form Template Dialog Box


Form Template Dialog Box

Specifies a form template to use for forms.

Class
Specifies the file name of the form template.
Class name
Lists classes in the currently selected class library.

See Also

Forms Tab, Options Dialog Box | Options Dialog Box | Form Set Template Dialog Box | IDE Tab, Options Dialog Box


General Tab, Options Dialog Box

Contains sound, programming, data entry, and other options in Visual FoxPro.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves all the options on all tabs.

Warning Sound

Off
Turns the error sound off. Corresponds to the SET BELL Command.
Default
Sets the error sound to your system default. Corresponds to the SET BELL Command.
Play
Sets the error sound to a .wav file. Type the name of the file in the box, or click the dialog button to select an existing .wav file. Corresponds to the SET BELL Command.

Programming

Cancel programs on Escape
Specifies that you can cancel a running program by pressing the ESC key. Corresponds to the SET ESCAPE Command.
Log compilation errors
Specifies that Visual FoxPro logs compilation errors in a file with the same name as the project file, but with an .err extension. Corresponds to the SET LOGERRORS Command.
SET DEVELOPMENT
Specifies that Visual FoxPro recompiles a program before running it if the object code is older than the source code. Corresponds to the SET DEVELOPMENT Command.
dBASE compatibility
Specifies compatibility with FoxBASE+ and dBASE languages. Corresponds to the SET COMPATIBLE Command.
Use Visual FoxPro color palette
Specifies that Visual FoxPro applies the default color palette to all bitmaps and OLE objects, which prevents palette shift when several pictures are displayed at once. Corresponds to the SET PALETTE Command.
Confirm file replacement
Specifies that Visual FoxPro prompts you for verification when you are about to overwrite existing files with new ones. Corresponds to the SET SAFETY Command.
Browse IME control
Specifies that Visual FoxPro displays an Input Method Editor when you navigate to a text box in the Browse window. This setting has no effect if you are not working in a double-byte character sets (DBCS) environment. Corresponds to the SET BROWSEIME Command.

Data Entry

Navigation keys
Specifies whether to use Windows- or MS-DOS–compatible navigation keys for tasks such as moving between controls in forms. Corresponds to the SET KEYCOMP Command.
Fill new records with current values
Specifies that Visual FoxPro automatically copies values from the current record to a new record that you are inserting or appending. Corresponds to the SET CARRY Command.
Enter or tab to exit fields
Specifies that you want to exit text boxes only by pressing ENTER or TAB. Otherwise, you can exit text boxes by typing past the last character in the text box. Corresponds to the SET CONFIRM Command.

Year 2000 Compliance

Strict Date Level
Specifies if ambiguous date and DateTime constants generate errors. Corresponds to the SET STRICTDATE Command.

See Also

Options Dialog Box | IMEStatus( ) Function | Trace Window


IDE Tab, Options Dialog Box

Contains options for Visual FoxPro editors.

Specify file/window

Makes it possible for you to specify which file types are affected by setting made in this tab.

Type:
Makes it possible for you to specify the editors or the types of files for which you are specifying default editing conditions.
Extensions:
Specifies the file extensions of the type of files selected.
Overide individual settings
Makes it possible for you to temporarily override default FoxUser settings.

Indentation

Makes it possible for you to specify the size and behavior of spaces and tabs.

Tab size
Specifies the width, in characters, of a tab for the currently selected file type. The range is 1 to 50. The default value is 4.
Indent size
Specifies the width, in characters, of a paragraph indent for the currently selected file type. If this is different from the tab size, extra tabs and/or spaces are used to create the specified value. The range is 1 to 50. The default value is 4.
Insert spaces
Specifies that spaces be inserted by the tab key for the currently selected file type. The default value is 4.
Keep tabs
Specifies that tabs be inserted by the tab key for the currently selected file type (default).

Save options

Makes it possible for you to specify how files of the selected type are saved.

Make backup
For some file types, specifies whether a backup file is created whenever you save a file of that file type.
Save with line feeds
Specifies that the current file type be saved with return and linefeed characters CHR(13)+CHR(10).
Save with end-of-file marker
Specifies that the current file type be saved with Ctrl+Z at the end of the file.
Compile before saving
Specifies that a compile be attempted before the current file type is saved.

Appearance and behavior

Makes it possible for you to specify how text appears in the selected file type.

Alignment:
Specifies whether the current file type if left-, center-, or right-formatted.
Font:
Specifies the font, style and size of the current file type.
Drag-and-drop editing
Specifies whether subsequent files of the selected file type provide drag-and-drop behavior. To disable drag-and-drop, you must also select the override individual settings checkbox. These selections, once applied, work on all files of the selected file types subsequently opened.
Automatic indent
Makes it possible for you to specify that an indent is automatically retained in lines subsequent to an indented line.
Show line/column position
Makes it possible for you to display, in the main window status line, the line and column number of the cursor in Memo fields
Word wrap
For some file types, makes it possible for you to specify whether words wrap to the next line at the editor window boundary.
Syntax coloring
Makes it possible for you to specify whether syntax coloring is available for the selected file type. You can manage syntax color parameters in the Editor Tab, Options Dialog Box.
Embedded hyperlinks
Makes it possible for you to specify whether hyperlinks can be included in the selected file type. Unvisited, visited, and hover attributes are available if you have Internet Explore installed.
Display white space
Makes it possible for you to specify whether space, tab, paragraph, and other non-character markers are displayed in editors for the selected file type.

Apply button

Saves pending settings for the currently selected file type.

Reset All button

Resets the Visual FoxPro defaults for the selected file type. To reset all type settings, you must use the Specify file/window list, then click Reset All for each file type in the list.

See Also

Editor Tab, Options Dialog Box | Options Dialog Box | Projects Tab, Options Dialog Box


Projects Tab, Options Dialog Box

Contains options for the Project Manager.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Project double-click action

Specifies whether Visual FoxPro runs or modifies a file when you double-click it in the Project Manager.

Run Selected File
Visual FoxPro runs the selected file when you double-click it.
Modify Selected File
Visual FoxPro opens the appropriate designer or editor when you double-click a file.
Prompt for Wizards
Specifies that Visual FoxPro prompts you to use a wizard, if applicable, when you choose New File from the Project Menu or choose New in the Project Manager.
Display user-defined container icons
Specifies that Visual FoxPro displays user-defined container icons in the Project Manager.

Source control options

Options in this box make it possible for you to specify what source control application to use, and how the source control application works when you add, modify, or remove components of your project.

Active source control provider
Specifies the name of the source control application to use. The name you specify here will apply to new projects. When you create a project, the name of the source control application in effect at the time is stored with the project so that Visual FoxPro knows what source control application to use each time the project is opened. To disable source control, choose None.
Automatically add new projects to source control
Specifies that you are prompted to put a project under source control when you create it. If you clear this option, new projects are not automatically put under source control and you must add them manually.
Check out files upon modify
Specifies that files are automatically checked out to a user who modifies them from the Project Manager. If a file is already checked out, Visual FoxPro displays an error. If you clear this option, users who attempt to modify files, which are not checked out from the Project Manager can view the files but cannot change them.
Note If users modify project files using commands in the Command window (such as MODIFY), they must check the files out first.
Add files to source control upon add
Specifies that files added to the project are automatically put under source control for that project. If you clear this option, files that you add become part of the project (the .pjx file), but are not put under source control. However, you can manually place project files under source control at any time.
Note Database (.dbc), table (.dbf), API library, and application (.app) files are not put under source control automatically when added to a project. However, you can put these files under source control manually.
Remove files from source control upon removal from project
Specifies that when you remove a file from a project, it is removed from source control as well. If you clear this option, when you remove a file from the project, the source control information for the file remains in the source control database. Doing so maintains archive information about this file, and if the file is not deleted from disk, makes it possible for you to access it using the source control system outside of Visual FoxPro.
Display dialog box for shortcut menu commands
Specifies that when you choose a source control command from the project shortcut menu, Visual FoxPro makes it possible for you to select more than one file on which to carry out the selected command. If you clear this option, the command applies only to the file selected in the project, but this can be overridden by pressing SHIFT+Right Mouse Click and choosing the command.
Text generation
Specifies the name of the application used to create a text representation of binary files (form, label, menu, report, or class library) each time the file is checked in. The resulting text file is checked in along with the table source file, and can be used to create a report of the differences between multiple versions of a file.
Project class
Displays the Project Reference dialog, making it possible for you to specify a default ProjectHook class as a template for new projects.

See Also

Project Manager Hooks | Controls Tab, Options Dialog Box | New File Dialog Box | Options Dialog Box | Project Manager Window


Regional Tab, Options Dialog Box

Contains options for date, time, and numeric formatting. You can temporarily or persistently override system settings in Visual FoxPro. The option settings on this tab are reflected in time, date, and currency output.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves the option settings in the registry (system Windows registration database).

Use System Settings
Specifies that all settings on this tab are read from the system (as established in the Control Panel). In this mode, most options are read-only.

If you clear this option, you can specify settings that override system settings.

Date and time

Specifies how date and time data is displayed by default. An example of the current settings appears in the top-right box of the option group.

Date format
Specifies the order of the day, month, and year in a date. Choose Short to remove leading zeros from the date. Choose Long to display the date written out. Corresponds to the SET DATE Command.
Date Separator
Specifies the character that appears between portions of a date. Clear this option to use the default separator. Corresponds to the SET MARK TO Command.
Century
Specifies that the year is displayed with century information (for example, 1997). Clear this option to display the year as 2 digits (for example, 97). Corresponds to the SET CENTURY Command.
12-Hour
Specifies that hours are displayed in 12-hour format with "AM" or "PM."
24-Hour
Specifies that hours are displayed in 24-hour format.
Seconds
Specifies that seconds are included in the time display.

Currency and numbers

Specifies how currency data is displayed by default. An example of the current settings appears in the top-right box of the option group.

Currency Format
Specifies the location of the currency symbol. Corresponds to the SET CURRENCY Command.
Currency Symbol
Specifies the character or characters used for currency. Corresponds to the SET CURRENCY Command.
1000 Separator
Specifies the character inserted at every third digit left of the decimal separator. Corresponds to the SET SEPARATOR Command.
Decimal Separator
Specifies a character used to indicate the decimal. Corresponds to the SET POINT Command.
Decimal Digits
Specifies the number of digits to follow the decimal separator. Corresponds to the SET DECIMALS Command.
Week Starts on
Specifies which day the week starts on. Corresponds to the SET FDOW Command.
First Week of Year
Specifies where a yearly calendar begins. Corresponds to the SET FWEEK Command.

See Also

Options Dialog Box | SET DATE Command | SET MARK TO Command | SET CENTURY Command | SET CURRENCY Command | SET SEPARATOR Command | SET POINT Command | SET DECIMALS Command | SET FDOW Command | SET FWEEK Command


Remote Data Tab, Options Dialog Box

Contains options for remote (ODBC) view and connection defaults.

When you choose Set As Default — which appears on every tab in the dialog box — Visual FoxPro saves all the options on all tabs.

Remote View Defaults

Settings in the Remote view defaults box represent Visual FoxPro cursor settings for the current session. If you choose Set As Default, the settings become the defaults for subsequent sessions. The options in this box correspond to settings you make or get using the CURSORSETPROP( ) Function and CURSORGETPROP( ) Function.

Share connection
Specifies that Visual FoxPro use a shared connection, if one is available. If a shared connection is not available, Visual FoxPro creates a unique connection when the view opens and cannot be shared with other views.
Fetch memo
Specifies that Visual FoxPro does not fetch memo and general fields from the data source until a memo or general field is activated in the view output. Clear this option to reduce the amount of data downloaded initially from the remote table — this results in faster performance.
SQL updates: Criteria
Specifies what fields Visual FoxPro checks on a remote server to determine whether a record has changed before you attempt to update it. The update fails if the data in the fields you specify has changed.
SQL updates: Method
Specifies whether Visual FoxPro uses SQL UPDATE or SQL DELETE and then INSERT to update information on the remote server.
Records to fetch at a time
Specifies how many records Visual FoxPro should return at a time from the remote data source. Choose All to specify that all records should be returned in the first fetch operation. This setting is limited by the value specified in Maximum records to fetch.
Maximum records to fetch
Specifies the total number of records returned by a view, which can help prevent you from downloading an excessive amount of data if you have constructed a query incorrectly. Choose All to specify that all records should be returned.
Use memo for fields >=
Specifies the maximum length of data in long Character fields. If character data exceeds the specified length, Visual FoxPro converts it to a memo field in the output of your view. The default is 255, the maximum size of a character field in Visual FoxPro.
Records to batch update
Specifies the number of update statements sent at once for views. The default is 1. Adjusting this value can greatly increase update performance. For more information, see the REPLACE command and Scope Clauses.

Connection Defaults

Settings in the Connection defaults box represent Visual FoxPro global default settings for connections. The options in this box correspond to settings you make or get using the SQLSETPROP( ) Function and SQLGETPROP( ) Function.

Asynchronous execution
Specifies that Visual FoxPro executes SQL pass-through commands (using SQLEXEC( ) Function, SQLMORERESULTS( ) Function, SQLTABLES( ) Function, and SQLCOLUMNS( ) Function) in the background after returning control to your application. If you choose this option, your application can display progress information and can make it possible for users to interrupt a command with the ESC key if SET ESCAPE Command has been set to true. You can determine the status of a SQL command executing asynchronously by calling one of the pass-through functions repeatedly until it reports that the command is done. The default is that this option is disabled (synchronous execution), which specifies that Visual FoxPro waits until the pass-through SQL command is complete before returning control to your application.
Display warnings
Enables the display of warning messages.
Batch processing
Specifies that when you send multiple SQL pass-through statements using SQLEXEC( ) Function Visual FoxPro does not return any results until all individual result sets have been retrieved. Corresponds to setting BatchMode in the SQLSETPROP( ) Function. If this option is disabled, you must call SQLMORERESULTS( ) Function to determine whether data is available.
Automatic transactions
Specifies that transactions are handled automatically by the connection on remote tables. If you clear this option, you must handle transaction processing manually using SQLCOMMIT( ) Function and SQLROLLBACK( ) Function.
Show login
Specifies whether to display login prompts when a connection is activated (if the connection requires users to be logged in). For example, Only When Necessary specifies that login prompts appear only for login information not specified in the connection or view definition.
Connection timeout (sec)
Specifies the number of seconds (between 0 and 600) to wait for a connection to be established with the remote server. If the connection cannot be established within the specified time, Visual FoxPro generates an error. Specify 0 to wait indefinitely for a connection.
Idle timeout (min)
Specifies the number of minutes of idle time allowed before the connection is deactivated. If a request to the server is not made within the specified time, Visual FoxPro terminates the connection. However, Visual FoxPro attempts to reconnect automatically if a request to the server is made after the connection has timed out.
Query timeout (sec)
Specifies the number of seconds (between 0 and 600) to wait for the server to respond to a request. If the server takes longer than the specified number of seconds to process the query, Visual FoxPro generates an error. Specify 0 to wait indefinitely for query results.
Wait time (ms)
Specifies the number of milliseconds that elapse before Visual FoxPro checks if the SQL statement has completed executing.

See Also

Creating Views | Sharing Connections for Multiple Remote Views | Memo Field Type | REPLACE command | Scope Clauses | SQLEXEC( ) Function | SQLGETPROP( ) Function | SQLSETPROP( ) Function | Options Dialog Box


Reports Tab, Options Dialog Box

Contains options and global settings for the Report Designer to use when creating reports.

When you choose Set As Default, which appears on every tab in the Options dialog box, Visual FoxPro saves all the options on all tabs.

Grid

Grid lines
Show or hide grid lines for aligning controls on the Report Designer surface. You can also select Grid Lines from the View menu.
Snap to grid
Align edges of newly drawn controls with the nearest grid lines in the Report Designer. You can also select Snap to Grid from the Format menu.
Horizontal spacing (pixels)
Specifies the number of pixels to horizontally space each grid section. You can also set horizontal spacing by selecting Set Grid Scale from the Format menu.
Vertical spacing (pixels)
Specifies the number of pixels to vertically space each grid section. You can also set vertical spacing by selecting Set Grid Scale from the Format menu.

Report Options

Use private data sessions
Run the report using a private data session. You can also select Private Data Session from the Report menu. For more information about private data sessions, see Using Data Sessions.
Save printer environment
Save the current printer environment setting inside a report. You can also select Printer Environment from the Report menu.
Use DBC field captions
Use database container (DBC) field captions when you drop fields onto a report.

Other options

Show position
Display the position, height, and width of the selected control in the status bar. You can also select Show Position from the View menu.
Ruler scale
Specify the scale of the ruler using the system default or pixels. You can also set vertical spacing by selecting Set Grid Scale from the Format menu. For more information, see
Default font
Specify the font, style, and size you want. You can also select Default Font from the Report menu.

See Also

Options Dialog Box | Set Grid Scale Dialog Box | Visual FoxPro Environment Settings | Viewing and Changing Environment Settings | Creating Reports and Labels | Walkthrough: Creating Reports with Visual FoxPro


View Tab, Options Dialog Box

Contains options for controlling the display of Visual FoxPro features.

When you choose Set As Default, which appears on every tab in the dialog box, Visual FoxPro saves all the options on all tabs.

Show

Status bar
Specifies whether Visual FoxPro displays the status bar at the bottom of the main window. Corresponds to the SET STATUS BAR Command.
Clock
Specifies whether the system clock appears in the status bar. You must choose the Status Bar option for this option to have effect. Corresponds to the SET CLOCK Command.
Command results
Specifies that Visual FoxPro displays the results of certain commands including APPEND FROM, AVERAGE, CALCULATE, COUNT, INDEX, SUM, and TOTAL, in the main Visual FoxPro window, the system message window, the graphical status bar, or a user-defined window. Corresponds to the SET TALK Command.
System messages
Specifies that Visual FoxPro displays certain system messages in the status bar. This option corresponds to the SET NOTIFY Command.
Most Recently Used list contains
Makes it possible for you to specify the number of files displayed in the MRU list. This option is disabled if Resource file in the File Locations Tab, Options Dialog Box has been unchecked or if SET RESOURCE Command has been set to OFF.
Open last project on startup
Specifies that Visual FoxPro opens the most recently used project when starting. This option is disabled if Resource file in the File Locations Tab, Options Dialog Box tab has been unchecked or if SET RESOURCE Command has been set to OFF.

See Also

Options Dialog Box | Visual FoxPro Environment Settings


Page Footer Dialog Box

Sets height and other options for the Page Footer band in a report or label. This dialog box appears when you double-click the Page Footer band separator bar in the Report Designer.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant band height
Select to prevent the band from stretching to accommodate lengthy data or adjust for removed blank lines.

Run expression

On entry
Specifies that an expression be evaluated before each new group header is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On exit
Specifies that an expression be evaluated after each new page is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Report Layout Preparation | Refining Page Layout


Page Header Dialog Box

Sets height and other options for the Page Header band in a report or label. This dialog box appears when you double-click the Page Header band separator bar in the Report Designer.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant band height
Select to prevent the band from stretching to accommodate lengthy data or adjust for removed blank lines.

Run expression

On entry
Specifies that an expression be evaluated before each new group header is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On exit
Specifies that an expression be evaluated after each new page is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Report Designer Band Dialog Boxes | Modifying Your Layout | Refining Page Layout | Report Layout Preparation


Page Setup Dialog Box

Lets you adjust column width and page layout for reports or labels. The settings you can adjust in this dialog box depend on the printer you have installed, and these settings are saved with the report or label.

This dialog box appears when you select Page Setup from the File menu.

Page Layout
Provides a graphical representation of the page, which reflects your layout in the Report Designer and Label Designer, and the settings you select or type in the Page Setup dialog box.

Columns

Number
Specifies the number of columns to print across the page.
Width
Specifies the width of individual columns, in inches or centimeters.
Spacing
Specifies the space between columns, in inches or centimeters.

Print Area

Printable Page
Specifies that the requirements of the currently selected printer driver determine the minimum margins.
Whole Page
Specifies that the paper size determines the minimum margins.
Left Margin
Specifies the width of the left margin, in inches or centimeters.
Dimensions
Indicates whether column width and spacing is reckoned in inches or centimeters.
Print Order
Specifies how records wrap when you have multiple columns.
Print Setup
Displays the Print Setup Dialog Box, where you select a printer, printer path, and paper setting.

See Also

Export Options Dialog Box | Print Dialog Box | Print Setup Dialog Box | SYS(1037) - Print Setup Dialog Box | Printing Query Results in a Report or Label | Report and Label Print Options Dialog Box


Paste Special Dialog Box

This dialog box makes it possible for you to link or embed an OLE object from the Clipboard. Visual FoxPro places the object in the current General field. You must open the General Field window to paste the data.

To use Paste Special, you must first copy the object you want to paste to the Clipboard and then open the General Field window; this will enable the command. Paste Special opens the Paste Special dialog box.

Source
Displays the application, directory, and file you are pasting from.
As
Displays the available formats for the object you are pasting. Select the format for the object according to what you want to be able to do with the stored object within Visual FoxPro. The Object format makes it possible for you to edit the object (for example, a Microsoft Excel worksheet object) by opening its source application from a field. If an object is in a Picture or Bitmap format, you cannot edit it from a table field. The Picture or Bitmap formats display the object and minimize the space it occupies in your file. If you plan to change the size of the object, choose the Picture format.
Paste
Embeds the object from the Clipboard in the current General field.
Paste Link
Links the object to Visual FoxPro so you can modify the object from within Visual FoxPro. Paste Link is only available when copying a saved object.
Note With a Microsoft Word document, both Paste and Paste Link are enabled.
Display As Icon
Displays the application icon instead of the data. This saves disk space when linking or embedding.
Change Icon
Displays the Change Icon dialog box, which makes it possible for you to specify the icon to be used for a linked or embedded object on a form or in a General field of a Visual FoxPro table. This button appears when you select the Display As Icon check box.
Results
Describes what actions will be performed on the contents of the clipboard after you click OK. You can alter the description displayed by choosing the Paste, Paste Link, or Display As Icon options.

See Also

General Field Window | Find Dialog Box | Change Icon Dialog Box | General Field Type | Adding OLE Objects to Applications | Text Editor and Clipboard Manipulation Routines | Dynamic Information Sharing


Pane Customization Dialog Box

The Pane Customization dialog box is used to create, modify, and delete panes in the Task Pane Manager.

New
Displays the Pane dialog box for you to enter basic information about the new pane to create. The following options are displayed:
  • Vendor Specifies the name of the company that is creating the new pane.
  • Unique ID Specifies a unique ID number for the pane content. It is recommended that you accept the default value.
  • Name Specifies the name of the new pane. This name appears at the top of the Task Pane Manager. To specify a hot key for the link at the top of the Task Pane Manager, include an escape character in the Name box. For example, \<My Pane would specify the letter M as the hot key in the panes link.
  • Pane Type Specifies the type of pane you want to create. The four types of panes you can create are explained in the following table.
    Pane Type | Description
    Web Page | Displays an Internet URL using the Internet Explorer ActiveX control.
    HTML | The pane and its content sections are displayed as HTML in the Internet Explorer ActiveX control.
    XML | The pane and its content sections are displayed as XML in the Internet Explorer ActiveX control. A local Extensible Stylesheet Language (XSL) file must be distributed with this type of pane.
    VFP Controls Specify a Visual FoxPro class library and class to create as the pane. This class should inherit from the PaneContainer class of the FoxPane library.
    DEFINE CLASS MyPane AS PaneContainer OF FoxPane
Delete
Delete a pane from the Task Pane Manager. When selected, a dialog box appears prompting you to delete the selected pane.
Publish
Displays the Publish Pane dialog box where you can publish the selected pane by wrapping the pane's content and its associated files into a manifest XML file for easy distribution. The following options are displayed:
  • Publish all content in pane Specifies that all content sections of the pane are published into the manifest XML file.
  • Publish selected content Specifies that only the content sections selected in the list are published into the manifest XML file.
  • Publish files associated with the pane Specifies that files associated with the pane are published into the manifest XML file.
  • Publish files common to all panes Specifies that files that are common to all panes are published into the manifest XML file. This option should be selected only if you need to distribute content in the root PaneCache folder.
View Content
Displays the Pane Content section on the right side of the Pane Customization dialog box.
View Files
Displays the Pane Files section on the right side of the Pane Customization dialog box.
Pane List
Lists all the installed panes in the Task Pane Manager. Selecting a pane updates the controls of the Pane Content and Pane Files sections with information on the selected pane.
Inactive
Specifies that the selected pane is inactive. Inactive panes do not show in the Pane List toolbar at the top of the Task Pane Manager or the Task Pane Options dialog box.
Save
Saves any changes to the selected pane, applies them to the Task Pane Manager, and closes the Pane Customization dialog box.
Apply
Saves any changes to the selected pane and applies them to the Task Pane Manager.

Pane Content

The Pane Content section is displayed when you select View Content. In this section, you can specify settings for the panes.

Add
Adds a new content section, which is displayed in Content Sections List below the button.
Remove
Prompts you to delete the selected content section.
Up Arrow
Moves the selected section up in the Content Sections List.
Down Arrow
Moves the selected section down in the Content Sections List.
Content Sections List
Lists the content sections for a pane. Selecting a content section updates the controls of the Pane Content section with information on the selected pane.

General Tab

Displays options for the root pane content or section content in which you specify general information on the selected item. For more information, see General Tab, Pane Customization Dialog Box.

Data Tab

Displays the URL for panes based on Web pages, or contains the XML data used to render a page for HTML- or XML-based panes. This pane is available only when the root pane type is Web Page, HTML, or XML. For more information, see Data Tab, Pane Customization Dialog Box.

Transform Data Tab

Specifies the XML transformation that is used to render panes based on HTML or XML. This pane is available only when the root pane type is HTML or XML. For more information, see Transform Data Tab, Pane Customization Dialog Box.

Default Data Tab

Specifies the data to be used when the pane is rendered if the pane's online content cannot be downloaded. This pane is available only when the root pane type is HTML or XML. For more information, see Default Data Tab, Pane Customization Dialog Box.

Handler Code Tab

Specifies handler code to handle user input in panes. This pane is available only when the root pane type is HTML or XML. For more information, see Handler Code Tab, Pane Customization Dialog Box.

Options Tab

Specifies custom options for a content section. For XML- and HTML-based panes, options can be specified only on subsection content. For Web Page and VFP Control panes, options can be specified only on the root content section. For more information, see Options Tab, Pane Customization Dialog Box.

Pane Files

The Pane Files section is displayed when you select View Files. In this section, you can add, edit, and remove files associated with a pane.

Add
Prompts the user to select a file to add to a pane.
Edit
Opens a file and its associated default editor for editing.
Remove
Prompts the user to remove the selected file from the pane.

See Also

Dialog Boxes | Task Pane Manager | Task Pane Options Dialog Box


Data Tab, Pane Customization Dialog Box

The Data tab contains the data that Web Page, HTML, and XML panes are based on.

Source
Specifies the data source type for the pane. The five data source types are explained in the following table.
Data source type | Description
Static Text Specifies that the data is well-formed XML. The default static text for XML Pane type is:
<VFPData>
   <!-- CONTENT -->
</VFPData>

You can type well-formed XML data instead of the comment. If the root pane has subsections, the default static text can remain because Visual FoxPro concatenates and places the XML data for the subsection here.

If you need to wrap your subcontent in XML so that the content sections can be further transformed by the root before finally displaying on the pane, use the following syntax in the root content section.

<VFPData>
   <!-- XMLCONTENT -->
</VFPData>

This wraps each subcontent in XML CDATA sections with the content between <HTMLText> tags. For example, a pane with two subcontent records might look like the following example:

<VFPData>
   <PaneContent id="uniqueid1">
   <PaneTitle>Content Title goes here</PaneTitle>
   <HTMLText><![CDATA[Transformed sub-content is placed here]]>
   </HTMLText>
   </PaneContent>
      <PaneContent id="uniqueid2">
   <PaneTitle>Content Title goes here</PaneTitle>
   <HTMLText><![CDATA[Transformed sub-content is placed here]]>
   </HTMLText>
   </PaneContent>
</VFPData>

The root content section's transformation then determines whether to handle transforming this XML data or distribute an XML file in the files section.
URL | The data is contained in a file on the Internet. You can then push dynamic content to the pane from a file on the Internet.
Script Specifies Visual FoxPro code to generate XML data. The code returns an XML string to be used as the data and accepts a parameter object to expose options set for the pane to the code.
LPARAMTERS oContent

The object exposes the following properties and methods:

  • CacheDir The directory of the user's pane cache
  • ContentTitle The name of the selected content section
  • Unique ID The unique ID of the selected content section
  • TaskPaneID The unique ID of the pane the content section belongs to
  • User User data that is contained in the User field in the PaneContent table
  • GetOption(cOptionName, xDefaultValue) Returns the value of the option specified. You can optionally specify the default value to be returned if the option is empty. All option values are returned as strings, unless xDefaultValue specifies a different data type.
File | Specifies a local file as the data source. This file is added to the list of associated files for the pane and copied to the pane's cache directory.
Web Service | Specifies that the data is obtained through an XML Web service on the Internet.
Modify
Opens a window to modify the Visual FoxPro Code or XML data.
Edit Box
Displays Visual FoxPro code or XML data.
Source of this content is from the Internet
Specifies that a Visual FoxPro code script is downloading content from the Internet. This enables the Check for New Internet Content option for the pane.
File
Specifies the name of the data file.
Ellipsis (...)
Prompts you to select a data file.
WSDL URL
Specifies the Web Services Description Language (WSDL) file URL for the XML Web service that provides the data for the pane. The WSDL describes the services offered by the server.
Method
Specifies the XML Web service method to call. The appropriate parameters for the method must also be specified. To specify pane options, use the ## delimiters. For example, GetPaneXML(##daysold##) references the GetPaneXML XML Web service method and uses the DaysOld option for a pane as the parameter.
Service
Specifies the service in the WSDL file that contains the operation specified in the Simple Object Access Protocol (SOAP) request. If this option is blank, the first service in the specified WSDL file is used when initializing the SoapClient object. (Optional)
Port
Specifies the name of the port in the WSDL file that contains the operation specified in the SOAP request. If this option is blank, the first port in the specified service is used when initializing the SoapClient object. (Optional)
WSML
Specifies the URL of the Web Services Meta Language (WSML) file. This is a required parameter only when using custom type mappers. For more information about custom type mappers, see the SOAP Toolkit documentation distributed with Visual FoxPro.

See Also

Pane Customization Dialog Box | Task Pane Manager


Default Data Tab, Pane Customization Dialog Box

The Default Data tab specifies the default data to display if live data cannot be retrieved from the Internet when a pane first displays. This information is optional and is used only if the data is not stored locally. If a pane successfully retrieves data from the Internet but fails on subsequent attempts, the pane uses the data stored in the PaneCache directory, not the default XML data.

Modify
Opens a window to edit the default XML data.
Edit Box
Displays the default XML data.

See Also

Pane Customization Dialog Box | Task Pane Manager


General Tab, Pane Customization Dialog Box

The General tab contains general information for the root pane content and sub-content sections.

Unique ID
Specifies a unique identifier assigned to the selected pane. A default ID is assigned when a pane is created. It is recommended that you accept the default value.
Name
Specifies the name of the content section. If the selected content section is the root content section, the name appears at the top of the Task Pane Manager. Hot keys can be assigned by placing an escape character in the Name box. For example, \<My Pane as the name of the root content section specifies the letter M as the hot key for this pane in the Task Pane Manager.
Help URL
Specifies the URL for help on the selected pane. The Help hyperlink to the URL appears in the Task Pane Options dialog box when the pane is selected.
Select Image
Displays a dialog box to select an image that will be associated with the selected pane. The selected image is shown along with the link to the pane at the top of the Task Pane Manager.
Class Library
Specifies the program file (.prg) or library file (.vcx) that contains the class and associated code to run the pane. The file is automatically copied to the selected pane's PaneCache folder, and the files are automatically added to the list of files associated with the selected pane. This field appears only if the selected pane is based on the VFP Controls type.
Class Name
Specifies the name of the container class to instantiate when creating the pane from the specified class library. This field appears only if the selected pane is based on the VFP Controls type.
Modify
Opens the class library for editing. This control appears only if the selected pane is based on the VFP Controls type.

See Also

Pane Customization Dialog Box | Task Pane Manager


Handler Code Tab, Pane Customization Dialog Box

The Handler Code tab specifies handlers to hyperlinks that are selected in a pane when the pane type is XML or HTML, and the hyperlink begins with vfps:. For example, the following code opens a browser window to the specified URL:

<a href="vfps:linkto?url=http://msdn.microsoft.com/vfoxpro/">Go to the VFP site</a>

The following table lists default handlers built into the Task Pane Manager.

Default handler | Description
vfps:refresh | Reloads the current pane.
vfps:linkto | Opens a browser window to the specified URL. The URL is specified with the url=cURL parameter.
vfps:gotopane | Switches the Task Pane Manager to the specified pane. The pane is specified with the uniqueid=cPaneUniqueID parameter.
vfps:help | Displays the specified Help by topic or ID. The Help is displayed by using the ID=cTopicID or Topic=cTopicName parameters.
vfps:options | Displays the Task Pane Options dialog box for the specified pane. The pane is specified with the uniqueid=cPaneUniqueID parameter.
vfps:message | Displays an informational message box. The message is specified with the msg=cMessage parameter.

You can include the refresh parameter with any handler code so that the pane reloads immediately after the handler is called. This is useful when the result of the link might affect the pane's content. You can use the refresh parameter with other parameters as shown in the following example:

vfps:message?msg=This is a message&refresh

The following table lists the parameters passed to the code when you use custom handler code.

Parameter | Description
cAction Specifies the action, which is the text following vfps: but preceding any parameters. For example, the following specifies to use a custom handler called MyAction:
<a href="vfps:MyAction?Param=Value">This is my handler</a>
oParameters A collection of the specified parameters. Additionally, if this is a form submit, the collection also includes the form values. To retrieve a value, call the GetParam( ) function with the parameter name as shown in the following example:
oParameters.GetParam("ParameterName")
oBrowser Contains the object reference to the Window object in the browser control on the pane. You can use this to access DHTML methods and properties. For example:
oBrowser.document.all("SearchResults").style.display = "none"
oContent | Contains a reference to the pane content definition so you can retrieve option values and the PaneCache folder specified in the Task Pane Options dialog box. This is the same object that is passed into a script on the Data Tab, Pane Customization dialog box.
Modify
Opens a window to edit the handler code.
Edit Box
Displays the handler code.

See Also

Pane Customization Dialog Box | Task Pane Manager


Options Tab, Pane Customization Dialog Box

The Options tab specifies custom options for a content section.

For XML and HTML pane types, options can be specified only on subsection content. For Web Page and Visual FoxPro Controls pane types, options can be specified on the root content section because these pane types do not have subcontent sections.

New
Opens the New Option dialog box prompting you for information on the new option. The New Option dialog box has the following fields.
  • Options name The name of the option that is referred to in code.
  • Type The type of control you want to create in the Task Pane Options dialog box. This can be a textbox, checkbox, spinner, or password control
  • Caption The label that appears next to the control in the Task Pane Options dialog box.
Delete
Prompts you to delete the selected option.
New Property
Displays a message box prompting you to enter the name of the new property. You can enter the value of the property using the Property List after you have added the property.
Delete
Prompts you to delete the selected property.
Options List
Displays a list of options for the selected pane or content section.
Property List
Displays list of properties and their default values for the selected pane or content section.

See Also

Pane Customization Dialog Box | Task Pane Manager


Transform Data Tab, Pane Customization Dialog Box

The Transform Data tab contains the XML transformation that is used to render a content section.

Type
Specifies the type of transformation data. The following are the two types of transformation data.
Type | Description
XML | Specifies that the transformation is Extensible Stylesheet Language (XSL).
Script | Specifies that the transformation is Visual FoxPro code.
Source
Specifies the source of the transformation data. The XML transformation data can come from the same sources as specified on the Data Tab, Pane Customization Dialog Box.
Modify
Opens a window to modify the Visual FoxPro code or XSL data.
Edit Box
Displays Visual FoxPro code or XSL data.

See Also

Pane Customization Dialog Box | Task Pane Manager


Print Dialog Box

Lets you print a text file, report, label, or the contents of the Command window or Clipboard.

This dialog box appears when you select Print from the File menu.

Shortcut

CTRL+P

Printer

Name
Displays the names of the printers currently installed on your machine.
Status
Displays whether or not the chosen printer is the default printer, and if it is ready to print.
Type
Displays the model of the selected printer. You specify the printer model when you first install the printer.
Where
Displays the network printer path.
Comment
Displays comments about the printer.
Properties
Displays the system Printer Properties dialog box, which allows you to set options for your printer.

Print Range

All
Specifies that all the pages in the document print.
Pages
Allows you to specify which pages of the document print.
Selection
Prints the highlighted selection in the document.

Copies

Number of Copies
Allows you to specify the number of copies of the document to be printed.
Collate
Specifies that if multiple copies of a document are printed, the printed copies will be collated.

See Also

Expression Builder | Print File Dialog Box | Print Setup Dialog Box | Printing Query Results in a Report or Label | Report and Label Print Options Dialog Box | Report Layout Preparation | Displaying and Printing Source Code Files in Color


Print File Dialog Box

Allows you to search a drive or directory for a file to print. This dialog box appears when you click the dialog button to the right of the File box in the Print dialog box.

Code Page
Displays the Code Page dialog box so you can attach the correct code page. If the file you want to print uses the extended character set, click Code Page and make the appropriate selections.

See Also

Print Dialog Box | Printing Query Results in a Report or Label | Report Layout Preparation | Print Setup Dialog Box | Report and Label Print Options Dialog Box | Code Page Dialog Box


Print Options Dialog Box

Lets you print a text file, report, label, or the contents of the Command window or Clipboard.

This dialog box appears when you select Options from the Print dialog box.

Print What

Type
Specifies the type of file to print. You may select Report, Label, Command Window, File, ASCII File, Clipboard, or any open text file (.qpr, .prg, or .txt).
Note The ASCII File option bypasses the printer driver and sends the contents of the selected file directly to the printer. Make sure that the file contains valid printer commands. Sending invalid printer commands to your print device may cause your printer to fail and to require a reset.
File
Specifies the path and file name of the file you want to print. Type the path and name, or click the dialog button to display the Print File dialog box, in which you can search directories and select the file to print.

Print Options

Line Numbers
Prints line numbers in the left margin. This option is enabled for the Command window, and the Clipboard.
Page Eject Before
Advances the printer to the top of the next page before printing the file.
Page Eject After
Advances the printer to the top of the next page after printing the file. This option is not enabled for reports and labels.
Restore Environment
For running FoxPro version 2.x reports, ensures that the data environment settings previously saved with the report are used to run the report. This option does not apply to Visual FoxPro reports because they use their own data environments.
Print Setup
Displays the Windows Print Setup dialog box, in which you can specify a local or network printer, page orientation, paper size, and additional printing options.
Options
Displays the Report and Label Print Options dialog box, in which you can create expressions using the Expression Builder dialog box to select the records you want to print.

See Also

Expression Builder Dialog Box | Print File Dialog Box | Print Setup Dialog Box | Report and Label Print Options Dialog Box | Printing Query Results in a Report or Label | Print Dialog Box | Report Layout Preparation


Print Setup Dialog Box

Selects a printer, printer path, and paper setting. The settings you can adjust in this dialog box depend on the printer you have installed, and these settings are saved with the report or label. You can also change the settings for the current print job; these settings are not saved with the report file.

Printer

Name
Displays the names of the printers currently installed on your machine.
Status
Displays whether or not the chosen printer is the default printer, and if it is ready to print.
Type
Displays the model of the selected printer. You specify the printer model when you first install the printer.
Where
Displays the network printer path.
Comment
Displays comments about the printer.

Orientation

Portrait
Orients the paper vertically for printing.
Landscape
Orients the paper horizontally for printing.

Paper

Size
Specifies the paper size to use. You can print either to paper or envelopes.
Source
Specifies the paper source (for example, upper tray) in the printer.

See Also

Print Dialog Box | Print File Dialog Box | Print Options Dialog Box | Report and Label Print Options Dialog Box | Printing Query Results in a Report or Label | Report Layout Preparation


Print When Dialog Box

Makes it possible for the conditional printing of an object based on the value of an expression and controls how objects print when bands are continued.

For field objects, this dialog box controls whether values that don't change from band to band are printed. For non-field objects, this dialog box controls how continued bands are printed.

This dialog box appears when you place a control on a report or label and choose Print When in the control's dialog box.

A slightly different version of Print When appears when you draw a rectangle or line on a report or label, double-click it, and choose Print When from the Rectangle/Line dialog box.

Print repeated values

This option appears for non-field objects only (such as OLE objects, labels, lines, rectangles, and rounded rectangles).

Yes
Objects will print when bands containing the object are started.
No
Object will not print at all unless one or both of the following are checked: In first whole band of new page/column and When detail overflows to new page/column.

Print Repeated Values

This option appears for Field objects only.

Yes
Displays repeated values.
No
Suppresses repeated values.

Also Print

In First Whole Band Of New Page/Column
Prints the field in the first band of a new page or column that is not an overflow from a previous page or column. This box is automatically enabled if you check Yes for Print Repeated Values, and optional if you check No for Print Repeated Values.
When This Group Changes
Prints the field when the chosen group changes. This option is available only if a data group exists and you choose a data group from the list box.
When Detail Overflows to New Page/Column
Prints the field when the Detail band overflows to a new page or a new column.
Remove Line If Blank
Collapses the band if an object is not printing and no other object is occupying the same horizontal space.
Print Only When Expression Is True
Provides space for typing an expression, or displays the Expression Builder dialog box so you can define an expression to be evaluated before the field prints. All other options in this dialog box except Remove Line If Blank are disabled if you include an expression.

See Also

Title Dialog Box | Expression Builder Dialog Box | Rectangle/Line Dialog Box | Report Designer | Report Expression Dialog Box | Setting Print Options for Controls


Project Information Dialog Box

Lets you view and edit information about the project and its files. This dialog box appears when you select Project Information from the Project menu.

Shortcut

CTRL+J in the Project Manager or ALT+ENTER.

See Also

Update Project List Dialog Box | Project Tab, Project Information Dialog Box | Select Directory Dialog Box | Build Options Dialog Box | EXE Version Dialog Box | Files Tab, Project Information Dialog Box | Projects Tab, Options Dialog Box | Servers Tab, Project Information Dialog Box


Project Tab, Project Information Dialog Box

Displays status information about the project.

Author
Displays the author's name, which you can change by typing it in the box.
Company
Displays the company name, which you can change by typing it in the box.
Address/City/State/Country/Postal Code
Displays the company address information, which you can change by typing it in the boxes.
Home
Displays the directory that contains the project file. To change the directory, type another name in the box or click the dialog button to display the Select Directory dialog box.
Last Built
Displays the date and time of the last project build. This information cannot be edited.
Files
Displays the number of files in the project. This information cannot be edited.
Debug Info
Specifies whether debugging information is included with the compiled file. If this is not checked, you cannot view program execution in the Trace window. Corresponds to the NODEBUG argument in the COMPILE command.
Encrypted
Specifies whether to scramble compiled files for security.
Attach Icon
Specifies whether to display a selected icon when the application is run. When checked, displays the Open dialog box if an icon has never been assigned to the application.
Icon
Displays the Open dialog box so that you can choose an icon. This button is available only if you select the Attach Icon check box. To display the icon correctly in the Windows Explorer, the icon file should contain both 32 x 32 and 16 x 16 icon images. The 32 x 32 image is used in the Explorer Large Icons view, and the 16 x 16 image is used in the Explorer Small Icons, List, and Detail views.

The following table lists the icon image formats that Visual FoxPro supports.

Colors | Size (pixels)
True Color (24 bit) | 16 x 16
True Color (24 bit) | 32 x 32
True Color (24 bit) | 48 x 48
True Color (16 bit) | 16 x 16
True Color (16 bit) | 32 x 32
True Color (16 bit) | 48 x 48
256 Color | 16 x 16
256 Color | 32 x 32
256 Color | 48 x 48
16 Color | 16 x 16
16 Color | 32 x 32
16 Color | 48 x 48
Project Class
Displays the Project Reference dialog, allowing you to specify a default ProjectHook class as a template for new projects.

See Also

COMPILE Command | Files Tab, Project Information Dialog Box | Project Manager | Select Directory Dialog Box | Trace Window | Servers Tab, Project Information Dialog Box | Project Information Dialog Box | Project Manager Hooks | Application Development and Developer Productivity


Select Directory Dialog Box

Allows you to set the home directory of the project. This dialog box appears when you choose the dialog button on the Project tab of the Project Information dialog box. The dialog button is associated with the Home option.

Directory
Displays a directory tree, where you click on the directory you want to set as the project home directory.
Drive
Allows you to select a drive so you can choose a directory on that drive.
Select
Makes the selected drive/directory combination the project home directory. This directory is then displayed in the Home box of the Project tab.
New Folder
Available when the nflag value of the GETDIR( ) function = 64. Allows you to create a new folder in the dialog box.

See Also

Project Information Dialog Box | Project Manager | Project Tab, Project Information Dialog Box | Files Tab, Project Information Dialog Box | Project Information Dialog Box


Files Tab, Project Information Dialog Box

Displays an alphabetical list of all project files, their type and include/exclude status, date and time last modified, and code page information.

Type
Displays an icon representing the file type.
Name
Displays the file name.
Last Modified
Displays the date and time the file was last modified.
Included
If you select this box, the file is included. If you clear the box, the file is excluded.
Code Page
Displays the code page number.
Update native code page
Updates the code pages for each file listed.

See Also

Project Manager | Project Tab, Project Information Dialog Box | Servers Tab, Project Information Dialog Box | Select Directory Dialog Box | Build Options Dialog Box | EXE Version Dialog Box | Determining the Code Page of a Project File | Code Pages in Visual FoxPro | Developing International Applications


Servers Tab, Project Information Dialog Box

Displays classes located on servers, their library, instancing, description, type, and Help information.

Server Classes
Displays a list of all the available classes, both .vcx and in code, which are marked as OLEPublic. Each class in the list has a corresponding .pjx file.
Class Library
Displays the directory path of the class library in which the selected class is stored.
Class Name
Displays the name of the class.
Instancing
Displays one of following options:

Single Use Specifies that you can create an instance of the class both inside Visual FoxPro and outside of Visual FoxPro using Automation. Each request for an instance of the class by an Automation client outside of the project causes a separate copy of the Automation server to start.

Instancing defaults to Single Use when you create a new project containing OLEPUBLIC classes. This setting is appropriate for building EXE servers.

Not Creatable Specifies that you can create instances of the class only inside Visual FoxPro.

Multi Use Specifies that you can create an instance of the class both inside Visual FoxPro and outside of Visual FoxPro using Automation. Each request for an instance of the class by an Automation client outside of the project causes an already running copy of the Automation server to be provided as the source for the new instance.

Instancing defaults to Multi Use when you create a .dll COM Server.

Description
Displays a small description of the class.

By default Visual FoxPro registers the full Project.Server notation as the description. This ensures consistent registry keys. You can specify a different Description here.

Help file
Displays the Help file associated with the server. Select the dialog button to display the Open dialog box if no file is listed.
Help context ID
Displays the context ID of the Help file associated with the application, if a Help file is distributed with the application.
Project name
Displays the name of the project associated with the server classes.
Typelib description
Displays a description of the class library the selected class is based on.

See Also

Files Tab, Project Information Dialog Box | Project Manager | Project Tab, Project Information Dialog Box | Classes in Visual FoxPro | Select Directory Dialog Box | EXE Version Dialog Box | Creating, Copying, and Removing Class Library Files


Prompt Options Dialog Box

Makes it possible for you to specify options for prompts in a customized menu system. Use this dialog box to define keyboard shortcuts, determine when the menu or menu item is disabled, include a message in the status bar when the menu or menu item is selected, specify a name for a menu title, and control menu title location during OLE visual editing.

This dialog box appears when you choose the Options button in the Menu and Shortcut Designers.

Comment
Provides space for adding a comment for personal use only. Comments do not affect generated code in any way; Microsoft Visual FoxPro ignores them when running the menu program.
Shortcut
Defines the optional shortcut key for a menu or menu item. Keyboard shortcuts for Visual FoxPro menu items are a combination of the CTRL key and another key.
Key Label
Displays your key combination. If a menu item does not have a keyboard shortcut, Visual FoxPro displays "(press the key)" in the Key Label box. Press the key combination you want for your shortcut key.
Key Text
Displays the text you want to appear beside the menu item. Unless you change it, this box repeats the keyboard shortcut from the Key Label box. For example, if both the Key Label and the Key Text were CTRL+R, you could change the Key Text to ^R.
Note You cannot assign CTRL+J as a keyboard shortcut for a menu item.
Skip For
Displays the Expression Builder Dialog Box. In the Skip For box of the Expression Builder, type the expression that determines whether the menu or menu item is disabled or enabled. The menu or menu item is disabled if the expression is true (.T.).
Negotiate
Specifies the location of menu titles when the user edits an OLE object in your application.
Container
Specifies how the menu title will be merged when Visual FoxPro is the container of an in-place active object.
Note Menu negotiation options are available only for OLE objects that can be edited in place.

The following table lists the menu title placement for each negotiation setting.

Setting | Placement
None | Specifies that the menu title not be placed on the menu bar. This is the same as not choosing any option.
Left | Specifies that the menu title be placed in the left group of menu titles on the menu bar.
Middle | Specifies that the menu title be placed in the middle group of menu titles on the menu bar.
Right | Specifies that the menu title be placed in the right group of menu titles on the menu bar.

For more information about object menu negotiation, see DEFINE PAD Command.

Message
Displays the Expression Builder dialog box. In the Message box of the Expression Builder, type the message that will appear in the Visual FoxPro status bar that describes the menu choice.
Pad Name
Makes it possible for you to specify an optional menu title. The name or number used in the generated menu program is optional, and Visual FoxPro provides one if you do not. Using this name or number, you can reference a menu or menu item at run time. This option is available for menus only.
Note This option is available only if the Result area in the Menu Designer window shows Command, Submenu, or Procedure.
Picture
Makes it possible for you to specify a graphics file to be displayed to the left of the menu bar text, or beside the resource in the Visual FoxPro system menu.
Bar #
Makes it possible for you to specify an optional shortcut menu title. This option is available for shortcut menus only.

See Also

Expression Builder Dialog Box | Menu and Shortcut Designers | PROMPT( ) Function | DEFINE PAD Command | Having Dialog Box | Set Index Order Dialog Box | Create One-To-Many Relationships Dialog Box


Query Destination Dialog Box

Lets you send the results of your query to seven different outputs.

This dialog box appears when you select Query Destination from the Query menu and is available only for queries.

Output destinations
Displays buttons for you to choose the type of output for the results of your query. The following table lists and describes the output types.
Button | Description
Browse Button, Query Destination Dialog Box | Displays the results of your query in a Browse window.
Cursor Button, Query Destination Dialog Box | Saves the results of your query in a cursor.
Table Button, Query Destination Dialog Box | Saves the results of your query as a table file.
Screen Button, Query Destination Dialog Box | Displays the results of your query in the active output window.

See Also

Dialog Boxes | Query and View Designers


Browse Button, Query Destination Dialog Box

Displays the results of your query in a Browse Window for examination and editing.

See Also

Query Destination Dialog Box | Browse Window | BROWSE Command | Cursor Button, Query Destination Dialog Box | Class Browser Buttons


Cursor Button, Query Destination Dialog Box

Saves the results of your query in a cursor with the name you assign it. The cursor is read-only, appears in the View window, and is available for browsing, reporting, or other uses until you close it. This command is available only for queries.

Cursor Name
Specifies the name of the cursor.

See Also

Query Destination Dialog Box | Browse Button, Query Destination Dialog Box, | Table Button, Query Destination Dialog Box | Storing Results in a Table, Array, or Cursor | SET CURSOR Command | Query and View Designers


Table Button, Query Destination Dialog Box

Saves the results of your query as a table file (.dbf) with the name you assign to it. This command is available only for queries.

Table Name
Specifies the name of the table. You can either type the name in the text box or use the dialog button to select an existing table that you want to overwrite.

See Also

Query Destination Dialog Box | Cursor Button, Query Destination Dialog Box, | Table File Structure (.dbc, .dbf, .frx, .lbx, .mnx, .pjx, .scx, .vcx)


Screen Button, Query Destination Dialog Box

Displays the results of your query in the active output window. This command is available only for queries.

Secondary Output

None
Specifies that the output not be sent to the printer or saved as a text file.
To Printer
Sends the results of the query to the printer as well as to the screen.
To Text File
Saves the results of the query as a text file. Click the button to select an existing file to overwrite, or type the name of a new file in the text box.

Options

Suppress Column Headings
Keeps headings from appearing at the top of the query results.
Pause Between Screens
Pauses at the end of each screen and displays a prompt for you to continue to the next screen. At the prompt, you can cancel the query by pressing ESC.

See Also

Query Destination Dialog Box


Quick Report Dialog Box

Makes it possible for you to select fields and a field layout for a report.

You can also use Visual FoxPro wizards to quickly create a report. These include the Report Wizard and the One-to-Many Report Wizard.

Field Layout
Shows column layout on the left and row layout on the right. Choose column layout to display the fields from left to right across the page. Choose row layout to display the fields one below the other down the page.
Titles
Determines whether field names will be displayed as titles in label controls either above or next to the corresponding field.
Add Alias
Automatically adds the alias to all field names in the Report Designer window.
Add Table to Data Environment
Automatically adds the table to the data environment.
Fields
Displays the Field Picker dialog box, in which you select fields to display in your report.

See Also

Report Variables Dialog Box | Report Expression Dialog Box | Field Picker Dialog Box | One-to-Many Report Wizard | Report Designer | Report Wizard | Adding Report Controls | Creating a Report Layout


Recall Records Dialog Box

Lets you unmark records that are marked for deletion. Corresponds to the RECALL command.

Scope
Allows you to specify the records on which Visual FoxPro is to act. Choose Next, All, Record or Rest from the drop-down list. Choose a number from the spinner on the right when you select Next or Record from the Scope drop-down list.
For
Displays the Expression Builder dialog box, where you create the logical expression that every record must meet to be affected by the command. Every record in the table is tested using the For expression.
While
Displays the Expression Builder dialog box. The While expression specifies that the action affects records only as long as the logical expression is true. The first time the expression evaluates to false, the action ceases without considering remaining records.
Recall
Recalls records using the Scope, For, and While values.

See Also

Delete Records Dialog Box | Expression Builder Dialog Box | RECALL Command | Scope Dialog Box


Rectangle/Line Dialog Box

Specifies position and printing options for rectangle and line controls. This dialog box appears when you draw a rectangle or line in a report or label and then double-click it while it's selected.

Print When
Displays the Print When dialog box so you can control exactly when the line or rectangle is printed in your report or label.

Object Position

Float
Specifies that the selected line or rectangle control move relative to the size of the surrounding fields.
Fix Relative to Top of Band
Causes the line or rectangle to remain in the position you give it in the Report or Label Designer and maintains that position relative to the top of the band.
Fix Relative to Bottom of Band
Causes the line or rectangle to remain in the position you give it in the Report or Label Designer and maintains that position relative to the bottom of the band.

Stretch Downwards

No Stretch
Specifies that the rectangle not stretch vertically as the band stretches to display field data.
Stretch Relative to Tallest Object In Group
Specifies that the rectangle stretch to accommodate the tallest object in the group.
Stretch Relative to Height of Band
Specifies that the rectangle stretch to fit in the band.
Comment
Makes it possible for you to add comments to the .frx or .lbx file. Comments are for reference only and do not appear anywhere in the printed report or label.

See Also

Print When Dialog Box | Round Rectangle Dialog Box | Report Picture Dialog Box | Adding Lines, Rectangles, and Circles | Setting Print Options for Controls


Remove Files from Source Control Dialog Box

Removes a file or selected files in your project from source code control.

Files to Remove
Lists the source-controlled files in your project.
Select All
Selects all files listed.

See Also

Add Files to Source Control Dialog Box | Update Project List Dialog Box | Compiling Source Code


Rename File Dialog Box

Lets you rename the selected file.

This dialog box appears when you select Rename File from the Project menu.

Rename
Displays the selected file's current file name.
To
Displays the current file name, which can be replaced by typing a new name into the box.
Note Exercise care when renaming files. If you rename a table that is referenced in the DataEnvironment property of a form, that form will not be able to find the table. If you rename a class that has been added to a form, the form will not be able to locate the class.

See Also

Project Manager | Description Dialog Box | New File Dialog Box | RENAME Command | DataEnvironment Property | RENAME TABLE Command


Replace Dialog Box

This dialog box makes it possible for you to search for and replace specified text in the current file. To replace within tables, click Replace Field on the Table menu. The keyboard shortcut to access this dialog box is CTRL+L.

Look For
Specifies the text string to search for.
Replace With
Specifies the replacement text.
Options
Defines the limits and direction of the search and replace. If you specify text to search for and do not get the expected results, make sure you have the following options selected:
  • Match Case Replaces text that exactly matches the combination of uppercase and lowercase letters you type in the Look For box.
  • Wrap Around Searches the current file, from the insertion point to the end of the file, and then from the beginning of the file to the original insertion point.
  • Match Whole Word Replaces distinct occurrences of words, except for embedded text.
  • Search Backward Searches backwards from the current insertion point to the beginning of the file.
  • Use wildcards Makes it possible for you to use wildcard characters in your search text.
Scope
Defines how extensive the search is. The Scope options are enabled when you are editing a procedure in a Code window.
  • Current Procedure Searches only the current procedure, which is displayed in the Code window.
  • Current Object Searches all procedures (event code) in the current (selected) object.
  • All Objects Searches all procedures (event code) in all objects in the current form or form set.
Find Next
Finds the next occurrence of the string you typed in the Look For box. This button is not enabled until you type text in the Look For box.
Replace
Changes the selected text to the text in the Replace With box. If you want to leave the selected text unchanged and move to the next occurrence, click Find Next.
Replace All
Finds and replaces all instances of the text in the Find What box with the text in the Replace With box. You can undo the replacements by choosing the Undo command.

See Also

Find Dialog Box | Go To Line Dialog Box | Replace Field Dialog Box | Code Window | Insert Object Dialog Box


Replace Field Dialog Box

Changes values stored in one record or in a range of records.

Field
Displays the name of table fields from the current table. When you click the down arrow, the types and sizes of fields are displayed.
With
Specifies the expression that describes the replacement values. Type the expression or choose the dialog button to display the Expression Builder dialog box and create a replacement expression.

Replacement Criteria

Scope
Allows you to specify the records on which Visual FoxPro is to act. Next, All, Record or Rest from the drop-down list. Choose a number from the spinner on the right when you select Next or Record from the Scope drop-down list.
For
Displays the Expression Builder dialog box, where you create the logical expression that every record must meet to be affected by the command. Every record in the table is tested using the For expression.
While
Displays the Expression Builder dialog box. The While expression specifies that the action affects records only as long as the logical expression is true. The first time the expression evaluates to false, the action ceases without considering remaining records.
Replace
Replaces records using the Scope, For, and While values. Enabled only when you have a field name or expression in both the Field and With text boxes.

See Also

Expression Builder Dialog Box | REPLACE Command | Scope Dialog Box | Recall Records Dialog Box | Delete (Records) Dialog Box


Report and Label Print Options Dialog Box

This dialog box appears when you click Options in the Print Options dialog box.

Scope
Allows you specify how much to print. Choose All, Next, Record, or Rest from the drop-down list. Choose a number from the spinner on the right when you select Next or Record from the Scope drop-down list.
For
Displays the Expression Builder dialog box, in which you create a logical expression, which every record must meet to be printed.
While
Displays the Expression Builder dialog box, in which you create a logical expression that must be true in order for records to print.

See Also

Expression Builder Dialog Box | Print Dialog Box | Scope Dialog Box | Printing Query Results in a Report or Label | Print File Dialog Box | Print Setup Dialog Box | Print Options Dialog Box | Report Layout Preparation


Report Designer Band Dialog Boxes

The Report Designer uses default and optional bands of information to build a report. Page Header, Detail, and Page Footer are the default bands that display when the Report Designer opens. Access other bands through the Title/Summary and Data Grouping options of the Report menu. For details on the band options, see the following topics in Help.

Column Footer Dialog Box
Column Header Dialog Box
Detail Dialog Box
Group Footer Dialog Box
Group Header Dialog Box
Page Footer Dialog Box
Page Header Dialog Box
Summary Dialog Box
Title Dialog Box

See Also

Format (Field) Dialog Box | Calculate Field Dialog Box | Report Designer | Report Expression Dialog Box


Report Dialog Box

Displays the results of your query in a report layout. You must have previously set up a report file (.frx) that accommodates the fields of output in the query. This command is available only for queries.

Open Report
Displays the Open dialog box for you to select a report file to use for your query. You can click the button or type the file name in the text box.
Wizard Icon
Displays the Wizard Selection dialog box, from which you can choose a report wizard to run.
Page Preview
Displays the output in the Page Preview window.
Console On
Displays the output in the active output window.
Eject Page Before Report
Prints a blank page at the beginning of the report to separate documents at the printer.

Secondary Output

None
Specifies that the output not be sent to the printer or saved as a text file.
To Printer
Sends the results of the query to the printer.
To Text File
Saves the results of the query as a text file. Click the button to select an existing file that you want to overwrite, or type the name of a new file in the text box.

Options

Suppress Column Headings
Keeps column headings from appearing at the top of the output.
Summary Information Only
Suppresses detail line printing. The report produced includes the headings, footers, totals, and so on, but excludes the detail lines.

See Also

Miscellaneous Tab, Query and View Designers | REPORT Command | Wizard Selection Dialog Box | Open Dialog Box | Report Layout Preparation


Report Expression Dialog Box

Defines the contents of a field control in a report. This dialog box appears when you place a field control on a report or label.

Expression
Displays the currently selected expression, such as a table field or variable, or makes it possible for you to type a new one. Choose the dialog button to display the Expression Builder dialog box if you want to create an expression and verify it before continuing.
Format
When a valid expression is displayed in the Expression box, you can specify a format in this text box. Choose the dialog button to display the Format (Field) dialog box if you want to specify the format for the field in your report.
Field position
Specifies position of the field in the report.
  • Float Specifies that the selected field move relative to the size of the surrounding fields.
  • Fix Relative to Top of Band Causes the field to remain in the position you give it in the Report or Label Designer and maintain that position relative to the top of the band.
  • Fix Relative to Bottom of Band Causes the field to remain in the position you give it in the Report or Label Designer and maintain that position relative to the bottom of the band.
Stretch with overflow
Specifies that the field expand down the report page to display all data in the field or expression.
Comment
Makes it possible for you to add comments to the .frx or .lbx file. Comments are for reference only and do not appear anywhere in the printed report or label.
Calculations
Displays the Calculate Field dialog box so you can select an expression to create a computed field.
Note SUM and COUNT commands do not function within report expressions.
Print When
Displays the Print When dialog box so that you can specify the conditions that must be met before the text is printed in your report or label.

See Also

Calculate Field Dialog Box | Expression Builder Dialog Box | Format (Field) Dialog Box | Print When Dialog Box | Report Designer | Quick Report Dialog Box | Creating Reports and Labels


Report Picture Dialog Box

Makes it possible for you to include bitmaps, icons, or other information from a General table field in your report or label. This dialog box appears when you choose the Picture/OLE Bound Control button from the Report Controls toolbar and place the control on a report or label.

Picture Form

File
Specifies the bitmap or icon file name. Type the path and file name in the box, or choose the dialog button to open the Open dialog box so you can select the desired bitmap or icon file.
Field
Specifies a General field to include in your report or label. Choose the dialog button to open the Choose Field/Variable dialog box so you can select the desired field, or type the name of the field in the text box.

If a General field in the table contains an object other than a picture or a chart (for example, a Microsoft Excel worksheet or a Microsoft Word document), an icon representing the object is printed in the report or label.

If Picture and Frame Different Size

Clip Picture
Shows a section of the original picture in the frame, retaining the picture's original dimensions if the picture is bigger than the frame you created in the Report or Label Designer. The picture is anchored at the top and at the left of the frame. You cannot see the lower-right portion of the picture that extends beyond the frame.
Scale Picture — Retain Shape
Displays the whole picture, filling as much of the frame as possible while retaining the relative proportions of the picture. This will protect your picture from vertical or horizontal distortion.
Scale Picture — Fill the Frame
Displays the whole picture, filling the frame completely. If necessary, the picture will be distorted vertically or horizontally to fit the frame.

Object Position

Float
Specifies that the selected picture move relative to the size of the surrounding fields.
Fixed Relative to Top of Band
Causes the picture to remain in the position you give it in the Report or Label Designer and maintains that position relative to the top of the band.
Fixed Relative to Top of Band
Causes the picture to remain in the position you give it in the Report or Label Designer and maintains that position relative to the bottom of the band.
Center Picture
Ensures that General field pictures smaller than the frame are centered in the report or label frame. The pictures included in a General field can be a variety of shapes and sizes. If the picture in a General field is smaller than the frame, it will be displayed in the upper-left corner of the frame unless you select Center Picture.
Note If you are including a bitmap or icon file in your report or label, Center Picture will have no effect on the single picture. Because a single picture has known parameters, the picture will never be smaller than the frame.
Print When
Displays the Print When dialog box so you can control exactly when the picture is printed in your report or label.
Comment
Makes it possible for you to add comments. Comments are entirely for your reference and do not appear in the printed report or label.

See Also

Choose Field/Variable Dialog Box | Picture Property | Print When Dialog Box | Round Rectangle Dialog Box | Rectangle/Line Dialog Box | General Field Type


Report Variables Dialog Box

Makes it possible for you to create variables within a report. Visual FoxPro uses variables to store the results of calculations performed while the report is being printed. Use this command to add new variables, change or delete existing variables, or change the order in which the variables are evaluated.

Variables
Displays the variables in the current report, and provides space for new variables.
Value to Store
Displays expressions stored in the current variable, or makes it possible for you to type an expression in the text box. To create an expression that will be stored in the variable, choose the dialog button to display the Expression Builder dialog box.
Initial Value
Displays the selected variable's value before any calculations are performed, and the value to which the variable is reset. You can enter a value in the text box, or, if you want to create an expression for the initial value, choose the dialog button to display the Expression Builder dialog box.
Release After Report
Releases the report variable from memory after the report is printed. If this option is not selected, the variable remains available in memory until you exit Visual FoxPro or release the variable with the CLEAR ALL or CLEAR MEMORY command.
Reset
Makes it possible for you to specify the point at which the variable is reset to its initial value. By default, End of Report is displayed in the list box. You can also select End of Page or End of Column. If you have specified groups in a report in the Data Grouping dialog box, the Reset box displays an item for each group in the report.
Insert
Inserts a blank text box in the Variables box so you can type a new variable name.
Delete
Deletes the selected variable name from the Variables box.

Calculate

These options make it possible for you to specify a calculation that the variable performs. The variable begins calculating with its initial value, and continues until it is reset to this initial value.

Nothing
Specifies that no calculations will be made on this variable.
Count
Counts the number of times a variable is printed per group, page, column, or report (depending on your selection in the Reset box). The calculation is based on the number of times the variable occurs, not on the variable's value.
Sum
Computes the additive sum of the variable's values. This option keeps a running total of the variable values for a group, page, column, or report (depending on your selection in the Reset box).
Average
Computes the arithmetic mean (average) of the variable values within a group, page, column, or report (depending on your selection in the Reset box).
Lowest
Displays the lowest value that occurred in that variable for a group, page, column, or report (depending on your selection in the Reset box). Places in the variable the value of the first record in the group. When a lower value is encountered, the variable's value changes accordingly.
Highest
Displays the highest value that occurred in that variable for a group, page, column, or report (depending on your selection in the Reset box). Places in the variable the value of the first record in the group. When a higher value is encountered, the variable's value changes accordingly.
Std. Deviation
Returns the square root of the variance for the variable values within a group, page, column, or report (depending on your selection in the Reset box).
Variance
Measures the degree to which individual field values vary from the average of all the values in the group, page, column, or report (depending on your selection in the Reset box).

See Also

CLEAR Commands | Data Grouping Dialog Box | Expression Builder Dialog Box | Quick Report Dialog Box | Defining Report Variables | Access to Visual FoxPro Variables and Fields | Variables


Round Rectangle Dialog Box

Specifies the exact shape, position, and printing options for round rectangle controls. This dialog box appears when you draw a round rectangle in a report or label and then double-click it while it's selected.

Style
Specifies the style of the round rectangle.

Object Position

Float
Specifies that the selected round rectangle control move relative to the size of the surrounding fields.
Fix Relative to Top of Band
Causes the round rectangle to remain in the position you give it in the Report or Label Designer and maintains that position relative to the top of the band.
Fix Relative to Bottom of Band
Causes the round rectangle to remain in the position you give it in the Report or Label Designer and maintains that position relative to the bottom of the band.

Stretch Downwards

No Stretch
Specifies that the round rectangle not stretch vertically as the band stretches to display field data.
Stretch Relative to Tallest Object In Group
Specifies that the round rectangle stretch to accommodate the tallest object in the group.
Stretch Relative to Height of Band
Specifies that the round rectangle stretch to fit in the band.
Print When
Displays the Print When dialog box so you can control exactly when the round rectangle is printed in your report or label.
Comment
Makes it possible for you to add comments to the .frx or .lbx file. Comments are for reference only and do not appear anywhere in the printed report or label.

See Also

Print When Dialog Box | Adding Lines, Rectangles, and Circles | Report Picture Dialog Box | Setting Print Options for Controls


Save As Class Dialog Box

Lets you save a form, or selected controls on a form, as a class definition. Create a class if you intend to create subclasses based on the form or reuse the controls for other forms.

This dialog box appears when you select Save As Class from the File menu.

Save
Specifies the part of the form to save as a class definition.
  • Selected Controls Saves only the selected controls as a class definition.
  • Current Form Saves the active form as a class definition.
  • Entire Form Set Saves a collection of related forms as a class definition. This command is enabled after you use the Create FormSet command on the Form menu.
  • DataEnvironment Saves a form's data environment and any contained cursors or cursor adapters in the specified visual class library (.vcx) file.
As Class
Specifies the class definition to which to save the selected controls, entire form, or form set.
  • Name Specifies the name assigned to the class.
  • File Specifies the name of the .vcx file in which to store the class definition.
  • Description Specifies the optional description for the class.

See Also

Save As Dialog Box | Import Dialog Box | Class Designer | Classes in Visual FoxPro | Class and Object Manipulation | Saving Forms


Save As Dialog Box

Saves a new file or saves an existing file with a different name. Corresponds to the PUTFILE( ) function.

The Save As command is enabled for the following file types:

  • Project
  • Query
  • Connection (see the following note)
  • View (see the following note)
  • Form
  • Report
  • Label
  • Program
  • Text File
  • Menu
    Note When you choose Save or Save As for a connection or view, the Save dialog box appears.

This dialog box appears when you select Save As from the File menu.

Code Page
This option is available if you are saving a text file or a table that has no code page. The Code Page dialog box is displayed so that you can attach the correct code page. If your existing text file uses the extended character set, choose Code Page and make the appropriate selections.

See Also

Code Page Dialog Box | Save As Class Dialog Box | Code Page Dialog Box | PUTFILE( ) Function | Save As HTML Dialog Box


Save As HTML Dialog Box

Enables you to create a new HTML (Hypertext Markup Language) version of the current form, menu, report, or table. Available from the Form Designer, Menu Designer, and Report Designer when the active form, menu, or report has been saved, or from a Browse window.

Save file for later use
Saves the file to disk as an .htm file.
Save and edit file
Saves the file to disk as an .htm file and opens the file in an editing window.
Save file and view in web browser
Saves the file as an .htm file and displays the file in your Web browser.

See Also

_GENHTML system variable | Save As Class Dialog Box | Save As Dialog Box | Print File Dialog Box | HTML Item Dialog Box | Saving a Form as HTML | Saving a Menu as HTML | Saving a Report as HTML | Saving a Table as HTML | Form Designer | Report Designer | Browse Window


Scope Dialog Box

Specifies which records Visual FoxPro acts on in the current table or view. This dialog box appears when you choose Scope from the Export Options Dialog Box.

All
The action affects all records in the table or view.
Next
The action affects a range of records beginning with the current record and continuing for the number of records you specify. Type a value of 1 to act on the current record.
Record
The action affects only the specified record number.
Rest
The action affects a range of records beginning with the current record and ending with the last record in the table or view.

See Also

Browse Window | Export Options Dialog Box | Filtering Data | Record Manipulation | Append From Dialog Box | Delete (Records) Dialog Box


Select Connection or Data Source Dialog Box

Allows you to select a data source or an existing connection to a data source to create a new remote view. You can also access the Connection Designer to create a new connection.

Appears when you select Remote View in the New Dialog Box, and then choose New File.

Connections in Database/Available Data Sources
Lists available ODBC data sources or existing connections, depending on which option you select in the Select option group. Select the data source or connection you want and choose OK.

Select

Connections
Displays existing connections for you to choose in the active database.
Available Data Sources
Displays the available ODBC data sources for creating a remote view.
New
Displays the Connection Designer, in which you can create and save a connection to a data source.

See Also

Create Dialog Box | New Label Dialog Box | Connection Designer | CREATE CONNECTION Command | Visual FoxPro as an Application Back End | New Dialog Box


Select Dialog Box

Makes it possible for you to select an XML Web service and insert code for it in a program or code editing window.

This dialog box appears when you type the characters, ws, followed by pressing the SPACEBAR in the editing window of a program.

Select an XML Web service
Specifies the XML Web service for which to generate proxy code.
Use Custom class
Specifies whether to include code that uses the WSHandler Foundation Class to wrap Simple Object Access Protocol (SOAP) client calls. Otherwise, code is generated to call the SOAP Toolkit 3.0 COM client directly.
Include error handling
Specifies whether to include structured error handling using TRY...CATCH...FINALLY code around SOAP client calls. For more information, see TRY...CATCH...FINALLY Command.
New
Opens the Visual FoxPro XML Web Services Registration dialog box so that you can register a new XML Web service. For more information, see Visual FoxPro XML Web Services Registration Dialog Box.

See Also

Dialog Boxes | Accessing XML Web Services


Set Grid Scale Dialog Box

Lets you define horizontal and vertical increments of the grid in pixels, and (for reports and labels) specifies whether the ruler displays in system units or pixels.

This command is available when you work with a report, label, form, or class.

You can set the default for Form Designer in the Forms Tab, Options Dialog Box.

Grid (in pixels)

Horizontal
Specifies the number of pixels per inch horizontally. The range is from 1 to 48 pixels. Use the spinner control or type a number in the edit box.
Vertical
Specifies the number of pixels per inch vertically. The range is from 1 to 48 pixels. Use the spinner control or type a number in the edit box.

Ruler Scale

System Default
Specifies inches or centimeters as the unit of measurement displayed on the ruler, depending on your language setting. This option appears only for reports and labels.
Pixels
Specifies pixels as the unit of measurement displayed on the ruler. This option appears only for reports and labels.

See Also

Form Designer | Forms Tab, Options Dialog Box | Adding, Copying, and Deleting Report Controls | Creating Reports and Labels | Grid Builder


Set Index Order Dialog Box

Sets the index order for a child table. This dialog box appears when you set the parent table of a relation in the Data Session Window and then click a child table in the Aliases list of the Data Session window if the child table has no index order already set.

Set Index Order List
Lists any predefined index orders, which exist for the selected child table.
No Order Button
Opens the Expression Builder Dialog Box where you can set your own relationship for the child table. You can also double-click on a table index listed in the dialog box to open the Expression Builder dialog box.

See Also

SET INDEX Command | Data Session Window | Expression Builder Dialog Box | Indexes Tab, Table Designer | Create One-To-Many Relationships Dialog Box


Spelling Dialog Box

Makes it possible for you to check spelling in a text file or memo field.

Not In Dictionary
Displays a word not found in the active dictionaries. If your text has column spacing or indents, this box changes to Extra Space.
Note If you don't want Visual FoxPro to count extra spaces, change the setting in the Spelling Options Dialog Box.
Change To/Suggestions
Type or select a replacement for the word not found in the dictionaries. To delete the word in the Not In Dictionary box from the document, delete the text in the Change To box and choose Change All.
Ignore
Leaves the specified word unchanged in the specified instance.
Ignore All
Leaves the specified word unchanged throughout the document.
Change
Changes the specified word to the word in the Change To box.
Change All
Changes the specified word throughout the document to the word in the Change To box.
Add
Adds the specified word to the dictionary.
Undo Last
Reverses the last replacement made in the document. You can reverse up to five of the most recent replacements.
Suggest
Displays a list of proposed suggestions after you type a word in the Change To box.
Options
Displays the Spelling Options dialog box, in which you can control the rules Visual FoxPro uses to check spelling.

See Also

Spelling Options Dialog Box | Macros Dialog Box | Beautify Options Dialog Box


Spelling Options Dialog Box

Controls the rules Visual FoxPro uses to check spelling. This dialog box appears when you choose Options in the Spelling Dialog Box.

Always Suggest
Displays a list of suggested corrections for each unmatched word when you check spelling.
Ignore Words In UPPERCASE
Skips words in which each character is an uppercase letter.
Ignore Extra Spaces
Skips extra spaces between words.

Dictionary

Language
Specifies the language of the active dictionary.
Type
Specifies the Normal, Concise, Complete, Medical, or Legal dictionary.

See Also

Spelling Dialog Box | Macros Dialog Box | _SPELLCHK System Variable | Beautify Options Dialog Box | Debugger Window


Summary Dialog Box

Sets height and other options for the Summary band in a report or label. This dialog box appears when you double-click the Summary band separator bar in the Report Designer. To see the Summary band, you must select Summary band in the Title/Summary dialog box.

Height
Specifies band height. Range is from 0.2083 to 20.00 inches. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed. This option cannot be unselected in the Summary dialog box.

Run Expression

On Entry
Specifies that an expression be evaluated before each new group header is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after each new page is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Title/Summary Dialog Box | Report Designer Band Dialog Boxes | Modifying Your Layout | Report Layout Preparation | Refining Page Layout


Tab Order Dialog Box

Adjusts the order in which objects are accessed in the form when you use the keyboard. This dialog box appears when you choose Tab Order from the View menu and you have selected the By List option for Tab Ordering in the Forms Tab. Options Dialog Box.

Object List
Lists all objects except graphic and text objects in the form or class. Objects are listed in the order in which they are currently accessible via the keyboard. Change the order by clicking the button to the left of the object picture and dragging the object to the position in the list that corresponds to its place in the desired access order.
By Row
Adjusts object order so objects are accessed by row, from left to right, across the form starting at the top.
By Column
Adjusts object order so objects are accessed by column, from top to bottom, down the form starting at the left side.

For more information, see Setting Tab Order for Controls.

See Also

Forms Tab, Options Dialog Box | Tab Index Property | General Options Dialog Box | Menu Options Dialog Box | Define Window Layout Dialog Box


Task Pane Options Dialog Box

The Task Pane Options dialog box allows you to customize the Task Pane Manager and the individual panes that it contains. Additionally, you can add new panes to your Task Pane Manager and access the Pane Customization dialog box to create your own panes.

Move Up
Moves the selected item in the tree view up.
Move Down
Moves the selected item in the tree view down.
Tree View
Displays the different areas of the Task Pane Manager where you can set options. When you click an item in the tree view, it expands the node to show additional categories for the selected item; it also displays the appropriate options for the selected item on the right side of the dialog box. Additionally, the order that panes appear in the tree view is the order they are shown at the top of the Task Pane Manager.
Help
Opens the Visual FoxPro Help file.

Task Pane Manager, General

Displays options that can be set for the Task Pane Manager.

Pane
Specifies the initial pane to be displayed when the Take Pane Manager is opened.
Check for New Internet Content
Selects how often to check for new content for Web-based panes. This option is the default for Web-based panes; however, different settings are available depending on the pane.
Open the Task Pane when Visual FoxPro starts
Specifies whether the Task Pane Manager is automatically opened when Visual FoxPro starts.

Task Pane Manager, Customize

Displays options for customizing panes and managing the Task Pane Manager.

Install Pane
Displays a dialog box to select a Microsoft or third-party pane to add to the Task Pane Manager.
Customize Panes
Displays the Pane Customization dialog box, which enables you to view and customize panes and to create your own custom panes.
Cleanup Tables
Removes deleted records from the Task Pane Manager tables and clears the Task Pane Manager's cache directory.
Restore to Default
Restores the Task Pane Manager to its default settings and panes.
Folder for Take Pane Manager content tables
Specifies the folder in which the Task Pane Manager accesses its tables.
Folder for cached files
Specifies the folder in which the Task Pane Manager stores its cached files.

Start, General

Displays options that can be set for the Start pane.

Start
Specifies whether the Start section of the Start pane is displayed.
My Tools
Specifies whether the My Tools section of the Start pane is displayed.
Recent Projects
Specifies whether your recently used projects are displayed on the Start pane.
Recent Databases
Specifies whether your recently used databases are displayed on the Start pane.
Check for New Internet Content
Selects how often to check for new Internet-based content.

Community, General

Displays options that can be set for the Community pane.

FoxCentral News
Specifies whether news from the FoxCentral Web site is displayed in the Community pane.
Universal Thread News
Specifies whether content from the Universal Thread Web site is displayed in the Community pane.
Wiki
Specifies whether content from the Visual FoxPro Wiki Web site is displayed in the Community pane.
Check for New Internet Content
Selects how often to check for new Internet-based content.

Community, FoxCentral News

Displays options that can be set for displaying news from the FoxCentral Web site.

Number of days to look back for news
Specifies how many days, of back news, from the FoxCentral Web site, the Community pane should display.

Community, Universal Thread News

Displays options that can be set for displaying content from the Universal Thread Web site.

Login name
Specifies the login name that the Community pane should use when downloading content from the Universal Thread Web site.
Password
Specifies the password that the Community pane should use when downloading content from the Universal Thread Web site.
Number of days to look back for news
Specifies how many days of back content from the Universal Thread Web site the Community pane should display.
News
Specifies whether the Community pane should list news content from the Universal Thread Web site.
Articles
Specifies whether the Community pane should list articles from the Universal Thread Web site.
Downloads
Specifies whether the Community pane should list downloads from the Universal Thread Web site.
Training
Specifies whether the Community pane should list Training announcements from the Universal Thread Web site.

Community, Wiki

Displays options for displaying content from the Visual FoxPro Wiki Web site.

Number of days to look back for news
Specifies how many days, of back content, from the Visual FoxPro Wiki Web site, the Community pane should display.

Solution Samples, General

Displays options that can be set for the Solution Samples pane.

Solution Samples
Specifies whether the Solution Samples section is displayed in the Solutions Samples pane.
Add-In Links
Specifies whether the Solution Samples Add-In section is displayed in the Solution Samples pane.
Check for New Internet Content
Selects how often to check for new Internet-based content.

XML Web Services, General

Displays options that can be set for the XML Web Services pane.

XML Web Services Tools
Specifies whether the XML Web Services Tools section should be displayed in the XML Web Services pane.
Explore an XML Web Service
Specifies whether the Explore an XML Web Service section should be displayed in the XML Web Services pane.
XML Web Services Resources
Specifies whether the XML Web Services Resources section should be displayed in the XML Web Services pane.
Check for New Internet Content
Selects how often to check for new Internet-based content.

Minesweeper

Displays options that can be set for the Minesweeper pane.

Size of matrix
Specifies how large the default game area is.

See Also

Dialog Boxes | Pane Customization Dialog Box | Task Pane Manager


Title Dialog Box

Sets height and other options for the Title band in a report or label. This dialog box appears when you double-click the Title band separator bar in the Report Designer. To see the Title band, you must select Title band in the Title/Summary dialog box.

Height
Specifies band height. Type a value in the box, click the UP ARROW or DOWN ARROW key to change the displayed value in increments of .05, or drag the band's separator bar with the mouse.
Constant Band Height
Prevents the band from stretching to accommodate lengthy data or shrinking to absorb blank lines that have been removed.

Run Expression

On Entry
Specifies that an expression be evaluated before each new group header is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.
On Exit
Specifies that an expression be evaluated after each new page is printed. Type the expression in the box, or choose the dialog button to display the Expression Builder dialog box.

See Also

Expression Builder Dialog Box | Label Designer | Report Designer | Title/Summary Dialog Box | Report Designer Band Dialog Boxes | Modifying Your Layout | Report Layout Preparation | Refining Page Layout


Title/Summary Dialog Box

Makes it possible for you to specify whether a Title and/or Summary band is included in the report.

Report Title

Title Band
Includes a title band for information that prints once at the beginning of the report.
New Page
Ejects a page after the title band information is printed. You can only check this if you check Title Band first.

Report Summary

Summary Band
Includes a Summary band for information that prints once at the end of the report.
New Page
Ejects a page before the Summary band information is printed. You can only check this if you check Summary Band first.
Page header
Include page header with the Summary band.
Page footer
Include page footer with the Summary band.

See Also

Report Designer | Title Dialog Box | Summary Dialog Box | Report Designer | Creating a Report Layout


Toolbars Dialog Box

Allows you to create, edit, hide, and customize toolbars.

Toolbars
Lists available toolbars. Selected toolbars are tiled or displayed in the active output window.
New
Displays the New Toolbar dialog box, where you can enter a name for your new toolbar.
Reset
Returns the selected toolbar to its built-in version. This button changes to Delete if you select a custom toolbar. You cannot reset a custom toolbar.
Delete
Deletes the selected custom toolbar. This button changes to Reset if you select a built-in toolbar. You cannot delete a built-in toolbar.
Customize
Displays the Customize Toolbar Dialog Box so that you can add and delete toolbar buttons.

Display

Color Buttons
Displays colored buttons on both built-in and customized toolbars. Clear this check box if you are using a black-and-white monitor.
Large Buttons
Displays toolbar buttons that are larger than the standard size. If your monitor has a high resolution, you may want to display larger buttons.
Show ToolTips
Displays the name of the button when you place the pointer over any button on a toolbar.

See Also

Customize Toolbar Dialog Box | Tab Order Dialog Box | General Options Dialog Box | Menu Options Dialog Box | Define Window Layout Dialog Box | Creating Custom Toolbars


Customize Toolbar Dialog Box

Allows you to add and delete toolbar buttons. The available buttons are displayed by category. Click a button to see its description.

This dialog box appears when you choose Customize in the Toolbars Dialog Box.

Categories
Lists the button categories.
Button
Displays the buttons included in the category you select in the Categories box. To add the button, drag it to the desired toolbar or drop it onto the Visual FoxPro desktop to create a new toolbar.
Description
Describes the selected button.

For more information, see Configuring Visual FoxPro Toolbars.

See Also

Toolbars Dialog Box | Tab Order Dialog Box | General Options Dialog Box | Menu Options Dialog Box | Define Window Layout Dialog Box | Creating Custom Toolbars


Undo Check Out of Files Dialog Box

Overwrites your changes to a file, and copies the latest checked in version to your development-environment working directory.

Files to Un-Check Out
Lists the currently checked out files. Click the files whose checkout you want to undo, or click Select All to select all the listed files.
Select All
Selects all files listed.

See Also

Check Out Files Dialog Box | Add Files to Source Control Dialog Box | Compiling Source Code


Update Project List Dialog Box

Displays the results when you choose Update Project List from the Source Control submenu on the Project menu.

Comments
Displays the results of the update.

See Also

Remove Files from Source Control Dialog Box | Project Information Dialog Box | Compiling Source Code


View Parameters Dialog Box

Sets up views that prompt for a value entry to complete the view.

Name
Specifies name of parameter.
Type
Specifies data type of parameter.
Insert
Inserts a blank row.
Delete
Deletes selected row.

See Also

Advanced Options Dialog Box | Query and View Designers | Query Destination Dialog Box | Creating a Parameterized Query | PARAMETERS Command


Visual FoxPro Converter Dialog Box

Converts FoxPro 2.6 and Visual FoxPro 3.0 files to Visual FoxPro 7.0 format, which is necessary for using these files with later versions of Visual FoxPro.

The Converter dialog box appears when you choose Open from the File menu and select a file created in a previous version of FoxPro, or when you type MODIFY PROJECT Command, MODIFY FORM Command, MODIFY REPORT Command, or MODIFY LABEL Command filename in the Command Window and select a file created in a previous version of FoxPro from the Open Dialog Box.

Convert Both Macintosh and Windows Form Records
Visible only if converting FoxPro 2.6 screens or projects containing platform-specific controls or information such as references to screen fonts or paths. If you select this option, the converter creates a separate form for each platform. The Windows version of the form will have the original name, and the Macintosh version will have the original name with the suffix "_MAC" added. If the original screen was part of a project, the new project is updated to include both new forms.
Retain Visual FoxPro 3.0 default property values
Visible only if converting Visual FoxPro 3.0 forms or projects. Visual FoxPro 7.0 format default property settings for fonts and colors are Windows 98 compliant and sometimes different from Visual FoxPro 3.0 settings. If you select this option, your converted forms will retain the Visual FoxPro 3.0 property settings.
Backup files
Makes it possible for you to specify a directory for backup files to be saved in.
Create log file
Makes it possible for you to save a list of the actions performed while converting your files.
Functional conversion
Visible only if converting FoxPro 2.6 screens or projects. This option creates form and control images and copies code to locations in object properties, events, and methods. Functional conversion provides immediate FoxPro 2.6 READ compatibility so you can use forms in Visual FoxPro without making extensive manual changes. To gain complete event model functionality, you must eliminate pages and page frames, change the form set WindowType Property, and manually relocate code in methods and events.
Visual conversion
Visible only if converting FoxPro 2.6 screens or projects. This option creates images of forms and all controls, but copies all the code from the original FoxPro 2.6 project or screens to a noncompilable .prg file. Choose Visual Conversion if you want to move to full Visual FoxPro functionality without having to eliminate pages and page frames, change the form set WindowType Property, and manually relocate code from object to object.
Continue
Displays the Visual FoxPro Transporter dialog box, which makes it possible for you to complete the file conversion process.
File
Specifies the file you want to convert. To locate a different file, click the ellipsis (...) button.
Directory
Use this option to convert all the files in a directory. When you click this button, you enable the options that specify the type or types of files you want to convert. You can also specify whether to convert subdirectories.

When you select this option, you can also choose whether to include all .scx and .vcx files, and whether to also check all subdirectories for convertible files.

See Also

Command Window | MODIFY FORM Command | MODIFY LABEL Command | MODIFY PROJECT Command | MODIFY REPORT Command | WindowType Property | Visual FoxPro Transporter Dialog Box


Visual FoxPro Transporter Dialog Box

Makes it possible for you to transport forms, labels, and reports across different FoxPro platforms and versions.

This dialog box appears only if you are trying to convert Macintosh or MS-DOS files that have never contained Windows records and when you click the Continue button in the Visual FoxPro Converter dialog box. The Transporter creates Windows platform records from the Macintosh or MS-DOS records so that the Converter can convert the files to the Visual FoxPro 7.0 file format (necessary for use of these files with later versions of Visual FoxPro).

Transport
Creates a Windows version of the Macintosh or MS-DOS records so that the Visual FoxPro Converter can recognize the file and convert it to the correct file format.
Don't Transport
Cancels the file transport and conversion process. You can still open the file in the older version of FoxPro.
Font
Opens the Font dialog box so you can choose the default font for your transported screen, report or label.
Transport Objects From
Makes it possible for you to choose the appropriate platform from the drop-down list.

See Also

_TRANSPORT System Memory Variable | Visual FoxPro Converter Dialog Box


Visual FoxPro XML Web Service Location Dialog Box

Specifies a local Uniform Resource Locator (URL) or virtual directory for publishing an XML Web service.

The Visual FoxPro XML Web Service Location dialog box appears the first time you select the Web Services Publisher wizard from the Wizards menu. You can open the dialog box by clicking Advanced in the Visual FoxPro XML Web Services Publisher dialog box. For more information, see Visual FoxPro XML Web Services Publisher Dialog Box.

Note All prior settings for previously published XML Web services are preserved, so you do not have to reset these values each time you want to republish a previously published XML Web service.
Existing
Select an existing location in the Select Location (Virtual Directory) box for publishing an XML Web service. This must be a URL location URL (virtual directory) available on an accessible IIS Web server.
New
Specifies a new virtual directory in the Select Location (Virtual Directory) box for publishing an XML Web service and to type a name for the virtual directory in the New Virtual Directory Name box.
Select Location (Virtual Directory)
Specifies the local URL (virtual directory) to publish an XML Web service. The box lists all available virtual directories on your IIS default Web server. If New is selected, the specified URL is used as the root location for the new virtual directory appearing in the New Virtual Directory Name box.
File Output Path
Displays the physical path for the new virtual directory location and is available only when New is selected. Click Ellipsis (...) button to the right of the File Output Path box to select a physical directory for the new virtual directory.
New Virtual Directory Name
Specifies the name of the new virtual directory and is available only when New is selected.

See Also

Dialog Boxes | Distributing XML Web Services | XML Web Services in Visual FoxPro


Visual FoxPro XML Web Services Publisher Dialog Box

Specifies information for publishing Visual FoxPro COM (.dll) servers as XML Web services that can be accessed on the Web. The Visual FoxPro XML Web Services Publisher dialog box appears when you click Publish an XML Web Service in the XML Web Services pane in the Task Pane Manager or when you click Web Services on the Wizards menu from the Tools menu.

Note The Visual FoxPro XML Web Services Publisher dialog box uses the Web Services Description Language (WSDL) generation engine from the SOAP Toolkit version 3.0. Therefore, certain complex types might not be supported. For more details about the WSDL or WSML files generated by the Visual FoxPro XML Web Services Publisher, see the SOAP Toolkit 3.0 documentation.

The Visual FoxPro XML Web Services Publisher dialog box uses the default URL location (virtual directory) for its settings. You can display and modify these default settings by clicking Advanced in the Publisher dialog box. Settings are preserved so that you can later republish your XML Web service with newly generated support files.

COM Server
Specifies the file name of the COM server to be published. Click the Ellipsis (...) button to select a COM server (.dll or .exe file).

By default, a COM Server associated with an active project is displayed. The COM Server box lists all COM Servers associated with open projects and any previously published COM Servers.

Select Class
Specifies an individual class (OLEPUBLIC) of the COM Server to be published. The Select Class box lists all classes in the COM Server.
Advanced
Displays the Advanced dialog box so that you can modify the default settings for the XML Web service you want to publish and for the support files generated for the XML Web service. These settings are used when you click Generate. They are preserved so that you can republish the XML Web service later with newly generated support files. The following settings are available:

Options tab

  • Service Name Specifies the name of the XML Web service to create. When generating the WSDL (and ASP) files, use this file name.
  • Listener URI Specifies the URL for the WSDL and ASP file.

    This box lists suggested locations based on the set of virtual directories on your default Web server. Clicking the Ellipsis (...) button displays the Visual FoxPro XML Web Service Location dialog box so you can choose an existing or new virtual directory. For more information, see Visual FoxPro XML Web Service Location Dialog Box.

  • File(s) Location Displays the physical location of the generated WSDL files. This location is determined by the location specified by clicking the Ellipsis (...) button on the right side of the Listener URI box.
  • Listener Type Specifies whether the XML Web service uses an ISAPI or ASP listener. The ISAPI listener is the default option and offers the fastest performance. If an ASP listener is specified, an ASP file is created along with the WSDL files when the Generate button is clicked.
  • ASP listener Application Displays the application name used in the ASP script of the listener file.
  • VBScript Specifies that the ASP listener file uses VBScript as the scripting language.
  • JScript Specifies that the ASP listener file uses JScript as the scripting language.
  • Automatically generate Creates a project hook with the COM Server project so that XML Web service support files are automatically generated when the COM Server is rebuilt.
  • Generate with UTF-16 Uses UTF-16 Unicode encoding when generating WSDL files. With UTF-16 encoding, every character uses two bytes. With UTF-8 encoding, most characters, for example, English characters, use one byte each. Other characters, such as Asian or Arabic, use up to three bytes each. Therefore, it is better to save files in UTF-16 format.

Methods tab

  • Methods Specifies a list of available methods in the selected COM Server class. Only selected methods are included as operations in the generated WSDL XML Web service file.

Namespaces tab Specifies different namespaces for URIs in your generated WSDL files. Each XML Web service needs a unique namespace for client applications to distinguish it from other services on the Web. It is recommend that you use a domain different from tempuri.org.

  • WSDL Namespace URI Specifies the namespace used for definitions in the WSDL document.
  • Schema Type Definition Namespace URI Specifies the namespace used for schema references in the WSDL document.
  • Message Namespace URI Specifies the namespace used for input or output messages, or method calls, in the WSDL document.
  • Base SOAP Action URI Specifies the URI used for operations in the WSDL document.
STK3 Wizard
Opens the SOAP Toolkit 3.0 WSDL Generator so that you can create a WSDL file from a COM object. You can use this wizard as an alternate method for publishing your COM Server as an XML Web service and contains many of the same options as the Visual FoxPro XML Web Services Publisher.
Generate
Generates all the XML Web service support files necessary to publish your COM server as an XML Web service including an ASP listener and WSDL files.

See Also

Dialog Boxes | Distributing XML Web Services | XML Web Services in Visual FoxPro


Visual FoxPro XML Web Services Registration Dialog Box

Specifies information for registering an XML Web service so you can use it in your applications.

The Visual FoxPro XML Web Services Registration dialog box appears when you click Register an XML Web Service in the XML Web Services pane in the Task Pane Manager. You can also open the dialog box from the XML Web Service Builder and Select dialog box when you type the characters, ws, in a code editing window.

WSDL URL Location
Specifies the location of the WSDL file and is usually a URL. However, the location can also be a local directory if stored locally. This value must be a valid WSDL location and file; otherwise, Visual FoxPro generates the appropriate message when you attempt to register the XML Web service.

The box also includes the previously registered WSDL location reference. If you specify a WSDL file that contains multiple ports (classes), you are prompted to pick a specific port.

UDDI Search
Displays the UDDI Search dialog box so that you can search for an XML Web service registered in the Microsoft Universal Description, Discovery, and Integration (UDDI) database. The UDDI Search dialog box contains the following options:
  • Enter name to search for in UDDI database Specifies a name to search for and can be the name of a company, business, or a simple category, such as weather or stock.
  • Web Services Displays the results of the UDDI search.

    The Results area displays details about the specified XML Web service. However, there might be times when the search returns a result that is not an XML Web service but a reference to a URL containing a link to an XML Web service. If this situation occurs, the Select button is not available; however, the description contains a link you can click for more information.

  • View Service Description (WSDL) Contains a hyperlink to the WSDL for the XML Web Service.
  • Go to Microsoft UDDI Web Site Contains a hyperlink to the Microsoft UDDI Web site.
  • Search Performs the UDDI search for the specified expression.

    The time required for the search depends on the expression entered. If no matches are found, a message box displays to indicate this.

  • Select Enters the selected XML Web service in the WSDL URL Location box in the Visual FoxPro XML Web Services Registration dialog box.
    Note If you need to perform a more complex search, visit the Microsoft UDDI Web site at http://www.microsoft.com/.

See Also

Dialog Boxes | Accessing XML Web Services | XML Web Services in Visual FoxPro


Wizard Selection Dialog Box

Displays a list of wizards from which you can choose. This dialog box is displayed when you choose Wizards from the Tools menu and then choose Query, Form, Report, or All from the submenu.

Select the wizard you would like to use
Displays all Visual FoxPro wizards available for a particular item. For instance, Visual FoxPro has three different report wizards.
Description
Gives a brief description of the currently selected wizard.

See Also

Wizards | Spelling Dialog Box | Macros Dialog Box | Class Browser Window


Work Area Properties Dialog Box

Lets you modify the structure of a table, select index files and fields, and define data filters. This dialog box appears when you choose Properties from the Table Menu.

Cursor
Displays the title of the currently opened table.
Enable data buffering
Sets buffering on.

Lock Records

When edited
Prevents access by other users while you edit records. This is also known as pessimistic buffering.
When written
Permits access by other users until the record is updated. This is also known as optimistic buffering.

Buffer

Current record
Enables buffering of the current record only. This is also known as record buffering.
All edited records
Enables buffering of all edited records. This is also known as table buffering.
Note When you select Buffer Current Record, SET MULTILOCKS Command are automatically set to ON (if they are currently off), but are not set to OFF if you clear Buffer Current Record or select Buffer All Edited Records. Set the defaults for new tables in the Data Tab, Options Dialog Box.
Data filter
Provides a text box for typing a data filter expression. Alternatively, the dialog button displays the Expression Builder Dialog Box, in which you can specify which records in the active table will be available for processing. Corresponds to the SET FILTER command.
Index order
Specifies the index order of the table. In the Database Designer, the table's primary index appears with a key symbol next to it in the list of indexes. Corresponds to the SET ORDER command.

Allow Access To

All fields in the work area
Specifies that the user have access to all fields in the work area. Corresponds to the SET FIELDS command.
Only fields specified by field filter
Specifies that only records which match the selections in the Field Picker Dialog Box be displayed or available for editing.
Field Filter
Displays the Field Picker dialog box, in which you control the number of active fields.
Modify
Displays the Table Designer, in which you can modify database and free tables, fields, and indexes.

See Also

Customizing Tables | Data Tab, Options Dialog Box | Database Designer | Expression Builder Dialog Box | Field Picker Dialog Box | SET FIELDS Command | SET FILTER Command | SET MULTILOCKS Command | SET ORDER Command | Table Designer


Field Picker Dialog Box

Limits the number of active fields in a table so you can customize what is displayed. Fields that are not active cannot be accessed, examined, or modified. Data in the table itself is not affected. The selections you make in this dialog box are ignored unless you select Only Fields Specified by Field Filter in the Work Area Properties Dialog Box.

This dialog box appears when you choose Field Filter in the Work Area Properties dialog box, or Fields in the Quick Report Dialog Box, Append From Options Dialog Box, or Export Options Dialog Box.

All Fields
Displays all field names in the current table.
Selected Fields
Displays field names you select in the All Fields box and copy with the Move button.
From Table
Specifies which table's fields are displayed in the All Fields box.
Move
Copies the selected fields from the All Fields box to the Selected Fields box.
All
Copies all fields from the All Fields box to the Selected Fields box.
Remove
Removes the selected fields from the Selected Fields box.
Remove All
Removes all fields from the Selected Fields box.

See Also

Append From Options Dialog Box | Export Options Dialog Box | Quick Report Dialog Box | Work Area Properties Dialog Box | Field Creation


Zoom <property> Dialog Box

Displays the text value of the selected property. This command is accessed through the shortcut menu on the Properties Window.

See Also

Properties Window | Expression Builder Dialog Box | ZOOM WINDOW Command | ZoomBox Property


XML Web Service - Client Detail Dialog Box

Makes it possible for you to specify the control, or client, to which you want to bind the results of the XML Web service operation. When calling an XML Web service operation, the results can be bound to a specific control on the form. You can then assign the return value, or the parameter as passed by reference, to a property of the control. Usually, you assign this return value to the Value or Caption property so that the user can see the results.

This dialog box appears when you click Add or Edit in the Clients group on the Operations tab of the XML Web Service Builder. For more information, see Operations Tab, XML Web Service Builder.

Select control
Displays and specifies controls or objects available on the current form to which you want to bind the results of the XML Web service operation.

If your XML Web service returns a simple data type, you might want to select a text box or label. You can bind an operation that returns an ADO.NET DataSet, which is a complex type, to a grid. For DataEnvironment objects, you can select a CursorAdapter object and bind the operation results to its CursorFill method, which is typical for XML Web service operations that return ADO.NET DataSets.

Control property used to assign the Web service results
Displays and specifies the property of the selected control to which you want to bind the operation results. When the operation is called, the results are assigned to the property.

For a TextBox control, you usually choose the Value property; however, if the operation returns an ADO.NET DataSet, you might want to use the ControlSource property.

For a Label control, the Caption property is selected by default.

For a Grid control, and if the operation returns an ADO.NET DataSet, you might want to use the RecordSource property.

Binding control to the Web service return value or parameter
Specifies the XML Web service parameter source to which the control property is bound.

The ReturnValue setting is selected as the default. However, you can also specify an operation parameter as the source. This can be useful for operations that have parameters passed by reference. It is also sometimes useful to display the original input value, for example, by using the Label Caption property.

Client description
Specifies a name you want to use for the client. (Optional)
Name of binding property
Specifies the name of a custom property you want to use as the event source for triggering the XML Web service operation call and subsequent control binding. This option is set to BindMe by default. However, all custom properties and methods of the control are included in the list for you to select another if desired.

If a CursorAdapter object is selected, the CursorFill method is selected by default so that the event causes a cursor to be created after calling the XML Web service. This is useful for operations that return an ADO.NET DataSet because the XML Web service enables the DataSet to be imported into CursorAdapter object, through an XMLAdapter object, which is used by the CursorAdapter CursorFill method.

XML Web service operations are called using Visual FoxPro event binding capabilities. At run time, a property specified by the Name of binding property option is added to the control. The added property serves as the event source and is bound to the InvokeClient method of the XML Web service. When the value of the binding property is set to True (.T.), an event occurs and calls the InvokeClient method, which in turn, calls the XML Web service operation. After the operation is called, the return value is set to the control property specified. You can also specify a custom method instead of a custom property. Calling this custom method triggers an event that calls the InvokeClient delegate.

Invoke at startup
Specifies that the XML Web service is called and the control is bound when the form or class is first instantiated.
Always call Web service
Specifies that each control makes its own call to the XML Web service operation to which it is bound.

The XML Web service control (wshandler) has the capability to detect when multiple client calls occur for the same operation. For performance, multiple clients reuse the results of an operation when those clients are called simultaneously, such as when the form or class is first instantiated.

For example, suppose you have a TextBox control that binds an operation's results to its Value property and a Label control that binds the first parameter, an input value, of the same operation to its Caption property. When the form or class instantiates, and both clients are called, only a single call to the XML Web service operation usually occurs. However, by selecting Always call Web service, you can specify that all clients make their own calls to the same operation. This also occurs if a client manually calls the operation when the form or class instantiates.

Complex Types
Displays a dialog box that makes it possible for you to set additional options when binding to operations that return complex types, such as an ADO.NET DataSet or XMLDOMNodeList. For more informatin, see XML Web Service - Complex Types Dialog Box.

See Also

Dialog Boxes | Operations Tab, XML Web Service Builder


XML Web Service - Complex Types Dialog Box

Makes it possible for you to specify information for complex types such as table and field names for XML Web service operations that return ADO.NET DataSets or property names for a returned object, such as an XMLDOMNodeList, which SOAP Toolkit 3.0 returns for most complex types.

This dialog box appears when you click Complex Types in the XML Web Service - Client Detail Dialog Box .

Dataset
Specifies a table and field name of the returned DataSet. The XML Web service control imports the DataSet into an XMLAdapter object object that your application can use. When the client operation is called, the cursor is automatically created.
  • Dataset tables Specifies a table from the tables available in the DataSet.
  • Table fields Specifies a field from the fields available in the selected DataSet table. Selecting a field can be useful when binding to the TextBox ControlSource property.
  • Use existing cursor if already opened Specifies to use an existing cursor that has the same name; otherwise, create a new cursor.
Object
Most XML Web service operations that return complex types are objects, which are treated by SOAP Toolkit 3.0 as XMLDOMNodeLists, and have properties to which you might want to bind your control.
  • Values Displays properties associated with the object.
Query
Calls the XML Web service so that you can view the available values for the DataSet or object.
Reset
Resets all values to empty strings.
Attach Schema
Sets the CursorAdapter CursorSchema property to the schema of the selected table. Available when a CursorAdapter object is selected in the Client Detail dialog box.

See Also

Dialog Boxes | XML Web Service - Client Detail Dialog Box


XML Web Service - Operation Detail Dialog Box

Makes it possible for you to choose specific operations, or methods, you want to call from your application. You can also specify parameter values for these operations.

This dialog box appears when you click Add or Edit in the Operations group of the Operations tab of the XML Web Service Builder. For more information, see Operations Tab, XML Web Service Builder.

Name
Specifies a name you want to use to refer to the operation.
Description
Specifies a description for the operation. (Optional)
Select an operation (method)
Specifies the operation you want to use. Details of the selected operation appear in the Syntax box, including any previously set parameters.
Set parameter(s)
Specifies how parameter values are set for the operation as follows:
  • Input values now Makes it possible for you to set parameter values in advance. To specify values or run-time parameter sources, click Set to open the XML Web Service - Parameter Values Dialog Box.
  • Programmatically set at run-time Set parameter values at run time using the operation's parameter collection.
  • Prompt at run-time Specifies that a dialog box appears for entering values when the operation is called at run time. The dialog box supports only simple data types.
Set
Displays a dialog box for you to set parameter values for the operation. This option is available only when Input values now is selected in the Set parameter(s) box.
Syntax
Displays the syntax for the operation.

Options

Allow Web service calls to be cached offline
Specifies that operation calls, including parameter values and results, are stored locally. If the operation is called offline using the same parameters, the original results are returned, making it possible for your application to run disconnected without interruption.

See Also

Dialog Boxes | Operations Tab, XML Web Service Builder


XML Web Service - Parameter Values Dialog Box

Makes it possible for you to set parameter values or specify a control and its property as a parameter source for a selected XML Web service operation.

Note You can specify only simple data types in this dialog box. You can set complex data types, such as arrays or ADO.NET DataSets, programmatically using the operation's parameter collection.

This dialog box appears when you select Input values now in the Set parameter(s) box of the XML Web Service - Operation Detail Dialog Box.

Select parameter
Specifies the parameter you want to set.
Parameter type
Displays the data type for the parameter.
Specify parameter source
Specifies the source that supplies the value for the selected parameter.
  • Value Specifies a particular value for the parameter. The value provided is automatically converted to the correct data type required by the parameter.

    You can also include an expression, which is evaluated at run time, by prefacing it with an equal sign (=). For example, you can set the current date as follows:

    =DATE()
  • Control/Property Displays available controls on the form and specifies that the property of the selected control or object supply the value for the parameter.

    When selecting a control, a list of properties available for that control appears so that you can select one to supply the value. If you want to have the user supply the value for the parameter, you might want to select the Value property.

See Also

Dialog Boxes | XML Web Service - Operation Detail Dialog Box


Task Pane Manager

The Task Pane Manager displays areas that contain information and expose essential tasks for easy use. Individual panes can contain static or dynamic information, gather content from the Internet, expose wizards to accomplish routine tasks, display Help, and present samples. Users can create customized panes that can be shared with other users.

The Task Pane Manager can be accessed on the Tools menu in the main Visual FoxPro screen.

Start
Contains sections that display information on Visual FoxPro, list user-selected tools, and list recently opened projects and databases.
Community
Contains information on the Visual FoxPro community. This pane is created using dynamic Internet-based content.
Environment Manager
Specify Visual FoxPro environment settings, and associate them with individual projects.
Solution Samples
Displays solution samples created in Visual FoxPro. Additional solution samples can be installed by using the Install Sample option.
XML Web Services
Aids users in using, publishing, and managing XML Web services. Also includes links to useful resources on XML Web services.
Filer
Specify search criteria to locate files.
Refresh
Reloads the content for the pane that is currently displayed. If this content contains dynamic Internet-based information, the content is downloaded as specified in the Task Pane Options dialog box.
Options
Displays the Task Pane Options dialog box where you can set options for the Task Pane or for individual panes.

See Also

User Interface Reference | _TASKPANE System Variable | Pane Customization Dialog Box | Task Pane Options Dialog Box


Toolbox

The Toolbox displays items used in the creation of applications, the items are displayed in toolsets (collections of tools) by category. The toolsets can be common resources such as native Visual FoxPro classes that can be placed onto a workspace. Additionally, the Toolbox supports items that are builders or wizards, ActiveX controls or classes, COM+ controls or classes, and text scraps. Furthermore, the Toolbox can hold file-based resources such as tables, images, reports, labels, and forms.

The individual tool sets can be fully customized. In addition, users can add new tool sets containing their own selection of items.

You can open the Toolbox by clicking Toolbox on the Tools menu or by clicking the Toolbox button on the Visual FoxPro standard toolbar. You can then drag and drop items from the Toolbox to your workspace or click them to perform other actions.

Favorites
A toolset for storing items that are used often. Items from other categories can be moved to this one for easy access.
Text Scraps
A toolset containing text scraps. New text scraps can be added by selecting text and dragging it onto this category.
VFP Base Classes
A toolset containing native Visual FoxPro classes.
VFP Foundation Classes
A toolset containing some of the most popular Visual FoxPro foundation classes.
My Base Classes
A toolset containing the FoxPro Foundation base classes from FFC\_BASE.VCX class library.
My XML Web Services
A tool set containing registered XML Web services.
My ActiveX Controls
A toolset containing registered ActiveX controls.

See Also

User Interface Reference | _TOOLBOX System Variable | Customizing the Toolbox | Customize Toolbox Dialog Box


Wizards

Visual FoxPro ships with several wizards. Wizards are interactive programs that help you quickly accomplish common tasks, such as creating forms, formatting reports, setting up queries, importing and upsizing data, graphing, creating mail merge output, generating pivot tables, creating cross-tab queries, and publishing in HTML format for the Web.

By answering questions or choosing options on the series of wizard screens, you are telling the wizard to build a file or perform a task based on your responses.

Most of the wizards have several output options in the last page. These output options are often to files that can be bound into your application. For example, the Web Publishing wizard has an output script option, which creates a program (.prg) file that dynamically generates an HTML page from FoxPro data. You can include this script file in your application and run it from a menu item or button on a form.

Note that additional wizards are available at the Visual FoxPro Web site at http://msdn.microsoft.com/vfoxpro/.

In This Section

Application Wizard
Allows you to create a project and a Visual FoxPro Enhanced Application Framework and then opens the Application builder, so you can add a database, tables, forms, or reports you have created already.
Cross-Tab Wizard
Allows you to create a cross-tab query to summarize data from existing tables.
Database Wizard
Makes it possible for you to use predefined templates to help you create a database containing appropriate tables.
Documenting Wizard
Enables you to format and produce text files from the code in your projects and program files.
Form Wizard
Makes it easy for you to use a single table to create a form for data entry.
Graph Wizard
Allows you to create a graph from a Visual FoxPro table using Microsoft Graph.
Import Wizard
Allows you to move data into Visual FoxPro table (.dbf) files from other file formats, such as plain text, Microsoft Excel, Microsoft Word, and other files.
Label Wizard
Allows you to create labels that you can affix to envelopes and packages or that you can use in your own custom situation.
Local View Wizard
Allows you to create views, which are customized displays of some or all information, using native Visual FoxPro data.
Mail Merge Wizard
Allows you to create either a data source, such as names or addresses, for a Microsoft Word merged document, such as a form letter, mailing labels, envelopes, or catalogs, or a text file, that can be used by any word processor.
One-To-Many Form Wizard
Allows you to create a data entry form that updates several tables from a single form.
One-To-Many Report Wizard
Allows you to create a report that groups records from a parent table with records from a child table.
PivotTable Wizard
Allows you to create interactive worksheet tables used to summarize and analyze data from existing tables.
Query Wizard
Allows you to create a query to select a group of records based on rules you specify.
Remote View Wizard
Allows you to create views, which are customized displays of some or all information, using remote data (ODBC).
Report Wizard
Allows you to create reports using one free table or one table or view in a database.
SQL Upsizing Wizard
Allows you to create a SQL Server database that duplicates, as much as possible, the functionality of a Visual FoxPro database.
Table Wizard
Allows you to create tables based on typical table structures and allows you to select a table to fit your needs from a list of sample tables.
Web Publishing Wizard
Displays data from a table or view in an HTML document.
Web Services Publisher
Enables you to publish an XML Web service.

Related Sections

User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Creating Applications with the Application Framework
Explains how to create applications with the Application Framework using the Application Wizard and the Application Builder.
Builders
Describes how Builders aid in setting properties of controls on a form. Unlike wizards, builders are reentrant, so you can reopen a builder on a particular control repeatedly.
Windows
Explains the options that appear on various dialog boxes, windows, and other user interfaces.
Dialog Boxes
Explains the options that appear on various dialog boxes.
Designers
Describes how Designers make it possible for you to design the windows, dialog boxes, and components in your application visually.


Application Wizard

The Application Wizard creates a Project and a Visual FoxPro Enhanced Application Framework and then opens the Application Builder, so you can add a database, tables, forms, or reports you have created already. You also can create a new application in the Application Builder using database or table templates.

To access the Application Wizard

  • From the Tools menu, choose Wizards, and click Application.

The wizard will display a dialog box in which you can specify the name and location of your new application.

Project name edit box
Makes it possible for you to specify the name of the project that is displayed in the Project title bar.
Project file edit box
Makes it possible for you to specify the file name and location of the new project.
Browse button
Makes it possible for you to locate an existing project file to use in the Application Builder.
Create project directory structure check box
Makes it possible for you to determine whether or not to have Visual FoxPro create the project directory structure for you automatically. The wizard creates a template that includes all possible application files, although you might not need them all. If you already have created your application files, leave this box cleared.

The Application Wizard will display a wait window that prompts you to wait as it generates the necessary Application framework file structure, the Visual FoxPro Application framework, for your application. When the process has completed, the wizard will display the new project window and the Application Builder so you can complete the details of your new application.

See Also

Application Builder | Application Framework Files | Visual FoxPro Framework Application Object | Wizards Overview | Application Wizard Object Members


Visual FoxPro Framework Application Object

The enhanced framework _application class includes, aside from its properties and methods, five objects: cuserror, cusdatasession, cuswindowhandler, custablesort, and custablenav.

The application object contains code for standard methods and includes a set of new methods that provide most of the enhanced functionality of the enhanced Application Framework in this version of Visual FoxPro. You can access the details of _application and its contained objects in _framewk.vcx.

See Also

Application Builder | Wizards Overview | Application Wizard Object Members | Application Wizard


Application Wizard Object Members

When an Application Wizard creates a new project, it automatically generates two forms for the new application, a Quick Start form and an About form, subclassed respectively from the wzQuickStartForm and Wzaboutdialog forms in the Appwiz.vcx library.

The subclassed forms are containers for the following objects.

Wzaboutdialog Members

Object | Class | Description
cmdOK | CommandButton | Releases the form.

WzQuickStartForm Members

Object | Class | Description
CmdClose | CommandButton | Closes the QuickStart form.
CmdRun | CommandButton | Runs the form currently selected in the list box.
LblForms | Label | Text label.
LstForms | List Box | Contains a list of all forms defined in the application, generated automatically in the list box's Init method. When the user double-clicks the name of a form, the form is run.

See Also

Application Wizard Object Members | Wizards Overview | Visual FoxPro Framework Application Object


Cross-Tab Wizard

This wizard creates a cross-tab query for summarizing table data in a spreadsheet format.

To access the Cross-Tab wizard

  1. From the Tools menu, choose Wizards, and click Query.
  2. In the Wizard Selection dialog box, choose Cross-Tab Wizard.

Step 1 - Select Fields

In this step, you can choose a free table or a table within a database as the source for your pivot table. You can select only fields from a single table or view. For more information, see Creating Views.

To select the fields for your cross-tab query

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select three or four fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

You need to choose at least three fields; one each for row values, column values, and data.

Step 2 - Define Layout

In this step, you can specify which field values will be calculated for the data. For example, if you have an Orders table that contains, among others, a field for city, a field for region, and a field for order amount, you could create a pivot table that would display in the data area, sums for all the cities, by region. At the bottom, the table will display totals for each column. At the far right, the table will display totals for each row.

To define the cross-tab layout

  1. From the Available fields list, drag a field to the Rows box. The cross-tab query will contain a row for each unique value in the field that you drag to the Rows box
  2. From the Available fields list, drag a field to the Columns box. The cross-tab query will contain a column for each unique value in the field that you drag to the Columns box
  3. From the Available fields list, drag a field to the Data box. Because this field will be summarized, generally it is best to drag a numeric field here.

If you have a large table, you might want to first create a view that contains the desired fields and then create a cross-tab query from that view. For more information, see Creating Views.

Step 3 - Add Summary Information

In this step, you can determine if you want to add a subtotal column and summary information in your data. To add summary information, select the appropriate radio button (Sum, Count, Average, Max, or Min) in the Summary section. To add a subtotal column, select the appropriate radio button (Sum of data, Number of cells containing data, or Percentage of the table total) in the Subtotals section. If you do not want to add a subtotal column, select the None radio button in the Subtotals section. The totals will appear in the rightmost column of your cross-tab query results.

Step 4 - Finish

This step makes it possible to save and specify the use of your cross-tab query.

Save cross-tab query
Saves the cross-tab query for use later.
Save and run cross-tab query
Saves the cross-tab query and runs it immediately.
Save cross-tab query and modify in the Query Designer
Saves the cross-tab query and opens it in the Query designer so you can modify it.

You can preview your cross-tab query by clicking the Preview button. To view null values, select the Display Null Values check box.

At any point after you save the cross-tab query, you can open and modify it as you would with any other query in the Query and View designers.

See Also

Wizards Overview | Query Wizard | Query and View Designers | Creating Queries


Database Wizard

The Database wizard uses predefined templates to help you create a database containing appropriate tables.

The following templates are included in Visual FoxPro.

Note You can use the Application wizard to create an application that uses these templates.
Template | Description
Address Book | Includes a table for a personal address book.
Asset Tracking | Includes tables useful in documenting assets and costs.
Books | Includes tables useful in documenting authors and books.
Contact | Includes tables useful in documenting and managing contacts.
Donation | Includes tables useful in managing donation campaigns.
Event Management | Includes tables useful in planning and managing events and personnel.
Expenses | Includes tables useful in documenting employee expenses and reporting.
Household Inventory | Includes tables useful in managing household furniture and equipment.
Inventory Control | Includes tables useful in tracking inventory.
Ledger | Includes tables useful in managing transactions.
Membership | Includes tables useful in managing club or other membership groups.
Music Collection | Includes tables useful in managing recordings collections.
Order Entry | Includes tables useful in managing order entry operations.
Picture Library | Includes tables useful in managing collections of film and photographs.
Recipes | Includes tables useful in managing household recipes.
Resource Scheduling | Includes tables useful in specifying, scheduling, and managing resources.
Service Call Management | Includes tables useful in managing service call jobs and personnel.
Students and Classes | Includes tables useful in managing students, teachers, facilities, and educational programs.
Time and Billing | Includes tables useful in managing client and employee accounts.
Video Collection | Includes tables useful in managing collections of videotapes.
Wine List | Includes tables useful in managing wine collections.
Workout | Includes tables useful in planning and managing a physical fitness program.

To access the Database wizard

  1. Open Visual FoxPro.
  2. From the Tools menu, choose Wizards, and click Database.

Step 1 – Select a Database

In this step, you can select a Visual FoxPro database template from the list in the Select database section. For more information about each of these templates, see the previous table. Alternatively, you can specify Visual FoxPro database or select an Access (.mdb) database template by clicking the Select button. This displays the Open dialog box from which you then locate the remote database to use as a template.

Step 2 – Select Tables and Views

In this step, you can choose the tables and views you want to include in your database. The template you specified in Step 1 provides a list of pre-selected tables and views. Select the check boxes for the tables or views you want to use in your database.

Step 3 – Index the Tables

In this step, you can determine how you want to index your tables. You can select which field you want to use as the primary index key.

To specify a field as primary index key

  1. In the Select table list box, highlight the table containing the field you want to use.
  2. In the Primary key list box, highlight the field you want to use.

You also can select check boxes beside the options offered in the Field Name section to create additional indexes.

Step 4 – Set up Relationships

In this step, you can establish or change the relationships between the tables in the database.

To specify a relationship between tables in your database

  1. In the Select table list box, highlight the table containing the field you want to use.
  2. In the My new X table list box (with X being the name of the table), highlight the relationship statement you want to edit, and then click the Relationships… button.
  3. In the Relationships dialog box, click the radio button next to the description of the type of relationship you want to create. You can select the key field or create a new field by typing in the edit box.
  4. Click OK. This returns you to Step 4 where the new or edited relationship is listed in the My new X table list box.

Step 5 – Finish

In this step, you select the final options for your database:

Save database for later use — Saves your database.

Save database and modify it in the Database Designer — Saves your database and opens it in the Database designer for further modification.

Populate tables with sample data — populates the new database with the sample data in the template.

After the wizard generates the database, you can add the database to a Project Manager window or to the Component Gallery, or you can open the Database designer to modify the database tables and relationships.

See Also

Wizards Overview | Project Manager Window | Starting with the Component Gallery | Database Designer


Documenting Wizard

The Documenting wizard formats and produces text files from your code in projects and program files. You can use these files to share the code or to more easily read large sections in projects and programs. For example, the wizard can produce files containing indented source code, capitalized reserved words and variables, and can also produce a report of the keywords in the program.

Note The wizard does not modify your code and only creates a text file to document the code.

You can customize the way the Documenting wizard works by adding certain directives to your code. For more information, see Customizing the Documenting Wizard.

To access the Documenting wizard

  • From the Tools menu, choose Wizards, and click Documenting.

Step 1 – Choose Source File

In this step, you can enter the name of a project file or a specific program file. If you choose a project file, the Documenting wizard documents all the programs in the project, including the event code for forms, class library code, and so on.

Step 2 – Set Capitalization

In this step, you choose how the Documenting wizard should capitalize keywords and symbols in the text file of your code. Keywords are all the reserved words in the Visual FoxPro programming language, such as MODIFY. Symbols are the variables and names that you define in your code. Capitalization makes it easier to read and identify elements in your code. The capitalization options are:

UPPERCASE
Keywords and symbols are displayed in all uppercase letters.
lowercase
Keywords and symbols are displayed in all lowercase letters.
MixedCase
Keywords are displayed with the first letter of each word in the keyword capitalized, for example, AddObject.
Match first occurrence
Symbols are displayed according to the capitalization of the first occurrence in the file. For instance, if you use initial capitals in the first occurrence in a file, all other occurrences of those keywords are displayed the same way, no matter how they might be typed in subsequent occurrences.
No change
Keywords and symbols are not modified.

Step 3 – Set Indentation

In this step, you specify how the Documenting wizard will indent lines in the text file of your code. The wizard can indent specific types of lines, and you can adjust how many spaces to use when indenting. Functionally, in code, there is no difference between spaces or tabs. Indenting makes it easier to read and understand your code.

Type of Indent
Choose whether the wizard should indent using tabs or spaces. To turn off indentation, choose No Change. If you choose Spaces, then you must select the number of spaces to be used. If you choose Tabs, then the Documenting wizard uses the current Visual FoxPro tab setting.
Text to indent
Specify the type of line that the wizard should indent. Your choices are Comments, Controls structures (such as loops, IF blocks, and DO CASE structures), and Lines continued by a semi-colon (statements that are split across multiple lines).

Step 4 – Add Headings

In this step, you specify where, if anywhere, you want the Documenting wizard to insert headings into the text file of your code. Headings are comments about the code that are relevant to the code that they precede. They can be placed at the beginning of files, procedures, class definitions, and methods to make your formatted code more understandable.

Step 5 – Select Reports

In this step, you specify the types of reports that the Documenting wizard creates. (The reports are actually text files.) The wizard can produce the types of reports listed in the following table.

Report Type | File Name | Remarks
Action Diagram | project.act | Shows the hierarchical relations within your code. If you are not working with ASCII code page 1250 and ANSI code page 1252, see the directive "*# document ACTIONCHARS" in Customizing the Documenting Wizard.
Cross-Reference | Xref.lst | Lists all the user-defined symbols.
File Listing | Files.lst | Lists all the files in the project.
Source Code Listing | project.lst | Puts all formatted code in a single file.
Tree Diagram | Tree.lst | Shows the procedure calling tree.

The wizard also automatically creates the following files:

  • Files.dbf Table with a record for each file in the project.
  • Fdxref.dbf Table with a record for each instance of user symbols (as listed in the following table) in the code. This table makes it possible for you to see what type of Visual FoxPro element is represented by each symbol.
Fdxref.dbf contains a field named Flag for identifying the keywords. The identifiers are the following.
Flag | Description
B | Base class
C | Class name
D | Defined PROCEDURE or FUNCTION (not method)
F | Function call: myproc( ) or DO myproc
K | Keyword
M | Method definition
N | Name of file
O | Object
P | Property of an object
R | User symbol reference
V | User symbols (variable) definition (PARA, PRIV, PUBL, DIME)

Step 6 – Finish

In this step, you can determine the location and structure that contains your code document. You also can specify whether the current document overwrites any previous documents.

By default, the wizard does not overwrite your existing files. Specify Overwrite existing files to overwrite your existing code files with the new ones that the wizard saves.

You can choose to have a single directory in which the wizard will save all the files, by selecting the Place files in a single directory option. When you click Finish, the wizard will prompt you to choose a directory that it creates.

To choose a new directory that will contain the full project tree of your project, select the Place files in a new directory tree. When you click Finish, the wizard will prompt you to choose a directory where it will create a copy of the project's source tree and save the new, formatted program files in the appropriate directories of the new tree.

When you select Cross-reference keywords, the wizard creates or adds to Fdxref.dbf, the table of keywords mentioned earlier. After running the wizard, you can use the table to create reports of the keywords you are using in your application. The wizard adds one record to Fdxref.dbf for each instance a of Visual FoxPro keyword in your code.

In addition, when this option is selected, the wizard matches keywords in your code with the first field, named Token, in the Fdkeywrd.dbf file. This file can be found in the ..\Wizards folder of the Visual FoxPro root directory and contains all the Visual FoxPro reserved words. The second column, Code, in Fdkeywrd.dbf contains an identifier that tells the wizard how to treat the keyword when analyzing your code. The following table describes the identifier codes.

Code | Description
I | Indent
U | Un-indent (remove indent)
R | Reset indentation to 0 (or 1 if in DefineClass)
F | Procedure or function
D | While or Case: DO clause
O | Object (Spinner, CommandButton)
P | Property (Scalemode, DecimalPoints)
M | Method (Init, KeyPress)
C | ClauseUsed only as a Clause: can't start a statement
Note Depending on the size of your code, this option might enlarge Fdxref.dbf by a large number of records. Before running the wizard and choosing the option to create keyword cross-references, be sure you have enough disk space.

When you select Run analyzer, the wizard starts the Visual FoxPro Code Analyzer, which dynamically traces the structure and symbols in Visual FoxPro application files. Code Analyzer provides visual controls, a menu, and keyboard options to navigate through the text file of your application file code by using output from the Documenting wizard.

See Also

Customizing the Documenting Wizard | Wizards Overview | Code Analyzer


Customizing Documenting Wizard Output

In addition to the options that you choose when running the Documenting wizard, you can employ additional options outside the wizard by changing the Fdkeywrd.dbf table, which contains all the Visual FoxPro reserved words, in the ..\Wizards folder or by adding Documenting wizard directives to your code.

Changing the Fdkeywrd.dbf

You can change the style of indent of the CASE structure by changing the code field value in Fdkeywrd.dbf. By default, the wizard looks for indentation in a CASE structure like this:

DO CASE
CASE case1=1
   case2=2
CASE case3=3
   case4=4
ENDCASE

Some developers prefer to indent the lines between DO CASE and ENDCASE an additional level like this:

DO CASE
   CASE case1=1
      case2=2
   CASE case3=3
      case4=4
ENDCASE

If you indent your CASE structures, as in the second example, specify this in Fdkeywrd.dbf.

To specify wholly nested indents in DO CASE statements

  1. Locate the Fdkeywrd.dbf file in the ..\Wizards folder of the Visual FoxPro root directory.
  2. Open the Fdkeywrd.dbf table.
  3. Locate the ENDCASE record.
  4. Change the value in the Code field to UU.

Adding Wizard Directives

You can place special directives in your code files that instruct the Documenting wizard to perform specific tasks when analyzing the code. The available wizard directives are as follows:

ACTIONCHARS
Specifies the characters used to create action or tree diagrams of your code. You might want to change the default settings if you use code pages other than ASCII 1250 or ANSI 1252 in FoxFont to get the characters you expect.
EXPANDKEYWORDS
Specifies whether keyword expansion is active or not in the Documenting wizard. The default value is OFF, which retains keywords as typed in code. If you have used four-character abbreviations throughout your code, you might want to make the code more reader friendly by setting keyword expansion ON.
XREFKEYWORDS
Specifies whether the wizard creates a file that shows all keywords and their locations in the code document. The file contains the keyword names, keyword type (according to the Fdxref.dbf table, as described in Step 5 of the Documenting wizard), the line it is located on, and the file containing it. The default is ON.
ARRAYBRACKETS
Specifies whether square brackets and parentheses are treated differently. The default, ON, treats square brackets as array delimiters and parentheses as function or method delimiters.
ACTIONINDENTLENGTH
Specifies the number of character spaces the wizard uses for indentation in tree or action diagrams. The minimum value is two characters. Functionally, in code, there is no difference between spaces or tabs. Indenting makes it easier to read and understand your code.

You can place wizard directives in the main program file of your project (to direct the wizard to analyze all code files in the project) or in individual code files (to instruct the wizard how to analyze specific files).

The syntax of the directives begins with an asterisk, so Visual FoxPro will treat them as comments and ignore them when compiling programs. The directives are not case sensitive. The syntax of the directives is:

*# document directive

For consistency throughout your code, it is a good idea to place the directives near the beginning of the main program file, so the Documenting wizard encounters the instruction when it begins analyzing.

The Documenting wizard directives are described below.

*# document ACTIONCHARS "abcdef"
By default, when the wizard creates an Action Diagram or a Tree Diagram, the wizard uses six characters that appear as lines and square corners when viewed under ASCII code page 1250 or under ANSI code page 1252 in FoxFont. Not all the characters map to line characters when viewed under other code pages. The six default characters and their corresponding FoxFont characters are listed below as a, b, c, d, e, and f.
abcdef | Default Chr( ) Value | As viewed in FoxFont
a | 32 | (space)
b | 196
c | 179
d | 218
e | 192
f | 195
Tip When using other code pages, insert the following code in your main program file to ensure that the lines in your diagrams map to line-like characters (the first character of the string enclosed in quotes is a space):
*# document ACTIONCHARS " -|+++"
Note For a list of supported code pages, see Code Pages Supported by Visual FoxPro.
*# document XREF cMode
Enables cross-referencing of variables. The default is ON.
cMode | Description
ON | Enables cross-referencing of variables
OFF | Disables cross-referencing of variables
SUSPEND Disables cross-referencing of variables in the current file until the Documenting Wizard encounters the next instance of:

*# document XREF ON
*# document EXPANDKEYWORDS cMode
Enables the expansion of abbreviated keywords in your code. For example, "DEFI WIND" would be expanded to "DEFINE WINDOW." The default is OFF.
Caution Not all keywords in Visual FoxPro begin with a unique string of four characters. For example, "REPL" could be short for "REPLACE" or "REPLICATE." Be careful if you include this directive and choose to overwrite existing files.
cMode | Description
ON | Enables keyword expansion
OFF | Disables keyword expansion
SUSPEND Disables keyword expansion in the current file until the next instance of:

*# document EXPANDKEYWORDS ON
*# document XREFKEYWORDS cMode
This directive corresponds to the Cross-Reference Keywords option on "Step 6 – Finish" in the Documenting Wizard. The default is OFF.
cMode | Description
ON | Enables cross-referencing of keywords
OFF | Disables cross-referencing of keywords
SUSPEND Disables cross-referencing of keywords in the current file until the next instance of:

*# document XREFKEYWORDS ON
*# document ARRAYBRACKETS cMode
The default is OFF.
cMode | Description
ON | The Documenting Wizard assumes that square brackets are used for arrays and that parentheses are used for functions and methods.
OFF | The Documenting Wizard treats both square brackets and parentheses as arrays.
*# document ACTIONINDENTLENGTH nSpace
nSpace is the number of character spaces that you want the Documenting Wizard to use for indentation. The minimum value allowed is 2.

See Also

Documenting Wizard | Wizards Overview | Code Pages Supported by Visual FoxPro


Form Wizard

This wizard makes it easy to use a single table to create a form for data entry. The wizard will populate the form automatically with all the fields from the table, so you can delete or rearrange them as you want. The size of the form is based on your Maximum design area setting on the Forms tab in the Options dialog box. Field mapping (what a form displays) is controlled by settings in the Field Mapping tab of the Tools menu, Options dialog box. This tab is not available while the Form wizard is open.

To access the Form wizard

  1. From the Tools menu, choose Wizards, and click Form.
  2. In the Wizard Selection dialog box, choose Form Wizard.

If you create a form within a database, the Form wizard can use input mask and format settings stored in the database. After you save the form, you can open and modify it later like any other form in the Form designer.

Step 1 - Select Fields

In this step, you can choose a free table or a table within a database as the source for your form. You only can select fields from a single table or view.

To select the fields for your form

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table and use the arrow buttons to move them to the Selected fields window.

Step 2 - Choose Form Style

In this step, you specify what the controls on your form will look like. When you click any of the styles listed in the Style text box, the wizard displays a picture in the magnifying glass as an example of the style.

The Button Type options refer to your form's navigation buttons.

Text Buttons
Places navigation text on the buttons of your form.
Picture buttons
Places navigation icons on the buttons of your form.
No buttons
Places no buttons on your form, so you can prevent navigation beyond the displayed or entered data.
Custom
Makes it possible for you to choose between two types of scrolling data windows.
  • Scrolling grid - Displays the fields you select from one record at a time.
  • Scrolling grid (justified) – Displays the fields you select from as many records, at one time, as will fit in the form.

The navigation buttons that the wizard creates on your form are as follows.

Button | Icon | Description
Top |  | Moves record pointer to first record.
Prev |  | Moves record pointer back one record.
Next |  | Moves record pointer forward one record.
Bottom |  | Moves record pointer to last record.
Find |  | Displays the Search dialog box.
Print |  | Prints a report.
Add |  | Adds a new record to the end of the table.
Edit |  | Makes it possible for a user to change values in current record.
Delete |  | Deletes current record.
Exit |  | Closes form.
Note After the wizard saves a form, you still can add fields to it using the same styles by selecting Quick Form on the Form menu to bring up the Form builder.

All controls created by the Form wizard and the Form builder are in the \Wizards directory in the file Wizstyle.vcx. If you want to modify the styles, modify the classes in this file using the Class designer.

Step 3 - Sort Records

Select the fields in the order that you would like to sort the records within each group. For example, if you are using two fields and have a first name field and a last name field, then you could choose to sort on first name+last name (such as PaulWilson) or on last name+first name (such as WilsonPaul). How you sort is determined by the order in which you selected those fields.

If your table already has one or more indexes, you can select the tag, which is listed below the fields in the Available fields window.

Step 4 - Finish

If you chose a large number of fields earlier and want to make sure they all fit on the form, you can select Add pages for fields that do not fit. Otherwise, if the number of fields exceeds the size of the form, Visual FoxPro provides a scrolling form.

You can use field mappings specified in the Options dialog box of the Tools menu or override those settings with information in the database. To preview the form before exiting the Form Wizard, click the Preview button.

After you save the form, you can open and modify it later like any other form in the Form designer.

See Also

Wizards Overview | Forms Tab, Options Dialog Box | Form Designer


Graph Wizard

The Graph wizard creates a graph from a Visual FoxPro table using Microsoft Graph. You will want to use a graph of one kind or another to make it easier to visually display or evaluate data contained in large tables or reported in dense spreadsheets.

The larger your table is, the longer it will take the wizard to process your graph. You might consider limiting the scope of records in a large table by creating a view before you run the Graph wizard. For more information, see Creating Queries.

To access the Graph wizard

  1. From the Tools menu, choose Wizards, and click Query.
  2. In the Wizard Selection dialog box, choose Graph Wizard.

Step 1 – Select Fields

In this step, you can choose a free table or a table within a database as the source for your graph. This can normalize the input in data entry forms, and thereby, your data tables. You can select fields from only a single table or view. This selection must include at least one numeric field.

To select the fields for your graph

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.
    Note If you choose a general or automation field in this step, the field will not be available in the next step for defining the graph layout.

Step 2 – Define Layout

In this step, you specify which numeric field is graphed and which field provides the divisions along which those values are graphed. Drag one or more of the available numeric fields from the Available fields window to the Data series window. Drag another field from the Available fields window to the Axis box beneath the graph picture. For example, in a table containing salary amounts as a numeric field, you might choose the salary field and a name or a region field to chart against.

Step 3 - Select Graph Style

In this step, you select a style of graph that effectively presents the information. Each graph style plots the data in a different manner. Look at the pictures on the buttons to choose a style that meets your needs. The following list summarizes the available chart types:

Area and 3D area
Indicates the relative importance of values over a period of time, and it emphasizes the amount of change rather than the rate of change.
Bar and 3D bar
Indicates values of discrete elements relative to each other. This is similar to a column chart but arrayed vertically.
Column and 3D column
Indicates variation over a period of time or draws comparisons between discrete items. The horizontal array of columns suggests time flow more than a bar chart.
Pie and 3D pie
Indicates the relationships or proportions of parts to a whole. This type of graph always contains just one data series.
Line and ribbon (3D line)
Indicates trends or changes in data over a period of time. This is similar to an area chart, but it emphasizes time flow and rate of change rather than amount of change.
Scatter (XY)
Indicates the relationship or degree of relationship between numeric values in different groups of data. This type of chart is useful for determining patterns or trends and for determining whether variables are dependent upon or affect one another.

Step 4 - Finish

In this step, you specify the way the graph is output and whether it will display the name of the selected numeric field and null values. You can save the graph to a form, you can use the graph on a report by saving it to a table, or you can create a query that generates the graph.

Saving to a Form

If you choose to save the graph to a form, the wizard creates a form containing the graph, and optionally, a legend of the charted value(s).

Saving to a Table

If you choose to save the graph to a table, the wizard creates a table with a single record containing a General field that stores an Automation object for your graph. You then can include this field on a report. After the wizard is finished, it leaves your new table open. To view the graph, browse the new table and double-click the Olegraph field.

Creating a Query

If you choose to create a query, the wizard saves a query that sends its results to the graph you have specified. After the wizard saves the query, you can open and modify it like any other query in the Query designer.

Show null values check box
Specifies that the graph represent any null values as well as all positive and negative values. For example, it might be important to your presentation to show that nothing happened on particular days or with particular clients.
Add a legend to the graph check box
Specifies that the graph include a legend naming the graphed value. This helps make your graph and its data more readable.
Preview button
Makes it possible for you to see the graph before saving it to a form, table, or query file.

See Also

Running Queries | Cross-Tab Wizard | Local View Wizard | Query Wizard | Remote View Wizard | Wizards Overview | Creating Queries


Import Wizard

You can use the Import wizard to move data into Visual FoxPro table (.dbf) files from other file formats, such as plain text, Microsoft Excel, or Word, and other files. For example, you might have a list of names and addresses in a Word file that you would find easier to use and more effective if it were in a Visual FoxPro table.

To access the Import wizard

  • From the Tools menu, choose Wizards, and click Import.

Step 1 – Identify Data

In this step, you identify the type and location of the data you want to import.

File Type drop-down list
Provides a list of known file types from which you can choose.
Source File edit box
Makes it possible for you to choose or to specify a file name and location. If you do not know either you can use the Locate button to find the file.
New table radio button
When you specify a destination file name and location, the wizard prompts you with a new table name in the same directory. The edit box makes it possible for you to specify a different name or location for the destination file. You can use the Locate button to specify another new file and location.
Existing table radio button
If you choose this button, the edit box makes it possible for you to specify the name and location of an existing file. If you do not know either you can use the Locate button to find the file.

Step 1a – Select a Database

In this step you can specify a database to which your table is added. You also can decide to import your data into a stand-alone table. If you choose a database, you can have enhancements like automatic and custom formatting options. For information on database enhancements, see Creating a Database

Step 2 – Determine Data Format

In this step, you can specify how the imported data was formatted — with or without delimiting characters between fields or columns and rows or as a single fixed-width column. You also can specify where within the file you want to begin importing data.

Delimited
Specifies that the fields in the file are separated by a character, such as a comma (,) or a semicolon (;).
Fixed Width
Specifies that the fields in the file are aligned in columns.
Field names in row
Makes it possible for you to specify the row of imported data that contains the field names. For instance, if the first line of your imported data contains the desired field names, set Field names in row to 1. If, however, field names are not part of the imported data, then in Step 3, you can specify field names for the new table.

The Import wizard automatically replaces spaces with underscores and reduces field name size to fit the 10-character maximum.

Begin import at row
Makes it possible for you to specify the starting row of data in the imported file. This option makes it possible for you to avoid importing header data.

If you are importing a spreadsheet, this step offers a drop-down list of worksheets available in the selected spreadsheet.

Step 2a – Describe Data or Set Columns

Step 2a of the Import wizard only appears if you have chosen to import a text (.txt) file. Depending on what you chose as the Data format in step 2, you will get one of two options for step 2a: Describe Data or Set Columns.

Describe Data

This step appears as Describe Data, if you select Delimited as the Data format in step 2. Select what delimiter separates the text strings in the selected file. View the effect of the delimiter selected in the Field grid in the lower portion of this wizard dialog box.

Set Columns

This step appears as Set Columns, if you select Fixed Width as the Data format in step 2. You can use the Field grid in the lower portion of this wizard dialog box to specify more columns by clicking below the displayed data, so the imported information is divided into discrete fields.

Step 3 - Define Imported Fields

In this step, you specify the name of the columns in the table, the data type of the columns, and the width of the columns. Click below the existing heading of the column in the Field grid and edit the information listed in the Name, Type, Width, and Decimal drop-down lists.

If you do not want to import a specific column, click below the existing heading, and then press DELETE. The space for the column will still be visible (without a column heading name), but when you finish the wizard and import the data, that column will be ignored.

Worksheet
Specifies the name of the worksheet if you are importing an Excel spreadsheet.
Field Grid
For a text file, this grid displays, at the bottom of the wizard dialog box, the record number and data as it is found in the file. For other types of files, it displays the file data as it will appear when you have completed the Import wizard.

Step 3a – Specify International Options

In this step, you can specify alternative settings for internationalization of the data to be imported into the table. You can choose to change the code page, currency symbol, 1000 separator, decimal separator, and date format.

Code Page button
Changing the code page can affect the way your charts appear, because the characters that form lines and corners differ among code pages. This option makes it possible for you to select from code pages supported by Visual FoxPro.
Currency Symbol edit box
This setting makes it possible for you to override the default currency setting for the file created by this wizard.
1000 Separator edit box
This setting makes it possible for you to override the default 1000 separator for the file created by the Import wizard.
Decimal Separator
This setting makes it possible for you to override the default decimal separator for the file created by the Import wizard.
Date Format
This option makes it possible for you to select one of the date formats supported by Visual FoxPro. For more information, see Dateformat Property.

See Also

Wizards Overview | Graph Wizard | Importing Data with the Import Wizard | Importing and Exporting Data | Developing International Applications | Dateformat Property


Label Wizard

You can use the Label wizard to create labels that you can affix to envelopes and packages or that you can use in your own custom situation. With the wizard, these labels are generated from the entries in a table.

To access the Label wizard

  • From the Tools menu, choose Wizards, and click Label.

Step 1 – Select Tables

In this step, you select a table or view as the source for your labels. If you use a table, then you will get all the fields in the table to use on your label. Choosing a view can make it possible for you to pre-select certain records or certain fields in each record from a table. For more information, see Creating Views.

Step 2 - Choose Label Type

In this step, you can choose a standard or custom label by name, size, and available columns.

The wizard lists the standard label types that are installed with Visual FoxPro. The wizard also lists any label types you create using the AddLabel application in the \Tools folder.

You also can launch the Add Label wizard by clicking the New Label button. For information, see Addlabel.app.

Step 3 – Define Layout

In this step, you select the fields you want to use on the label and specify the layout, font, and any commentary text you want to appear on the label.

Add the fields in the order you want them to appear on the label. You can use the punctuation (comma, period, colon, and hyphen), new line, and Space buttons to format the label. Use the Text box to add text. You also can use the Font button to change the font used on labels.

As you add items to the label, the picture in the wizard window is updated to show approximately how your label will look. Check this picture to see if the fields you have chosen will fit on the label. The text lines will extend beyond the bottom edge of the label if there are too many lines.

Step 4 – Sort Records

In this step, you can specify the sort order of your labels. For example, if they are to be mailing labels, then you might sort by city, state, or zip code. However, if they are folder or party labels, then you might want to sort alphabetically by names.

Select the fields or index tag in the order that you would like to sort the records.

Step 5 - Finish

In this step, you choose how to save your labels. You can save them for later use; you can save them for modification in the Label designer, which makes it possible for you to use one of the default labels as a basis for a custom label of your own design; or you can print the labels immediately from Visual FoxPro.

You can choose Preview to verify your choices before finishing.

See Also

Wizards Overview | Import Wizard | Graph Wizard | Working with Tables | The Process of Importing Data | Code Pages in Visual FoxPro


Local View Wizard

With the Local View wizard, you can create views, which are customized displays of some or all information, using native Visual FoxPro data. You might want to use a view if the amount of source data is large, but you only need to display a particular portion of that data. If you do not have a database open, you are prompted to open a database or create one.

To access the Local View wizard

  1. From the Tools menu, choose Wizards, and click Query.
  2. In the Wizard Selection dialog box, choose Local View Wizard.

Step 1 – Select Fields

In this step, you specify which tables or views from a Visual FoxPro database you want to use as source for your local view. Using a view, you can gather information from one or more tables into a single display of information. A local view, unlike a Browse window, can make it possible for you to create very effective, perhaps simple, display from large or complex data sources.

You can select fields from several tables or views. First, select fields from one table or view and move them to the Selected fields box; then select fields from another table or view and move those.

Step 2 – Relate Tables

This step displays only if you select fields from more than one table or view. You can specify which fields in each table or view contain like information and can govern the relationship between the tables or view, thereby determining the included records.

Select the desired fields from the two drop-down list boxes, and then choose Add. If you use multiple tables in your view, then you must relate the tables by indicating which fields contain matching data in each table.

Step 2a – Include Records

This step displays only if you select fields from more than one table or view. You can specify which records from the selected tables will be made available to the Local View wizard.

If you are using more than one table, you can specify a join condition. For more information, see Creating a Multitable View. For example, if you specify only matching rows in Step 2a, you can further refine that choice in Step 3 by specifying a particular value for a field.

Limit the records to only matching rows
Returns only records from both tables that match the comparison condition set between the two fields in the join condition. This is called an inner join.
All rows from either table
Returns all the rows from the selected table. This makes it possible for you to create a left or right outer join.
All rows from both tables
Returns matching and non-matching records from both tables. This is called an outer join.

By default, only matching records are included.

Step 3 – Filter Records

This step appears immediately after Step 1 if you have chosen only one table or view as source for your local view. You can specify a filter condition, so only certain of the records you have chosen to make available are used in the local view.

To determine the filter condition

  1. Select a field from the Field drop-down list.
  2. Specify an operator, such as equals or contains, in the Operator drop-down box.
  3. Specify a value in the Value textbox.

    For example, if you wanted to filter on a specific city, such as Helena, you might choose city from the Field drop-down list, choose equals in the Operator drop-down list, and enter Helena in the Value textbox.

You can reduce the number of records by creating expressions that filter records from the selected tables or views. You can create two expressions and connect them with And, which returns only records meeting both specified criteria, or Or, which returns records meeting either criteria.

You can see the result by clicking the Preview button.

Step 4 – Sort Records

This step makes it possible for you to specify one or more fields by which to sort the records in your local view.

Choose up to three fields or an index tag that already exists in the database to determine the order in which your view results will be sorted. Select Ascending to sort the view in ascending order or Descending to sort the view in descending order.

Step 4a – Limit Records

This step appears only if you have specified one or more sort fields in Step 4. You can further limit the number of records in the view, based on either a percent of the records returned or an actual number of records.

To see a percentage of the available records, choose the Percent of records radio button, and then specify the percentage in the Portion value edit box. See all records by selecting Number of records and then selecting All records. As shown in the following procedures, you can choose a portion of records from the beginning or the end of the available records.

To see the first 10 items

  1. Choose the Number of records radio button.
  2. Enter 10 in the Portion value box.

To see the last 10 records

Note This changes the sort order to last record = first read.
  1. In Step 4, change the sort order to Descending.
  2. In Step 4a, select the Number of records radio button.
  3. Enter 10 in the Portion value box.

Step 5 - Finish

In this step, you can choose how to handle the newly defined local view.

Save local view
Saves the newly defined local view and exits the wizard.
Save local view and browse
Makes it possible for you to save the new local view and then open it in a Browse window, so you can review the displayed data.
Save local view and modify it in the View Designer
Makes it possible for you to save the new local view and then modify it when it opens in the View designer.

See Also

Defining Results | Creating Persistent Relationships | Adding Tables to a Database | Cross-Tab Wizard | Graph Wizard | Query Wizard | Remote View Wizard | Wizards Overview | View Designer


Mail Merge Wizard

The Mail Merge wizard creates either a data source, such as names or addresses, for a Microsoft Word merged document, such as a form letter, mailing labels, envelopes, or catalogs, or a text file that can be used by any word processor.

Visual FoxPro Setup can install ODBC functionality through the Visual FoxPro OLE DB Provider. For information about merged documents, see Microsoft Word Help. For more information, see OLE DB Provider for Visual FoxPro.

To access the Mail Merge wizard

  • From the Tools menu, choose Wizards, and click Mail Merge.

Step 1 – Select Fields

This step makes it possible for you to specify the fields that contain the information you want to use with the merged document, which can be a Word document or a file from another word processor. You can select fields from a single table or view only.

Step 2 - Choose Word Processor

In this step, you specify whether you will create a file for use with Word or a generic, comma-delimited file for use with another word processor.

You must have a current version of Word installed on your computer if you select Microsoft Word. If you select Comma-delimited text file, the wizard will skip Steps 3 and 4 and go straight to the Finish screen.

Step 3 - Select Document Type

This step makes it possible for you to either create a new document, such as a mailing list, or to add to an existing document, such as a roster.

Step 4 - Choose Document Style

In this step, you choose a type of document to create.

Form Letter
Makes it possible for you to create or to use a letter template into which the data from the specified Visual FoxPro file will be merged.
Label
Makes it possible for you to create or to use a label template into which the data from the specified Visual FoxPro file will be merged.
Envelope
Makes it possible for you to create or to use an envelope template into which the data from the specified Visual FoxPro file will be merged.
Catalog
Makes it possible for you to create or to use a file that contains labels, such as Item or Color or Catalog number, into which the data from the specified Visual FoxPro file will be merged.

Step 5 - Finish

This step makes it possible for you to save the data as a text file or to continue into Word to specify how the Visual FoxPro data is merged into the existing or new merged document.

If you have chosen to create a Word document, the wizard will open the document in Word. If you have chosen to create a text file, the wizard will prompt you to save your comma-delimited file.

See Also

Importing and Exporting Data | Wizards Overview | Local View Wizard | Mail Merge Object


One-To-Many Form Wizard

You can use this wizard to create a data entry form that updates several tables from a single form. For example, you can create one form might update customer and order tables. The size of the form is based on your Maximum design area setting on the Forms tab in the Options dialog box.

To access the One-To-Many Form wizard

  1. From the Tools menu, choose Wizards, and then click Form.
  2. In the Wizard Selection dialog box, choose One-To-Many Form Wizard.

Step 1 – Select Parent Table Fields

In this step, you choose a free table or table or view from a database that will provide the controlling fields data presented in your form. This specifies which field of the parent or controlling table determines the records selected in the child or controlled table.

To select the fields for your form

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

You can select fields from a single table or view only.

Step 2 - Select Child Table Fields

In this step, you choose the fields from the related table. This determines which fields from a child or controlled table are displayed on the form. For example, the parent table might hold only customer names, ID numbers, and addresses, and the child table might hold orders information, such as ID numbers, amount, date, discount, and so on. One customer might have many orders.

As with the parent table fields, you can select fields from a single child table or view only.

Step 3 – Relate Tables

In this step, you specify from the fields list how the parent and child tables are related. In the example from step 2, both tables contain the customer ID field, so that is one way to relate them. There might be other ways depending on the available fields and what you want to report.

Step 4 - Choose Form Style

In this step, you choose the basic format of your form from the styles built into the wizard. When you click any of the styles listed in the Style box, the wizard displays a picture in the magnifying glass as an example of the style.

The button type options refer to your form's navigation buttons. The navigation buttons that the wizard creates on your form are as follows.

Text Buttons
Places navigation text on the buttons of your form.
Picture buttons
Places navigation icons on the buttons of your form.
No buttons
Places no buttons on your form, so you can prevent navigation beyond the displayed or entered data.
Note The Custom button type is unavailable in the One-to-Many Form wizard.
Button | Icon | Description
Top |  | Moves record pointer to first record.
Prev |  | Moves record pointer back one record.
Next |  | Moves record pointer forward one record.
Bottom |  | Moves record pointer to last record.
Find |  | Displays the Search dialog box.
Print |  | Prints a report.
Add |  | Adds a new record to the end of the table.
Edit |  | Allows user to change values in current record.
Delete |  | Deletes current record.
Exit |  | Closes form.
Note After the wizard saves a form, you can add additional fields to it using the same styles by selecting Quick Form on the Form menu.

All controls created by the Form wizard and the Form builder are in Wizards\Wizstyle.vcx. If you want to modify the styles, modify the classes in this file.

Step 5 – Sort Records

In this step, you select in the parent table the fields in the order that you want to sort the records. For example, if you are using two fields and have a first name field and a last name field, then you could choose to sort on first name+last name (such as PaulWilson) or on last name+first name (such as WilsonPaul). How you sort is determined by the order in which you selected those fields.

If your table already has one or more indexes, you can select the index tag, which is listed below the fields, separated by a line, in the Available fields window.

Step 6 - Finish

In this step you can choose how and when to use the form.

Save form for later use
Makes it possible for you to save the form as a file, which you can open later.
Save and run form
Saves the form as a file and then opens it in Visual FoxPro for immediate use.
Save form and modify in the Form Designer
Saves the form as a file and then opens it in the Form designer, so you can modify it.

If you select the Use field mappings check box, then you can use field mappings specified in the Options dialog box of the Tools menu. For more information, see Field Mapping Tab, Options Dialog Box. If you use tables from a database, you can select Override with DBC field display classes so that your form uses information from the database, otherwise this option is unavailable.

To preview the form before exiting the One-To-Many Form wizard, click the Preview button.

See Also

Create One-To-Many Relationships Dialog Box | Form Designer | Wizards Overview | Forms Tab, Options Dialog Box | Creating Persistent Relationships


One-To-Many Report Wizard

The One-To-Many Report wizard creates a report that groups records from a parent table with records from a child table, for example, names and address from a Customer table and amounts and discounts from an Orders table. The wizard prompts you with simple questions as you go through a brief series of steps, in which you specify the table and fields that you want to use to create controls on your report.

To access the One-To-Many Report wizard

  1. From the Tools menu, choose Wizards, and then click Report.
  2. In the Wizard Selection dialog box, choose One-To-Many Report Wizard.

Step 1 - Select Parent Table Fields

In this step, you choose a free table or table or view from a database that will provide the controlling fields data presented in your report. This specifies which field of the parent or controlling table determines the records selected in the child or controlled table.

To select the fields for your report

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

You can select fields from a single table or view only.

Step 2 - Select Child Table Fields

In this step, you choose the fields from the related table. This step determines which fields from a child or controlled table are displayed on the form. For example, the parent table might hold only customer names, ID numbers, and addresses, and the child table might hold orders information, such as ID numbers, amount, date, discount, and so on. One customer might have many orders.

You can select fields from a single child table or view only.

Step 3 – Relate Tables

In this step, you specify from the fields list how the parent and child tables are related. In the example from step 2, both tables contain the customer ID field, so that is one way to relate them. There might be other ways depending on the available fields and what you want to report.

Step 4 – Sort Records

In this step, you can select in the parent table the fields in the order that you would like to sort the records. For example, if you are using two fields and have a first name field and a last name field, then you could choose to sort on first name+last name (such as PaulWilson) or on last name+first name (such as WilsonPaul). How you sort is determined by the order in which you selected those fields.

If your table already has one or more indexes, you can select the index tag, which is listed below the fields, separated by a line, in the Available fields window.

Step 5 - Choose Report Style

In this step, you can choose the basic format of your form from the styles built into the wizard. When you click any of the styles, the wizard updates the graphic in the magnifying glass as an example of the style.

The Summary options button makes it possible for you to specify whether your report will include one or more calculations, such as sum or average, on available fields.

You also can choose whether your report will display or print in portrait or landscape orientation.

Step 6 - Finish

In this step, you can choose how and when to use the report.

Save report for later use
Makes it possible for you to save the report as a file, which you can open later.
Save report and modify in the Report Designer
Saves the report as a file and then opens it in the Report designer, so you can make modifications to it.
Save and print report
Saves the report as a file and then immediately prints it.

If you select Use display settings stored in the database, then your report uses information from the database.

If the number of fields you selected cannot fit on a single line within the width of your report, the fields will wrap to the following line. If you do not want the fields to wrap, clear the Wrap fields that do not fit check box. Click the Preview button to view the report without exiting the wizard.

After you save the report, you can open and modify it like any other report in the Report designer.

See Also

Working with Tables | Adding Tables to a Database | Create One-To-Many Relationships Dialog Box | Creating Persistent Relationships | Report Wizard | Wizards Overview | One-To-Many Form Wizard | Working with Tables


PivotTable Wizard

With the PivotTable wizard, you can create pivot tables, which are interactive worksheet tables used to summarize and analyze data from existing, and perhaps large, tables. You can choose either to save a pivot table directly in Microsoft Excel or to add one as an object on a form.

You must have Microsoft Excel with Microsoft Query installed on your computer to create a pivot table. For more information, see Microsoft Excel Help.

To access the PivotTable wizard

  • From Tools menu, choose Wizards, and then click PivotTable.

Step 1 – Select Fields

In this step, you can choose a free table or a table within a database as the source for your pivot table. You can select only fields from a single table or view. For information, see Creating Views.

To select the fields for your pivot table

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select three or four fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

The wizard will not permit you to proceed to the next step until you have chosen at least three fields; one each for row values, column values, and data.

Step 2 - Define Layout

In this step, you can specify which field values will be calculated for the data. For example, if you have an Orders table that contains, among others, a field for city, a field for region, and a field for order amount, you could create a pivot table that would display in the data area, sums for all the cities, by region. At the bottom, the table will display totals for each column. At the far right the table will display totals for each row.

To define the pivot table layout

  1. From the Available fields list, drag a field to the Rows box. The pivot table will contain a row for each unique value in the field that you drag to the Rows box
  2. From the Available fields list, drag a field to the Columns box. The pivot table will contain a column for each unique value in the field that you drag to the Columns box
  3. From the Available fields list, drag a field to the Data box. Because this field will be summarized, generally it is best to drag a numeric field here.

You also can drag a field to the Page box. If you drag a field to the Page box, the pivot table will contain a drop-down list from which you can select the different pages. There will be one page for each unique value that exists in the field you drag to the Page box.

If you have a large table, you might want to first create a view that contains the desired fields, then create a pivot table from that view. For information, see Creating Views.

Step 3 - Finish

If you select Create a Microsoft Excel pivot table, the wizard will display your finished pivot table in Excel. The default calculation for the pivot table wizard is sums. If you create an Excel pivot table, then you can change the calculation easily to another supported by Excel, such as average or count.

If you select Create a new form containing an embedded pivot table, the wizard will create a new form containing the embedded pivot table and open it in the Form designer. Double-click the embedded object to modify it in the Form designer.

See Also

Creating Views | Form Designer | Wizards Overview


Query Wizard

With the Query wizard, you can select a group of records based on some rules you specify, For example, if you have tables that contain large amounts of information in one or more tables, you can use a carefully designed query to collect or display just a few records that satisfy some numeric or logical value.

To access the Query wizard

  1. From Tools menu, choose Wizards, and then click Query.
  2. In the Wizard Selection dialog box, select Query Wizard.

Step 1 – Select Fields

In this step, you can choose free tables or tables within a database as the source for your query. You can select fields from one or more tables or views.

To select the fields for your query

  1. Use the Databases and Tables controls to locate and select the tables or views you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

Repeat this process to add fields from other tables or views.

Step 2 – Relate Tables

This step displays only if you select fields from more than one table or view. You can specify which fields in each table or view contain the same information and can therefore govern the relationship between the tables or views, thereby determining the included records.

Select the desired fields from the two drop-down list boxes, and then choose Add. If you use multiple tables in your view, then you must relate the tables by indicating which fields contain matching data in each table.

Step 2a – Include Records

This step displays only if you select fields from more than one table or view. You can specify which records from the selected tables will be made available to the Query wizard.

If you are using more than one table, you can specify a join condition. For more information, see Creating a Multitable View. For example, if you specify only matching rows in Step 2a, you can further refine that choice in Step 3 by specifying a particular value for a field.

Only matching rows
Returns only records from both tables that match the comparison condition set between the two fields in the join condition. This is called an inner join.
All rows from this table
Returns all the rows from one of the listed tables or views. This makes it possible for you to create a left or right outer join.
All rows from both tables
Returns matching and non-matching records from both tables. This is called an outer join.

By default, only matching records are included.

Step 3 – Filter Records

This step appears immediately after Step 1 if you have chosen only one table or view as source for your query. You can specify a filter condition, so only certain of the records you have chosen to make available are used in the query.

To determine the filter condition

  1. Select a field from the Field drop-down list.
  2. Specify an operator, such as equals or contains, in the Operator drop-down box.
  3. Specify a value in the Value textbox.

    For example, if you wanted to filter on a specific city, such as Helena, you might choose city from the Field drop-down list, choose equals in the Operator drop-down list, and enter Helena in the Value textbox.

You can reduce the number of records by creating expressions that filter records from the selected tables or views. You can create two expressions and connect them with And, which returns only records meeting both specified criteria, or Or, which returns records meeting either criteria.

You can see the result by clicking the Preview button.

Step 4 - Sort Records

In this step, you can specify the sort order of your query records. For example, if your query will be used to assess orders by region, then you might sort by state or zip code.

Choose up to three fields or an index tag that already exists in the database to determine the order in which your view results will be sorted. Select Ascending to sort the view in ascending order or Descending to sort the view in descending order.

Step 4a – Limit Records

This step appears only if you have specified one or more sort fields in Step 4. You can further limit the number of records in the view, based on either a percent of the records returned or an actual number of records.

To see a percentage of the available records, choose the Percent of records radio button, and then specify the percentage in the Portion value edit box. See all records by selecting Number of records and then selecting All records. As shown in the following procedures, you can choose a portion of records from the beginning or the end of the available records.

To see the first 10 items

  1. Choose the Number of records radio button
  2. Enter 10 in the Portion value box.

To see the last 10 records.

Note This changes the sort order to last record = first read.
  1. In Step 4, change the sort order to Descending.
  2. In Step 4a, select the Number of records radio button.
  3. Enter 10 in the Portion value box.

Step 5 - Finish

In this step, you can choose how to save your query.

Save query
Makes it possible for you to save the query for later use.
Save query and run it
Makes it possible for you to save the query and run it immediately
Save query and modify it in Query Designer
Makes it possible for you to save the query and then use the Query designer to enhance or modify it.

See Also

Defining Results | Creating Persistent Relationships | Adding Tables to a Database | Cross-Tab Wizard | Graph Wizard | Local View Wizard | Remote View Wizard | Wizards Overview | Query and View Designers


Remote View Wizard

With this wizard, you can create views using remote data (ODBC). You must have an existing database to store your view in, as well as an existing data source or named connection stored in a database. If you do not have a database open, you are prompted to select an existing database or create one.

Before you run the Remote View wizard, you can set options for remote view and connection defaults on the Remote Data tab in the Options dialog box. You can create connections in the Connection designer.

To access the Remote View wizard

  1. From Tools menu, choose Wizards, and then click Query.
  2. In the Wizard Selection dialog box, choose Remote View Wizard.

Step 1 - Choose Data Source

In this step, you can specify, from a list of available ODBC data sources or a list of named connections, which one contains the target data. If the box is empty, you must define your data sources and connections in Microsoft Windows before you run the wizard. You can define your data sources using the Data Sources control panel of the Administrative Tools control panel. If your remote data source requires a password, you will be prompted for it when you click Next.

You also can include System tables for ODBC drivers that support them.

After you select an ODBC data source, you might see the Configure Connection dialog box in which you specify whether to use a database or free table, and the location of the target table.

Step 2 – Select Fields

In this step, you specify which fields you want to use in your remote view.

To select the fields for your view

  1. Use the Tables controls to locate and select the table you want to use.
  2. In the Available fields box, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields box.

    You can use fields from other tables by repeating this process. You can select as many fields as you need and move them into the Selected fields box.

Step 3 – Relate Tables

This step displays only if you select fields from more than one table. You can specify which fields in each table contain the same information and can govern the relationship between the tables, thereby determining the included records.

Select the desired fields from the two drop-down list boxes, and then choose Add. If you use multiple tables in your view, then you must relate the tables by indicating which fields contain matching data in each table.

If a relationship does not exist currently and the wizard could not suggest fields for a join, you must choose the fields. Typically, tables include fields for this purpose and often have the same name.

Step 4 - Include Records

This step displays only if you select fields from more than one table. You can specify which records from the selected tables will be made available to the Remote View wizard.

Only matching rows
Returns only records from both tables that match the comparison condition set between the two fields in the join condition. This is called an inner join.
All rows from this table
Returns all the rows from the selected table. This makes it possible for you to create a left or right outer join. For more information, see Creating a Multitable View.

Step 5 – Sort Records

This step makes it possible for you to specify one or more fields by which to sort the records in your remote view.

Select up to three fields or indexes to determine the order in which your view results will be sorted. If your table already has one or more indexes, you can select the index tag, which is listed below the fields, separated by a line, in the Available fields window. Select Ascending to sort the view in ascending order, or Descending to sort the view in descending order.

Step 6 - Filter Records

In this step, you can specify a filter condition, so only certain of the records you have chosen to make available are used in the remote view.

To determine the filter condition

  1. Select a field from the Field drop-down list.
  2. Specify an operator, such as equals or contains, in the Operator drop-down box.
  3. Specify a value in the Value textbox.

    For example, if you wanted to filter on a specific city, such as Helena, you might choose city from the Field drop-down list, choose equals in the Operator drop-down list, and enter Helena in the Value textbox.

You can reduce the number of records by creating expressions that filter records from the selected tables or views. You can create two expressions and connect them with And, which returns only records meeting both specified criteria, or Or, which returns records meeting either criteria.

You can see the result by clicking the Preview button.

Step 7 -Finish

In this step, you can choose how to handle the newly defined remote view.

Save remote view
Saves the newly defined remote view and exits the wizard.
Save remote view and browse
Saves the new remote view and then opens it in a Browse window, so you can review the displayed data.
Save remote view and modify it in the View Designer
Saves the new remote view and then modify it when it opens in the View designer.

See Also

Execution of ODBC Extensions to SQL | ODBC Registry | Cross-Tab Wizard | Graph Wizard | Local View Wizard | Query Wizard | Wizards Overview | Remote Data Tab, Options Dialog Box | Connection Designer | Query and View Designers


Report Wizard

With this wizard, you can create reports using one free table or one table or view in a database. You can use this wizard to quickly create and save for future reuse, reports that you can run at any time. Whenever you run the saved report it will display or print the then-current information from a table or view.

To access the Report wizard

  1. From Tools menu, choose Wizards, and then click Report.
  2. In the Wizard Selection dialog box, choose Report Wizard.

Step 1 – Select Fields

In this step, you can choose a free table or a table within a database as the source for your report. You can select fields from only a single table or view.

To select the fields for your report

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields window, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields window.

Step 2 – Group Records

In this step, you can use data grouping to categorize and sort your records, so they are easier to read. When you select a field in one of the Group by drop-down boxes, you can choose Grouping Options and Summary Options to refine your grouping selection. You can choose up to three fields for grouping.

Choosing Grouping Options opens the Grouping Intervals dialog box that makes it possible for you to select levels of filtering that are relevant to the type of data contained in the fields you selected for grouping.

Choosing Summary Options opens the Summary Options dialog box that makes it possible for you to specify from the following list the type of calculation to perform on specific numeric fields:

Summary Option | Return
Sum | Total of values in the specified numeric field.
Avg | Average of the values in the specified numeric field.
Count | A count of the number of records containing a non-nil value in the specified field.
Min | The minimum value in the specified numeric field.
Max | The maximum value in the specified numeric field.

You also can choose Detail and Summary, which provides group subtotals and totals, Summary only, which provides only totals, or No Totals for the report. Use the Calculate percent of total for sums to track the percentage of the total represented by each subtotal.

Fields that you select as groupings here are not available in Step 3 - Sort Records.

Step 3 - Choose Report Style

In this step, you can choose the basic format of your report from the styles built into the wizard. When you click any of the styles, the wizard updates the graphic in the magnifying glass as an example of the style.

Step 4 - Define Report Layout

In this step, you specify the number of rows or columns of the report and whether the report is to be portrait or landscape oriented.

When you specify a number of columns or select a layout option, the wizard updates the graphic in the magnifying glass as an example of the selection.

Note If you specified a grouping option in Step 2, the Columns and Field Layout selections in this step are not available.

Step 5 - Sort Records

This step makes it possible for you to specify one or more fields by which to sort the records in your report.

Choose up to three fields or an index tag that already exists in the database to determine the order in which your view results will be sorted. Select Ascending to sort the view in ascending order or Descending to sort the view in descending order.

Step 6 -Finish

In this step, you can choose how and when to use the report.

Save report for later use
Makes it possible for you to save the report as a file, which you can open later.
Save report and modify in the Report Designer
Saves the report as a file and then opens it in the Report designer, so you can make modifications to it.
Save and print report
Saves the report as a file and then immediately prints it.

If the number of fields you selected cannot fit on a single line within the width of your report, the fields will wrap to the following line. If you do not want the fields to wrap, clear the Wrap fields that do not fit check box. If you have used a table or view from a database, you can choose Use display settings stored in the database, otherwise this option is not available. Click the Preview button to view the report without exiting the wizard.

After you save the report, you can open and modify it like any other report in the Report designer.

See Also

One-To-Many Report Wizard | Wizards Overview | Working with Tables | CREATE REPORT Command | Report Designer


SQL Server Upsizing Wizard

The SQL Server Upsizing wizard creates a SQL Server database that duplicates, as much as possible, the functionality of Visual FoxPro database.

You can create a local working model of your application using Visual FoxPro tables, views, and databases to represent data that eventually will be accessed on a remote server. When you are ready to move this prototype to its working location, you will upsize it. You can use the SQL Server Upsizing wizard to:

  • Move local data to a remote server.
  • Transform local base tables and local views into remote base tables and remote views.
  • Migrate a local application to a client/server application.
Note Upsizing can take a long time, depending on the size of your data, the amount of network traffic, and the number of concurrent demands being handled by your server. Large tables may require several hours to upsize.

Before you run the SQL Server Upsizing wizard, you must prepare both the client and server sides. You must have certain CREATE and SELECT permissions on the server and named connections on the client. For more information, see SQL Server Upsizing Wizard Preparation.

To access the SQL Server Upsizing wizard

  • From Tools menu, choose Wizards, and then click Upsizing.

    -or-

    From Tools menu, choose Wizards, click All Wizards... to open the Wizards Selection dialog box, and choose Microsoft SQL Server Upsizing Wizard.

Step 1 - Select Local Database

In the first step, you choose which local database you want to upsize.

Database to upsize
Lists the currently open databases. Select the database you want to upsize. If you do not have a database open, choose the Open button to select and open a database.

Step 2 - Select Data Source

In this step, you specify options to select the ODBC SQL Server data source or named connection you want to use.

ODBC data sources
Choose this option button to display SQL Server ODBC data sources. When selected, the adjoining list is titled Available data sources.
Connections
Choose this option button to display connections stored in the open database that connect to SQL Server data sources. When selected, the adjoining list is titled Existing connections.
Available data sources
Lists the ODBC data sources that connect to the SQL Server. This list is displayed when the ODBC data sources option button is selected.
Existing connections
This list is displayed when the Connections option button is selected. It lists the connections stored in the open database that connect to SQL Server data sources.
All
Use this check box to display all data sources that are not identified explicitly with the "SQL Server" keywords in the title. The words "SQL Server" must appear in the data source name for Visual FoxPro to identify the data source as a SQL Server data source. If your data source uses a third-party driver to connect to SQL Server, it might not be identified as a SQL Server data source.

The list displayed depends upon whether you have the ODBC data sources or the Connections option button selected.

When you click Next, the wizard connects you to SQL Server and displays the SQL Server Login dialog box. If you used a named connection with a saved password, the wizard logs you on to the SQL Server you've selected without prompting you for ODBC login information.

Using a Named Connection

If you use a named connection to access your data source, the SQL Server Upsizing wizard associates the named connection with any remote views it creates during upsizing. If the connection definition includes a password, the Save Password With View option (later in Step 8) is selected automatically for you and disabled; this prevents the password from being removed from the connection definition.

Using a Data Source

If you use a data source name rather than a connection name to log on to the data source, and you choose to have the wizard create remote views, the SQL Server Upsizing wizard creates a named connection called "Upsize" (or "Upsize2," "Upsize3," and so on, if a connection definition exists with the suggested name).

Step 3 – Choose Tables

In this step, you can select the Visual FoxPro tables you want to export to SQL Server.

Available tables
Lists all the tables stored in the database you have chosen to upsize.
Selected tables
Lists the tables you've chosen to upsize into the database on the server.

You must select at least one table, and you can choose the >> button to export all tables.

When you choose Next, the SQL Server Upsizing wizard reads the list of tables you've selected to upsize and tries to open those tables for exclusive use in the database you choose to upsize. Any tables that can't be opened exclusively won't be available to upsize. The tables are opened exclusively to prevent other users from changing the data in the tables during the upsizing process, which helps to ensure the accuracy of exported data. If any tables are already open and shared, the wizard closes them and then reopens them exclusively; this might cause you to lose any temporary relations established with the SET RELATION or SET SKIP commands.

Choosing Tables to Export

It's very important to choose the tables you export carefully, as this choice has a significant impact on the performance of your application. Exporting all tables might result in excessive (and slow) server queries. A well-designed client/server database usually consists of a mix of local and remote tables.

In general, keep tables, which change rarely or infrequently, in your local database, such as a table of state names and abbreviations. Export tables that change frequently and are accessed by many users, such as a table of orders.

The SQL Server Upsizing wizard exports the table's field names, data types, and data. For more information, see Designing Client/Server Applications and Optimizing Client/Server Performance .

Step 4 - Map Field Data Types

In this step, Visual FoxPro displays the default data type mappings used to convert local data to remote data, as tables are upsized to the server. You can choose to change these default mappings.

You cannot change the default mapping for a key field to a data type that prevents the field from being indexed. You can change the default mapping of a field that is part of an index key if you choose a data type that is indexable; however, you might want to change the data types for the other fields in the key to match. Visual FoxPro warns you if you change the default data type mapping for a field that is not a key field but is used in a Visual FoxPro index. If you make a mistake, click Default to reset the data types.

Table
Select the table whose fields you want to map from the list of all the tables you've chosen to upsize.
Timestamp column
Select this check box to add a timestamp column to the server version of the table. If you want to apply this to all tables, you can save time by selecting the All Tables check box.
Identity column
Select this check box to add an identity column to the server version of the table. If you want to apply this to all tables, you can save time by checking the All Tables check box.
Default
Choose this button to reset all table field settings for all fields in the selected table back to their defaults. This button in effect undoes any changes you have entered for a specific table earlier in Step 4.
Field Name
Lists the fields contained in the table you selected in the Table list box.
FoxPro Type
Lists the Visual FoxPro data type for the field.
Server Type
Lists the server data type to which Visual FoxPro data in this field will be mapped when the table is copied to the server. Click this field to display a drop-down list from which you can select a different server data type.
Width
Specifies the width of the field.
Precision
Specifies the decimal precision of the field, when applicable.

Creating Timestamp Columns

A SQL Server timestamp column contains a unique value, generated by SQL Server that is updated whenever the server record is updated. Using a timestamp field on an updateable remote table can increase performance and reliability.

If you update fields using the Visual FoxPro SQL WhereType values DB_KEYANDMODIFIED or DB_KEYANDUPDATABLE, Visual FoxPro must check all modified or all updateable fields to determine whether they were changed by another user. Because text or image fields can be many megabytes in size, comparing these fields for changes can be network-intensive and time-consuming, thereby reducing performance. Reliability also can be affected, because converting the value of a floating-point field between client and server might cause the value to appear to have changed when it has not.

When you add a timestamp field to a remote table and update using the SQL WhereType value DB_KEYANDTIMESTAMP, Visual FoxPro uses only the value in the timestamp field to determine whether a record has been changed before updating it. Because Visual FoxPro can compare the value in the timestamp field more quickly than it can evaluate the contexts of large text or image fields, you can increase performance on remote data. However, if you use the SQL WhereType value DB_KEYANDTIMESTAMP, any change in the remote record is recognized as an update conflict, whether or not the changed remote field is in the list of fields you've set as modifiable in your remote view.

If you prefer to update fields using the Visual FoxPro SQL WhereType values DB_KEYANDMODIFIED, you might improve performance by setting the remote view's Compare Memo property to false (.F.). When CompareMemo is set to false, Memo fields are removed from the list of remote view fields compared against the data in the remote server row.

Step 5 - Select Target Database

In this step, you can select the database on the data source server to which you want to copy tables.

After you have connected to a server and have chosen a data source, the tables you want to upsize, and the field data type mapping, you can use an existing database or create a new database as the destination for your upsized local database. If you chose a named connection earlier in Step 2, you can use the database named in the connection or create a new database as the destination.

Available databases on 'database name'
This list is displayed when you select the Existing option button to add Visual FoxPro tables to an existing SQL Server database. Select the database into which you want to copy Visual FoxPro tables when you upsize.
New database name
This text box is displayed when the New option button is selected. Enter a name for the new database you want to create on the remote server to which you are upsizing. The name can be up to 30 characters in length and can include letters, digits, and the symbols #, $, and _. Spaces are not allowed.

If you upsize to an existing database, the wizard jumps to Step 8.

If you use a version of Microsoft SQL Server later than 6.x, the wizard jumps to Step 8 whether you use an existing database or create a new one.

Step 6 - Set Database Properties

If you chose to create a new SQL Server database earlier in Step 5, then the wizard displays this step to help you to select the database device and size for your database. You can choose to create your new SQL Server database on an existing device, or create a new device.

Selecting an Existing Device

Database device
Displays all the devices on the SQL Server you logged on to, including default devices. Select a device with sufficient free space for your database.
Size
Displays the size in megabytes of the database device selected in the adjoining Database Device list box.
Free Space
Displays the amount of free space remaining on the database device selected in the Database Device list box.
Database size
Enter the amount of space, in megabytes, you want to allocate for the new database. The size of a new database must be at least two megabytes, because that is the minimum allowed by SQL Server.

Default Devices

If one or more devices have been set as default devices on your SQL Server, the SQL Server Upsizing wizard includes a Default entry in the list of available devices. The Default entry can represent more than one device. Choosing the default device does not ensure you'll have enough room to upsize your database. The SQL Server Upsizing wizard checks the devices specified as default to make sure there's enough room for the database.

Tip To place your database on multiple devices, make those devices (and no others) default devices. When you run the SQL Server Upsizing wizard, select Default for your database.

For more information on setting the default status of devices, see your SQL Server documentation for a description of the sp_diskdefault system procedure.

Creating a New Device

If existing devices are too full, you might want to create a new device. You must be a system administrator to create new SQL Server devices.

To create a new SQL Server device

  1. Select Create new device from the list of devices.

    If you are a system administrator, a dialog box appears. Otherwise, an error message appears.

  2. Type a name for the new device.

    The device name must be 30 characters or less and consist of letters, digits, and the symbols #, $, or _. Spaces are not allowed.

  3. Click OK.

    The new device name is added to the devices list box.

  4. Type a device size.

    The device size must be at least two megabytes. The combined size of new devices cannot exceed available disk space.

If you are a system administrator, the SQL Server Upsizing wizard displays the amount of space on the server drive storing the Master SQL Server database.

Note The size of a device cannot be changed after it has been set. Make sure you create sufficiently large devices.

The selected new device is created after you choose the Finish button. The SQL Server Upsizing wizard creates the new device in the same directory as the Master database device. If you add a new device to the list but don't select the new device as the database device, then the new device is not created.

The SQL Server Upsizing wizard can generate a report that includes the logical name, physical name, and other information about new devices you create.

Device Number Limitations

Every SQL Server device is given a number when it is created. However, the available pool of device numbers is limited. The default value is 10, although the number might be different on your server. The SQL Server Upsizing wizard searches for an available device number. If all device numbers are taken, you won't be able to create a new device.

Note To increase the number of SQL Server device numbers available, see your SQL Server documentation for a description of the sp_configure system procedure.

Step 7 - Specify Log Properties

In this step, you can specify the size and device to store a transaction log. A transaction log is created for your database by SQL Server, and can be used to reconstruct the database in the event of a serious system problem.

Log Device
Displays a list of log devices on the remote server. Select the device you want to use for the transaction log.

Ideally, a database and its corresponding log should be placed on devices that are on separate physical disks. These devices must be created before you start the SQL Server Upsizing wizard, as the wizard creates all new devices on the same physical disk — the disk where the master database device resides.

If you have only one physical disk, you should place the database and its log on separate devices, so that you can use the SQL server DUMP TRANSACTION command.

Size
Displays the size in megabytes of the database device selected in the adjoining Log Device list box.
Free Space
Displays the amount of free space remaining on the log device selected in the Log Device list box.
Log Size
Enter the amount of space, in megabytes, you want to allocate for the transaction log. For more information on how to determine the log size you need, see Specifying Log Size later in this topic.
Database Size
Displays the amount of space allocated for the new database in Step 6.

Specifying Log Size

As a general guideline, you allocate 10 to 20 percent of the size of the new SQL Server database; this guideline is dependent upon a number of considerations that are discussed in your SQL Server documentation.

You can enter a value of 0 for the log size, which causes the wizard to place the log (a table called syslogs) on the same device as the database. When the log size is set to 0, the log consumes the minimum amount of space on the server but also fills up very quickly.

When you upsize to a new database, the SQL Server Upsizing wizard dumps the transaction log every time it fills up. The dump makes a backup copy of a database and its transaction log in a form that can be read in with LOAD DATABASE. For more information on the SQL Server DUMP TRANSACTION command and on estimating the amount of space to allocate for a transaction log, see your SQL Server documentation.

Note You can increase the size of a log or move it to a new device. For more information, see your SQL Server documentation for a description of the ALTER DATABASE command and the sp_logdevice system procedure.

Step 8 - Set Upsizing Options

In this step, you can control how the SQL Server Upsizing wizard exports your tables. You also can specify the changes you want the SQL Server Upsizing wizard to make to the local database. You can create upsizing reports, redirect views to use remote data, create new remote views on tables that are upsized, and save passwords with views.

Specifying Table Attributes to Upsize

By default, the SQL Server Upsizing wizard exports a table's structure and its data. Along with field names and data types, you can also export:

  • Indexes
  • Defaults
  • Relationships (referential integrity constraints)
  • Validation rules

The SQL Server Upsizing wizard can export additional table properties and create timestamp columns on certain SQL Server tables. The SQL Server Upsizing wizard also can modify your Visual FoxPro database so your queries, forms, and reports use the data in your new SQL Server tables, rather than the data in the local Visual FoxPro database.

Visual FoxPro indexes and defaults become SQL Server indexes and defaults. If you choose to export validation rules, the SQL Server Upsizing wizard attempts to export field- and row-level validation rules to SQL Server, where they become stored procedures called from SQL Server triggers. Exported table relationships also become part of the triggers.

Tip If you export table relationships, be sure to export indexes as well or you might experience mediocre performance.

Table Attributes to Upsize

Indexes
Select to upsize Visual FoxPro .cdx indexes.
Defaults
Select to upsize default values for table fields.
Relationships
Select to upsize relationships stored in the database you are upsizing.
Validation rules
Select to upsize field and table validation rules.
Structure only, no data
Select to upsize the empty table structure, without copying table data to the SQL Server data source.
Use declarative referential integrity
Enabled when upsizing to a SQL Server version 6.x database. Select to create SQL constraints to enforce referential integrity.
Null Mapping
Select the fields that can accept .NULL.

This option helps to ensure that insert and update commands against remote data succeed. This option allows you to override the existing null setting fields in the Visual FoxPro tables being upsized. If you choose the General and Memo fields option, then all general and memo fields in your selected Visual FoxPro tables will be upsized with these fields set to allow nulls.

There are differences in how Visual FoxPro SQL commands such as INSERT and UPDATE affect local and remote data depending on the null settings for fields. For example, if you have an INSERT command that does not include all the fields in a table, Visual FoxPro inserts blanks into the unspecified fields for local data. If the INSERT command is issued for a remote view (SQL Server data), then nulls are inserted into the fields not specified in the command. The command will fail if any one of these fields does not support nulls. It's fairly easy to write an INSERT command, which includes all the fields and values to be inserted. Note, however, that inserting content into a general field is a little more cumbersome.

Changes to Make Locally

Create upsizing report
Creates a series of reports documenting the results of the upsizing process.
Redirect views to remote data
Changes the definition of local views in the database you are upsizing to remote views that use the upsized server tables as base tables. Your queries, forms, and reports then use views on the data in the new SQL Server data source rather than the original Visual FoxPro data.
Create remote views on tables
When you upsize a local table, you need a remote view to access the upsized table on the remote server. The SQL Server Upsizing wizard can create new, remote views as you upsize. As the wizard creates new remote views, it renames all local versions of tables by adding the suffix "_local" to the table name.
Note Creating remote views on tables as you upsize is not recommended, because these unoptimized views select all the data in the table rather than selecting only the information your application needs. The preferred method is to create parameterized views. You can either create a local parameterized view, which you then upsize by choosing Redirect views to remote data, or create a new parameterized remote view on the table after you've completed the upsizing process. For more information, see Creating Views.
Save password with views
By default, you must enter your password and login ID when opening a remote view in a new session with Visual FoxPro. Select this option to store your password locally with the remote view definition in your database.
Note This check box is checked automatically for you and disabled if you used a named connection earlier in Step 2 to access your data source and that named connection includes a password. This prevents the password from being removed from the connection definition.

Creating Upsizing Reports

When you select Create Upsizing Report, Visual FoxPro generates upsizing reports that document the tables, views, fields, indexes, and referential integrity constraints the SQL Server Upsizing wizard creates on SQL Server. The wizard places the reports in a new project, using the following report names:

  • RptErrors
  • RptField
  • RptIndex
  • RptRels
  • RptTable
  • RptViews

The upsizing reports include information about any devices and databases that are created, information about any errors encountered during the upsizing process, and a complete explanation of the way in which each Visual FoxPro object is mapped to a SQL Server object. You can view or print these reports after upsizing is complete.

Upsizing All Tables Used By a Local View

If you upsize all the tables used by a local view, the local view is renamed by adding the suffix "_local" to the existing local view name. The SQL Server Upsizing wizard creates a new view based on the SQL statement of the local view, substituting the remote table names for the local table names. The KeyField and other update properties of the view are preserved.

Upsizing Some of the Tables Used By a Local View

If you upsize only some of the tables used by a local view, the SQL Server Upsizing wizard does not rename the local views. Instead, it renames the Visual FoxPro tables you export with the suffix "_local." For example, if you export a table named "Employees," the table is renamed "Employees_local" in your database. The wizard then creates a remote view for each of the tables you exported. Each view selects all fields and all records from the remote table.

Note Visual FoxPro handles local and remote data in different ways. The data access design of an application using local data may become very inefficient when applied as is to remote data.

Advanced Dialog Box

Make Primary Key a Clustered Index
By default, tables that have a primary key automatically get a clustered index created on SQL Server by the Upsizing wizard. This is because it is a SQL Server default if the [CLUSTERED | NONCLUSTERED] clause is not specified in the ALTER TABLE statement, which the wizard uses. Being that primary keys are often already in sequential order, a clustered index may not be needed. This option allows you to control whether a clustered index is created.
Drop Local Tables
If you choose to create remote views for your tables, the wizard will create a new set of remote views using the names of their corresponding tables (and rename the original tables). It is possible that you no longer need to use the local tables. This option allows you to drop the local tables from the database.
Default Remote View Name
If you choose to create remote views, you may want to control the naming of these tables. By default, the name used is that of the original table (and the original table is renamed). The following options allow you to control the naming of remote views.
  • Prefix Specifies a character string to prepend to each of the newly created remote view names.
  • Suffix Specifies a character string to add to the end each of the newly created remote view names.
  • None (Same as local table name.) Defaults to using table name, and renames original table.

Step 9 -Finish

In this step, you can choose to:

  • Upsize without generating SQL code.
  • Only generate SQL code for upsizing.
  • Upsize and generate SQL code.
Upsize
Select to begin creating databases and tables, as applicable, on the remote server.
Save generated SQL
Select to have the upsizing wizard generate the SQL script necessary to upsize your database and then stop without beginning to create databases and tables on your remote server.

You can use this option to provide a SQL upsizing script that you then customize to meet the needs of your application. Once you've modified and saved the SQL script, you then run the script to complete the upsizing process. This two-step process provides tremendous flexibility, allowing you to use Visual FoxPro to generate the large majority of the code you'll need, yet providing a method for fine-tuning the upsized installation.

Upsize and save generate SQL
Select to upsize your database and save the SQL script generated by the wizard.

The first and third upsizing options are available only if you have CREATE TABLE permission on the server. If you choose either of the options that save generated SQL code, all the SQL code generated by the SQL Server Upsizing wizard is stored on your hard disk.

Note Upsizing can take a long time, depending on the size of your data, the amount of network traffic, and the number of concurrent demands being handled by your server. Large tables can require several hours to export.

To upsize your database

  1. Select the upsizing option you want.
  2. Choose the Finish button.

    The SQL Server Upsizing wizard creates devices and databases if necessary, and begins exporting Visual FoxPro objects to SQL Server.

Troubleshooting

If any errors occur while the SQL Server Upsizing wizard is exporting data, you are asked whether you want to save error information. If you choose to save error information, an error report is generated.

Most upsizing errors occur because there isn't enough space on your server's database or log device, or because your remote database is not large enough to accept the data you're exporting to the server. Make sure that you select devices with ample free space and that you set your database size sufficiently high.

Database or Log Full

The SQL Server Upsizing wizard runs out of space and stops if the SQL database you selected or created is too small. To resolve this problem, you can increase the space for the database or the log. This solution can involve dropping (removing) the database or the log from the upsizing process.

To increase the space for a new database or log

  1. Drop the database.
  2. If the SQL Server Upsizing wizard changed the names of any local tables, restore tables to their original names by:
    • Copying your backup version of your local database's .dbc file onto your system, overwriting the altered .dbc file.

      -or-

    • Renaming local tables to their original names.
  3. When you run the wizard again, specify a larger database or log size.

To increase the space for an existing database

  1. Increase the size of the database.
  2. If the SQL Server Upsizing wizard changed the names of any local tables, rename them to their original names.
    • Copying your backup version of your local database's .dbc file onto your system, overwriting the altered .dbc file.

      -or-

    • Renaming local tables to their original names.
  3. Run the wizard again.

To increase the space for an existing log

  1. Increase the size of the log.

    -or-

    Dump the transaction log.

  2. If the SQL Server Upsizing wizard changed the names of any local tables, rename them with their original names.
    • Copying your backup version of your local database's .dbc file onto your system, overwriting the altered .dbc file.

      -or-

    • Renaming local tables to their original names.
  3. Run the wizard again.

You should overwrite tables from the previous partial upsizing to make sure all table relationships are created.

For information on increasing the database or log size, see the ALTER DATABASE command in your SQL Server documentation. For information on dumping the transaction log, see the DUMP TRANSACTION command in your SQL Server documentation.

Device Full

The device on which a database or log is located can fill up. You can extend the database or log to another device using the ALTER DATABASE command or the SQL Server Administrator, or you can create a larger device.

To create a larger device

  1. Drop the device.
  2. Restart SQL Server.
  3. Create a larger device.
    Caution Dropping a device deletes all databases and logs on the device, not just the database to which you are upsizing.

You can use the sp_dropdevice system procedure to drop a device. For more information, see your SQL Server documentation.

See Also

Wizards Overview | Upsizing Visual FoxPro Databases | How the SQL Server Upsizing Wizard Works


Table Wizard

The Table wizard creates tables based on typical table structures. It provides table templates, optional style settings, support for both Character and Memo binary data types, and access to databases and lets you select a table that fits your needs from the list of sample tables. You can customize the table's structure and fields as you step through the wizard, add your table to a database, and use database settings to determine the formats of fields you add to your table. You also can establish relationships between tables in the database.

If you have one or more databases open, the Table wizard automatically adds the new table to the current database. If you add your table to a database, the Table wizard provides automatic formatting of selected fields. If no databases are open, the wizard creates a free table.

To access the Table Wizard

  • From the Tools menu, choose Wizards, and click Table.

    -or-

    From the File menu, choose New, choose the Table option, and click the Wizard button.

To create a table with the Table wizard

  1. In the Project Manager, select the Data tab and select Free Tables.
  2. Choose New.
  3. Choose the Table Wizard button.
  4. Follow the instructions on the wizard screens.

If you base your table on a database, you can use styles, field mappings, or a primary key, and establish or use relationships in the database tables.

Step 1 – Select Fields

In this step, you can choose one of the sample tables and select from the available fields to create your table.

To select fields for your table

  1. Use the Sample Tables list box to locate and select the table you want to use.
  2. In the Available fields list box, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields box.

You can categorize your selection as Business or Personal, and you can select fields from more than one table. If you want to add one of your own tables to the Sample tables box, choose Add.

Step 1a - Select a Database

In this step you can choose to add your table to a database. Adding the table to a database gives you enhanced functionality, but your table can be completely functional without being part of a database. If you create your table in a database, the Table wizard will provide automatic and custom formatting options in the next step.

You can also specify a friendly or descriptive name for the new table.

Note If you create a stand-alone table, you won't be able to change field captions.

Step 2 - Modify Field Settings

In this step you can change any default field settings. For example, you can change the maximum width of a character field, or the number of decimal places allowed in a numeric field.

You can specify whether fields can contain null values and you can change the field caption or type.

If you are creating your table in a database, you can also select one of the predefined data input masks for each field type or create a custom input mask. The Format windows display the mask and format code you choose.

Step 3 - Index the Table

In this step you can specify a field that will be the primary index key for your table. You can also designate other fields as secondary index keys.

Step 4 - Set Up Relationships

In this step, if you are creating your table within a database, you can establish relationships between fields in your new table and existing tables in the database.

Highlight the field for which you want to establish a relationship, and then click the Relationships button.

To define a relationship

  1. Click the radio button that identifies the type of relationship you want to establish.
  2. Select the field that relates the tables within the database. If you select <newfield>, type in the field name.
  3. Click OK.

    The Relationships dialog box will close and return you to Step 3, where the list displays the new relationship.

Step 5 - Finish

In this step you can specify how your table is saved and used.

Save table for later use
Saves the table to disk for later use when you click Finish.
Save table and browse it
Saves the table to disk and opens it so you can immediately add records by choosing Append New Record from the Table menu after you click Finish.
Save table and modify it in the Table Designer
Saves the table to disk and then opens it in the Table Designer so you can immediately modify it after you click Finish.

See Also

Index Creation for Tables | Wizards Overview | Creating a Free Table | Working with Tables


Web Publishing Wizard

This wizard uses data from a table or view to create an HTML document. You can use or share the file that the Web Publishing wizard creates in your browser or edit it in a text editor.

To access the Web Publishing wizard

  • From the Tools menu, choose Wizards, and click Web Publishing.

In the Web Publishing wizard, you can specify the layout for data as well as the layout and style of the head and body of the HTML page. You can use the default layouts and visual styles that come with the wizard or customize those layouts and styles. In addition, you can load an existing cascading style sheet (.css) file.

Step 1 – Select Fields

In this step, you can choose a free table or a table within a database as the source for your Web page. You can select fields from only a single table or view.

To select the fields for your Web page

  1. Use the Databases and Tables controls to locate and select the table you want to use.
  2. In the Available fields list box, select one or more fields you want to use from the selected table, and use the arrow buttons to move them to the Selected fields box.

Step 2 – Sort Records

This step makes it possible for you to specify one or more fields by which to sort the records in your Web page.

Choose up to three fields or an index tag that already exists in the database to determine the order in which your view results will be sorted. Select Ascending or Descending to determine the order of the sort.

Use Remove to eliminate a field from the sort list.

Step 3 – Choose Style

This step makes it possible for you to select a data layout and a visual style for your Web page.

You can modify the selected layout by using the Options button. You can override the default visual style settings and add your own HTML tags by using the Advanced button.

Options
Opens the Layout Options dialog box so that you can modify specific properties of the data layout you chose.
Advanced
Opens the Advanced dialog box so you can modify the appearance of your Web page by adding a cascading style sheet (.css), colors, text, and HTML tags.
Preview
Displays a sample of your Web page in the selected data layout and visual style. The preview is limited to 10 records per page.

Step 4 - Finish

In this step, you specify how to save and use your Web page.

Save Web page for later use
Saves the Web page to disk for later use.
Save Web page and modify it in a text editor
Saves the Web page to disk and opens it in your default text editor so you can modify it.
Save Web page and open it in a browser
Saves the Web page to disk and opens in your default Web browser.
Create script for generating Web page
Creates a program file that will dynamically create your Web page.

Save style

Use to specify and save the name of the style you apply to a Web page.

See Also

Wizards Overview | HTML Help


Advanced Dialog Box

This dialog box is part of the Web Publishing wizard and makes it possible for you to specify additional characteristics for your Web page. It is displayed from the Step 3, Advanced button. You can specify formatting and objects from cascading style sheets (.css) and add additional HTML items that can include headings, text, or other Web page items and characteristics.

To access the Advanced dialog box

  1. From Tools menu, choose Wizards, and then click Web Publishing.
  2. Navigate through the wizard until you reach Step 3.
  3. Click Advanced.
Cascading style sheet
This control makes it possible to specify or locate a cascading style sheet (.css) file to use for your Web page.
Body
Color This drop-down box makes it possible for you to specify a color from the list to use for the body background. This option overrides any color specified in the selected data layout or visual style.

Image This textbox makes it possible for you to specify or locate an image file to display on your Web page.

Copy graphics to HTML output location
This check box makes it possible for you to specify that any graphic files used in your data layout or visual style are copied to the same location as your Web page file.
Save Settings
This button makes it possible for you to keep your visual style changes in a file to use later.
Load Settings
This button makes it possible for you to access a saved layout or to remove a saved layout you no longer want.
Additional HTML Items
This section makes it possible for you to add HTML tags for formatting, text, and references to your Web page.
Add
This button opens the HTML Item dialog box, so you can specify additional HTML items and formatting for your Web page. For more information, see HTML Item Dialog Box.
Edit
This button opens the HTML Item dialog box, so you can edit the selected HTML item for your Web page. For more information, see HTML Item Dialog Box.
Remove
This button makes it possible for you to delete the selected HTML item from your Web page.

See Also

Web Publishing Wizard | HTML Item Dialog Box | Layout Options Dialog Box | Wizards Overview


HTML Item Dialog Box

The HTML Item dialog box is part of the Web Publishing wizard. This dialog box makes it possible for you to specify additional items and their attributes for the Web page you create.

To access the HTML Item dialog box

  1. From Tools menu, choose Wizards, and then click Web Publishing.
  2. Navigate through the wizard until you reach Step 3.
  3. Click Advanced.
  4. In the Advanced dialog box, click Add.
Type
This drop-down list provides a list of HTML tag items that you can add to your page.
Location
This drop-down list makes it possible for you to specify where on the Web page you want the selected HTML item to appear — in the header, before data, or after data.
Text Formatting
  • Text Specify the exact text you want to display in the location you selected in the Location drop-down list.
  • Heading Specify, from the drop-down list, the HTML heading tag you want to apply to the specified text.
  • Bold (Strong) Specify whether you want the specified text to be formatted bold.
  • Italic Specify whether you want the specified text to be formatted italic.
  • Font name Specify the font you want to use for the specified text. If you chose a Heading, then this option is disabled, and your Web page will use the heading value set in the viewing browser.
  • Size Specify the font size you want to use for the specified text. If you chose a Heading, then this option is disabled, and your Web page will use the heading value set in the viewing browser.
  • Alignment Specify the left-to-right page alignment of the specified HTML item.
  • Forecolor Specify the foreground (default text) color of the specified HTML item.
  • Backcolor Specify the color of the specified HTML item.
Attributes
  • File/HREF Specify or locate the file (or URL) you want to use if you chose Hyperlink or Image item in the Type drop-down list.
  • Style Class Specify a path reference to a class contained in a cascading style sheet (.css).

When you click OK, you are returned to the Advanced dialog box where you can specify another HTML item, save the current data layout and style information, or proceed to Step 4 of the Web Publishing wizard.

See Also

Web Publishing Wizard | Advanced Dialog Box | Layout Options Dialog Box | Wizards Overview


Layout Options Dialog Box

The Layout Options dialog box is part of the Web Publishing wizard. This dialog box makes it possible for you to modify the default values of the selected data layout. You can save any changes you make as a new data layout and style specification by using the Save Settings button in the Advanced dialog box.

To access the Layout Options dialog box

  1. From Tools menu, choose Wizards, and then click Web Publishing.
  2. Navigate through the wizard until you reach Step 3.
  3. Click Options.
Border
This tab makes it possible for you to select the background and border colors and border width. You also can specify a .gif or .jpg file as a background image.
  • Border color Specify the border color.
  • Background color Specify the background color for graphics and text.
  • Background image Specify the name of a background .gif or .jpg image and, if necessary, its location.
  • Border width Specify the thickness of the border in points.
Font
This tab makes it possible for you to specify one or more HTML-defined fonts in case a user does not have a particular font. This can help provide good cross-platform browser behavior.

You also can specify the font name and change the default font color.

  • Font names Specify the font name and, if necessary, its location.
  • Font size Specify the font size.
  • Forecolor Specify the color of the text.
Other
This tab makes it possible for you to specify the name of an HTML-defined class to use in your Web page.

The Other tab also can provide access to properties settings that are specific to a particular layout choice.

  • Style class Specify the name and location of a .css file that contains a style class to use for your Web page.
  • First row color Specify from the drop-down list the color of the first rows of your Web page.
  • Next row color Specify from the drop-down list the color of rows following the number of offset rows on your Web page.
  • Row offset Specify the number of rows in each block of the displayed table. Each of the row colors you choose will be used in this number of alternating rows.
Reset Defaults
Use this button to restore your selections to the original wizard default values.

When you click OK, the dialog box closes and returns you to Step 3 of the Web Publishing wizard.

See Also

Web Publishing Wizard | Advanced Dialog Box | HTML Item Dialog Box | Wizards Overview


Windows

Explains functions of and options that appear in various Visual FoxPro windows.

In This Section

Accessibility Browser Window
Makes it possible for you to explore various user interface elements of an application through their Iaccessible interface.
Automated Test Harness Window
Makes it possible to record and play back mouse and keyboard events in your applications.
Browse Window
Displays the records in the active table.
Call Stack Window
Makes it possible for you to display procedures, programs, and methods that are executing. While a program is running, it is listed in the Call Stack window.
Class Browser Window
Displays the classes in a class library or a form and the type library information in a .tlb, .olb, or .exe file.
Code References Window
Makes it possible to for you to select and replace code references or text after performing a search using the Look Up Reference dialog box.
Code Window
Use the Code window to write, display, and edit form, event, and method code.
Command Window
Displays Visual FoxPro language commands when you choose menu commands. The Command window is a Microsoft Visual FoxPro system window.
Component Gallery Window
Displays, as shortcut icons, components available to your Microsoft Visual FoxPro projects, applications, designers, wizards, and builders, which makes it possible for you to manage, in various ways, any file available to your system.
Coverage Profiler Window
Contains a group of Coverage Profiler Tool Buttons and options that make it possible for you to specify how you display the information returned by the Coverage Engine.
Data Session Window
Enables you to open and display tables or views, establish temporary relationships, and set work area properties.
Debug Output Window
Makes it possible to display output from active programs, procedures, or method code.
Debugger Window
Contains the Debugger menus, the Debugger toolbar, and several debugging windows.
Document View Window
Allows you to view and navigate to any procedure, function, or #DEFINE definition or preprocessor directive in your program.
Editing Window
Provides text and program file editing.
General Field Window
Makes it possible for you to create or insert OLE objects.
Go To Definition Window
Makes it possible for you to choose from multiple code definitions resulting from using View Definition to view definitions of code elements in your program.
Locals Window
Allows you to display all the variables, arrays, objects, and object members that are visible in a given program, procedure, or method.
Object Browser Window
Displays the classes, properties, methods, events, and constants available for COM object libraries.
Project Manager Window
Enables you to organize and manage your files in projects.
Properties Window
Contains the list of properties, events, and methods for a selected form, data environment, cursor, relation, or control.
Task List Manager Window
Describes important information about tasks through the use of visual cues, such as different colored text and icons.
Trace Window
Makes it possible to see your lines of code as they are being executed.
Visual FoxPro Intellisense Manager Window
Makes it possible for you to specify the appearance and behavior of the syntax statements and other tool tip information displayed in properties sheet, editor, and code windows.
Visual FoxPro System Windows
Provided by Visual FoxPro as part of the product interface.
Watch Window
Makes it possible for you to display expressions and their current values, and set breakpoints on an expression.

Related Sections

User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.
Creating Applications with the Application Framework
Describes how the Application Framework is designed to include all required, and many optional, elements that make an application effective and pleasurable to use.
Builders
Describes tools that aid in setting properties of controls on a form. Unlike wizards, builders are reentrant, so you can reopen a builder on a particular control repeatedly.
Dialog Boxes
Explains the options that appear on various dialog boxes.
Developing Visual FoxPro Applications
Includes conceptual information about how to develop Visual FoxPro applications, instructions for creating databases and the user interface, and other tasks needed to create Visual FoxPro applications.
Programming in Visual FoxPro
Describes how understanding object-oriented programming techniques and the event-driven model can maximize your programming productivity and enable you to access the full power of Visual FoxPro.


Accessibility Browser Window

The Visual FoxPro Accessibility Browser is a modeless window that makes it possible for you to explore various user interface elements of an application through their IAccessible interface.

For details on the various IAccessible properties and methods in the Member detail section, refer to technical documentation on the Microsoft Accessibility Web site at http://www.microsoft.com/enable/.

This VFP session option
When clicked, the UI element list box is populated with the current instance of Visual FoxPro.
Separate VFP session option
When clicked, the UI element list box is populated with a new instance of Visual FoxPro.
Refresh command button
Refreshes the UI element list box based on the Session options and Forms only check box settings.
Forms only check box
When selected, only Visual FoxPro forms (those from the _VFP.Forms collection) are displayed. Otherwise, all UI elements in the Visual FoxPro application are included.
+ command button
Expands the UI element list box.
- command button
Collapses the UI element list box.
UI element list box
Contains a hierarchical (based on parent containership) listing of all accessible user interface elements. The list is populated when the Refresh button is clicked. When you click an item in the list, IAccessible properties for that item are displayed in the Member detail section.
Member detail section
This section contains a list of IAccessible properties (and their values) for the item selected in the UI element list box.
Go command button (accParent)
Selects parent of current item in UI elements list box.
Go command button (accChild)
Selects child of current item in UI elements list box. The child selected is one selected in the accChild drop-down list preceding the Go button.
Do It command button
Performs the default action of the selected item.
<- command button
Navigates to prior UI element.
-> command button
Navigates to next UI element.
Select command button
Selects the current UI element in the list box.
Focus command button
Puts focus on the current UI element in the list box.
Click command button
Clicks the current UI element in the list box.
Flash command button
Displays a yellow border around the actual user interface element selected in the UI elements list box.
Highlight check box
When selected, automatically shows a yellow border around the actual user interface element as you change item selected in the UI elements list box.

Platforms Supported

Windows 2000 and later includes all the core support for Accessibility. Earlier versions of Windows support Accessibility to various degrees.

Platform | Description of support
Windows 98 | Includes Active Accessibility version 1.1 in the initial release of Windows 98; however you can run msaardk.exe to upgrade to a later version of Active Accessibility. All language versions of Windows 98 are supported, and future Windows 98 Service Packs will contain updated, localized versions of Active Accessibility.
Windows NT 4.0 | Provides Limited support for Windows NT 4 with Service Pack 4 (SP4) or later. SP6 has full support and is the recommended version of NT to use for Active Accessibility. To use Active Accessibility, you must run msaardk.exe to install the Active Accessibility core system components. The msaardk.exe package fails if SP4 (or later) is not already installed. Only Intel architecture is supported.
Windows 2000 | Includes the Active Accessibility core system files for all language versions of the operating system. Support for both Intel and Alpha processors is provided in Windows 2000.
Windows Me | Accessibility options are installed by default during Windows Me setup, making the Accessibility Wizard and accessibility utilities instantly available. The increased integration of Microsoft Active Accessibility in Windows Me helps make many accessibility aids run more smoothly and effectively with the operating system and other applications.

See Also

Using the Accessibility Browser | Development Productivity Tools | Accessibility for People with Disabilities


Automated Test Harness Window

The Visual FoxPro Automated Test Harness Window makes it possible for you to record and play back Mouse and Keyboard events in your Visual FoxPro applications.

Scripts Tab
This tab makes it possible for you to view and work with existing scripts that were recorded earlier with the Test Harness. You can edit any script by highlighting it in the grid and then clicking the Edit the test script toolbar button or selecting the Edit Script menu item. One or more scripts can be played back at a time. Click checkboxes next to the scripts you want to play back and then click the Play the script toolbar button or select the Play menu item. The following options are available in this tab:
  • Scripts grid

    Displays all recorded scripts. Information for a script is displayed on a line including pre and postscripts that get executed before and after the main script. The main script uses the event log. Items checked in the first column are used when deleting or playing back scripts. The Edit script function only applies to the current row highlighted in the grid.

  • Delete button

    Deletes scripts selected (first column checked) in the grid.

Options Tab
This tab has optional settings you can select for both recording and playback. The following options are available in this tab:
  • Overwrite the existing script

    If checked, an existing script of the same name will automatically be overwritten without prompting for confirmation during recording.

  • Always launch new VFP Window

    If checked, recording will always start with a new instance of Visual FoxPro.

  • Validate startup window before playback

    If checked, the startup window is validated against the recorded window. If it doesn't match, it will prompt with an error. The test will fail if an unexpected window appears or an error occurs.

  • Check for presence of each object

    If checked, the object associated with every event will be verified before playback. For example, if the keypress event is recorded on a textbox, the presence of the same object name is verified before playing back the event. An error will be displayed if the object does not exist.

  • Check for program error

    This option is used to report an error in the testing application. If checked and there is an error during playback, the error will be logged in the test log. The test results can be viewed in the Test Log tab.

  • Run count

    Specifies the number of times each script selected in the Scripts tab is run during play back.

  • Delay between events

    Makes it possible for you to specify a specific delay (milliseconds) between events during playback.

  • On script failure

    Provides error handling options if a problem occurs during script playback. You can abort the entire script, skip only the event that failed or continue playing back the script after retrying the failed event.

Test Log
This tab has details on results from test runs (playbacks). The following options are available in this tab:
  • Test Log grid

    Displays useful information on recently played-back scripts. The memory usage is the difference in the memory before and after the test run.

  • Delete button

    Deletes the selected test log.

Coverage Log
You can set coverage logging by using the settings in the Coverage Log tab. During playback, it will turn on coverage logging and save the log in the file specified.
  • Turn on coverage logging during playback

    If checked, creates a coverage log during playback of a script.

  • Overwrite the log if file exists

    If checked, automatically overwrites the log if it already exists without confirmation.

  • View Log button

    Displays a coverage log for the test if one exists.

  • Coverage Profiler button

    Invokes the Coverage Profiler, which will load the coverage log if it exists; otherwise, it will prompt for a log.

See Also

Using the Automated Test Harness | Testing and Debugging Applications | Debugging and Error Handling | Accessibility Browser Window | Coverage Profiler Application


Browse Window

Displays the records in the active table.

When you are browsing a table in the Browse window, you can view records in two different modes, Browse and Edit. You can switch modes by choosing Browse or Edit from the View menu.

Note When you open a table using Open from the File menu, you have to choose Browse <table> from the View menu in order to see the table.

To select fields, click a cell or press TAB, ENTER, or the arrow keys. Move a column to a new position by clicking on the field name, dragging the column where you want it, and releasing the mouse button.

To enter a null value in a field that accepts null values, press CTRL+0. As long as a field that contains a null value remains active, nothing is displayed in it. After you activate a different field, the one containing the null value will display the string defined by the SET NULLDISPLAY command (for example, ".NULL.")

If you choose Append from the View menu, the Browse window adds a new, blank record. When you fill in the new record, the Browse window automatically adds another new record.

Note In some cases, if you browse a table or cursor generated by a crosstab query, the field names start with a character and a dash, indicating the data type of the field. For example, a numeric field starts with N-.

See Also

Controlling Display of a Field | Table Creation | BROWSE Command | SET BRSTATUS Command | SET REFRESH Command | Customizing a Browse Window


Call Stack Window

Makes it possible for you to display procedures, programs, and methods that are executing. While a program is running, it is listed in the Call Stack window. If you run a procedure or another program from within the first program, while the second program is running, both program names are displayed in the Call Stack window, and so on.

This window is activated when you choose Call Stack from the Window Menu, Debugger Window.

Output Pane
Displays currently executing procedures, programs, and methods.
Call Stack Indicator
Points to the currently running program, procedure, or method.

You can configure the Call Stack window in the Debug Tab, Options Dialog Box.

See Also

Debug Tab, Options Dialog Box | Debugger Window | Debugger Keyboard Shortcuts and Menus | Debug Output Window | Watch Window


Class Browser Window

The Class Browser displays the classes in a class library or a form and the type library information in a .tlb, .olb, or .exe file. You can use the Class Browser to view, use, and manage classes and their user-defined members.

To run the Class Browser

  1. Open Visual FoxPro.
  2. From the Tools menu, click Class Browser.
    Note You can open the Class Browser shortcut menu by clicking the right mouse button on the Class Browser window or by pressing ALT+F10.

Class Browser Buttons

Perform various Class Browser commands. Additional functionality is provided through the Class Browser shortcut menu.

Type Box
Allows selection or entry of a class type or character string to filter the move. The drop-down list shows the base classes. The list also keeps a history of class types and filters you have selected or entered for the current instance of the Class Browser.
Class Move Icon
Displays an icon representing the selected class. The icon can be dragged to the main Visual FoxPro window to create an instance of the class. A user-defined bitmap can be assigned to the class move icon.
Class List
Lists the classes and subclasses contained in a class library (.vcx) or a form (.scx) in a hierarchical or alphabetical view. A chevron (<<) next to a class indicates that the parent class is in a file not displayed in the current Class list. To see the parent class, choose Select ParentClass from the shortcut menu. To modify any class in the Class Designer, double-click the class name.
Member List
Lists the user-defined properties and methods of the class or form selected in the Class list. You can filter this list by selecting options from the Member list shortcut menu.
  • Protected filter If a protected icon (a key) is displayed beside the Protected filter shortcut menu item, protected members are displayed in the Member list. Protected members are also indicated by an asterisk (*).
  • Hidden filter If a hidden icon (a lock) is displayed beside the Hidden filter shortcut menu item, hidden members are displayed in the Member list. Hidden members are also indicated by a caret (^).
  • Empty filter If a check mark is displayed beside the Empty filter shortcut menu item, empty methods are displayed in the Member list. Empty methods are indicated by a tilde (~).
Class Description Box
Displays a description for the selected class. This box is located at the bottom left of the Class Browser window. You can edit the description in this box.
Member Description Box
Displays information about the selected member of a class. This box is located at the bottom right of the Class Browser window.

For object members, the box is a read-only display of class and base class. For property or method members, the box displays a description you can edit. For instances, the box displays a read-only description that includes the variable scope (public or hidden), member names, and property values.

See Also

Adding Controls to Forms with the Class Browser | Browsing Classes with the Class Browser | Class Browser Buttons | Class Browser Methods | Class Browser Properties | Class Designer | Command Window | Customizing the Class Browser | Filtering the Class Browser Class List | Keyboard Shortcuts | Modifying Class Icons and Descriptions | Viewing Class Hierarchies


Class Browser Buttons

When the Class Browser is open, a toolbar with a single button is also open. You can choose this Edit ParentClass Method button when you are editing method code. If there is code associated with the method in the parent class, the code is displayed in a separate window so you can see the functionality you can inherit or override.

The following buttons are displayed in the Class Browser Window.

Component Gallery
Toggles between the Class Browser and the Component Gallery for managing foundation class items.
Open
Opens an existing class library (.vcx) file, creates new class library and type library files, or opens an existing form/form set (.scx) file.
View Additional File
Adds an existing class library (.vcx) file or a form or form set (.scx) file to the class list, or creates a new class library file. Right-click to list the most recent files opened in the Class Browser.
View Class Code
Displays the code for the class definitions of the selected class. In Visual FoxPro, this code is editable and can be saved to a new program file from the File menu. You cannot change the underlying class.
Find
Searches for specific text in class names, class descriptions, member names, and member descriptions.
New Class
Creates a subclass of the selected class or any existing class.
Rename
Changes the name of the selected class, property, or method.
Caution Renaming a class might invalidate forms or classes that are not currently displayed in Class Browser windows and that rely on the class. Changing the name of a property or method can cause code that references the property or method to fail.
Redefine
Changes the parent class of the selected class.
Clean Up Class Library
Runs the PACK command to remove records in the .vcx file marked for deletion.

See Also

Adding Controls to Forms with the Class Browser | Browsing Classes with the Class Browser | Class Browser Methods | Class Browser Properties | Class Browser Window | Managing Classes with the Class Browser | Viewing Class Definition Code | PACK | Component Gallery


Code References Window

Displays the results from a code reference search that meet the project/folder scope and file types specified in the Look Up Reference dialog box. For more information, see Look Up Reference Dialog Box.

The Code References window appears after you perform a search in the Look Up Reference dialog box or when you select Code References from the Tools menu when searching for a previously searched code reference in the same project or folder. The currently active project always takes precedence over Folder scope. If the Look Up Reference dialog box has been previously opened, you can also call the Code References window using the following code:

DO(_FOXREF)

You can set the Code References window to always appear in the foreground when other windows are active.

To always display the Code References window in the foreground

  1. In the Code References window, right-click in the area to the right of the toolbar.
  2. From the shortcut menu, select Always On Top.

However, if you selected Always on Top for other Visual FoxPro windows, you will see no difference in behavior.

The following buttons are available in the Code References window. You can find some of these commands on shortcut menus available from different panes in the Code Reference window.

Open (folder icon)
Opens or brings forward the designer for the selected file. The Open command is available only when a file node is selected.
Arrow
Switches between project scope and folder scope.
Search
Displays the Look Up Reference dialog box for you to perform a new code reference search.
Refresh
Updates previous search results with current results.
Replace
Displays a Replace dialog box for you to specify a replacement expression for selected code references in the results pane. The following options are available in the Replace dialog box:
  • Replace with Specifies the replacement expression for the selected code reference or references.
  • Confirm replacements Opens a dialog box for you to confirm, decline, or cancel the replacement operation for each code reference.
  • Preserve case Performs replacement operations using the original casing of the code reference or text being replaced. Case preservation of text includes only uppercase, lowercase, and title (proper) case, in which the first letter of each word is capitalized. This option does not support mixed case such as in "FoxPro" because the lengths of the original and replacement values can differ.
  • Create backup of modified files Makes a backup copy of the selected files before performing a replacement operation. Backup copies are stored in the same locations as the original files. You can open the Options dialog box from the Code References window or Look Up Reference dialog box to control the naming of backup files.

Visual FoxPro creates an activity log containing the most recent results of individual code reference replacements. These activity logs are shown below the Replacement Logs node in the search pane. Each log contains the following items:

  • A line that shows the original and replacement value
  • Whether the replacement operation succeeded and whether a reference was skipped using the Confirm Replacements option
  • Details and code for you to make data structure changes if data files might be affected
    Note Search and replace operations can include all Visual FoxPro files, including data files. As a result, performing replacement operations can change data structures.
    When this possibility occurs, Visual FoxPro shows a dialog box prompting you to confirm or decline the replacement operation. If you confirm the replacement operation, Visual FoxPro performs only those replacements that do not affect data files and provides code in the search string node under the Replacement Logs node for you to manually perform the desired changes. If you decline replacement, no changes are made.
    Additionally, the Code Reference tool does not support replacement of property or method names in a form (.scx) or visual class library (.vcx) because of possible changes to subclasses and outstanding references.
Print
Displays a Print dialog box for you to select a set of code reference search results for printing. The following options are available in the Print dialog box:
  • Search set Specifies all code reference search results or a set of results that you want to print.
  • All Specifies that all references in the selected set of code references should be printed.
  • Selected items only Specifies that only the selected items for a set of code references are printed.
  • Print Prints the specified set of code references.
  • Preview Opens a Print Preview dialog box and the Report Designer for you to preview the set of code references to be printed.

You can specify a different report if desired by modifying the following fields in the RefAddin.dbf file:

  • Type Specify Report.
  • Data Specify description of the report.
  • Filename Specify the name of the report, such as "report1.frx".
Export
Displays an Export dialog box for you to export all or a set of code reference search results to a variety of formats. The following options are available in the Export dialog box:
  • Type Specifies the target file type for your search results. To make XML Output Options available, select Extensible Markup Language (XML) in the Type drop-down list.

    When exporting your search results to HTML, Visual FoxPro generates the file using XML and XSLT. By default, Visual FoxPro searches for a FoxRef.xsl file in the Visual FoxPro home directory or HOME(0). If the file is not found, Visual FoxPro copies an internal .xsl file and places it in the Visual FoxPro User Application Data directory or HOME(7) unless you specify a different directory. You can supply an XSLT file for formatting the HTML file by renaming your XSLT file to FoxRef.xsl and replacing the original .xsl file with the new file.

  • To Specifies a file name for the exported file. To choose a location other than the current folder for the exported file, click the ellipsis (...) button.
  • Search set Specifies all code reference search results or a set of results that you want to export.
  • View after export Specifies that you view the generated results after the export operation finishes. This option becomes unavailable if you select Clipboard as the target file type.
  • XML Output Options Specifies the following additional options for exporting search results to XML output:

    Generate element-based XML Generates an XML file in which fields are stored as elements.

    Generate attribute-based XML Generates an XML file in which fields are stored as attributes.

    Include schema Adds XML Schema Definition (XSD) schema to XML output.

  • All Specifies that all references in the selected set of code references should be exported.
  • Selected items only Specifies that only the selected items for a set of code references are exported.
Options
Opens the Options dialog box to set additional options for your search. For more information, see Look Up Reference Dialog Box, Options Dialog Box.
Help
Opens the Visual FoxPro Help file.

Search Pane

The search pane, or upper-left window, contains a collapsible tree view of the results from a code reference search. The tree view displays an All Results node, each code reference, and the files that contain the reference. When you click a file name, the view in the results pane, or upper right window, is filtered to represent only the results from that particular file.

A Replacement Logs node appears in the search pane when logs containing the most recent results of individual code reference replacement operations are created.

The following commands are additionally available from a shortcut menu that appears when you right-click a navigation, code reference, or file node inside the search pane:

Copy
Copies all information in the results pane, including the file name, class, method or procedure, and line information, for the item selected to the clipboard so that you can paste the information elsewhere.
Clear Result
Removes the selected result from the search pane. The Clear Result command is not available if the All Results node is selected. If a file is selected, only that file is removed from the search pane.
Clear All Results
Removes all search results from the search pane.

Results Pane

The results pane, or upper-right window, displays results from a code reference search, including potential definitions, if they exist, which you can quickly jump to, and multiple references that might exist in a single line of code. If multiple references per line exist, the results pane displays an indicator (the number of references enclosed by a circle) on that line.

The results pane shows the following items:

  • Check boxes for you to select individual lines of code
  • # Number of code reference instances that occur in the result, if more than one
  • File Name File name and location of the code reference
  • Class.Method, Line Class, method, and line number
  • Code Line of code that contains the code reference

You can sort items in each column by clicking each of the column headers.

The following commands are additionally available from a shortcut menu that appears when you right-click a selected reference inside the results pane:

Copy
Copies all information for the selected line, including the file name, class, method or procedure, and line information, to the clipboard so that you can paste the information elsewhere.
Select All
Selects all the items in the results pane.
Clear Selections
Clears the check boxes in the results pane.
Sort by
Organizes the items in the following manner:
  • File Name Organizes items based on file name.
  • Class.Method Organizes items based on class name followed by method name.
  • Selected Groups items by whether they are selected.
  • File Type Organizes items based on file type (extension).
  • Location Organizes items by folder location.

Description Pane

The description pane, or bottom window, displays information about a code reference search such as the project or folder searched and the matches found. When a reference is selected, the description pane shows the location of the reference and the line of code in which the expression appears.

To hide or display the description pane

  1. In the Code References window, right-click in the area to the right of the toolbar.
  2. From the shortcut menu, select Display Descriptions.

See Also

Windows | Look Up Reference Dialog Box | Look Up Reference Dialog Box, Options Dialog Box | Viewing Code Definitions | HOME( ) Function


Code Window

Use the Code window to write, display, and edit form, event, and method code. You can open as many Code windows as you want, so you can easily view, copy, and paste the code from different forms.

The Code window appears when you double-click a form or form control in the Form Designer, double-click in the Data Environment Designer window, or double-click an event or method in the Properties Window. Doing this has the same effect as choosing the Code command on the View menu.

Object
Lists the current form, form set, data environment, toolbar objects, cursor, relation, and all the controls on the current form.
Procedure
Lists all the events recognized by Microsoft Visual FoxPro for the form, form set, data environment, cursor, relation, or control displayed in the Object box. When you select an event or method from the Procedure box, the parameters passed to the event or method (if any) are displayed in the editing region of the Code window. Event names in boldface text contain code. Access and Assign methods created for a property are also displayed in the Procedure box.
Tip If you need help on syntax for functions, statements, properties, events, or methods while working in the Code window, type the keyword or the property, event, or method name, select it, and press F1 for online Help. You can also select an event or method in the Procedure box and press F1 for information about the selected event or method. Press PAGE DOWN to jump to the next event or method that has code in it.

See Also

Access and Assign Methods | Form Designer | Properties Window | Data Environment Designer


Command Window

The Command window is a Visual FoxPro system window. When you choose menu commands, Visual FoxPro language commands are echoed in the Command window.

You can also type Visual FoxPro commands directly into the Command window. In the Command window, you can:

  • Delete text by pressing ESC if you haven't already pressed ENTER to execute the command.
  • Reissue a previous command by placing the cursor anywhere on the command line, and then pressing ENTER.
  • Re-issue a block of code by selecting it, and then pressing ENTER.
  • Split lengthy commands by typing a semicolon after a space in the command where you want it to break, and then pressing ENTER.
  • Move text within the Command window and to other editing windows. Select the desired text and drag it to the desired spot.
  • Copy text within the Command window and paste it into other editing windows without using Edit menu commands. Select the desired text, hold down CTRL, and then drag the text to the desired spot.

You can change font, line spacing and indentation by selecting the appropriate command from the Format Menu.

Right-click in the Command window to display a shortcut menu with these options:

  • Cut, Copy, Paste. Move or delete characters to and from the Command window.
  • Build Expression. Display the Expression Builder dialog box window, in which you can define an expression using commands, literals, fields, or other expressions. The expression you build is pasted into the Command window when you click OK.
  • Execute Selection. Execute the text selected in the Command window as a new command.
  • Clear. Remove the list of previously executed commands from the Command window.
  • Properties. Display the Edit Properties dialog box window in which you can change edit behavior, tab width, fonts, and syntax coloring options for the Command window.

Persistence of Contents

The contents of the Command window are saved to a file, _command.prg, automatically unless the noRecentDocHistory system policy is enabled or you are not using a FoxUser resource file. You can clear the window by selecting Clear from the Command Window shortcut menu. To enable its use by multiple instances of Visual FoxPro, the file is only read when starting Visual FoxPro, and written when exiting Visual FoxPro. The file is located in the same directory as the FoxUser resource file. You can determine or change the location of the resource file from the Options dialog box, File Locations tab, or via language using SET("RESOURCE") or SET RESOURCE respectively.

See Also

Edit Properties Dialog Box | Expression Builder Dialog Box | Editing Window | Operating the Command Window | Visual FoxPro Configuration | File Locations Tab, Options Dialog Box, | SET RESOURCE Command


Component Gallery Window

The Component Gallery window displays, as shortcut icons, components available to your Visual FoxPro projects, applications, designers, wizards, and builders, enabling you to manage, in various ways, any file available to your system.

The Component Gallery window contains a Component Gallery Toolbar plus the following options:

Catalog (Left) Pane
Displays the Component Gallery hierarchy of catalogs and folders. Select a catalog or folder here to display the items of the container in the Object panel to the right.
Object (Right) Pane
Displays items contained in a catalog or folder.

For information on using items in the Component Gallery, see Starting with the Component Gallery.

Description Box
Provides information on the selected item. The Visual FoxPro status bar reports Component Gallery process status.

See Also

Starting with the Component Gallery | Component Gallery Properties Dialog Boxes | Add Class to Project Dialog Box


Open Catalog Dialog Box

Enables you to select an existing catalog description or file name to open in the Component Gallery.

Open
Open the selected catalog or catalog description.
Browse
Opens the Windows system Open Dialog Box so you can locate a catalog to open.

See Also

Starting with the Component Gallery | Open Dialog Box | Class Browser Window | Component Gallery Window | Component Gallery Options Dialog Box | Find Component Dialog Box


Component Gallery Options Dialog Box

Enables you to specify global settings for catalogs and views in the Component Gallery.

Tab Options

The options available in the Component Gallery Options dialog box are grouped on the following tabs.

Tab | To access these features
Standard Tab, Component Gallery Options Dialog Box | Enables you to specify global defaults. This tab is always available.
Catalogs Tab, Component Gallery Options Dialog Box | Enables you to add catalogs to the Component Gallery and to specify whether catalogs are global or default.
Dynamic Views Tab, Component Gallery Options Dialog Box | Enables you to add, edit, or remove views from your view list. This tab is always available.

See Also

Component Gallery Overview | Standard Tab, Component Gallery Options Dialog Box | Catalogs Tab, Component Gallery Options Dialog Box | Dynamic Views Tab, Component Gallery Options Dialog Box | Component Gallery Window


Standard Tab, Component Gallery Options Dialog Box

Enables you to specify default behavior settings that are global for all catalogs and folders, or items. The following settings are available in this tab:

Global Defaults

Enable item renaming
Enables select-delay label editing within the Component Gallery panes. Renaming is always available from the shortcut menu.
FFC Builder Lock
Enables you to specify that a builder opens when you drop a class on a form.
Drag and drop to desktop
Enables gallery items to open as samples in the Visual FoxPro desktop window.
Advanced editing enabled
Enables the Type, Scripts, Views, and Comments advanced editing tabs of all Item Properties Dialog Box.

Catalog default behavior

Open file as new view
Changes default double-click behavior of gallery items from Modify to Run.
Add file to current view
Changes default double-click behavior of gallery items from Open to Add.

Item default behavior

Modify item file
Sets the default double-click behavior of gallery items to Modify.
Run item file
Sets the default double-click behavior of gallery items to Run.

See Also

Component Gallery Options Dialog Box | Component Gallery Window | Catalogs Tab, Component Gallery Options Dialog Box | Dynamic Views Tab, Component Gallery Options Dialog Box | Item Properties Dialog Box


Catalogs Tab, Component Gallery Options Dialog Box

Displays the names of the views that are currently available in the Component Gallery. This is the list that displays in the View Type drop-down list.

Tab Options

Global
Sets a catalog to contain any type of folder. You can access global catalogs and their contents no matter what other catalogs are open.
Default
Enables a catalog to automatically open when the Component Gallery starts. All catalogs that are marked as default are available whenever you select the default view.
New
Displays the Open Catalog Dialog Box so you can add a catalog to the list.

See Also

Component Gallery Window | Dynamic Views Tab, Component Gallery Options Dialog Box | Standard Tab, Component Gallery Options Dialog Box | Component Gallery Options Dialog Box


Dynamic Views Tab, Component Gallery Options Dialog Box

Displays the names of the Dynamic Views currently available in the Component Gallery. You can specify dynamic views in the Component Gallery Options dialog box.

Tab Options

New
Enables you to create a new Dynamic View in the Component Gallery.
Edit
Enables you to edit an existing Dynamic View by displaying the Edit View dialog box for the selected view.
Remove
Enables you to remove the selected Dynamic View from the Component Gallery.

See Also

Catalogs Tab, Component Gallery Options Dialog Box | Find Component Dialog Box | Component Gallery Options Dialog Box | Component Gallery Window | Standard Tab, Component Gallery Options Dialog Box


Find Component Dialog Box

Enables you to search catalogs or folders by any of several criteria. The search criteria is saved as a view that you can use again.

This dialog box appears when you click the Find button on the Component Gallery toolbar. Your search criteria are automatically saved as a view description before you close the Find Component dialog box. You can remove any gallery views you no longer need by using the Remove button of the Options dialog Dynamic views tab.

Dialog Box Options

Containing
Specifies a comma-separated list of expressions for which to search. You can use the same expressions used in Filtering the Class Browser Class List.
Look in
A selectable list of available catalogs and an "all catalogs" option. You can add a new scope for the search.
Keywords
Displays the Keywords Dialog Box for selecting within the Keywords field of the selected catalog.
Note All keywords are stored in the Keywords.dbf table in the HOME( ) folder.

Search fields

These check boxes select fields from the highlighted catalog:

Item Name
Searches for the Name as displayed in the General tab of the Item Properties dialog box.
Class Name
Searches for Class Name as displayed in the Class Item tab of the Item Properties dialog box.
Description
Searches for the Description as displayed in the General tab of the Item Properties dialog box.
Properties
Searches contents of Properties as displayed in the Scripts tab of the Items Properties dialog box.
File Name
Searches for the file name displayed as Class Library in the Class Items tab of the Item Properties dialog box.
Item Types
A list of the available default and user-defined item types to select as search targets.
Find
Starts the search once all criteria are set.
Cancel
Cancels a search.
New Search
Clears current criteria so you can start a new search specification.
Result View
Displays the name of the view you are creating or editing.

See Also

Component Gallery Properties Dialog Boxes | Filtering the Class Browser Class List | Component Gallery Options Dialog Box | Component Gallery Window


Component Gallery Properties Dialog Boxes

In the Component Gallery you can use the Properties option on shortcut menus to view or change the properties of gallery catalogs, folders, or other items. The following topics provide details on each type of properties dialog:

Catalog Properties Dialog Box

Folder Properties Dialog Box

Item Properties Dialog Box

See Also

Component Gallery Options Dialog Box | Component Gallery Window | Add Class to Project Dialog Box


Catalog Properties Dialog Box

Allows you to customize the behavior of a Component Gallery catalogs by accessing values in the related table.

This dialog appears when you click Properties on the shortcut menu of a selected catalog.

General Tab

Enables you to specify settings that are global for all catalogs. The following settings are available in this tab:

Name
Displays the value in the Text field as the component label in the Component Gallery.
Description
Optional information from the Desc field that displays in the description pane of the Component Gallery.
Picture
Value in the Folderpict field that specifies the path and file name of the graphic used to represent the item in the gallery.
Item picture
Value in the Picture field which specifies the path and file name of the graphic used to represent items in this catalog that have no specified picture.
Item Desc.
Value in the Typedesc field which contains a description that applies to all items contained in this catalog or folder.

Node Tab

A node is any selectable gallery item. Enables specifying settings that are global for all catalogs. The following settings are available in this tab:

ID
The name of the table plus the value in the ID field for the selected catalog.
Link ID
If the selected item is a link, specifies the name of the source item.
Class name
The value in the Classname field, which specifies the name of the class of the selected catalog or folder.
Class library
The value in the Classlib field, which specifies the name and path to the class library containing the gallery item.
Item class
The value in the Itemclass field that specifies the default class of items in the selected catalog that have no previously assigned class.
Dynamic Catalog
Value in the Filename field, which contains the target expression, filename, or URL that is launched when you select this dynamic catalog item.

Scripts Tab

This tab provides a place to specify events or properties that are global for all catalogs. The following areas are available in this tab:

Script
The value in the Script field that contains any event script related to this catalog and its items.
Properties
The value in the Properties field, which can contain value assignments to properties of the item.

Comments Tab

Enables specifying settings that are global for all catalogs. The following settings are available in this tab:

Comments
The value in the Comment field, which contains user comments about usage, characteristics, or anything.
User
The value in the User field, which contains user comments about usage, characteristics, or anything.

Item Types Tab

Enables specifying settings that are global for all catalogs. You can edit the setting of existing catalogs by selecting a catalog type from the list, or you can add a new type by clicking the Add button.

The tab provides a listbox that enables you to select an existing item type so you can view or modify its options. The following settings are also available in this tab:

Add button
Enables you to add new item types to the component gallery. You can then configure and specify the following properties:
Text
Specifies the label that displays in the Component Gallery.
Class
Specifies the class name of the selected item.
Class library
Specifies the name and path to the class library containing the gallery item.
File types
Specifies the file extension options the GETFILE( ) dialog box will provide for this item.
Item Type
Specifies whether the new item type is a folder or a gallery item.
Properties
Can contain value assignments to properties of the item.
Redirect
Specifies which extensions to use based on gallery item type.
Remove button
Enables you to remove an existing gallery item type.

See Also

Folder Properties Dialog Box | Item Properties Dialog Box | Component Gallery Window | Folder Properties Dialog Box | Item Properties Dialog Box | Component Gallery Properties Dialog Boxes


Folder Properties Dialog Box

Allows you to customize the behavior of Component Gallery folders.

This dialog appears when you click Properties on the shortcut menu of a selected folder.

General Tab

Enables specifying settings that are global for all catalogs. The following settings are available in this tab:

Name
Displays the value in the Text field as the component label in the Component Gallery.
Description
Optional information from the Desc field that displays in the description pane of the Component Gallery.
Picture
Value in the Folderpict field that specifies the path and file name of the graphic used to represent the selected item in the gallery.
Item picture
Value in the Picture field which specifies the path and file name of the graphic used to represent items in this catalog that have no specified picture.
Item desc
Value in the Typedesc field which contains a description that applies to all items contained in this catalog or folder.

Node Tab

A node is any selectable gallery item. Enables specifying settings that are global for all catalogs. The following settings are available in this tab:

ID
The name of the table plus the value in the ID field for the selected folder.
Link ID
If the selected item is a link, specifies the name of the source item.
Class name
The value in the Classname field which specifies the name of the class of the selected folder.
Class library
The value in the Classlib field which specifies the name and path to the class library containing the gallery item.
Item class
The value in the Itemclass field which specifies the default class of items in the selected folder that have no previously assigned class.
Dynamic folder
Value in the Filename field which contains the target expression, filename, or URL that is launched when you select this dynamic folder item.

Scripts Tab

This tab provides a place to specify events or properties that are global for all folders. The following areas are available in this tab:

Script
The value in the Script field which contains any event script related to this catalog and its items.
Properties
The value in the Properties field which can contain value assignments to properties of the item.

Comments Tab

Enables specifying settings that are global for all catalogs. The following settings are available in this tab:

Comments
The value in the Comment field which contains user comments about usage, characteristics, or anything.
User
The value in the User field which contains user comments about usage, characteristics, or anything.

See Also

Catalog Properties Dialog Box | Item Properties Dialog Box | Component Gallery Properties Dialog Boxes | Component Gallery Window


Item Properties Dialog Box

Allows you to customize the behavior of Component Gallery items.

This dialog appears when you click Properties on the shortcut menu of a selected item. When you select Advanced editing enabled in the Component Gallery Options Dialog Box, this dialog will also display the Type, Scripts, Views, and Comments tabs.

General Tab

Enables you to specify the following settings in this tab:

Name
Displays the value in the Text field as the component label in the Component Gallery.
Description
Optional information from the Desc field of this record in the selected table (specified in Node tab.ID). This item displays in the description pane of the Component Gallery.
Picture
Value in the Folderpict field which specifies the path and file name of the graphic used to represent the item in the gallery.

Views Tab

Enables you to specify characteristics that control display of this item in the Component Gallery.

Views
Specifies the name of the view and folder that contains the selected item in the following syntax:
<viewName>=<folderName>
Keywords
Displays the keywords by which the selected item can be found. You can add to this list by clicking the dialog button and selecting from the default list of gallery keywords.

Node Tab

A node is any selectable gallery item. Enables you to specify settings for the selected item. The following settings are available in this tab:

ID
The name of the table plus the value in the ID field of the record of the selected item in its parent catalog.
Link
If the selected item is a link, specifies the name of the source item.
Class Name
Specifies the gallery class of the selected item
Class Library
Specifies the path and file to the library containing the gallery class of the selected item.

Scripts Tab

Provides a place to specify events or properties that are global for all items. The following areas are available in this tab:

Script
The value in the Script field of the record of this item in its parent catalog. The field contains any event script related to this item.
Properties
The value in the Properties field which can contain value assignments to properties of the item.

Comments Tab

Enables specifying settings for the selected item. The following settings are available in this tab:

Comments
The value in the Comment field of this record in the parent catalog (specified in Node tab.ID) which contains user comments about usage, characteristics, or anything.
User
The value in the User field of this record in the parent catalog (specified in Node tab.ID) which contains user comments about usage, characteristics, or anything.

Item Tabs

Item tabs are generated by the Component Gallery and added to the Item Properties dialog box for most items you add to the gallery. Each Item tab provides a set of properties information that is specific to the particular item of that type. An Item Properties dialog box can include the Class Item tab, File Item tab, Form Item tab, Menu Item tab, Program Item tab, Project Item tab, and Report Item tab.

Class Item Tab

Enables you to specify the class and class library that contains the gallery item.

Class name
Specifies the Class name.
Class library
Specifies the name and path to the class library containing the gallery item.
Base class
Specifies the class from which this gallery item is subclassed.
Sample file
Specifies the name and path to a file containing an example of this gallery item.

File Item Tab

Enables you to specify the path and file name of the gallery item.

File name
Specifies the path and file name.

Form Item Tab

Enables you to specify the path and file name of the gallery item .scx file.

Form name
Specifies the path and form name.

Menu Item Tab

Enables you to specify the path and file name of the gallery item .mnx file.

Menu name
Specifies the path and form name.

Program Item Tab

Enables you to specify the path and file name of the gallery item file.

File name
Specifies the path and file name.

Project Item Tab

Enables you to specify the path and file name of the gallery item .pjx file.

File name
Specifies the path and file name of the source project.
Output name
Specifies the path and file name of the output file.
Build action
Specifies which build option (Rebuild Project, Build Application, Build Executable, or Build OLE DLL) is used when you build this project.
Rebuild all
Enables you to rebuild all files or only those that have changed since the last build.
Show Errors
Enables you to Build Option errors to an edit box after the compile is complete.
Run after build
Enables you to run the application after the build is complete.

Report Item Tab

Enables you to specify the class and class library that contains the gallery item.

Report Name
Specifies the path and file name of the source report.

See Also

Catalog Properties Dialog Box | Folder Properties Dialog Box | Build Options Dialog Box | Component Gallery Options Dialog Box


Add Class to Project Dialog Box

Adds a class from the Component Gallery to a project.

Add class to project
Adds the class to the project.
Create new class from selected class
Creates a new class and then adds the new class to a project. The New Class dialog box is displayed, allowing you to specify a name for the new class and the class library in which the new class is stored.
Create new form from selected class
Adds a form to the project. This option is only available adding a form to the project.

See Also

Component Gallery Window | New Class Dialog Box | Component Gallery Properties Dialog Boxes


Coverage Profiler Window

Contains a group of Coverage Profiler Tool Buttons and options that let you specify how you display the information returned by the Coverage Engine.

Source List Pane
The upper Source List pane is divided into two columns. The left-hand column lists the classes within the selected file or All Classes, Objects, and Processes. The right-hand column displays the file containing the source code for this item. This file can be a .frx, .lbx, .scx or .vcx containing the class or object listed in the left pane, the .prg file for the ALL Classes selection or any other type of file that stores source code. For example, a .dbc could be listed if stored procedures were logged; an .frx could be listed if the Data Environment of a report form contained code.
Source Code Pane
The lower Source Code pane (in Preview mode) displays the code of the item you select in the upper Source List pane. The mode you select determines some of the content and the format of the code displayed.
Coverage Mode
In Coverage mode, the Source Code pane displays the code of the item highlighted in the upper section. The Coverage Profiler can mark the lines run and the lines not run. The default setting marks, with the symbol or symbols specified in the Coverage Profiler Options Dialog Box, each line that was not actually run. Use this mode when testing your application, to verify which lines of code actually run.

By marking both the lines run and the lines not run (with different marks) you can more easily distinguish between lines that are never run, such as comments, from lines that were not run during this coverage analysis.

Profile Mode
In profile mode, the Source Code pane displays the code of the item highlighted in the upper Source List pane, the number of times a line was hit, and the duration of each line. Use this mode if you want to evaluate the performance of running code.

Lines can report 0.000 duration (both 1st and Avg) even though column one shows 1 or more Hits for these lines. This happens when lines are executed so quickly that duration is less than .001 second.

See Also

Coverage Profiler Application | Coverage Profiler Options Dialog Box | Coverage Profiler Statistics Dialog Box | Coverage Profiler Tool buttons | Coverage Engine Object


Coverage Profiler Tool Buttons

Contains the following Tool buttons:

Button | Description
Open Catalog Dialog Box | Displays the Open dialog box so you can open a coverage log.
Save As Dialog Box | Displays the Save As dialog box so you can save the Coverage Profiler application information as a table (.dbf).
Coverage Profiler Statistics Dialog Box | Displays the Coverage Profiler Statistics dialog box so you can view summaries of the Coverage Profiler details and review Coverage Profiler statistics relative to a specific Visual FoxPro project.
Coverage Profiler Add-Ins Dialog Box | Displays the Coverage Profiler Add-Ins dialog box so you can specify Add-Ins to use with the Coverage Profiler.
Coverage Profiler Window | Displays coverage results in the lower pane of the Coverage Profiler window or in the Zoom window.
Coverage Profiler Window | Displays profiler results in the lower pane of the Coverage Profiler window or in the Zoom window.
Coverage Profiler Window | Displays the Coverage Profiler window as a single dialog box of two panes.
Coverage Profiler Window | Displays the Coverage Profiler as two separate dialog boxes that you can arrange and resize.
Coverage Profiler Find dialog box | Displays the Coverage Profiler Find dialog so you can search for specific item in the coverage log.

See Also

Coverage Profiler Application | Coverage Profiler Options Dialog Box | Coverage Profiler Statistics Dialog Box | Coverage Profiler Window | Coverage Profiler Add-Ins Dialog Box


Coverage Profiler Options Dialog Box

Enables you to specify the path sensitivity, dialog format and environment, and the marks used for marking lines of code that run in your program or application, and the fonts for display and code.

Use Smart Pathing
Sets the Coverage Profiler to make certain assumptions about the location of files in your project or application according to how the files are listed in the coverage log. By default, Coverage Profiler prompts you to locate source files referenced in the coverage log. If you check this option, Coverage Profiler assumes that folders in which you have already located files contain additional source files you need.

Uncheck this option for more complete control or if you have source files with the same name in different folders.

Register Add-Ins when run
Sets the Coverage Profiler to retain for future use the path and name information of Add-Ins as you run them so that you can locate them in the drop-down list of the Coverage Profiler Add-Ins Dialog Box.
Mark all code while log loads
Marks lines of code as the Coverage Profiler processes the coverage log (.log). This setting can slow load performance, especially in larger files.

Coverage Marks

Executed
Allows you to type a character or several characters, such as asterisks, to be used to mark each executed line of code.
Not Executed
Allows you to type a character or several characters to be used to mark each line of code that is not run. A vertical bar is the default character.
Note Some lines in code, such as comments, DEFINE CLASS and ELSE statements, and lines within TEXT… ENDTEXT do not appear in coverage logs because they are not executable. Also, lines broken by continuation symbols (semicolons) are considered as a single line of code and are marked only on the last line.

Start Mode

Coverage
Specifies that the Coverage Profiler application opens as a coverage analyzer, marking code that actually runs in selected projects or applications.
Profile
Specifies that the Coverage Profiler application opens as a profiler, determining the amount of time required to run lines of code in the selected project or application.

Environment

Coverage frame
Specifies that the Coverage Profiler application opens in the Windows desktop.
FoxPro frame
Specifies that the Coverage Profiler application opens within the main Visual FoxPro window.

Fonts

Display Font
Allows you to specify the font used in the Source List pane of Coverage Profiler window.
Code Font
Allows you to specify the font used in the Source Code pane of the Coverage Profiler window.
Set as default
Saves your selected options in the Windows registry. Start mode and Environment settings take effect when you restart Coverage Profiler.

See Also

Coverage Profiler Window | Coverage Profiler Tool Buttons | Coverage Profiler Add-Ins Dialog Box | Coverage Profiler Statistics Dialog Box


Coverage Profiler Add-Ins Dialog Box

Enables you to locate and run .app, .fxp, or .prg files to change or enhance the Coverage Profiler. You can use these Add-Ins to add controls, queries, dialog boxes, and other enhancements to the Coverage Profiler.

Add-Ins

Allows you to select an Add-In program to run.

Register this Add-In after running
Adds the current Add-In to a drop-down list so that you can access the Add-In in the future.
Note You can set the Coverage Profiler to register new Add-Ins by default by selecting the Register Add-Ins when run check box in the Coverage Profiler Options dialog box.
Run
Starts the Add-In program.

See Also

Coverage Profiler Window | Coverage Profiler Tool Buttons | Coverage Profiler Statistics Dialog Box | Coverage Profiler Options dialog box | Coverage Profiler Add-Ins


Coverage Profiler Statistics Dialog Box

Displays summary information from the current .log file and provides access to project, source text, and skipped files information.

Statistics

Displays summary information on the file selected in the Source List pane. The content of this area is dependent on the type of file selected. The dialog box displays only statistics on lines in the cases of database (.dbc) or program (.prg) files. In the case of file types such as .frx, .lbx, .scx, and .vcx, that contain classes, the dialog box displays information on lines and on classes. The details that comprise this information are displayed in the Source Code pane as either Coverage or Profile mode information.

View Details

Statistics by Project
Enables you to select a project file and generate a detail and summary report on the coverage of the project.
Source Text Log
Displays the current log file in the Visual FoxPro editor.
Source Files Skipped
Opens a Browse window on the SkippedFiles cursor. This cursor contains names of files for which the Coverage Profiler provides no information. These files can be files for which you have no uncompiled code, files Coverage Profiler was unable to locate, or Coverage Profiler source code.

See Also

Coverage Profiler Window | Coverage Profiler Tool Buttons | Coverage Profiler Add-Ins Dialog Box | Coverage Profiler Find dialog box


Coverage Profiler Find Dialog Box

Enables you to search the Coverage log for specific items.

Options

Match Case
Match the case of the search item
Wrap Around
Specifies that a search begun from within a file, continues past EOF through BOF to the current cursor position.

Search

Classes
Search through the classes in the coverage log.
Files
Search through the files in the coverage log.
Source code
Search through the source code in the current display.

See Also

Coverage Profiler Add-Ins Dialog Box | Coverage Profiler Options Dialog Box | Coverage Profiler Statistics Dialog Box | Coverage Profiler Window | Coverage Profiler Tool Buttons


Coverage Profiler Exit Dialog Box

Stops the Coverage Profiler application and enables you to choose how to continue or end coverage logging. This dialog box displays if you have issued SET COVERAGE Command FileName before running the Coverage Profiler application.

The dialog provides the following options:

Button | Result
Yes | Enables you to continue logging data by appending more records to the current .log file for use in the Coverage Profiler application.
No | Enables you to continue logging data but overwrites the records in the current .log file.
Cancel | Leaves logging set off after closing the Coverage Profiler application.

See Also

Coverage Profiler Window | Coverage Profiler Tool Buttons | SET COVERAGE Command | Coverage Profiler Find dialog box | Coverage Profiler Statistics Dialog Box | Coverage Profiler Add-Ins


Data Session Window

You can use the Data Session window to open and display tables or views, establish temporary relationships, and set work area properties.

Current Session
Displays the name of the current data session.
Aliases
Displays the view name or table name without the file extension.
Relations
Indicates the temporary relationship established between the tables or views in the Aliases box.
Properties
Displays the Work Area Properties dialog box, in which you can modify the structure of a table, select index files and fields, and define data filters. If no tables or views are listed in the Aliases box, an Open dialog box appears to make it possible for you to open a table or view.
Browse
Displays the table or view selected in the Aliases box in a Browse window, where you can examine, edit, or append data.
Open
Displays an Open dialog box, similar to the Add Table or View dialog box, so you can select a table or view to open.
Close
Removes the selected table or view and any associated files from the Aliases box.
Relations
Defines the relations between tables or views, using the Expression Builder dialog box. The Set Index Order dialog box appears before the Expression Builder dialog box when no index order has been set between the two tables.
1-To-Many
Displays the Create One-To-Many Relationships dialog box, which makes it possible for you to establish a one-to-many temporary relationship between child tables and parent tables. This button is enabled when you establish relations between two or more tables by selecting them in the View dialog box and then clicking Relations.

See Also

Working with Tables | Adding Tables to a Database | Creating Persistent Relationships | Browse Window | Create One-To-Many Relationships Dialog Box | Expression Builder Dialog Box | Open Dialog Box | Work Area Properties Dialog Box


Debug Output Window

Makes it possible for you to display output from active programs, procedures, or method code.

This window is activated when you choose Output from the Window Menu, Debugger Window.

Output Pane
Displays character strings specified by the DEBUGOUT command and, if event tracking is enabled, the names of system events as they occur.

To save the text in the window

  • Choose Save Output As from the File menu in the Debugger window.

See Also

DEBUGOUT Command | Event Tracking Dialog Box | Debugger Window | Debugger Keyboard Shortcuts and Menus


Debugger Window

The Visual FoxPro Debugger window contains the Debugger menus, the Debugger toolbar, and several debugging windows.

This window is activated when you choose Debugger from the main Visual FoxPro Tools Menu, as long as the Environment option on the Debug menu (under Options on the Tools menu) is set to Debug Frame. If FoxPro Frame is selected, the Debugger window will not be accessible, and the individual debugger windows will be available from the FoxPro main menu.

Trace Window
Makes it possible for you to see your lines of code as they are being executed.
Locals Window
Displays the visible variables, arrays, objects, and object members from the current program, procedure, or method.
Watch Window
Displays expressions and their current values, and makes it possible for you to set breakpoints on an expression.
Call Stack Window
Displays procedures, programs, and methods that are executing.
Debug Output Window
Displays debug-specific output from your programs.

The debugging windows and toolbar can be docked and positioned.

To | Do
Resize adjacent docked windows | Drag the separator bar between them.
Float a window | Choose Undock from the shortcut menu.
View an open, hidden window | Click the toolbar button associated with the window twice: once to close the window and a second time to reopen the window.

See Also

Trace Window | Locals Window | Watch Window | Call Stack Window | Options Dialog Box


Debugger Keyboard Shortcuts and Menus

The following keyboard shortcuts apply to the debugging tools in the Debugger window or in the FoxPro frame.

Action | Keyboard
Resume | F5
Cancel | ESC
Step Into | F8
Step Over | F6
Step Out | SHIFT+F7
Run To Cursor | F7
Trace Window | ALT+8
Watch Window | ALT+3
Locals Window | ALT+4
Call Stack Window | ALT+7
Debug Output Window | ALT+2
Toggle Breakpoint | F9
Clear Breakpoints | CTRL+SHIFT+F9
Breakpoints | CTRL+B
Open File | CTRL+O
Save Configuration | ALT+S
Exit Debugger | ALT+F4

File Menu, Debugger Window

This contains options that make it possible for you to open programs and debugging configurations. You also can save debug output to a file.

Menu Commands

Open
Displays the Open dialog box so you can specify a program to display in the Trace window. Opening a program does not run the program.
Load Configuration
Loads breakpoints, watches, and events to be tracked from a configuration file (.dbg file). Select the dialog button to display the Open dialog box, which makes it possible for you to specify a file.
Save Configuration
Saves the current breakpoints, watches, and events to be tracked into a configuration file (.dbg file) so they can be restored later. Select the dialog button to display the Open dialog box, which makes it possible for you to specify a file.
Save Output As
Writes the text displayed in the Debug Output window to a file specified in the Save As dialog box.
Exit
Closes the Debugger window and returns you to the main Visual FoxPro window.

Debug Menu, Debugger Window

This contains options for stepping through code. You also can set the speed at which commands are executed as you watch.

Menu Commands

Do
Begins executing the program open in the Trace window. If no program is open in the Trace window, this displays the Do dialog box, so you can specify a program or form to trace. The program or form you specify is executed with program execution suspended at the first line of executable code.
Resume
Is available if program execution is suspended. Continues execution of the program in the Trace window at the current line of code.
Cancel
Closes and stops executing the program or form in the Trace window.
Fix
Is available if program execution is suspended.

If you are tracing through a program, Fix prompts you to cancel the program and then opens it in an editing window, at the same position that the cursor is in the Trace window.

If you are tracing through code in a form, Fix prompts you to cancel execution and clear the form object from memory. Then an editing window in the Form Designer opens at the same position that the cursor is in the Trace window.

Step Out
Continues executing the code in a procedure without stepping through the code line by line. Program execution is suspended again on the line of code following the procedure call in the calling program.
Step Over
Executes the next line of code. If the next line of code calls a function, method, or procedure, then the function, method, or procedure is executed in the background.
Step Into
Executes the next line of code.
Run To Cursor
Executes code from the current line indicator to the line of code with the cursor. Click the line of code on which you want to suspend execution to place the cursor on that line.
Throttle
Opens the Execution Throttle dialog box so you can specify the delay in seconds between the execution of each line of code.
Set Next Statement
Places the current line marker on the line of code with the cursor. This line of code will then be executed when you step or resume execution.

Tools Menu, Debugger Window

This provides access to the Debugger dialog boxes.

Menu Commands

Breakpoints
Opens the Breakpoints dialog box so you can add, delete, enable, or disable breakpoints.
Event Tracking
Opens the Event Tracking dialog box so you can specify which events are written to the Debug Output window or a file when they occur.
Coverage Logging
Opens the Coverage dialog box so you can turn coverage logging on or off and specify a file for the coverage log.

See Also

Debugger Window | Debug Output Window | Keyboard Shortcuts


Document View Window

Makes it possible for you to view and navigate to any procedure, function, or #DEFINE definition, class or preprocessor directive in your program.

You can activate this window from the Tools menu or when you choose Document View from the shortcut menu of a program in an editing window.

Note When the Document View window is open for a .prg file, you can use Ctrl-PgUp and Cltr-PgDn to navigate to the prior/next procedure.

Right-click in this window to access the following options.

Sort by Name
Specifies that list items are sorted by name.
Sort by Location
Specifies that list items are sorted by location in the program. When you select this option, you can use Ctrl+PageUp or Ctrl+PageDown to navigate through the listed items. Also, the Document View Window will automatically select the procedure that currently contains the insertion carat in the editor.
Sort by Type
Specifies that list items are sorted alphabetically by item type.
Display #define definitions
Toggles display of #DEFINE definitions in the list.
Display preprocessor directives
Toggles display of preprocessor directives. The display reports the following items:
#INCLUDE
#IF...#ELIF...#ELSE...#ENDIF
#IFDEF...#ELSE...#ENDIF
#IFNDEF...#ELSE...#ENDIF
Font
Opens the Font Dialog Box so you can change the font used in the Document View window

The Document View Window visually indicates each procedure or function, preprocessor definition, class, and preprocessor directive with the following symbols:

  • A red # (number sign) represents a preprocessor definition.
  • A yellow # (number sign) represents a preprocessor directive.
  • A blue box represents a function or procedure.
  • A set of multicolored boxes represents a class.

See Also

Insert Object Reference Dialog Box | #DEFINE ... #UNDEF Preprocessor Directive | #NAME Preprocessor Directive | Font Dialog Box | APROCINFO( ) Function


Editing Window

Provides text and program file editing. If you have selected Modify Selected File in the Projects tab, Options dialog box, the Editing window opens when you double-click a text or program file in the Project Manager.

In the Editing window, you can:

  • Move text within the Command window and to other editing windows. Select the desired text, and then drag it to the desired spot.
  • Copy text within the Command window and paste it into other editing windows without using Edit menu commands. Select the desired text, hold down CTRL, and then drag the text to the desired spot.

Change font, line spacing, and indentation by selecting the appropriate command from the Format menu.

See Also

Displaying and Printing Source Code Files in Color | Projects Tab, Options Dialog Box | Project Manager Window | Command Window


General Field Window

This window is displayed when you double-click a General field's type designator in a browsed table, or press CTRL+PAGE UP or CTRL+PAGE DOWN to open the General Field window from the keyboard.

With this window displayed, you can create or insert OLE objects by using the Insert Object command on the Edit menu. You can edit the existing object by double-clicking it or by selecting Bitmap Image object Edit or object Open from the Edit menu.

See Also

General Field Type | Table Designer | Insert Object Dialog Box | Adding a General Field


Go To Definition Window

Displays multiple code element definitions that you can choose from when searching for a code definition.

The Go To Definition window appears after the selection of the View Definition command results in multiple code element definitions. You can select the View Definition command from the shortcut menu that appears when you right-click inside a program's Editing window.

File
Lists the file name and location of the code definition.
Class.Method (Line)
Lists the class, method, and line number, if available, of the code definition.
Code
Lists the code that contains the code definition.
Go To
Moves to the location of the code definition selected.

See Also

Windows | Viewing Code Definitions | Editing Window


Locals Window

Makes it possible for you to display all the variables, arrays, objects, and object members that are visible in a given program, procedure, or method.

This window is activated when you choose Locals from the Window Menu, Debugger Window.

Locals for
Indicates the procedure whose variables, arrays, and objects are displayed in the Locals window.
Name
Displays the names of the visible locals.
Value
Displays the current values of the visible locals.
Type
Displays characters that represents the data types of the visible locals.

Use the shortcut menu to control the category of variable displayed.

Category | Description
Public | Variables declared with the PUBLIC keyword.
Local | Variables declared with the LOCAL keyword.
Standard | All variables in the scope of the procedure displayed in the Locals for box.
Objects | Object variables.

To see the values of array elements or object properties, click the box to the left of the array or object name. The Locals window makes it possible for you to see properties of all objects in the container hierarchy.

See Also

LOCAL Command | PUBLIC Command | Debugger Window | Debugger Keyboard Shortcuts and Menus


Object Browser Window

The Object Browser displays the classes, properties, methods, events, and constants available for COM object libraries. You can use it to find and use objects you create, as well as objects from other applications.

To launch the Object Browser from the Tools menu, choose Object Browser and open a COM library to view.

The Object Browser application is referenced by _OBJECTBROWSER system variable (which by default references objectbrowser.app). You can set this from the File Locations tab of the Options dialog box.

Classes & Members pane
Lists the classes, members, interfaces, enums, constants, and other information available from the class type library. To display members of each category, expand the category.
Members pane
Lists the member details of the selected item in the Classes & Members pane. If a class is selected, its events, methods, and properties are displayed.
Description pane
Displays the definition of the selected item, prototype syntax, and a hyperlink to the class, library, or type to which the item belongs. Some members have hyperlinks to their parent class. When an interface is selected, the description pane includes the Interface ID number.

You can copy or drag text from the description pane to the editing window.

Open Type Library button
Displays the Open Type Library dialog box so you can select a particular COM Component or ActiveX Control. To display a list of recently opened libraries, click the down arrow.
Open Type Library dialog box
Appears when you click the Open Type Library button or right-click the Object Browser and then click Open.
Name | Description
Recent History tab | Displays a list of recently opened libraries. To add a library to the Object Browser, select the check box next to the library. To clear all content in the Recent History list, click Clear History.
COM Libraries tab Shows a list of all available COM class libraries on your system. The list includes libraries for COM components and ActiveX controls.

The first time you click this tab, the COM libraries are read from your system registry and cached to a local FoxRefs.dbf table. When you click the tab again, libraries are read from this table.

To reload all class libraries from your system, click the Refresh button. To select and load an individual library (.tlb, .ocx, .olb, .dll, .exe), click Browse to open a file picker dialog box.
Current Selection Tab Displays a list of all open libraries.

To close individual libraries, clear the check box next to the library name. To close all libraries, click Close All.
Back button
Moves selection focus back to the last item that you viewed.
Forward button
Moves selection focus to the item you were viewing before clicking the Back button.
Refresh button
Refreshes the contents of the Object Browser by reloading the selected libraries. This is useful for frequently changing COM components under development. Additionally, cached libraries are refreshed.
Copy button
Makes it possible for you to copy the selected item in the current list. If there is no explicit selection in the Description pane, the entire text is copied.
Find button
Displays the Find view so you can enter a specific text string to search for within the libraries opened in the Object Browser.
Find view
Expands at the top of the Object Browser when you click the Find button. Use the Find view to search for a specific text phrase in the library.
Name | Description
Look for: textbox | Enter text for which to search. The default search includes all opened libraries, all their members, and any item that contains the search text.
Go button | Click button to search for text entered in the text box. When you click this button a new node is added for each opened library to the Classes & Members pane with expression "(Search: <searchtext>)" appended to the end of the library. You can refine search using the Advanced view.
Switch to advanced find... link | Displays additional search options to perform a more refined search.
Libraries dropdown | Limits search to all opened libraries or just a single one. Advanced Find view only.
Scope dropdown | Limits search to members of all libraries or just a single one. The list of available options includes Classes, Constants, Enums, Interfaces, Methods, Events, and Properties. Advanced Find view only.
Options dropdown | Determines how text search is made. Options include Contained in, Starts with, and Exactly like. Advanced Find view only.
Options button
Displays the Options dialog box so that you can control various display options. You can also set custom add-ins for use with the Object Browser.
Display Options tab, Options dialog box
This tab in the Options dialog box makes it possible for you to control the visual aspects of the Object Browser.
Name | Description
Highlight Potential Sources of Events check box | Specifies whether a potential source of events (interface or method) is highlighted.
Highlight Default Items check box | Specifies whether default items are highlighted using a bold font style.
Display Hidden Items check box | Specifies whether hidden items (such as interface, methods, and properties) are displayed.
Auto Expand Details check box | Specifies whether top-level items in the detail pain are expanded automatically.
Auto Drill Down Details check box | Specifies whether complex hierarchies in the Methods pane (such as methods and properties for each interface) are expanded automatically.
Display VTable Interfaces check box | Specifies whether VTable based interfaces and their members are displayed.
List all interfaces defining a method, event, or property in detail check box | Specifies whether all interfaces defining a method or property are listed in the Description pane.
Display properties that start with an underscore (_) check box | Properties that start with an underscore are usually placeholders for enums (a collections of constants). For this reason, they are not displayed by default.
Display members that are defined in IUnknown or IDispatch check box | All COM objects have methods that are defined in the IDispatch and IUnknown interfaces. These methods must be there to work in a COM environment; however, they usually are not useful directly to the Visual FoxPro developer.
List members parameters in detail check box | Method parameters can be listed directly in the Members pane. However, note that the parameters are listed in more detail in the Description pane.
List interfaces in class details check box | All creatable classes are based on one or more interfaces. Often interfaces listed in the Members pane simply show the same information as the entire class, but sometimes they provide more insight.
Show Interface Inheritance structure check box | Specifies whether inherited interfaces shall be displayed in the Members pane.
Font button | Specifies font for interface elements of the Object Browser.
Add Ins tab, Options dialog box
This tab in the Options dialog box makes it possible for you to add custom add-ins.
Name | Description
Install Add-In button | Installs a new add-in.
Installed Add-Ins list | Displays all loaded add-ins.
Remove button | This button is displayed in the Add-Ins list next to an installed add-in. Click this button to remove an add-in. The add-in file is not actually deleted.
Help button
Displays documentation on the selected member. In addition, you can press F1.

See Also

Using the Object Browser | Class Browser | _ObjectBrowser System Variable | DEFINE CLASS | EVENTHANDLER( ) | Viewing Type Library Information


Project Manager Window

Use the Project Manager to organize and manage your files in projects. A project is a collection of files, data, documents, and Visual FoxPro objects that is saved as a file with a .pjx extension. When the Project Manager window is active, Visual FoxPro displays the Project menu on the menu bar.

The items in the Project Manager are organized in an outline-like view that you can expand or collapse. A plus sign appears next to a symbol if there are one or more items of that type in the project. Click the plus sign next to a symbol to see items in the list. Click the minus sign to collapse an expanded list.

Initially, the Project Manager appears as a separate window. You can move the container, resize it, or collapse it so that only the tabs show.

As with toolbars, you can dock the Project Manager by dragging it to the top of your screen or double-clicking the title bar. When the Project Manager is docked, it becomes part of the toolbar area of the window. You can't expand the Project Manager window when it's docked; instead, click on individual tabs to use them. You can also tear off tabs from a docked Project Manager.

You can customize your visual work area by changing your view of the Project Manager or by setting double-click to run files in the Project Manager. For more information, see Customizing the Visual FoxPro Environment.

Tabs

Display items by category. When the Project Manager is collapsed, you can tear off tabs by dragging them away from the Project Manager. To replace a tab, just drag it back to its original position, or click the Close box.

To tear off a tab, collapse the container, select a tab and drag it away from the Project Manager. When a tab is floating, you can access the options on the Project menu by right-clicking the mouse in the floating tab.

If you want the tab to always remain on top, click the pushpin icon at the top of the tab. The tab will remain on top of other Visual FoxPro windows. You can set more than one tab to be "always on top." To remove the "always on top" setting on a tab, click the pushpin icon again.

Expanding/Collapsing Button

Expands and collapses the Project Manager. When the Project Manager is collapsed you can "tear off" tabs by placing the mouse pointer over a tab and dragging it away from the Project Manager.

Items List

Lists the items contained in the project in an outline-like view. Icons appear to the left of the item to identify its type.

The symbol appears next to items that are excluded from the project.

When files are included in the project, they are compiled into a single .app file when the project is built. All included files are read-only at run time. In the Programs, Forms, Queries, or Menus group, the name of the main program file appears in bold.

Project Manager Buttons

New
Creates a new file or object. This button has the same effect as the New File command on the Project menu. The new file or object's type is the same as that of the currently selected item.
Note Files created from the File menu are not automatically included in a project. Files created from the New File command on the Project menu (or the New button in the Project Manager) are automatically included in a project.
Add
Adds an existing file to the project. This button has the same effect as the Add File command on the Project menu. After clicking Add, you can select multiple files by pressing the SHIFT or CTRL key in the Open dialog box while clicking files to add them.
Modify
Opens the selected item in the appropriate designer. This button has the same effect as the Modify File command on the Project menu.
Browse
Opens a table in a Browse window. This command has the same effect as the Browse File command on the Project menu, and is enabled only when a table is selected.
Close
Closes an open database. This command has the same effect as the Close File command on the Project menu, and is enabled only when a table is selected. If the selected database is already closed, this button changes to Open.
Open
Opens a database. This command has the same effect as the Open File command on the Project menu, and is enabled only when a table is selected. If the selected database is already open, this button changes to Close.
Remove
Removes the selected file or object from the project. Visual FoxPro asks you if you want to just remove the file from the project or if you want to remove it from the project and delete it from disk. This command has the same effect as the Remove File command on the Project menu.
Build
Builds a project or application and can also build an executable or Automation server. This command has the same effect as the Build command on the Project menu.
Preview
Displays the selected report or label in Print Preview mode. Enabled when you select a report or label in the Project Manager. This command has the same effect as the Preview File command on the Project menu.
Run
Runs the selected query, form, or program. Enabled when you select a query, form, menu, or program in the Project Manager. This command has the same effect as the Run File command on the Project menu.

See Also

Browse Window | Browse Window | Referencing Modifiable Files | User Interface Creation without Programming | Compiling an Application


Properties Window

Displays properties, events, and methods and their settings for a selected form, data environment, cursor, relation, or control. For more information about how to set values for object properties, events, and methods, see Manipulating Objects.

You can view the value for a read-only property that extends beyond the right edge of the Properties window without widening the window by using the Zoom option.

To view the value for a read-only property

  1. In the Properties window, right-click the property you want to view.
  2. From the shortcut menu, select Zoom.

The Zoom dialog box usually allows you to edit values for read/write properties with the exception of properties such as Visible or ColorSource. Though you can select and copy all or part of a read-only property value in the Zoom dialog box, you cannot edit the value.

Object list

Shows the currently selected object and displays a list of available objects when you click the arrow to the right of the list. This list includes the current form, form set, and all the controls on the form.

If the Data Environment Designer is open, the Object list includes the data environment and all cursors and relationships in the data environment.

Tabs

Display properties, events, and methods by category:

  • All All properties, events, and methods
  • Data Properties associated with what and how data is displayed or manipulated by the object
  • Methods Methods and events
  • Layout All layout properties
  • Other Miscellaneous and user-defined properties

Property Settings Box

Makes it possible for you to change the value of the property that is selected in the properties list.

If the selected property has predefined settings, clicking the arrow appearing to the right of the property settings box opens a list of settings from which you can choose. You can also cycle through settings by double-clicking the property name in the properties list. If the setting requires a file name or a color, clicking the ellipsis (...) button that appears displays the appropriate dialog box or window, such as the color picker dialog box.

The following buttons appear to the left of the property settings box:

  • Cancel (X) Cancels the changes you made to the setting and restores the original value.
  • Accept (check symbol) Confirms changes you made to a setting.
  • Function (Fx symbol) Opens the Expression Builder Dialog Box. You can set literal values or values returned by functions or expressions.

Properties List

This list shows all properties that can be changed at design time and their current settings. To get Help for a specific property, select the property and press F1.

The property settings in the properties list can appear as follows:

  • Property settings that are expressions are prefaced with an equal sign (=).
  • Settings for properties, events, and methods that are read-only appear in italics.
  • Methods and events display inheritance details as follows:
    Default

    -or-

    Inherited cClassname ClassLibrary

    For more information about viewing inherited code for a method or event, see Manipulating Objects.

Keyboard Shortcuts

The following table describes keyboard shortcut commands for the Properties window.

Shortcut | Action
ALT+DOWN ARROW | Opens the drop-down list of objects.
ALT+UP ARROW | Closes the drop-down list of objects.
CTRL+PAGE DOWN or DOWN ARROW or RIGHT ARROW | Moves to next object in the drop-down list of objects.
CTRL+PAGE UP or UP ARROW or LEFT ARROW | Moves to previous object in drop-down list of objects.
CTRL+END | Moves to last object in drop-down list of objects.
CTRL+HOME | Moves to first object in drop-down list of objects.
TAB | Cycles to the next control on the Properties window.
SHIFT+TAB | Cycles to the previous control on the Properties window.
SHIFT+F10 | Displays the appropriate shortcut menu.
CTRL+ALT+letter | Selects the next property in the properties list that begins with the letter character. For example, pressing CTRL+ALT+B selects the next property that begins with B.

See Also

Creating Forms | Customizing Forms | Setting the Data Environment | Creating Reports and Labels | Expression Builder Dialog Box | Form Designer | Data Environment Designer | Viewing and Setting Database Properties | Zoom <property> Dialog Box


Task List Manager Window

Makes it possible for you to keep track of tasks.

The Task List Manager appears when you click Task List on the Tools menu. You can also access the Task List Manager using the _TASKLIST system variable, which references Tasklist.app by default. You can modify this reference on the File Locations tab in the Options dialog box. For more information, see _TASKLIST System Variable or File Locations Tab, Options Dialog Box.

The task list is stored as a table in the FoxTask.dbf file. You can specify a different file using the _FOXTASK system variable. For more information, see _FOXTASK System Variable.

Task List Visual Cues

The Task List Manager indicates important information through visual cues:

Visual cue | Description
Red text | Indicates that the Due Date has passed already.
Black text | Indicates that the Due Date has not yet arrived yet.
Blue text | Indicates that today is the Due Date.
Bold text | Indicates that the task has not been Read yet.
Strikethrough text | Indicates that the task has been Completed.
Red up arrow | Indicates a high Priority task.
Blue down arrow | Indicates a low Priority task.
Icon with arrow | Indicates a Shortcut task.
Icon with person/task | Indicates a User-Defined or Other task.

Task Fields

The Task List Manager includes the following fields:

Field Name | Description | Initially Displayed | Removable | Shortcut Editable | User- Defined Editable
Priority | Dropdown showing priority of task. | X | X | X
Task Completed | Checkbox indicating if task is complete. | X | X | X
Task Type Visual representation of task type (icon). Internally, the types are represented by the following values in the Foxtask Type field:
S - Shortcut
U – User-Defined
O – Other
 X
Contents | Description of the task. | X | X
File Name | Name of file containing the Shortcut or one associated with task. | X | X | X
Due Date | Date when task is scheduled to be completed. | X | X | X | X
Class | Name of class containing the Shortcut or task association. | X | X
Line | Line number of Shortcut or task association. | X | X
Method | Name of method containing the Shortcut or task association. | X | X
Timestamp | Numeric datetime stamp when task was first added. | X
Custom | You can add custom fields for tasks. | X | X | X
Tasklist Options dialog box
Displays options for adding, removing, and browsing custom fields in the Task List Manager. You can also edit the table structure and clean up the Task List table. The Tasklist Options dialog box appears when you right-click the Task List Manager and click Options.
  • New button Creates a new table and displays the Table Designer so you can add new custom fields and their data types. Do not modify the initial UniqueID field in the table definition.
    Note The Fields tab in the Task Properties dialog box treats all custom fields as Character type and does not perform any type validation.
  • Edit Structure button Makes it possible for you to edit the structure of the user-defined columns table.
  • Clear button Removes the custom fields table association from the Task List. The table and its contents are left untouched so that they can be restored later if necessary.
  • Browse button Makes it possible for you to select an existing custom fields table so you can set up an association to the main FoxTask.dbf table.
    Note When a custom fields table has been created, it cannot be altered directly from the Task List Manager. You must do this manually in Visual FoxPro using the Table Designer.
  • Clean Up FoxTask Cleans and packs the underlying Task List table.

See Also

Using the Task List Manager | _TASKLIST System Variable | _FoxTask System Variable | Creating Bookmarks and Task List Shortcuts


Trace Window

Makes it possible for you to see your lines of code as they are being executed.

This window is activated when you choose Trace from the Window Menu, Debugger Window.

Object
Available when running object code. The code in the Trace window is associated with the object displayed in the Object list. The Object list contains all objects contained in the highest-level parent container of the object whose code is currently executing.
Procedure
Available when running object code. The code in the Trace window is associated with the method or event displayed in the Procedure list. The Procedure list contains all methods of the object in the Object list that have code associated with them.

The left area of the Trace window can contain the following symbols:

Symbol | Description
 | Currently executing line of code.
 | Active breakpoint.
 | Inactive breakpoint.
 | Call stack position if you are examining code at a different level than the currently executing code.

See Also

Debugger Window | Debugger Keyboard Shortcuts and Menus | Locals Window | Watch Window | Call Stack Window | Debug Output Window


Visual FoxPro IntelliSense Manager Window

The IntelliSense Manager is an application that can be accessed by the _CodeSense system variable (which by default references FoxCode.app). The IntelliSense Manager makes it possible for you to specify the appearance and behavior of the syntax statements and other tool tip information displayed in properties sheet, editor, and code windows.

You can enable or disable IntelliSense functionality programmatically by setting the _VFP.EditorOptions property value. For more information, see EditorOptions Property.

In the Tools menu, choose IntelliSense Manager, and then make your selections from the following options.

General Tab

Enable IntelliSense check box
Specifies whether to enable or disable IntelliSense in Visual FoxPro. Clearing the Enable IntelliSense check box disables IntelliSense for the current session.
List members drop down
Specifies whether the Auto List Members functionality of IntelliSense is active. If disabled, you can still access List Member IntelliSense from the Editor menu or Ctrl+J keyboard shortcut. For details, see List Members.
Quick info tips drop down
Specifies whether the Auto Quick Info functionality of IntelliSense is active. If disabled, you can still access Quick Info IntelliSense from the Editor menu or Ctrl+I keyboard shortcut. For details, see Quick Info.
Tips command button
Opens a window that displays syntax information as soon as you type enough information to disambiguate a Visual FoxPro command.

Use this for commands and functions that have many clauses or parameters. The Tips window only displays Visual FoxPro command and function information contained in FoxCode.dbf. Class and object IntelliSense is not displayed.

Browse command button
Opens a browse window on FoxCode.dbf (_FOXCODE), which provides the data for the IntelliSense Manager.
Capitalization/Expansion
This section provides ability to control how native Visual FoxPro syntax is capitalized. In addition to standard capitalization options, you can also choose to disable expansion or have it derived from the _FOXCODE default.
Functions drop down
Provides a list of format choices for Visual FoxPro functions. The default is all UPPERCASE.
Commands drop down
Provides a list of format choices for Visual FoxPro commands. The default is all UPPERCASE.
FoxCode Default drop down
Provides a list of format choices for entries in FoxCode.dbf. This is a global default setting that other entries in FoxCode.dbf can use if they do not have their own capitalization setting. This setting is stored in the first version record of FoxCode.dbf.
Apply changes to Visual FoxPro language only check box
Makes it possible for you to specify whether changes are made to all or only Visual FoxPro native commands and functions. These are denoted by the "RESERVED" keyword in the Source field of the FoxCode.dbf file.

Types Tab

Controls the display of data types when specifying strong typing for a variable (such as LOCAL myvar AS). Types can be core intrinsic elements such as string, number, or Visual FoxPro or COM classes. You can add COM or Visual FoxPro classes by clicking the Add Type Library or Add Class command button.

Types list box
You can uncheck a checkbox if you do not want a particular item to appear in the strong typing list. Click on a column header to sort by that column. An asterisk in the third column denotes that the FoxCode.dbf Data field for that item contains script code.
Edit command button
The Edit button makes it possible for you to edit the selected Type reference in the FoxCode.dbf file. You can also double-click on that item in the list box.
Type Libraries command button
Displays the Type Library References dialog box. This dialog box scans your Windows Registry to detect available COM Server and ActiveX Control type libraries. Select type libraries from this dialog box that you want included in your strong typing list.
Classes command button
Makes it possible for you to select a Visual FoxPro class that you want included in your strong typing list.
Web Services command button
Opens the Visual FoxPro XML Web Services Registration dialog box. For details, see Visual FoxPro XML Web Services Registration Dialog Box.

Custom Tab

Makes it possible for you to add your own custom items in FoxCode.dbf. These can include custom shortcuts to provide auto expansion of commands and functions. A property item can be added to serve as a script to execute (such as displaying a custom Value Editor) when one attempts to set the value of a property. You can also add custom scripts to be executed by your items.

Replace text box
Enter the shortcut you want to trigger auto expansion of the With textbox word.
With text box
Enter the word you want the shortcut in the Replace textbox to expand.
Custom list box
Select an item you want to edit. Once selected, the Replace or With values can be changed. You can double-click to edit the item directly in FoxCode.dbf. An asterisk in the third column denotes that the FoxCode.dbf Data field for that item contains script code.
Type drop down
Makes it possible for you to set the type of your custom item.
Script command button
Brings up an edit window to add or edit script for that item.
Edit command button
Displays entire record for that item for editing.
Add command button
Adds a new item with the specified Replace and With textbox values to FoxCode.dbf. The Add button changes to show Replace if you are modifying an existing item in the listbox.
Delete command button
Deletes a custom item.

Advanced Tab

Custom properties
Makes it possible for you to control various special IntelliSense behaviors by specifying custom property values.

Edit Properties command button Opens the Custom Properties dialog box so you can specify the value for Advanced IntelliSense behavior.

Select a property in the Property list, and its description will appear in the Description box. The value of the property is displayed in the Value text box. These custom properties are:

Property | Description | Default Value
lEnableFullSetDisplay | Controls whether TO is automatically added after certain SET commands | T
lHideScriptErrors | Suppresses screen output of IntelliSense script errors | F
lKeywordCapitalization | Enables capitalization and expansion of command keywords | T
lPropertyValueEditors | Enables scripts that trigger value editors for certain properties | T
lExpandCOperators | Enables auto expansion of C type operators, such as ++, --, +=, -+, *=, and /= | T

To change a value, select a property, and type a new value in the Value text box. Closing the Custom Properties dialog box saves the changes.

Maintenance
Makes it possible for you to restore defaults for FoxCode.dbf and the Most Recently Used (MRU) lists, and to perform other IntelliSense maintenance routines

Cleanup command button Opens the Maintenance dialog box.

  • Use the Restore FoxCode command button to re-establish Visual FoxPro IntelliSense defaults. A clean copy of FoxCode.dbf is restored to your system. Custom items are preserved.
  • Use the Cleanup FoxCode command button to remove any records you have marked for deletion from the _FOXCODE table.
  • Use the Cleanup lists command button to remove files from MRU lists that no longer exist.
  • Use the Zap lists command button to zap all content from the MRU list.

See Also

_FOXCODE System Variable | _CodeSense System Variable | List Members | Quick Info | List Values | IntelliSense Overview | Customizing IntelliSense Using FoxCode


Visual FoxPro System Windows

Visual FoxPro System windows are windows provided by Visual FoxPro as part of the product interface. The following table provides details that enable you to access and control these windows.

Window | Code access | Default Docking status
Command | ACTIVATE WINDOW Command | Dockable, undocked
Data Session | SET VIEW ON, ACTIVATE WINDOW VIEW | Dockable, undocked
Document View | ACTIVATE WINDOW Document | Dockable, undocked
Properties | ACTIVATE WINDOW Properties | Dockable, undocked
Debugger | DEBUG ACTIVATE WINDOW Debug[ger] | Undockable
Call Stack | (see note) | in Debugger, Dockable
Debug Output | (see note) | in Debugger, Dockable
Locals | (see note) | in Debugger, Dockable
Trace | (see note) | in Debugger, Dockable
Watch | (see note) | in Debugger, Dockable
Note Individual Debugger windows are dockable only when the Debugger is enabled in the FoxPro Frame. You cannot open the Debugger sub windows, alone, in code unless you first set the Debugger to use the Visual FoxPro Frame. For example, normally if you use ACTIVATE WINDOW "call stack" the entire Debugger opens with the Call Stack window highlighted. If you first set the Debugger to the Visual FoxPro Frame, ACTIVATE WINDOW "call stack" opens the Call Stack window.

See Also

Debug Tab, Options Dialog Box


Watch Window

Makes it possible for you to display expressions and their current values, and set breakpoints on an expression. This window is activated when you choose Watch from the Window Menu, Debugger Window. Visual FoxPro enables IntelliSense in the Watch window but limits support to only List Members.

Watch
The value or expression you want to examine. Type expressions here to add them to the grid of active watch expressions below.
Name
Displays the names of the current watch expressions.
Value
Displays the values of the current watch expressions.
Type
Displays characters that represent the data types of the current watch expressions.

You can select expressions, delete them, or add breakpoints to them.

To create a new watch expression

  • Select text in any Visual FoxPro window and drag it to the Watch window.

To edit a watch expression

  • Double-click the watch expression.

See Also

Debugger Window | Debugger Keyboard Shortcuts and Menus | Call Stack Window


Error Messages

This topic contains information about some of the more common error messages in Visual FoxPro.

In This Section

Error Messages A-Z
Contains a list of error message topics in alphabetical order.
Error Messages by Number
Contains a numeric list of error messages.
Error Message Parameters
Lists the error messages for which you can return the file, field, or variable name as a parameter by using SYS(2018).

Related Sections

Reference
Includes topics on productivity tools, as well as the controls, objects, properties, methods, events, statements, functions, and constants available.
General Reference
Provides Visual FoxPro related technical information, including file types, file structures, and other reference information about Visual FoxPro elements.
Language Reference
Provides a list of language reference topics in alphabetical order
User Interface Reference
Explains the options that appear on various dialog boxes, windows, and other user interfaces. These types of topics generally appear when you press F1 in a dialog box or window.


Error Messages A-Z

Jump to this letter:

A | B | C | D | E | F | G - H | I | J - K | L | M
N | O | P | Q | R | S | T | U | V | W | X - Z
1815 | "cursor" must be created with SELECT ... INTO TABLE.
1832 | "field | variable" is not unique and must be qualified.
1130 | 'field' phrase is not found.
1165 | "field" is not related to the current work area.
1196 | "file" is not a Visual FoxPro .EXE file.
1309 | "file" is not an object file.
1298 | "name" band is too large to fit on page.
1929 | "name" can only be used within a method.
1932 | "name" cannot be closed while suspended.
1794 | "name" cannot be enumerated.
1462 | "name" internal consistency error.
1737 | "name" is a method, event, or object.
1740 | "name" is a read-only property.
226 | "name" is not a file variable.
1992 | "name" is not a function, procedure or program.
225 | "name" is not a variable.
1294 | "name" is not a valid resource file.
1745 | "name" is not a Visual FoxPro event.
232 | "name" is not an array.
1924 | "name" is not an object.
1983 | "name" objects cannot return a value.
1429 | "OLE error".
78 | ** or ^ domain error.
*** | *bad date*
*** | *Interrupted*
1550 | .DBC internal consistency error.
115 | .DIF file header is invalid.
117 | .DIF type indicator is invalid.
116 | .DIF vector is invalid - .DBF field mismatch.
120 | .SYLK file dimension bounds are invalid.
121 | .SYLK file format is invalid.
119 | .SYLK file header is invalid.

A

1727 | A .DBF-style Help file is required.
1771 | A member object with this name already exists.
2024 | A sharing violation occurred.
1538 | A stored procedure is executing.
1961 | A subdirectory or file "name" already exists.
1889 | A table in multiple relationships can only have one child order.
1640 | Access to system Registry denied
2081 | ADODB.Command is already opened.
2080 | ADODB.Recordset is already opened.
2143 | ADODB.Recordset is not opened.
13 | Alias is not found.
24 | Alias name is already in use.
103 | Allowed DO nesting level exceeded.
1870 | ALTER TABLE operation interrupted.
2032 | Ambiguous date/datetime constant.
1211 | An IF | ELSE | ENDIF statement is missing.
1781 | An object's control source cannot be set to its Value property.
2028 | API call caused an exception.
1098 | API function _UserError( ) was called.
1726 | API library is not found.
1711 | API library revision mismatch. Rebuild library.
1178 | Application file "file" is not closed.
1936 | Application object not initialized.
1972 | Array "name" is in use.
230 | Array dimensions are invalid.
1764 | Array is not a member of the parent object.
1974 | Arrays cannot be assigned to array elements.

B

1542 | Base table fields have been changed and no longer match view fields. View field properties cannot be set.
1590 | BEGIN TRANSACTION command failed. Nesting level is too deep.
38 | Beginning of file encountered.
2140 | Both Unicode and IsBinary properties can not be set to .T..
227 | Box dimensions are invalid.
1164 | Browse structure has changed.
1163 | Browse table is closed.

C

2147 | Calling OpenTables or CloseTables is not allowed while either of those methods are in the process of executing.
1651 | CANCEL or SUSPEND is not allowed.
62 | Cannot access characters beyond string.
1106 | Cannot access file "file"; transaction is in progress.
1152 | Cannot access the selected table.
1421 | Cannot activate the OLE server.
1741 | Cannot add "name". Class definition is cyclical.
1755 | Cannot add an object to this class.
1769 | Cannot add this object to a Column.
1768 | Cannot add this object to a Grid.
1537 | Cannot add this table: it belongs to database "name".
*** | Cannot allocate screen map
1672 | Cannot append from password protected file.
1795 | Cannot arrange an untransported form.
1952 | Cannot base a view on itself.
2002 | Cannot build a DLL without OLE public classes.
1689 | Cannot build without a main program.
2012 | Cannot call SetFocus from within a When, Valid, RangeHigh or RangeLow event.
1573 | Cannot change modality of a visible form.
1758 | Cannot change property "name" in SetAll method.
1770 | Cannot clear class "class" because it is in use.
176 | Cannot clear menu that is in use.
177 | Cannot clear popup that is in use.
1951 | Cannot clear the object "object" because it is in use.
2079 | Cannot close or detach extended cursor because it is currently in design mode.
1546 | Cannot close table during execution of a table-bound expression.
1535 | Cannot close this database because it is being used by a project.
1971 | Cannot compile until the current COMPILE command has completed.
102 | Cannot create file "file".
1102 | Cannot create file "file".
2019 | Cannot create offline view on a currently modified view.
*** | Cannot create program workspace.
169 | Cannot define menu item.
1572 | Cannot delete a database object while it is open in a designer.
2030 | Cannot delete file "name".
1307 | Cannot divide by 0.
1871 | Cannot DROP all existing columns.
1754 | Cannot find entry point "name" in the DLL.
1562 | Cannot find object "name" in the database.
*** | Cannot find spell check program.
*** | Cannot find the beautify program.
1944 | Cannot find the builder program.
1798 | Cannot find the converter program.
1693 | Cannot find the menu-generation program.
1791 | Cannot find the text generation program.
*** | Cannot find the spell check program.
*** | Cannot find the wizard program.
1563 | Cannot find view "name" in the current database.
1846 | Cannot GROUP by aggregate field.
1671 | Cannot import from password-protected file.
1547 | Cannot insert an empty row from a view into its base table(s).
1566 | Cannot issue the PACK command on a database while its objects have open cursors.
1720 | Cannot issue the SET FORMAT command while a READ command is in progress on a format file.
1753 | Cannot load 32-bit DLL "name".
1527 | Cannot locate ODBC library, ODBC32.DLL.
1412 | Cannot locate the COMSPEC environment variable.
2006 | Cannot locate your Web browser.
1731 | Cannot modify a base class.
1948 | Cannot modify a class that is in use.
1844 | Cannot nest aggregate functions.
1926 | Cannot nest class definitions.
1254 | Cannot nest key labels.
1337 | Cannot nest the PRINTJOB command.
*** | Cannot open configuration file.
101 | Cannot open file "file".
2013 | Cannot open persistent table buffer directly.
1930 | Cannot redefine "name".
174 | Cannot redefine a menu that is in use.
175 | Cannot redefine popup that is in use.
170 | Cannot release menu item.
1253 | Cannot rename the current directory.
1153 | Cannot rename the file to different device.
1970 | Cannot reopen project file "name".
1976 | Cannot resolve backlink.
2017 | Cannot reuse offline view in different mode.
1191 | Cannot save form: an object has an invalid name.
2045 | Cannot set DBCEventFile property when DBCEvents is off.
1706 | Cannot sort .IDX files in descending order.
2085 | Cannot update ADODB.Recordset because FOX cursor does not have an ADOBookmark column.
2084 | Cannot update ADODB.Recordset because it does not support a Bookmark property.
2083 | Cannot update ADODB.Recordset because it is read-only.
2082 | Cannot update ADODB.Recordset while cursor, created by CursorAdapter.CursorFill method, is not attached to a CursorAdapter object.
1909 | Cannot update project from project metafile.
111 | Cannot update the cursor "cursor", since it is read-only.
1157 | Cannot update the file "file".
292 | Cannot use 0 or negative as the argument for LOG10( ).
1979 | Cannot visually modify a class based on a nonvisual class.
1978 | Cannot visually modify a class of this type.
1502 | Cannot write to the record because it is in use.
1761 | Class "name" already exists.
1434 | Class "name" has not been registered.
1776 | Class "name" is in use.
1752 | Class "name" is in use by MODIFY CLASS.
1576 | Class "name" is not found in the class library.
1762 | Class "name" is not found.
1441 | Class cannot be instantiated because member "name" does not exist
1442 | Class cannot be instantiated because member "name" has wrong # of parameters
1313 | Class creation canceled.
1733 | Class definition "name" is not found.
1950 | Class definition "name" is recursive.
1747 | Class file "name" is invalid.
1746 | Class file name for "name" is not valid.
1751 | Class file version is greater than the current version.
1993 | Class library file "name" is not found.
2029 | Class "name" is not a Form class.
1949 | Class name is invalid.
1914 | Code page number is invalid.
1915 | Collating sequence "name" is not found.
1728 | Color scheme is reserved.
1642 | Color set resource is not found.
1695 | COLUMN | FORM | ALIAS | NOOVERWRITE | WIDTH are only allowed with the FROM clause.
1698 | COLUMN | ROW | ALIAS | NOOVERWRITE | SIZE | SCREEN are only allowed with the FROM clause.
223 | Column number must be between 0 and 255.
1657 | Column number must be between 0 and the right margin.
1579 | Command cannot be issued on a table with cursors in table buffering mode.
1593 | Command cannot be issued within a transaction.
1220 | Command contains invalid character.
36 | Command contains unrecognized phrase/keyword.
1297 | Command is allowed only in interactive mode.
1221 | Command is missing required clause.
1981 | Compile error in file "name".
1252 | Compiled code for this line is too long.
1541 | Connection "name" is busy.
1466 | Connection handle is invalid.
1497 | Connection name is invalid.
1526 | Connectivity error: "name".
1522 | Connectivity internal consistency error.
1725 | Constant is already created with #DEFINE.
1509 | Conversion canceled. Adjust the memo BLOCKSIZE.
2136 | Conversion from Unicode has failed.
1799 | Conversion is canceled.
2135 | Conversion to Unicode has failed.
1168 | Could not add icon to executable file.
1181 | Could not add version resource to executable file.
2033 | CTOD and CTOT can produce incorrect results.
1988 | Currency value is out of range.
2112 | Cursor "name" is attached to another CursorAdapter object.
1166 | Cursor is corrupt or in wrong format.
2078 | CursorAdapter "name" cannot be loaded for design.
2125 | CursorAdapter and XMLTable objects do not belong to the same data session.
2092 | CursorAdapter cannot locate current record in the buffer. The record may have been reverted.
2090 | CursorAdapter does not have an associated cursor.
2138 | CursorAdapter is unable to determine DataSourceType for the operation.
2075 | CursorSchema property is not specified.
44 | Cyclic relation.

D

1966 | Data environment is already loaded.
1967 | Data environment is already unloaded.
2068 | Data environment "name" does not contain a cursor object.
1549 | Data session #number cannot be released with open transaction(s).
1599 | Data session #number was forced to ROLLBACK all transactions to avoid deadlock.
1732 | Data type is invalid for this property.
9 | Data type mismatch.
1534 | Database "alias" is not open.
1569 | Database "name": File access denied.
1561 | Database is invalid. Please validate.
1570 | Database is read-only.
1709 | Database object is being used by someone else.
1773 | Database object type is invalid.
1544 | DataType property for field "name" is invalid.
2035 | Date/datetime contains illegal characters.
2034 | Date/datetime evaluated to an invalid value.
2027 | Declare DLL call caused an exception.
1232 | DIMENSION contains variable declaration without required subscript arguments.
1963 | Directory is not found.
216 | Display mode is not available.
1907 | Drive specifier is invalid.
1156 | Duplicate field names.

E

4 | End of file encountered.
1591 | END TRANSACTION command cannot be issued without a corresponding BEGIN TRANSACTION command.
1214 | ENDTEXT does not have corresponding TEXT statement.
1473 | Environment-level property is invalid.
1957 | Error accessing printer spooler.
1779 | Error adding "name" to the object. Duplicate member/property name.
1112 | Error closing the file.
1941 | Error code is not valid.
1424 | Error copying the OLE object to Clipboard.
1973 | Error creating table: "name".
1423 | Error creating the OLE object.
1735 | Error in the class definition. "Details"
1258 | Error in the PICTURE clause.
1574 | Error initializing application object.
1508 | Error initializing OLE.
1554 | Error instantiating cursor. Table "alias" cannot be opened. Object will be ignored.
1736 | Error instantiating the object "object".
1958 | Error loading printer driver.
1995 | Error loading the data environment. Table is in use.
1881 | Error loading file - record number n. "object" <or one of its members>. "Issue": "error".
2049 | Error loading HtmlHelp 2.0 collection.
1797 | Error occurred in conversion.
1584 | Error reading a property from the database. The property is ignored.
1104 | Error reading file "file".
1296 | Error reading the resource.
1422 | Error saving the OLE object.
2005 | Error with "name" - "property": "error".
1105 | Error writing to file "file".
1445 | EventHandler object "name" does not IMPLEMENT an interface
1977 | Exclusive open required to update this file. Please reopen.
1523 | Execution was canceled by the user.
46 | Expression evaluated to an illegal value.
67 | Expression evaluator failed.
1148 | Expression has been re-entered while the filter is executing.
1759 | Expression is invalid. Use a valid expression for "name" property.
1940 | Expression is not valid outside of WITH/ENDWITH.
1947 | Expression is too complex.
293 | Expression used with ACOS( ) is out of range.
291 | Expression used with ASIN( ) is out of range.

F

*** | Fatal error nExpr reporting error nExpr.
1001 | Feature is not available.
1580 | Feature is not supported for non-.DBC tables.
1953 | Feature is only available if the object is in design mode.
1530 | Fetching canceled; remote table is closed.
1581 | Field "name" does not accept null values.
1088 | Field "name" is read-only.
1582 | Field "name" validation rule is violated.
1647 | Field expression contains an invalid data type.
2142 | Field for Unicode value should not use code page translation.
1913 | Field must be a General field.
350 | Field must be a Memo field.
1712 | Field name is a duplicate or invalid.
2141 | Field size for Unicode value can not be odd number.
1713 | Field width or number of decimal places is invalid.
2014 | Fields marked as update keys will be cleared.
1529 | File "name" already exists as part of a database.
1 | File "name" does not exist.
1553 | File "name" is a database.
1551 | File "name" is an invalid database.
1552 | File "name" is not a database.
1933 | File "name" is not closed.
1558 | File "name" is not part of a database.
1565 | File "name" is part of a database.
1718 | File "name" is read-only.
1190 | File "name" is too large.
1705 | File access is denied.
7 | File already exists.
1184 | File cannot be closed because outstanding references exist.
1503 | File cannot be locked.
108 | File is in use by another user.
3 | File is in use.
1113 | File is not open.
1708 | File is open in another work area.
1338 | File is the wrong version.
1637 | File must be opened exclusively to convert the Memo file.
110 | File must be opened exclusively.
1918 | File name is too long.
1750 | File was created in a later version of Visual FoxPro than the current version.
91 | File was not placed in memory using the LOAD command.
1140 | FILTER expression exceeds allowed size.
1749 | Form (.SCX) file must contain at least one Form.
1991 | Form file "name" is from a previous version of FoxPro. It must be converted to the current format before it can be executed.
1686 | Form file "name" is invalid.
2069 | Forms or Form classes that specify a DEClass and DEClassLibrary cannot be converted to or used with a FormSet.
2043 | Foxcode script "name" failure.
2042 | Foxcode table not found, is not correct version or is incompatible.
2046 | Foxtask table is corrupted or not the correct version.
11 | Function argument value, type, or count is invalid.
1999 | Function is not implemented.
1536 | Function is not supported on native tables.
1525 | Function is not supported on remote tables.
1300 | Function name is missing ).
1304 | Function name is missing (.
1504 | Function not supported for SQL pass-through cursors.
1586 | Function requires row or table buffering mode.

G - H

1986 | GDI memory is low, close one or more windows and try again.
1489 | General fields cannot be used in the WHERE condition of an update statement. Change the WhereType property of the view.
2053 | GroupBy clause is too long.
2050 | Help for this topic/context not implemented.

I

1167 | Icon is corrupt or in wrong format.
1587 | Illegal nested OLDVAL( ) or CURVAL( ).
1910 | Illegal printer driver recursion.
1887 | Illegal recursion in rule evaluation.
1960 | Illegal redefinition of variable "name".
1594 | Illegal to attempt a file lock in a transaction after taking prior record locks.
1679 | Import only Worksheet A for Lotus 1-2-3 version 3.0 files.
1241 | Improper data type in the group expression.
1994 | Include file "name" is not found.
1471 | Incorrect column format.
1470 | Incorrect property name.
1886 | Index does not accept NULL.
114 | Index does not match the table. Delete the index file and re-create the index.
23 | Index expression exceeds maximum length.
19 | Index file does not match table.
1683 | Index tag is not found.
1684 | Index tag or file name must be specified.
2061 | Index or expression does not match an existing member of the collection.
1002 | Input/output operation failure.
1588 | INSERT cannot be issued when row or table buffering is enabled or when integrity constraints are in effect.
1308 | Insufficient stack space.
1443 | Interface "name" not found
1000 | Internal consistency error.
1243 | Internal error: Too many characters in the report.
231 | Invalid argument used with the SET function.
1477 | Invalid call issued while executing a SQLCOLUMNS( ) sequence.
1474 | Invalid call issued while executing a SQLEXEC( ) sequence.
1475 | Invalid call issued while executing a SQLMORERESULTS( ) sequence.
1476 | Invalid call issued while executing a SQLTABLES( ) sequence.
1783 | Invalid class specified for @...Class command.
2048 | Invalid COMATTRIB value for "name"
*** | Invalid compact EXE file. Rebuild EXE.
1959 | Invalid coordinates.
1578 | Invalid database table name.
2098 | Invalid element in XMLTable.Fields collection.
1245 | Invalid expression in label definition file.
1111 | Invalid file descriptor.
1510 | Invalid file format. If this is a dBASE file, it must be converted first. To convert it, type MODIFY LABEL labelfilename.
2146 | Invalid key column name "name".
112 | Invalid key length.
2026 | Invalid locale ID.
2011 | Invalid operation for offline view.
2008 | Invalid operation for offline view while being used online.
2007 | Invalid operation for offline view while offline.
1115 | Invalid operation for the cursor.
*** | Invalid or duplicate field name.
*** | Invalid or missing EXE file.
202 | Invalid path or file name.
1103 | Invalid seek offset.
31 | Invalid subscript reference.
1479 | Invalid update column name "name".
1652 | Invalid use of a Visual FoxPro function as an array.
1223 | Invalid variable reference.

J - K

1124 | Key exceeds allowed size.
1117 | Key field length does not match.
1255 | Key label "label" is invalid.
1257 | Key string is too long.
356 | Keyboard macro file format is invalid.

L

54 | Label file is invalid.
1653 | Label nesting error.
221 | Left margin including indent must be less than the right margin.
21 | Length of variable strings exceeds amount of memory.
1691 | Library file "name" is invalid.
18 | Line is too long.
222 | Line number must be less than page length.
1194 | Link command failed.
1911 | Localized product is required for this environment.
58 | LOG( ): Zero or negative used as argument.
*** | Logical expression required
1662 | Lotus 1-2-3 version 1.0 file format is invalid.
297 | Lotus 1-2-3 version 2.0 file format is invalid.
1678 | Lotus 1-2-3 version 3.0 file format is invalid.

M

355 | Macro is not defined.
1609 | Maximum menu item length (50) is exceeded.
1607 | Maximum menu items allowed (128) is exceeded.
1608 | Maximum menus allowed (25) is exceeded.
1431 | Maximum number of OLE arguments is exceeded.
392 | Maximum record length exceeded in the import file.
1943 | Member "name" does not evaluate to an object.
1760 | Member "name" is a class member.
1975 | Member object "name" has not been instantiated.
1756 | Member object removed – cannot complete the Save operation.
41 | Memo file "name" is missing or is invalid.
55 | Memory file is invalid.
2000 | Memory is low, so streaming output updating has been disabled.
1687 | Menu file is invalid.
178 | Menu has not been activated with ACTIVATE MENU.
179 | Menu has not been activated with ACTIVATE POPUP.
168 | Menu has not been defined with DEFINE MENU.
165 | Menu has not been defined with DEFINE POPUP.
167 | Menu item position must be a positive number.
2051 | Menu item's conditional statement is too long.
1611 | Menu items and titles must be type Character.
287 | Menu size is too small.
181 | Menu specified in ACTIVATE MENU is already in use.
182 | Menu specified in ACTIVATE POPUP is already in use.
164 | Menu title has not been defined with DEFINE PAD.
279 | Menu was not pushed.
1765 | Method contains syntax errors. Method is not saved.
1661 | Microsoft Excel file format is invalid.
1723 | Mismatched #IF/#ELSIF/#ELSE/#ENDIF.
1256 | Mismatched braces in key label.
1724 | Missing #ENDIF.
1193 | Missing .RTT section.
1306 | Missing comma (,).
152 | Missing expression.
1231 | Missing operand.
1670 | Multiplan version 4.0 file format is invalid.
1875 | Multiple warnings occurred performing the requested index modifications.
1710 | MULTISELECT or MOVER clause is not supported for PROMPT style menus.
1145 | Must be a character or numeric key field.
1226 | Must be a file variable.
1225 | Must be a variable or array.
94 | Must specify additional parameters.

N

96 | Nesting error.
1488 | No connection associated with this cursor
1520 | No database is open or set as the current database.
1878 | No default value to DROP.
47 | No fields found to process.
138 | No fields were found to copy.
1492 | No key columns specified for the update table "name". Use the KeyFieldList property of the cursor.
1605 | No menu is defined.
1604 | No menu item is defined.
166 | No menu items have been defined for this menu.
1621 | No menu titles have been defined for this menu.
1964 | No PageFrame or Page is found in FormSet or Form with WindowType set to READ or READ MODAL.
1238 | No PARAMETER statement is found.
1649 | No previous PRINTJOB command to correspond to this command.
1879 | No primary key.
1796 | No records are found for the current platform.
1463 | No result set has been returned by the server.
1877 | No rule to DROP.
1774 | No sheet is found.
1612 | No such menu or menu item is defined.
52 | No table is open in the current work area.
1491 | No update tables are specified. Use the Tables property of the Cursor object.
45 | Not a character expression.
27 | Not a numeric expression.
1439 | Not a ProjectHook class.
15 | Not a table.
1682 | Not a user-defined window.
256 | Not a valid Framework II database/spreadsheet.
255 | Not a valid RapidFile database.
1149 | Not enough memory for buffer.
1150 | Not enough memory for file map.
1151 | Not enough memory for filename.
1600 | Not enough memory to open a table with the USE command.
1696 | NOWAIT/SAVE/NOENVIRONMENT/IN/WINDOW clauses are not allowed with the FROM clause.
39 | Numeric overflow. Data was lost.

O

1766 | Object "name" is not found.
1923 | Object "name" is not found.
1985 | Object already has a data environment; cannot use another one with the SaveAs method.
1744 | Object class is invalid for this container.
1719 | Object file "name" is in use and cannot be removed from memory.
1195 | Object file "file" was compiled in a previous version of FoxPro.
2009 | Object is not an offline view.
1938 | Object is not contained in a "name".
1575 | Object name is invalid.
1942 | Objects cannot be assigned to arrays.
1987 | Objects cannot be programmatically added to the Form Designer's FormSet.
1989 | Objects cannot be programmatically deleted from the Form Designer.
1528 | ODBC entry point missing, "name".
2015 | Offline view must be used online for this command
2010 | Offline views must be used exclusively when being used online.
2003 | OLE Changed Properties stream is the wrong version. Subclassed properties ignored.
1426 | OLE error code 0x"name".
1440 | OLE exception error "name". OLE object may be corrupt.
1427 | OLE IDispatch exception code "name".
1428 | OLE IDispatch exception code "number" from "name": "name".
1420 | OLE object is invalid or corrupted.
1965 | One of the members of this class is based on a nonvisual class. Cannot write .VCX file.
1968 | One of the members of this Form or FormSet is based on a nonvisual class. Cannot write .SCX file.
1436 | Only insertable objects are allowed in General fields.
1885 | Only structural tags can be defined as candidate.
1912 | Operation is invalid for a General field.
34 | Operation is invalid for a Memo, General, or Picture field.
2076 | Operation is not allowed for CursorAdapter.
2077 | Operation is not allowed for CursorAdapter at this time.
107 | Operator/operand type mismatch.
2052 | OrderBy clause is too long.

P

1413 | Page frame cannot be sized that small.
1688 | Paradox file format is invalid.
1767 | Parent object will not allow this property setting for "name".
1217 | Picture error in GET statement.
1108 | Picture too big, corrupt, or in wrong format.
*** | Popup too big, first nExpr entries shown.
1722 | Preprocessor expression is invalid.
1681 | PREVIEW clause is not allowed with OFF/NOCONSOLE or TO PRINT/FILE.
1883 | Primary key already exists.
1567 | Primary key property is invalid; please validate database.
1956 | Printer access denied.
1643 | Printer driver is corrupted.
1644 | Printer driver is not found.
125 | Printer is not ready.
124 | Printer redirection is invalid.
1162 | Procedure "procedure" is not found.
1937 | Procedure file "name" is not found.
*** | Product has not been properly installed.
1202 | Program is too large.
1946 | Project file "name" is in the wrong version.
1685 | Project file is invalid.
1169 | Project file is read-only.
1763 | Property "name" already exists.
2145 | Property "name" has invalid value.
1738 | Property "name" is not a method or event.
1734 | Property "name" is not found.
1757 | Property "name" is protected.
1743 | Property "name" is read-only.
1138 | Property does not have a default value.
1467 | Property is invalid for local cursors.
1468 | Property is invalid for table cursors.
1559 | Property is not found.
1739 | Property setting will not take effect until data environment reloaded.
1560 | Property value is invalid.
1469 | Property value is out of bounds.

Q

2055 | Query Parse Error - Try rebuilding in Query Wizard or by using View Designer Join Tab.
1716 | Queue "queue" is not found.

R

2018 | Reconnect of offline view failed.
109 | Record is in use by another user.
20 | Record is not in index.
130 | Record is not locked.
5 | Record is out of range.
1126 | Record is too long.
1583 | Record validation rule is violated.
1206 | Recursive macro definition.
1880 | Related table is not found in current database.
1882 | Related tag is not found or not primary or candidate.
1183 | Relation already exists.
1555 | Relational expression is not valid.
2016 | Removing a class member is not allowed.
1645 | Report contains a nesting error.
50 | Report file "name" is invalid.
2074 | Result is incompatible with cursor schema.
2060 | RETURN/RETRY statement not allowed in TRY/CATCH.
1592 | ROLLBACK command cannot be issued without a corresponding BEGIN TRANSACTION command.
30 | Row or column position is off the screen.
1598 | Rule and trigger code must balance transaction usage.
1405 | RUN|! Command failed. "Details"
1411 | RUN|! command string is too long.

S

1490 | Saving a converted form as a class is not supported.
1507 | Screen code is too large for available memory.
2139 | SelectCmd is empty.
1851 | Selects are not UNION compatible. "Details"
1715 | Server "server" is not found.
1540 | Session number is invalid.
*** | Source code not found.
*** | Source code out of date.
1890 | SQL: Cannot determine data type of SQL column "column".
1802 | SQL: Cannot locate table
1845 | SQL expression is too complex.
1499 | SQL parameter "name" is invalid.
1493 | SQL parameter is missing.
1465 | SQL pass-through internal consistency error.
1498 | SQL SELECT statement is invalid.
1472 | SQL statement parameter is required for non-prepared SqlExec() calls.
1811 | SQL: Aggregate on non-numeric expression.
1802 | SQL: Cannot locate table.
1806 | SQL: Column "field | variable" is not found.
1819 | SQL: DISTINCT is invalid.
1831 | SQL: Error building temporary index.
1801 | SQL: Error correlating fields.
1818 | SQL: FROM clause is required.
1807 | SQL: GROUP BY clause is invalid.
1803 | SQL: HAVING clause is invalid.
1828 | SQL: Illegal GROUP BY in subquery.
1830 | SQL: Index is not found.
1800 | SQL: Internal error.
1822 | SQL: Invalid aggregate field.
1865 | SQL: Invalid SET expression in UPDATE.
1866 | SQL: Invalid TOP specification.
1810 | SQL: Invalid use of subquery.
1839 | SQL: Operation was canceled.
1808 | SQL: ORDER BY clause is invalid.
1809 | SQL: Out of memory.
1814 | SQL: Queries of this type are not supported.
1820 | SQL: SELECT contains invalid *.
1826 | SQL: SELECT is invalid.
1804 | SQL: Statement is invalid.
1812 | SQL: Statement too long.
1825 | SQL: Subquery is invalid.
1842 | SQL: Subquery nesting is too deep.
1841 | SQL: Too many columns referenced.
1864 | SQL: Too many fields in UPDATE.
1805 | SQL: Too many subqueries.
1834 | SQL: Too many UNIONs.
1867 | SQL: TOP requires an ORDER BY.
1813 | SQL: Use of UNION in subquery is invalid.
1833 | SQL: WHERE clause is invalid.
61 | SQRT argument cannot be negative.
95 | Statement is not allowed in interactive mode.
1931 | Statement is not in a procedure.
1927 | Statement is not valid in a class definition.
1928 | Statement is only valid within a class definition.
1934 | Statement only valid within a method.
1903 | String is too long to fit.
1707 | Structural .CDX file is not found.
1235 | Structure is invalid.
1212 | Structure nesting is too deep.
1860 | Subquery returned more than one record.
1234 | Subscript is outside defined range.
1236 | Suspend program before using RESUME.
1673 | Symphony version 1.0 file format is invalid.
1674 | Symphony version 1.1 file format is invalid.
1242 | Syntax error in the field expression.
10 | Syntax error.

T

228 | Tab stops must be in ascending order.
1548 | Table "alias" has one or more non-structural indexes open. Please close them and retry the Begin Transaction.
1564 | Table "name" already exists in the database.
2091 | Table "name" has become corrupted. The table will need to be repaired before using again.
1577 | Table "name" is referenced in a relation.
1545 | Table buffer for alias "name" contains uncommitted changes.
1596 | Table buffering is not enabled.
1556 | Table cannot be browsed because cursor object is no longer valid.
26 | Table has no index order set.
17 | Table number is invalid.
1690 | Table operation is invalid during indexing.
1589 | Table or row buffering requires that SET MULTILOCKS is set to ON.
1888 | Tag name is too long.
1147 | Target table is already engaged in a relation.
1792 | Text generation is canceled.
2044 | Textmerge is recursive.
1954 | The builder program is already running.
1478 | The ChildOrder property of a relation object in the data environment is no longer valid. The relation is being removed.
2020 | The class file associated with this field cannot be found - class association cleared.
1969 | The clipboard contained one or more objects that could not be added to the container. Those objects were not pasted.
2036 | The current Help file is empty.
1935 | The current object does not inherit from class "name".
1945 | The current object has been released.
2021 | The DataObject cannot be modified in the OLEDragOver or OLEDragDrop event.
1742 | The data source for this object must be a variable reference.
1557 | The database must be opened exclusively.
1997 | The default value for field "name" does not evaluate to the correct type for the field.
1962 | The directory is not empty.
1984 | The fields in table "name" did not match the entries in the database.
1131 | The file specified in the FROM clause is empty.
1699 | The IN clause is not supported for this window.
1998 | The index expression for index "name" contains an invalid reference to a Memo, General, or Picture field.
42 | The LOCATE command must be issued before the CONTINUE command.
1571 | The name "name" is already used for another object. Please choose a different name.
2001 | The name of the object file for "file" is already used by another program in the project.
1793 | The network request is not supported.
1438 | The ActiveX control module failed to register correctly.
*** | The Remote View Wizard was unable to obtain column information for this remote table. This may be the result of an ODBC error, or the remote table may not be owned by the current user.
1524 | The selected printer driver does not support direct access.
2057 | The specified class library does not exist or does not contain a valid member class.
2022 | The specified file or path was not found.
2062 | The specified Key already exists.
2056 | The specified member class does not exist or is of wrong type.
1531 | The table changes cannot be performed as the index or filter expression for index name would be invalid.
2004 | The table file "name" has moved. Please validate database "name" and try again.
1659 | The table has memo fields that cannot be converted while open read-only.
1778 | The table must be converted before appending.
1982 | The TO clause can only be used with modal Forms and FormSets.
1996 | The validation rule for field "name" does not evaluate to a logical or NULL type.
2105 | There is a duplicate field "name" in XML schema.
2104 | There is a duplicate table "name" in XML schema.
1213 | There is a missing keyword in the FOR ... ENDFOR or DO CASE ... ENDCASE command structure.
2023 | There is no application associated with the given filename extension.
56 | There is not enough disk space for "name".
43 | There is not enough memory to complete this operation.
1780 | This array element has been defined as an object and cannot be redefined in the class definition.
1777 | This command is not supported for views.
2116 | This feature requires MSXML4 SP1 or later.
1748 | This file is incompatible with the current version of Visual FoxPro.
1784 | This object is derived from a base class and does not have a parent class.
1782 | This OLE property cannot be an expression.
1521 | This operation not supported for class member objects.
1533 | This property is read-only.
1916 | To use this feature, set CODEPAGE=AUTO in your CONFIG.FPW file and restart Visual FoxPro.
1229 | Too few arguments.
1230 | Too many arguments.
1310 | Too many characters are specified in the PICTURE clause.
1872 | Too many columns.
1694 | Too many extensions are specified.
6 | Too many files open.
1201 | Too many names used.
1250 | Too many PROCEDURE commands are in effect.
1249 | Too many READ commands are in effect.
22 | Too many variables.
1116 | Too many windows open.
1646 | Total field type must be Date or Numeric.
1246 | Total label width exceeds allowed size.
1539 | Trigger failed in "cursor".
2058 | TRY/CATCH/FINALLY/ENDTRY mismatch or error.
1532 | Type conversion is not supported.
1501 | Type conversion is not supported for output parameters.
1543 | Type conversion required by the DataType property for field '"name"' is invalid.
1444 | Type Library "name" not found

U

2101 | Unable to attach object with empty XMLName property.
2103 | Unable to change XMLName property while XMLField object belongs to XMLTable object.
2122 | Unable to close offline view in ADMIN/ONLINE mode inside a transaction.
2102 | Unable to change XMLName property while XMLTable object belongs to XMLAdapter object.
1410 | Unable to create temporary work files.
2133 | Unable to emit XML, two or more cursors use different code pages.
2120 | Unable to infer XML schema.
1717 | Unable to generate a printer driver.
*** | Unable to locate desired version of Visual FoxPro.
2121 | Unable to open offline view in ADMIN/ONLINE mode inside a transaction.
*** | Unable to process error.
1437 | Unable to register the ActiveX control.
2123 | Unable to set external schema location when inline schema is used.
2059 | Unhandled Structured Exception
1884 | Uniqueness of index "name" is violated.
*** | Unknown error code nExpr.
104 | Unknown function key.
1925 | Unknown member "name".
16 | Unrecognized command verb.
1141 | Unrecognized index file revision. Re-create the index.
1595 | Update conflict. Some of your changes in the current row batch were committed. Use TABLEUPDATE( ) with the lForce parameter to commit the update or the manual transaction to roll back the update.
1585 | Update conflict. Use TABLEUPDATE( ) with the lForce parameter to commit the update or TABLEREVERT( ) to roll back the update.
1097 | User-defined functions are not allowed.
2031 | User-interface operation not allowed at this time.
2071 | User Thrown Error

V

2100 | Value of XMLField.XMLName must be used as key value for collection.
2134 | Value of XMLName, XMLNamespace or XMLPrefix property should be a Unicode string.
2099 | Value of XMLTable.XMLName must be used as key value for collection.
12 | Variable "variable" is not found.
1134 | Variable must be in the selected table.
2137 | Vfp.VFPXMLProgId doesn't support cSchemaLocation parameter for XMLUpdateGram().
1494 | View definition has been changed.
1568 | View fields have been changed. The Update and Key field properties have been reset to the default values.
127 | View file is invalid.
1597 | Views require either DB_BUFOPTROW or DB_BUFOPTTABLE.
1922 | Volume does not exist.

W

1485 | Warning: Invalid data conversion(s) starting at record "name".
1486 | Warning: Invalid memo field conversions starting at record "name".
1496 | Warning: No information is available to check remote update conflicts.
1483 | Warning: The connection packet size cannot be set.
1480 | Warning: The connection sync/async mode cannot be set.
1481 | Warning: The connection timeout cannot be set.
1487 | Warning: The connection transaction mode cannot be set.
1495 | Warning: The key defined by the KeyField property for table "alias" is not unique.
1484 | Warning: The next "cExpr" modified records have already been updated remote.
1482 | Warning: The query timeout cannot be set.
1908 | Width or decimal place argument is invalid.
1955 | WIN.INI/registry is corrupted.
1714 | Window "name" has not been defined.
1632 | Window file format is invalid.
215 | Window has not been activated with ACTIVATE WINDOW.
214 | Window has not been defined with DEFINE WINDOW.
332 | Window specified in DEFINE WINDOW has invalid coordinates.
1939 | WITH/ENDWITH mismatch.
1775 | Worksheet "name" is not found.
1680 | Worksheet A for Lotus 1-2-3 version 3.0 file is hidden.

X - Z

2124 | XML document does not have a root element.
2126 | XML document is not a DiffGram.
2096 | XML document is not loaded.
2110 | XML Error: "error"
2128 | XML node does not belong to MSXML4.DOMDocument.
1435 | XML Parse Error
2094 | XML Schema is too complex.
2129 | XMLAdapter object doesn't have associated tables.
2107 | XMLAdapter.ToXML cannot be called while there is a loaded XML document.
2127 | XMLAdapter.XMLName is empty.
2118 | XMLAdapter: fractionDigits must not be greater than or equal to maxLength.
2144 | XMLField object is already associated with XMLTable object.
2109 | XMLTable has child table.
2132 | XMLTable object already has parent or is associated with XMLAdapter object.
2097 | XMLTable object does not have associated fields.
2095 | XMLTable object does not have associated XMLAdapter object.
2130 | XMLTable object with XMLName "name" does not have associated fields.
2108 | XMLTable.Alias is empty.
1772 | You may not change the RecordSource of a BROWSE object.
1127 | You must use a logical expression with a FOR or WHILE clause.
37 | You must use a logical expression with FILTER.

See Also

Error Messages by Number | Error Message Parameters | ERROR Command | ERROR( ) Function


"cursor" must be created with SELECT ... INTO TABLE (Error 1815)

You have tried to use a repackaged cursor as a source for another SELECT statement.

  • Some cursors cannot be used in successive queries.

    Use the INTO TABLE clause of the SELECT - SQL statement instead.


"field | variable" is not unique and must be qualified (Error 1832)

You have referenced a field that exists in more than one table.

For example, if you use the TESTDATA database and issue the following command, the same error occurs because the cust_id field exists in both the customer and orders tables:

SELECT cust_id FROM customer,orders
  • To work around the non-uniqueness of field names, issue the following command:
    SELECT customer.cust_id FROM customer,orders

    For more information, see SELECT - SQL.


"field" is not related to the current work area (Error 1165)

You have issued a command that requires a relation in order to exist.

For example, issuing SET SKIP TO prior to the relation being established would generate this error.

  • Issue SET RELATION prior to issuing the command that failed.


"field" phrase is not found (Error 1130)

The field specified in PROMPT field was not found.

  • You are using a command with a PROMPT clause that references an unknown field.


"file" is not a Visual FoxPro .EXE file (Error 1196)

The .EXE file you specified was not created by Visual FoxPro.

  • Use RUN | ! to run external executable files.


"file" is not an object file (Error 1309)

An attempt was made to load a compiled Visual FoxPro program that doesn't have a proper header.

  • Verify the name of the file you are trying to run using DO.


"name" band is too large to fit on page (Error 1298)

You have attempted to use a report band that is too large to fit on a page.

  • Redesign your report form and try this operation again.

    For more information, see Report Designer.


"name" can only be used within a method (Error 1929)

One of the following commands was used outside of a method: THIS, THISFORM, or THISFORMSET.

  • You used the statement in a procedure, but it can only be used within a method.

    Move the THIS, THISFORM, or THISFORMSET command into the appropriate method.


"name" cannot be closed while suspended (Error 1932)

Issue either RESUME or CANCEL for the stored procedure before re-attempting this operation.


"name" cannot be enumerated (Error 1794)

The FOR EACH comand can only be used to enumerate a Visual FoxPro array, an OLE array, a Visual FoxPro collection, or an OLE collection.


"name" internal consistency error (Error 1462)

Internal product error. Visual FoxPro closes all open files and exits.

  • Visual FoxPro cannot reconcile two opposing internal states in the product.

    Record your recent actions while using Visual FoxPro and then call Microsoft Support.


"name" is a method, event, or object (Error 1737)

name cannot store a value because it is not a property

  • Only properties can store values.

    Verify the property names for the object you are working with (see its Help topic), and then use one of the existing properties or define your own in the New Property dialog box.


"name" is a read-only property (Error 1740)

Read-only properties cannot store values.

  • Only writable properties can store values.

    Verify the property names and attributes for the object you are working with (see its Help topic), and then use one of the existing writable properties or define your own in the New Property dialog box.


"name" is not a file variable (Error 226)

A variable or an array was used where a file variable (table field) is required. For more information, see Fields, or Working with Fields and Records.


"name" is not a function, procedure or program (Error 1992)

An Access method must return an object reference.


"name" is not a valid resource file (Error 1294)

A resource file is corrupted. By default, your resource file is FoxUser (FoxUser.dbf and FoxUser.fpt).

  • FoxUser.dbf, FoxUser.fpt, or one of your default resource files is corrupted.

    Restore your resource files from backup, or exit Visual FoxPro, delete the resource files, and then restart Visual FoxPro.

    To check your default resource file, see the File Locations tab of the Options dialog box or use the SET RESOURCE command.


"name" is not a variable (Error 225)

A file variable (table field) was used where a variable or array is required. For more information, see Variables, Arrays, or Working with Arrays.


"name" is not a Visual FoxPro event (Error 1745)

An event specified in the SET EVENTLIST command isn't a Visual FoxPro event.


"name" is not an array (Error 232)

A variable or file variable (table field) was used where an array is required. For more information, see Variables, Fields, or Working with Fields and Records.


"name" is not an object (Error 1924)

This name was previously defined as something other than an object.

  • You have another occurrence of name.

    Check your code for duplicate instances of name.


"name" objects cannot return a value (Error 1983)

The root object of the form stores the return value from its Unload event with the TO clause of the DO FORM command.

  • Only Form and FormSet objects can return values.

    Make sure the root object is a form or a form set.


"OLE error" (Error 1429)

The Automation server is transmitting an error to Visual FoxPro.

  • This error text was passed to Visual FoxPro from the Automation server.


** or ^ domain error (Error 78)

Negative numbers can only be raised to integer values.

  • The exponentiation operator cannot accept fractional values for negative numbers.

    Use an integer exponent.


*bad date*

The date expression is invalid.


*Interrupted*

Program execution has been halted temporarily.

  • You pressed the ESC key.

    Choose Cancel, Suspend, or Ignore from the error dialog box.


.DBC internal consistency error (Error 1550)

An internal database error has occurred.

  • The database is corrupt.

    Try VALIDATE DATABASE to diagnose or repair the problem.

  • The database container index (.dcx) is corrupt or not synchronized with the database container file (.dbc), usually as a result of an abnormal system shut-down.

    Rebuild the index by closing the database, deleting the index file dbc_name.DCX, and reopening the database.

    If the problem is not corrected, record your recent actions while using Visual FoxPro and then call Microsoft Support.


.DIF file header is invalid (Error 115)

The .dif file header is incorrect.


.DIF type indicator is invalid (Error 117)

The .dif file has an invalid data type indicator.


.DIF vector is invalid - .DBF field mismatch (Error 116)

The .dif file you have attempted to import has an internal conflict between its header and its data.


.SYLK file dimension bounds are invalid (Error 120)

The file you have attempted to import is indicating invalid rows or columns.


.SYLK file format is invalid (Error 121)

The file you have attempted to import is not in a valid SYLK file format.


.SYLK file header is invalid (Error 119)

The file header of the file you have attempted to import has an incorrect SYLK file header.


A .DBF-style Help file is required (Error 1727)

SET HELPFILTER works only with a .DBF-style help file.


A Key cannot be specified when adding an item to this collection. (Error 2064)

You cannot specify a key when adding a new item to a collection in which all items do not have keys. Either all items in a collection have keys or do not have keys. To determine if a collection requires keys, use GetKey(1) and the EMPTY( ) function as follows:

? EMPTY(Collection.GetKey(1))


A Key must be specified when adding an item to this collection. (Error 2063)

You must specify a key when adding a new item to a collection in which all items have keys. Either all items in a collection have keys or do not have keys. To determine if a collection requires keys, use GetKey(1) and the EMPTY( ) function as follows:

? EMPTY(Collection.GetKey(1))


A member object with this name already exists (Error 1771)

You tried to add a member object to a container that already has a member with the same name.

  • Member objects must have unique names within a given container.

    Review your member names.


A sharing violation occurred. (Error 2024)

Another application is using the file that you attempted to drop in an OLE drag-and-drop operation.


A stored procedure is executing (Error 1538)

You have attempted to recompile or unload stored procedures (for example, MODIFY PROCEDURE or CLOSE DATABASES) while in the middle of executing a stored procedure. This is an invalid operation.


A subdirectory or file "name" already exists (Error 1961)

You have chosen a name that already exists.


A table in multiple relationships can only have one child order (Error 1889)

You have specified more than one child order for a table in multiple relationships. This operation is not allowed.


Access to system Registry denied (Error 1640)

You do not have access to the system Registry and cannot perform operations such as creating COM servers. Make sure you are logged on and have the proper access rights.


ADODB.Command is already opened. (Error 2081)

Visual FoxPro requires that an ADO Command objects, State, is equal to adStateClosed, when attempting to pass an ADO Command object to the CursorFill methods Source parameter.


ADODB.Recordset is already opened. (Error 2080)

Visual FoxPro requires that an ADO Recordset is closed when it is being added to a CursorAdapter object. This is because, the CursorFill method attempts to open the ADO Recordset when it is being added. To use an ADO Recordset that is already open, pass it to the Source parameter of the CursorFill method.


ADODB.Recordset is not opened. (Error 2143)

Visual FoxPro requires that an ADO Recordset is opened when it is passed to the CursorFill methods Source parameter.

  • Make sure that the ADO Recordset has been properly opened and that the ADO Recordsets State is set to adStateOpen (1).


Alias is not found (Error 13)

You have attempted to specify an alias that has not been defined. There is no such alias currently in use.


Alias name is already in use (Error 24)

You have attempted to use a table with an alias that is associated with another table already in use.


Allowed DO nesting level exceeded (Error 103)

The DO command limits nesting to 128 levels.


ALTER TABLE operation interrupted (Error 1870)

You have interrupted the ALTER TABLE command during the copying of records to the new record format. Some data might not have been copied. Verify the data.


Ambiguous Date/DateTime constant (Error 2032)

This error occurs when a Date or DateTime does not adhere to the strict format.


An IF | ELSE | ENDIF statement is missing (Error 1211)

See the IF ... ENDIF topic for details on executing commands conditionally.


An object's control source cannot be set to its Value property (Error 1781)

You have attempted to set a control source of an object to itself. Use a valid data source. For more information about setting up data sources, see "Setting up an ODBC Data Source" under the section Installing Visual FoxPro.


API call caused an exception. (Error 2028)

The parameters passed to an API caused an exception in the API.

Make sure that you pass all the necessary parameters to the API and that the parameters are of the proper type.


API function _UserError( ) was called (Error 1098)

A user-supplied error string was displayed.


API library is not found (Error 1726)

You have attempted to issue SET LIBRARY TO or RELEASE LIBRARY, but the library you have specified cannot be found.


API library revision mismatch. Rebuild library (Error 1711)

The API library you are using does not match your version of Visual FoxPro.

  • You are using an older version of an .FLL file.

    Rebuild the .FLL file, or obtain an updated version.

  • The ActiveX control calling the Visual FoxPro API is out of date.

    Rebuild the ActiveX control or obtain an updated version.

For more information, see Accessing the Visual FoxPro API,.


Application file "file" is not closed (Error 1178)

Visual FoxPro was attempting to build an application while a file in the application was already open.

  • All files in the application must be closed before you can build it.

    Close the file and rebuild the application.


Application object not initialized (Error 1936)

The Automation server or type library is not registered correctly.

  • Your registry file is corrupted.

    Remove the registry entry.


Array "name" is in use (Error 1972)

An object attempted to resize the array that contains it.


Array dimensions are invalid (Error 230)

Arrays must have more than 0 and fewer than 65,000 elements.

  • You used an illegal value when you declared the array.

    Use a valid number for the rows and columns of an array. For more information, see DIMENSION..


Array is not a member of the parent object (Error 1764)

Check your array references.


Arrays cannot be assigned to array elements (Error 1974)

Check your assignment names.


Base table fields have been changed and no longer match view fields. View field properties cannot be set (Error 1542)

The name or number of columns in the base table or base view of a view definition have been changed and no longer match the view definition.

  • View properties cannot be loaded into the view cursor.

    Recreate or modify the view to reflect the structure changes in any base tables/views.

  • The lUseCursorSchema parameter for CursorFill method is True (.T.), and the number of fields defined in the CursorSchema property is fewer or greater than the number of fields in the base table.


BEGIN TRANSACTION command failed. Nesting level is too deep (Error 1590)

Transactions may only be nested 5 levels deep.

  • You must end a transaction before another transaction can begin.

    Call END TRANSACTION or ROLLBACK first.


Beginning of file encountered (Error 38)

The record pointer is at the beginning of the file.

  • You have attempted to position the record pointer before the first record in the file.

    Use BOF( ) to test for the beginning of the file.


Both Unicode and IsBinary properties can not be set to .T.. (Error 2140)

Visual FoxPro does not allow for both the Unicode property and the IsBinary property to be set to True (.T.) on the same XMLField object.


Box dimensions are invalid (Error 227)

Row 2, column 2 must be larger than row 1, column 1 when using the @ ... BOX command.


Browse structure has changed (Error 1164)

The structure of a Browse window was changed by a Browse validation routine.


Browse table is closed (Error 1163)

A Browse window was closed by a Browse validation routine.


Calling OpenTables or CloseTables is not allowed while either of those methods are in the process of executing. (Error 2147)

The OpenTables or CloseTables methods cannot be called, in either the BeforeOpenTables or AfterCloseTables events, as these events are not recursive.


CANCEL or SUSPEND is not allowed (Error 1651)

The dBASE IV report or label file you are running calls a SUSPEND. This is not a valid operation in Visual FoxPro.


Cannot access characters beyond string (Error 62)

You have attempted to access characters beyond the last byte of a string variable or table field.


Cannot access file "file"; transaction is in progress. (Error 1106)

Visual FoxPro cannot access the table, index, or memo file because a transaction in progress is not yet complete.

FLOCK( ) and RLOCK( ) usually do not prevent other users from reading the locked information. This message, which scrolls from left to right to indicate that Visual FoxPro is still active, provides compatibility with the Novell transaction tracking system (TTS).


Cannot access the selected table (Error 1152)

You have attempted to select a table outside the 32K work area range or are attempting to reference a file variable in a table that is not open.


Cannot activate the OLE server (Error 1421)

The object cannot be activated.

  • The object is static.

    Link the object to a file.

  • The OLE server (also called Automation server) cannot be accessed.

    Make sure the server application is installed and accessible. Also, make sure there is enough memory to launch the application.


Cannot add "name". Class definition is cyclical (Error 1741)

You have attempted to specify a class in an ADD OBJECT statement whose class definition is the same as the class being defined. For more information, see DEFINE CLASS..


Cannot add an object to this class (Error 1755)

If a class is based on the Control base class, you can only add an object to it if its immediate parent is the CONTROLS class.


Cannot add this object to a Column (Error 1769)

The grid column does not support objects such as forms, form sets, toolbars, and columns.

  • You used the AddObject method on the grid column.

    Use AddObject only for objects that are reasonably represented in a column. If you would like the appearance of a form in the column, save the contents of the form to a container class and add it to the column.


Cannot add this object to a Grid (Error 1768)

You have attempted to execute the Grid.AddObject method to add an object other than a column to the grid.

  • You are trying to add an object to a column, rather than adding a column to the grid.

    To add an object to a column, use the Grid.Column syntax with the AddObject method.


Cannot add this table: it belongs to database "name" (Error 1537)

The operation you have attempted is supported only for free tables. Try again with a file of the correct type: a .dbf file that does not belong to a database.


Cannot allocate screen map

There was not enough memory to run Visual FoxPro.


Cannot append from password protected file (Error 1672)

The file you have attempted to append is encrypted.


Cannot arrange an untransported form (Error 1795)

When you move screens between different FoxPro 2.x platforms, you must transport the screens with the Transporter (TRANSPRT.PRG) before they can be arranged.


Cannot base a view on itself (Error 1952)

You have attempted to modify a view in the View Designer by selecting Add, and then selecting the view being modified as a base view from the dialog box. This is not a valid operation.


Cannot build a DLL without OLE public classes (Error 2002)

The BUILD DLL command requires that OLE public classes be defined.

  • You chose the wrong option from the Build Options dialog box.

    Choose another action, such as Build Application.

  • No OLE public classes are defined.

    Define one or more OLE public classes. For more information, see the Class Info dialog box or the OLEPUBLIC clause of the DEFINE CLASS command.


Cannot build without a main program (Error 1689)

The main program in the specified project cannot be found or has not been set.

  • Projects must have a main program.

    For more information, see Set Main on the Project menu.


Cannot call SetFocus from within a When, Valid, RangeHigh or RangeLow event (Error 2012)

The SetFocus method conflicts with these events, which are testing to see if the object can get or lose focus.

  • You are calling SetFocus from a When event.

    Call SetFocus from the GotFocus event instead.

  • You are calling SetFocus from a Valid, RangeHigh, or RangeLow event.

    Call SetFocus from the LostFocus event instead.


Cannot change modality of a visible form (Error 1573)

The nStyle parameter of the Show method cannot be changed while a form is visible.

  • You are calling a form's Show method with a parameter while the form is visible.

    Change the modality of the form while it is not visible by using code similar to the following:

    Form1.Hide
Form1.Show(nStyle)


Cannot change property "name" in SetAll method (Error 1758)

The Name and TabIndex properties must have unique values and cannot be set with the SetAll method.


Cannot clear class "class" because it is in use. (Error 1770)

The class specified cannot be deleted from a .vcx library file while the class definition is in use. This error can occur when using the REMOVE CLASS command, the OVERWRITE clause of the ADD CLASS command, or the RENAME CLASS command.

  • Issue CLEAR ALL to remove all references to the class and try again.


Cannot clear a menu that is in use (Error 176)

You have attempted to clear an active menu.

  • The CLEAR MENU and RELEASE MENU commands cannot be applied to active menus.

    Use DEACTIVATE MENU before clearing or releasing the menu.


Cannot clear a popup that is in use (Error 177)

You have attempted to clear an active menu.

  • The CLEAR POPUP and RELEASE POPUP commands cannot be applied to active menus.

    Use DEACTIVATE POPUP before clearing or releasing the menu.


Cannot clear the object "object" because it is in use. (Error 1951)

Method or event code is currently running for the object. This message can also occur when attempting to remove class definitions from memory with the CLEAR ALL command.

  • Interrupt the running code or wait until it completes before clearing memory.


Cannot close or detach extended cursor because it is currently in design mode. (Error 2079)

This occurs if the cursor in the system data session is inadvertently closed.


Cannot close table during execution of a table-bound expression (Error 1546)

Do not attempt to close tables during this operation.


Cannot close this database because it is being used by a project (Error 1535)

You have attempted to close a database container that a project is using to display data.

  • The database must remain open while the project is open.

    Leave the database open, or close the project.


Cannot compile until the current COMPILE command has completed (Error 1971)

You have attempted to compile code while another compilation was in progress. The compiler can complete only one thing at a time.


Cannot create file "file" (Error 102)

The operating system cannot create the specified file for the following possible reasons:

  • The disk or directory is full.

    Remove files and try again.

  • You do not have access to the target directory.

    Check your permission level.

  • You specified an invalid file name.

    Check for typing mistakes.


Cannot create file "file" (Error 1102)

The operating system cannot create the specified file for the following possible reasons:

  • The disk or directory is full.

    Remove files and try again.

  • You do not have access to the target directory.

    Check your permission level.

  • You specified an invalid file name.

    Check for typing mistakes.


Cannot create offline view on a currently modified view (Error 2019)

CREATEOFFLINE is not a valid operation.

  • You are modifying the view in the View Designer..

    Close the view and try CREATEOFFLINE again.


Cannot create program workspace.

Visual FoxPro was not able to create enough workspace at startup.

  • The disk or directory is full.

    Remove files and try again.

  • You do not have access to the target directory.

    Check your permission level.


Cannot define menu item (Error 169)

You have attempted to add a menu bar to a menu item that was defined with files or structure.


Cannot delete a database object while it is open in a designer (Error 1572)

A view or connection is open in a designer.

  • You tried to delete the view or connection in the Command window or from the Database Designer.

    Close the View Designer or the Connection Designer first.


Cannot delete file "name". (Error 2030)

Visual FoxPro is unable to delete a file. For example, Visual FoxPro cannot delete a file if the file is marked as read-only.


Cannot divide by 0 (Error 1307)

You specified 0 (zero) as the second argument in the MOD( ) function.


Cannot DROP all existing columns (Error 1871)

An existing table must have at least one column.


Cannot find entry point "name" in the DLL (Error 1754)

The dynamic link library (DLL) entry point that you have declared is invalid. Check both the name of the entry point and the name of the DLL.


Cannot find object "name" in the database (Error 1562)

A reference has been made to a database object that cannot be found in the database. Use DISPLAY DATABASE or LIST DATABASE to confirm the names of the existing database objects.


Cannot find spell check program.

The spelling check program cannot be found.

  • The _SPELLCHK system variable does not contain a valid file name.

    Verify the value of _SPELLCHK.


Cannot find the beautify program.

Visual FoxPro cannot find the program called BEAUTIFY.APP because the program was either deleted, renamed, or moved out of the main Visual FoxPro directory. You can:

  • Run Visual FoxPro Setup to install BEAUTIFY.APP.


Cannot find the builder program (Error 1944)

The builder application cannot be found.

  • The _BUILDER system variable does not contain a valid file name.

    Verify the value of _BUILDER.


Cannot find the converter program (Error 1798)

The converter application cannot be found.

  • The _CONVERTER system variable does not contain a valid file name.

    Verify the value of _CONVERTER.


Cannot find the menu-generation program (Error 1693)

The programs that create menus and screens (GENMENU and GENSCRN, respectively) cannot be located.


Cannot find the spell check program.

Visual FoxPro cannot find the program called SPELLCHK.APP because the program was either deleted, renamed, or moved out of the main Visual FoxPro directory. You can:

  • Run Visual FoxPro Setup to install SPELLCHK.APP.


Cannot find the text generation program (Error 1791)

The program that generates text versions of binary files for source control cannot be located.

  • The _SCCTEXT system variable does not contain a valid file name.

    Verify the value of _SCCTEXT.


Cannot find the wizard program.

Visual FoxPro cannot find the program called WIZARD.APP because the program was either deleted, renamed, or moved out of the main Visual FoxPro directory. You can:

  • Run Visual FoxPro Setup to install WIZARD.APP.


Cannot find view "name" in the current database (Error 1563)

The name you have specified is not the name of a view in the current database. Check that the name entered is correct and that the current database is the required database. Use DISPLAY VIEWS or LIST VIEWS to confirm the names of the existing database views.

If the view name is in the list, the .dbc index might be corrupted.

To rebuild the index

  1. Close the database.
  2. Delete the index file (database_name.DCX).
  3. Re-open the database.
  4. Re-create the index.


Cannot GROUP by aggregate field (Error 1846)

You have attempted to use an aggregate function (MIN( ), MAX( ), SUM( ), AVG( ), COUNT( ), NPV( ), STD( ) or VAR( )) in a GROUP clause.


Cannot import from password-protected file (Error 1671)

The file you have attempted to import is encrypted.


Cannot insert an empty row from a view into its base table(s) (Error 1547)

While a view is updating, a new empty record (with no modified fields) is being inserted into one of the base tables of the view.

Make sure each record inserted from a view into a base table has at least one field that has been modified in the view prior to the view update.


Cannot issue the PACK command on a database while its objects have open cursors (Error 1566)

Close all database tables before issuing the PACK command.


Cannot issue the SET FORMAT command while a READ command is in progress on a format file (Error 1720)

The format file you have specified calls upon a format file currently in use.


Cannot load 32-bit DLL "name" (Error 1753)

The dynamic link library (DLL) file is missing or invalid.


Cannot locate ODBC library, ODBC32.DLL (Error 1527)

The file ODBC32.DLL cannot be found.

  • This file must be in the current path to use connectivity features.

    If the file is not on your system, reinstall the ODBC component of Visual FoxPro. If present, copy the file to your default system directory.


Cannot locate the COMSPEC environment variable (Error 1412)

Visual FoxPro can't find an environment variable it needs. This error usually occurs when you try to run Visual FoxPro from within another program and MS-DOS environment variables are passed improperly.


Cannot locate your Web browser (Error 2006)

Visual FoxPro could not run the Web START command for the Web location you chose.

  • There is no Web browser available on your machine.

    Install (or re-install) a Web browser.


Cannot modify a base class (Error 1731)

You have attempted to modify a Visual FoxPro base class.

To make modifications, you must first define your own subclass based on the Visual FoxPro base class.


Cannot modify a class that is in use (Error 1948)

You have attempted to modify a class that is currently in use.

Use CLEAR CLASS to release the class definition from memory and try again.


Cannot nest aggregate functions (Error 1844)

Nesting of the aggregate functions MIN( ), MAX( ), and/or the CALCULATE command sub functions: AVG( ), CNT( ), MAX( ), MIN( ), NPV( ), STD( ), SUM( ), or VAR( ), is not permitted.


Cannot nest class definitions (Error 1926)

A class definition cannot contain another class definition.


Cannot nest key labels (Error 1254)

You cannot nest key labels.


Cannot nest the PRINTJOB command (Error 1337)

After encountering a PRINTJOB command, an ENDPRINTJOB command was not found before another PRINTJOB command was encountered.


Cannot open configuration file.

Visual FoxPro found a configuration file but did not have the proper rights to open it.


Cannot open file "file". (Error 101)

Visual FoxPro cannot open the file specified. The file might be locked by another user on a network.


Cannot open persistent table buffer directly (Error 2013)

The change buffer (.TBF) file for an offline view cannot be opened directly.

Only the .dbf file corresponding to the offline view can be opened.


Cannot redefine "name" (Error 1930)

You have tried to assign a value to THIS, THISFORM, THISFORMSET, or a reserved system variable. For more information, see Reserved Words.


Cannot redefine a menu that is in use (Error 174)

You have attempted to issue a DEFINE MENU command while the menu is active in memory.

Issue a DEACTIVATE MENU command first.


Cannot redefine popup that is in use (Error 175)

You have attempted to issue a DEFINE POPUP command while the menu is active in memory.

Issue a DEACTIVATE POPUP command first.


Cannot release menu item (Error 170)

You have attempted to release a prompt that was defined with files or structure.


Cannot rename the current directory (Error 1253)

The directory you have flagged in the Filer could not be renamed.


Cannot rename the file to different device (Error 1153)

To move the file to another drive, use COPY FILE.


Cannot reopen project file "name" (Error 1970)

Visual FoxPro attempted to open the project you left open in the previous session.

  • The project no longer exists. If the project exists but cannot be opened, it might be corrupted.

    Locate a valid project, or ignore the message.


Cannot resolve backlink (Error 1976)

Visual FoxPro was unable to successfully match a table with its database.

Use VALIDATE DATABASE to verify the links in the database.


Cannot reuse offline view in different mode (Error 2017)

Offline views can only be opened in the mode they were originally created.

  • You opened an offline view online inside a transaction and then attempted to open it offline.


Cannot save form: an object has an invalid name (Error 1191)

Objects must be named correctly before the form can be saved.

  • One or more object names are set to the empty string.

    Search for Name properties set to "".


Cannot set DBCEventFile property when DBCEvents is off. (Error 2045)

You have tried to use DBSETPROP( ) without setting DBCEvents On.


Cannot sort .IDX files in descending order (Error 1706)

.IDX index files do not support a DESCENDING clause.


Cannot update ADODB.Recordset because FOX cursor does not have an ADOBookmark column. (Error 2085)

Visual FoxPro requires that a cursor is associated with an ADO Recordset, if it is to be used to update an ADO Recordset.

  • To verify a cursor is associated with an ADO Recordset check its SourceType property by using the CursorGetProp( ) function. Valid values for the SouceType property are 4, 104, and 204.


Cannot update ADODB.Recordset because it does not support a Bookmark property. (Error 2084)

Occurs when the supplied ADO Recordset does not support bookmarks. This is data source dependant.

  • Make sure the ADO Recordset is configured to support updates.


Cannot update ADODB.Recordset because it is read-only. (Error 2083)

Occurs when the supplied ADO Recordset is in a non-updateable configuration and is set as the data source.

  • Make sure the ADO Recordset is configured to support updates. The ADO Recordset must typically have its CursorType property be adOpenKeyset, adOpenDynamic, or adOpenStatic, and its CursorLocation property must typically be adUseClient.


Cannot update ADODB.Recordset while cursor, created by CursorAdapter.CursorFill method, is not attached to a CursorAdapter object. (Error 2082)

Visual FoxPro requires a cursor, created from an ADO Recordset using the CursorFill method, to be attached to a CursorAdapter object, before it can be updated.

  • To update the cursor, reattach the cursor to the CursorAdapter object.


Cannot update project from project metafile (Error 1909)

There is a conflict in the project metafile (.PJM file).

  • You edited the .PJM file directly.

    Restore the file to a previous version and use the interface to make changes: undo the checkout of the .PJM file and update the project list.

  • There is a conflict in the project information section of the .PJM file.

    Resolve the conflict by removing complete lines only, if possible.

  • The formatting in the project metafile is incorrect.

    For example, some information has an unexpected data type, or commas are misplaced.


Cannot update the cursor "cursor", since it is read-only. (Error 111)

Visual FoxPro cannot update the specified cursor because it is read-only. This can occur when attempting to write to a file created or accessed for read-only purposes.


Cannot update the file "file" (Error 1157)

Visual FoxPro cannot update the specified file. A critical error occurred while writing to the disk, such as lack of disk space or read/write failure.


Cannot use 0 or negative as the argument for LOG10( ) (Error 292)

A zero or a negative number has been used as the argument for a base-10 logarithm. For more information, see LOG10( ).


Cannot visually modify a class based on a nonvisual class (Error 1979)

You have attempted to modify a class that was defined in a program. You must use the Class Designer to modify classes based on base classes or classes defined in .vcx files.


Cannot visually modify a class of this type (Error 1978)

You have attempted to create a class based on one of the Cursor, DataEnvironment, Page, Column, Header, or Relation base classes. You cannot visually modify any of these base class types.


Cannot write to the record because it is in use (Error 1502)

Visual FoxPro could not write to the selected record because it is in use.


Class "name" already exists (Error 1761)

The ADD CLASS or RENAME CLASS command was issued with a class name that already exists in the class library.


Class "name" has not been registered (Error 1434)

You have attempted to use a form that contains an OLE object whose server has not been installed on the current machine.


Class "name" is in use (Error 1776)

The class specified with the SaveAsClass method already exists and is in use elsewhere.

Issue CLEAR ALL to free the class and allow it to be overwritten.


Class "name" is in use by MODIFY CLASS (Error 1752)

You have attempted to use a class that is currently being edited in the Class Designer.


Class "name" is not a Form class. (Error 2029)

The class you specify in the AS clause of CREATE FORM must be based on a Form class.


Class "name" is not found (Error 1762)

The REMOVE CLASS command specified a class name that does not exist in the class library.


Class "name" is not found in the class library (Error 1576)

The class you have specified cannot be found.

Make sure you are using the correct class name.


Class cannot be instantiated because member "name" does not exist (Error 1441)

When using IMPLEMENTS, you have tried to use a member not included in the definition for this class.


Class cannot be instantiated because member "name" has wrong # of parameters (Error 1442)

When using IMPLEMENTS you have specified an incorrect number of parameters for this class.


Class creation canceled (Error 1313)

While attempting to create a class based on an ActiveX control, you canceled the dialog box.


Class definition "name" is not found (Error 1733)

The class definition specified in a CREATEOBJECT( ) function cannot be located.


Class definition "name" is recursive (Error 1950)

You have attempted to create an instance of one class that depends on another class that depends on the first class.


Class file "name" is invalid (Error 1747)

The visual class library (.vcx) file is corrupt and must be restored from a backup file or recreated.


Class file name for "name" is not valid (Error 1746)

A class stored in a visual class library (.vcx) file, based on a class that is also stored in a .vcx file, has been given a name that exceeds the maximum allowable file name length.


Class file version is greater than the current version (Error 1751)

You have attempted to use a visual class library (.vcx) file that was created by a later version of Visual FoxPro than the version you are currently using.


Class library file "name" is not found (Error 1993)

The visual class library (.vcx) file specified in the RELEASE CLASSLIB or CLEAR CLASSLIB command is not in the SET CLASSLIB list.


Class name is invalid (Error 1949)

The class name you have specified is not valid or does not exist.


Code page number is invalid (Error 1914)

The code page number you have specified (related to the country and language being used) is not valid for this version of Visual FoxPro. Verify that the code page number is correct. Localized versions can have support for additional code pages in the optional .INT file.


Collating sequence "name" is not found (Error 1915)

This error occurs when attempting to use a collating sequence that is not supported by the current code page. The collating sequence assigned with SET COLLATE command or the COLLATE clause in the CREATE TABLE - SQL, ALTER TABLE - SQL, or INDEX commands must be a valid Visual FoxPro collating sequence.

You must specify a compatible code page in your Visual FoxPro configuration file. For example, you might see the error, "Collating sequence "CZECH" is not found" when you issue the command:

SET COLLATE TO "CZECH"

To enable support for the CZECH collating sequence, add the following line of code to your Config.fpw file and restart Visual FoxPro:

CODEPAGE = 1250

For more information about collating sequences, see the SET COLLATE Command for valid collating sequences and Optimization of International Applications.


Color scheme is reserved (Error 1728)

Color schemes are included for backward compatibility only. Color schemes 13 through 16 are reserved. User-defined color schemes are numbers 17 through 24.


Color set resource is not found (Error 1642)

You have attempted to SET COLOR SET TO a color set not found in the current resource file. Verify the current resource file with SYS(2005).


COLUMN | FORM | ALIAS | NOOVERWRITE | WIDTH are only allowed with the FROM clause (Error 1695)

These options are available only when you create a quick report with the FROM clause.


COLUMN | ROW | ALIAS | NOOVERWRITE | SIZE | SCREEN are only allowed with the FROM clause (Error 1698)

These options are available only when you create a quick screen with the FROM clause.


Column number must be between 0 and 255 (Error 223)

The printer column number specified is out of range.


Column number must be between 0 and the right margin (Error 1657)

There was an attempt to set the _PCOLNO system variable to an invalid number. This system variable is included for backward compatibility. For better results in the current version, use the Report Designer.


Command cannot be issued on a table with cursors in table buffering mode (Error 1579)

Change the buffering mode to a non-table mode before executing this command.


Command cannot be issued within a transaction (Error 1593)

You must end all open transactions with END TRANSACTION or ROLLBACK before issuing this command. Visual FoxPro won't allow anything that modifies a database (.dbc) to be part of a transaction. The following commands are illegal within a transaction:

  • CLEAR ALL
  • CLOSE ALL
  • CLOSE DATABASE
  • CLOSE TABLES
  • COPY INDEXES
  • CREATE / DELETE / MODIFY DATABASE
  • CREATE / DELETE / MODIFY VIEW
  • CREATE / DELETE TRIGGER
  • CREATE / DELETE / MODIFY CONNECTION
  • APPEND / MODIFY / COPY PROCEDURES

The following commands are not legal for transaction-participating tables:

  • ALTER TABLE
  • CREATE TABLE (of a table in a database container)
  • DELETE TAG
  • INDEX ON
  • INSERT (non-SQL)
  • MODIFY STRUCTURE
  • PACK
  • TABLEREVERT( )
  • Turning off table buffering (by changing the Buffering property from 3 or 5 to 1, 2, or 4 with the CURSORETPROP( ) function).
  • Closing a table (by issuing the USE command in the work area of a transaction-participating table)
  • ZAP


Command contains invalid character (Error 1220)

The source line contains an invalid character. This is probably caused by control characters embedded in the source line by an external editor.


Command contains unrecognized phrase/keyword (Error 36)

A phrase beginning with an invalid keyword was used in a command line.


Command is allowed only in interactive mode (Error 1297)

You are attempting to use a command that is only allowed in interactive mode. This command can be issued only through the Command window.


Command is missing required clause (Error 1221)

A command was used without a clause that was required by the Visual FoxPro syntax. Select the command and press F1 to get context-sensitive Help on the command.


Compile error in file "name" (Error 1981)

You have attempted to add stored procedures to a database with the FROM clause of the APPEND PROCEDURES command, from a file which cannot be successfully compiled. Check that the file contains valid code.


Compiled code for this line is too long (Error 1252)

The object code produced for this statement exceeded the size of the Visual FoxPro internal code buffer.

  • This line contains too many long expressions.

    Subdivide the line into multiple statements.


Connection "name" is busy (Error 1541)

This remote connection is in use by another executing statement.

Wait until it completes or cancel it before retrying this operation.


Connection handle is invalid (Error 1466)

The connection handle supplied is invalid.

Use SQLCONNECT( ) or SQLSTRINGCONNECT( ) to generate a valid connection handle.


Connection name is invalid (Error 1497)

The name you have specified is not the name of a view in the current database.

Check that the name entered is correct and that the current database is the required database.


Connectivity error: "name" (Error 1526)

An ODBC error has occurred. Visual FoxPro provides this message as a wrapper for the actual ODBC error. The ODBC error can be generated by the ODBC driver manager, by the ODBC driver, or by the back-end data server. AERROR( ) returns the ODBC errors. The format of an ODBC error 1526, as returned by AERROR( ), is as shown in the following table:

Element number | Description
1 | Numeric. Contains 1526.
2 | Character. The text of the error message.
3 | Character. The text of the ODBC error message.
4 | Character. The current ODBC SQL state.
5 | Numeric. The error number from the ODBC data source.
6 | Numeric. The ODBC connection handle.
7 | The null value.

The ODBC error message (element number 3) contains the source of the error as the last name in the list preceding the actual error text.

Use the ODBC state code (element number 4) to look up the error in the ODBC book (Programmer's Reference).

For a server error, the data source error is set (element number 5). Use it to look up the error in the server documentation.


Connectivity internal consistency error (Error 1522)

Internal connectivity error.

If this error occurs, record your recent actions while using Visual FoxPro and then call Microsoft Support.


Constant is already created with #DEFINE (Error 1725)

The constant has already been defined with #DEFINE.

Use #UNDEF to release it before redefining.


Conversion canceled. Adjust the memo BLOCKSIZE (Error 1509)

You are trying to convert a dBASE table with a memo blocksize less than 512K.

To successfully convert the file for Visual FoxPro, go back to dBASE and adjust the memo blocksize to greater than, or equal to, 512K.


Conversion from Unicode has failed. (Error 2136)

Occurs when a problem is encountered while Visual FoxPro attempts to convert an Unicode string to an ANSI character.

  • Examine your data, table, and field names to insure that they contain values that Visual FoxPro can convert properly to ANSI character.


Conversion is canceled (Error 1799)

The conversion has been canceled. The files involved might not be converted.


Conversion to Unicode has failed. (Error 2135)

Occurs when a problem is encountered while Visual FoxPro attempts to convert a string to Unicode.

  • Examine your data, table, and field names to insure that they contain values that Visual FoxPro can convert property to Unicode.


Could not add icon to executable file (Error 1168)

You have specified an invalid icon file (.ICO) while creating your distributable, executable files.


Could not add version resource to executable file (Error 1181)

The resource could not be added to the executable file at build time.

  • The resource might be corrupt.

    Recreate the resource.

  • You might have used a letter in the VersionNumber property cBuildNumber setting.

    Use only numbers for the cBuildNumber setting.


CTOD and CTOT can produce incorrect results. (Error 2033)

This error occurs for the same reasons as error 2032, but CTOD( ) and CTOT( ) may be non-compliant or ambiguous.


Currency value is out of range (Error 1988)

The maximum size of a numeric or float field is 20 digits.


Cursor "name" is attached to another CursorAdapter object. (Error 2112)

Visual FoxPro does not allow a cursor to be attached to a CursorAdapter object if it is already associated with another CursorAdapter object.

  • To check if a cursor is already attached to a CursorAdapter, check its SourceType property by using the CursorGetProp( ) function.


Cursor is corrupt or in wrong format (Error 1166)

You have attempted to set the DragIcon property to an invalid .CUR file. A valid .CUR file must include an uncorrupted black and white cursor.


CursorAdapter "name" cannot be loaded for design. (Error 2078)

Visual FoxPro cannot instantiate the cursor adapter.


CursorAdapter and XMLTable objects do not belong to the same data session. (Error 2125)

Occurs when a CursorAdapter object and an XMLTable are created in different data sessions.

  • Make sure that the CursorAdapter object and the XMLTable are created in the same data session before they are used together.


CursorAdapter cannot locate current record in the buffer. The record may have been reverted. (Error 2092)

Occurs when Visual FoxPro cannot find an inserted, deleted or modified record in the buffer.

  • Make sure other operations are not changing the field state of modified records.


CursorAdapter does not have an associated cursor. (Error 2090)

Occurs when calling an operation that requires an attached cursor, but there is not an associated cursor for the CursorAdapter object.

  • Check to make sure that the CursorAdapter object has an associated cursor.


CursorAdapter is unable to determine DataSourceType for the operation. (Error 2138)

The DataSourceType property must be specified.

  • Make sure the DataSourceType property has been specified for the CursorAdapter object.
  • Make sure the UseDeDataSource property is set to True (.T.).
  • Check to make sure the DataSourceType property for the associated DataEnvironment object is correctly set.


CursorSchema property is not specified. (Error 2075)

If the data environment contains a cursor adapter, but the cursor adapter does not contain valid data in CursorSchema property, the Data Environment Designer does not open.

  • Check that the cursor adapter's CursorSchema property contains valid data.


Cyclic relation (Error 44)

A circular relationship was attempted by defining a sequence of relations that eventually points back to a table that is already related.


Data environment "name" does not contain a cursor object. (Error 2068)

The Data Environment Designer does not open if the DataEnvironment class does not contain a CursorAdapter or Cursor object.


Data environment is already loaded (Error 1966)

You are invoking the OpenTables method of the data environment and the data environment is already loaded.


Data environment is already unloaded (Error 1967)

The form is attempting to close tables as it shuts down.

  • AutoCloseTables is set to true (.T.).

    Don't programmatically close the data environment tables.

  • The CloseTables method is being called before the form is closed.

    Set AutoCloseTables to false (.F.).


Data session #number cannot be released with open transaction(s) (Error 1549)

A data session-based object is being closed while there are open transactions. The data session will remain active.

Close the data session by issuing SET DATASESSION TO number followed by the appropriate number of END TRANSACTION or ROLLBACK commands.


Data session #number was forced to ROLLBACK all transactions to avoid deadlock (Error 1599)

A deadlock was detected from another data session attempting to lock an index or memo file held by data session #number. A forced ROLLBACK was completed, leaving data session number in an error state.

Issue the appropriate number of ROLLBACK commands to clear the error state. These situations can be avoided by setting SYS(3052) on for index and memo files.


Data type is invalid for this property (Error 1732)

Data type mismatch.

  • The value specified for the property is not the correct data type.

    For more information, see Data and Field Types.


Data type mismatch (Error 9)

An expression is invalid because it is composed of data types that Visual FoxPro cannot evaluate together.

  • You have either specified an inappropriate data type, or the two fields specified in an operation between two tables (such as UPDATE, REPLACE, SET RELATION) did not have the same data type.


Database "alias" is not open (Error 1534)

You have attempted to SET DATABASE TO a database that is not yet open.

Try OPEN DATABASE first.


Database "name": File access denied (Error 1569)

You have attempted to write to a write-protected database container (.dbc) file.


Database is invalid. Please validate (Error 1561)

Visual FoxPro has detected a problem with the structure of the database.

Try running VALIDATE DATABASE to diagnose or repair the problem.


Database is read-only (Error 1570)

Commands such as VALIDATE DATABASE RECOVER and those involving creation or modification of database objects require writing to the database.

Close the database and re-open it with writable access.


Database object is being used by someone else. (Error 1709)

Another user is accessing this database object.

  • Visual FoxPro is accessing records temporarily in response to another user's actions.

    Wait a few minutes and try again.

  • Another user is modifying a table or connection.

    Contact the user. If you are modifying a table or a connection, you are preventing others from having access while you are in the designer. For more information, see MODIFY STRUCTURE, MODIFY CONNECTION, and so on.

  • Another user is modifying a view.

    You can still use the view. If you want to modify it, contact the user. For more information, see MODIFY VIEW.


Database object type is invalid (Error 1773)

Valid types are: CONNECTION, VIEW, TABLE, RELATION, FIELD, INDEX. Some commands are appropriate only for a subset of these types.


DataType property for field "name" is invalid (Error 1544)

The value of the view field DataType property is not a valid Visual FoxPro data type.

Change the view field DataType property to a valid type.


Date/DateTime contains illegal characters (Error 2035)

The Date or DateTime constant contains characters that are not supported in Date and DateTime constants.


Date/DateTime evaluated to an invalid value (Error 2034)

A Date or DateTime is not in the valid Date or DateTime format, or is outside the valid Date or DateTime range.


Declare DLL call caused an exception. (Error 2027)

The parameters passed to a DLL caused an exception in the DLL.

Make sure that you pass all the necessary parameters to the DLL and that the parameters are of the proper type.


DIMENSION contains variable declaration without required subscript arguments (Error 1232)

A DIMENSION statement contains a variable declaration without the required subscript arguments.


Directory is not found (Error 1963)

The directory you have specified does not exist.


Display mode is not available (Error 216)

You have attempted to select an unavailable display mode.


Drive specifier is invalid (Error 1907)

You specified an invalid drive name in a DIR command.


Duplicate field names (Error 1156)

You have specified a duplicate name in the FIELDS clause for SORT or a COPY command. Correct your program or command and try again.


End of file encountered (Error 4)

The record pointer was positioned past the last record in the file.


END TRANSACTION command cannot be issued without a corresponding BEGIN TRANSACTION command (Error 1591)

Contain transaction code between matched BEGIN TRANSACTION and END TRANSACTION pairs.


ENDTEXT does not have corresponding TEXT statement (Error 1214)

An ENDTEXT statement is missing a corresponding TEXT statement.


Environment-level property is invalid (Error 1473)

You have specified a property that cannot be set in the environment to be inherited by new cursors. You must first create the cursor and then use CURSORSETPROP( ).


Error accessing printer spooler (Error 1957)

An internal call to the GetPrinter( ) function has failed. Visual FoxPro calls this function through either PRTINFO( ) or SET PRINTER TO.


Error adding "name" to the object. Duplicate member/property name (Error 1779)

The member or property name you are trying to add to the object already exists.


Error closing the file (Error 1112)

An error was returned by the operating system while Visual FoxPro was attempting to close a file.


Error code is not valid (Error 1941)

The input to the ERROR command is not recognized.


Error copying the OLE object to Clipboard (Error 1424)

There are not enough resources available.


Error creating table: "name" (Error 1973)

The table definition used in the FROM clause of the CREATE TABLE command contains an invalid field definition.


Error creating the OLE object (Error 1423)

There are not enough resources available, or Visual FoxPro can't find the server application.


Error in the class definition. "Details" (Error 1735)

An error occurred in the class definition for one of the following reasons:

  • The array does not exist.
  • Pages cannot be removed in the class definition.
  • Columns cannot be removed in the class definition.
  • Could not find the class name in the form.
  • CREATEOBJECT( ) was used in a class definition.
  • Grid columns were deleted in a class definition by setting the ColumnCount in the parent class to one value, and then setting the ColumnCount to a lower value in the child class.
  • Page frame-type pages were deleted in a class definition by setting the PageCount in the parent class to one value, and then setting the PageCount to a lower value in the child class.
  • The ADD OBJECT a[1] clause from the DEFINE CLASS command was used where a is not an array.


Error in the PICTURE clause (Error 1258)

The compiler has detected an error when compiling a PICTURE clause. A picture must be a valid bitmap (.BMP) or icon (.ICO) file.


Error initializing Application object (Error 1574)

The Automation server or type library is not registered correctly.

  • Your registry file is corrupted.

    Remove the registry entry.


Error initializing OLE (Error 1508)

There is not enough memory or there has been an improper installation for this operation. Close any other running applications and try again.


Error instantiating cursor. Table "alias" cannot be opened. Object will be ignored (Error 1554)

An error occurred in design mode while attempting to load the data environment. The cursor was not created. If you save the form, the object will be lost.


Error instantiating the object "object". (Error 1736)

The server for the object is not registered properly, resources are low, or a required .dll file is not present. Other reasons are as specified.


Error loading file - record number n. "object" <or one of its members>. "Issue": "error" (Error 1881)

An error occurred while attempting to read in a form (.scx) or class (.vcx) file. Issue relates to either "Properties," "Methods," or "User Properties."

To resolve the error:

  1. To access the record referenced in the error, open the form or class as a table as follows:
    USE myform.scx
  2. To move to that record, use the GO command.

You can often find the cause of the error in the Properties, Methods, Class, Classloc, Objname, or Parent fields.

Note You should make a backup copy of your form and class file before modifying the contained records and fields directly.


Error loading HtmlHelp 2.0 collection. (Error 2049)

The HTML Help 2.0 collection specified did not load properly. Check the File Locations Tab, Options Dialog Box to make sure the file you specified is in the location specified.


Error loading printer driver (Error 1958)

An internal call to the LoadLibrary( ) function has failed. Visual FoxPro calls this function through either PRTINFO( ) or SET PRINTER TO.


Error loading the data environment. Table is in use (Error 1995)

Check to see if the table has been opened exclusively in another data session.


Error occurred in conversion (Error 1797)

The converter has run and returned a non-error status, but the resulting report form (.FRX) file is not in Visual FoxPro format. If you have changed the value of _CONVERTER, the converter you are using doesn't generate proper Visual FoxPro .FRX files.


Error reading a property from the database. The property is ignored (Error 1584)

An error occurred while loading rule or trigger code from the database container. The rule or trigger will be ignored.

Try running VALIDATE DATABASE before reopening this table.


Error reading file "file" (Error 1104)

The operating system returned an error while Visual FoxPro was attempting to read the specified file.


Error reading the resource (Error 1296)

An internal Visual FoxPro error has occurred.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Error saving the OLE object (Error 1422)

There is not enough disk space or resources available to save the object.


Error with "name" - "property": "error" (Error 2005)

You have attempted to set a property to an illegal value through the language.


Error writing to file "file" (Error 1105)

The operating system returned an error while Visual FoxPro was attempting to write to the specified file. Most often, this error occurs when attempting to write to a write-protected disk.


EventHandler object "name" does not IMPLEMENT an interface (Error 1445)

For the EVENTHANDLER( ) function, you have specified an interface that is not implemented by the specified EventHandler object.


Exclusive open required to update this file. Please reopen (Error 1977)

You do not have exclusive rights to this file.

Re-open the file with the EXCLUSIVE clause of the USE command.


Execution was canceled by the user (Error 1523)

You canceled a remote command by pressing the ESC key.


Expression evaluated to an illegal value (Error 46)

Occurs when an expression specified by SET MEMOWIDTH, BROWSE, or an @ ... TO command evaluates to an illegal value.

-or-

Occurs when the value specified for LockColumns or LockColumnsLeft properties is greater than the number of columns that are visible in a grid panel.


Expression evaluator failed (Error 67)

An internal consistency check in the Visual FoxPro expression evaluator failed. This might be caused by a damaged Visual FoxPro object code file.

Recompile the program that caused the error.


Expression has been re-entered while the filter is executing (Error 1148)

The expression in SET FILTER TO has been re-entered while the filter is executing. This can happen with complex setups involving SET RELATION or SET FILTER, or during the use of Visual FoxPro functions or user-defined functions which reference other work areas, such as LOOKUP( ) or SEEK( ).


Expression is invalid. Use a valid expression for "name" property (Error 1759)

The expression you entered for a grid property is not valid. The expression is cleared from the property setting.

  • If you are setting the expression in the AfterRowColChange event of the grid, the error itself causes the event to fire again, leading to an recurring loop of error messages.

    Press Cancel in the dialog box to disable the expression. You will not be able to set or change the expression.

  • The expression contains syntax errors.

    Make sure your expression is valid and without syntax errors.

  • Variables in the expression are not scoped properly.

    Make sure that any variables you use in the expression are globally scoped, or scoped to the form. If your expression contains a variable that is local to the function that you are setting the expression in, the variable will go out of scope when the function returns. However, the expression will be evaluated in the future when the grid tries to paint, and this will cause an error.


Expression is not valid outside of WITH/ENDWITH (Error 1940)

You can use an expression of the form .property=some_value only within a WITH ... ENDWITH construct.

  • This error might also occur if you are using .NULL. as an expression.

    Put quotes around the .NULL. to keep it from being identified as a property.

  • You might have forgotten an ending period with a value such as true (.T.), false (.F.) or a null value (.NULL.)

    Check for matching periods on either side of the constant.


Expression is too complex (Error 1947)

Your index expression is too long. The maximum number of characters allowed in an .IDX index key is 100. The maximum number of characters allowed in a .CDX index key is 240.


Expression used with ACOS( ) is out of range (Error 293)

The expression you have used with the arc cosine function has a value out of the range of – 1.0 to +1.0.


Expression used with ASIN( ) is out of range (Error 291)

The expression you have used with the arc sine function has a value out of the range of – 1.0 to +1.0.


Fatal error nExpr reporting error nExpr.

No error number is returned. Visual FoxPro closes all open files and exits.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Feature is not available (Error 1001)

The Visual FoxPro feature you have attempted to use is not supported in this version of Visual FoxPro.


Feature is not supported for non-.DBC tables (Error 1580)

You have tried to implement a feature, such as a nullable field, a primary key, a persistent relation, a default value, a validation rule, or a trigger, on a free table. These features are available only for tables that are contained in a database (.dbc).

Use ADD TABLE to add a free table to a database.


Feature is only available if the object is in design mode (Error 1953)

The operation you have attempted is only valid in design mode.


Fetching canceled; remote table is closed (Error 1530)

You interactively canceled a local function execution as part of remote data fetch by pressing the ESC key.


Field "name" does not accept null values (Error 1581)

You attempted to store a null value in a field that does not accept null values.

You can change this setting by checking the NULL checkbox when modifying a field in the Table Designer, or specifying the NULL keyword in a field definition.


Field "name" is read-only. (Error 1088)

Occurs when attempting to insert, update, or replace a value in a field that uses autoincrementing, and the AutoIncError property is set to True (.T.) or ON via the SET AUTOINCERROR command.

Try setting the AutoIncError property to False (.F.) or OFF using the SET AUTOINCERROR command.


Field "name" validation rule is violated (Error 1582)

Fix the field value or revert the record.


Field expression contains an invalid data type (Error 1647)

A picture data type was encountered by REPORT for a field expression.


Field for Unicode value should not use code page translation. (Error 2142)

Occurs when Visual FoxPro attempts to convert Unicode data to or from XML, and the NoCpTrans property evaluates to False (.F.).

  • Check to make sure that your character and memo fields being used for Unicode data have the NoCpTrans property set to True (.T.).


Field must be a General field (Error 1913)

You have attempted to enter a non-general field name with APPEND GENERAL or MODIFY GENERAL., or you have attempted to enter a non-general field name into the Report Picture dialog box.


Field must be a Memo field (Error 350)

You have attempted to enter a field name that is not a Memo field type with the APPEND or COPY MEMO command.


Field name is a duplicate or invalid (Error 1712)

A field in the table already has that name, or else you used a space, or one of the characters ., ", /, \, [, ], :, |, <, >, +, =, ;, *, or ? in the field name.


Field size for Unicode value can not be odd number. (Error 2141)

Occurs when attempting to convert Unicode data to or from XML, and the field size does not evaluate to an even number.

  • Make sure that Unicode strings are being used.
  • Check to make sure that field sizes are always even numbered.


Field width or number of decimal places is invalid (Error 1713)

The field width or number of decimal places you have specified is not valid. For a list of the requirements, see System Capacities..


Fields marked as update keys will be cleared (Error 2014)

Memo, General, and Picture fields cannot be key fields.

  • A key field was changed to Memo, General, or Picture.

    Visual FoxPro will clear the update key marker.


File "name" already exists as part of a database (Error 1529)

You have attempted to overwrite an existing file that is part of a database.

To avoid database corruption, first issue a REMOVE TABLE on the existing table from within its database.


File "name" does not exist (Error 1)

The file specified does not exist.


File "name" is a database (Error 1553)

The operation you have attempted is not supported for database files.

Try again with a file of the correct type.


File "name" is an invalid database (Error 1551)

Problems were detected trying use the named database.

Try opening it and running VALIDATE DATABASE to diagnose or repair the problem.


File "name" is not a database (Error 1552)

The database operation you have attempted failed because the file was not a valid database.

Try again with a file of the correct type.


File "name" is not closed (Error 1933)

Internal consistency error. A form (.scx) or visual class library (.vcx) file was closed but the method and event code that is stored in it is still in use.


File "name" is not part of a database (Error 1558)

The operation you have attempted is not supported for free tables.

Try again with a file of the correct type.


File "name" is part of a database (Error 1565)

The operation you have attempted is supported only for free tables.

Try again with a file of the correct type.


File "name" is read-only (Error 1718)

You have attempted to write to a read-only file.


File "name" is too large (Error 1190)

The file is too large to be modified.

  • The file is larger than 2 GB.

    Use another method to reduce the file size, and then try again.


File access is denied (Error 1705)

You have attempted to write to a file that is write protected.


File already exists (Error 7)

The file name you have attempted to rename already exists. This error is usually generated by the RENAME command.


File cannot be closed because outstanding references exist (Error 1184)

Outstanding references exist to an object in this form or form set.


File cannot be locked (Error 1503)

Visual FoxPro cannot lock the requested file. It may already be locked by another user on the network.


File is in use (Error 3)

You have attempted a USE, DELETE, or RENAME command on a file that is currently open.


File is in use by another user (Error 108)

You have attempted a USE, DELETE, or RENAME command on a file that is being used by another user on a network.


File is not open (Error 1113)

You have attempted to read from, or write to, a file that is not currently open.


File is open in another work area (Error 1708)

Commands that require exclusive use of a table (PACK, MODIFY STRUCTURE, ZAP, and so on) cannot be used on a table that has been opened in multiple work areas with the AGAIN clause of the USE command.


File is the wrong version (Error 1338)

You have attempted to open a screen or a report file that is not a Visual FoxPro file.


File must be opened exclusively (Error 110)

You have attempted to perform an operation that requires exclusive use of the table.


File must be opened exclusively to convert the Memo file (Error 1637)

The table file you are using must be opened exclusively to be able to convert the memo file.


File name is too long (Error 1918)

The name of the file exceeds current system capacities.


File was created in a later version of Visual FoxPro than the current version (Error 1750)

There is a discrepancy in the comparison of the version number built into the form (.scx) or database container (.dbc) file and the version number stored in the product for these files.


File was not placed in memory using the LOAD command (Error 91)

An error occurred when attempting to CALL or RELEASE a module that was not loaded.


FILTER expression exceeds allowed size (Error 1140)

You have attempted to issue SET FILTER TO on an expression that is longer than the maximum allowable size of 160 characters.


Form (.SCX) file must contain at least one Form (Error 1749)

To add a form to an .scx file, use the Form Designer.


Form file "name" is from a previous version of FoxPro. It must be converted to the current format before it can be executed (Error 1991)

You have attempted to compile a form file (.scx) from a previous version of FoxPro.

Convert to the current version and try again.


Form file "name" is invalid (Error 1686)

The screen file specified has become corrupted.


Forms or Form classes that specify a DEClass and DEClassLibrary cannot be converted to or used with a FormSet. (Error 2069)

Visual FoxPro does not support the DataEnvironment DEClass and DEClassLibrary properties for form sets. An error occurs under the following conditions at design time:

  • When attempting to convert a form to a form set after the DEClass and DEClassLibrary properties have been specified for the form.
  • When attempting to add a Form class that specifies the DEClass and DEClassLibrary properties to a FormSet class when the form set is open in the Form Designer.


Foxcode script "name" failure. (Error 2043)

The script specified in your _FOXCODE system variable table has failed. Determine the file associated with the system variable by typing the following:

? _FOXCODE

Then, check the syntax of the appropriate script record.


Foxcode table not found, is not correct version or is incompatible. (Error 2042)

The table specified by the _FOXCODE system variable does not exist or is incompatible with this version of Visual FoxPro. Determine the file associated with the system variable by typing the following:

? _FOXCODE

Then, make sure the file is a properly structured table for this version of Visual FoxPro. For details, see Customizing IntelliSense Using Foxcode.


Foxtask table is corrupted or not the correct version. (Error 2046)

The table specified as the value of the _FoxTask System Variable is invalid.


Function argument value, type, or count is invalid (Error 11)

A value passed to a function is not of the expected data type, or the value of the argument is out of range for this function, or you are passing too many arguments to a function.


Function is not implemented (Error 1999)

You have attempted to call a function that is not supported in the current version of Visual FoxPro.


Function is not supported on native tables (Error 1536)

The command or function you are using — for instance, REQUERY( ) — is not applicable to native Visual FoxPro tables.


Function is not supported on remote tables (Error 1525)

The command or function you are using — for instance, PACK or ALTER TABLE — is not applicable to remote tables.


Function name is missing (Error (Error 1304)

A function name is missing a left parenthesis.


Function name is missing ) (Error 1300)

A function name is missing a right parenthesis.

  • The current line contains a left parenthesis which has not been matched.
  • The function contains too many arguments and thus the right parenthesis is undetected.


Function not supported for SQL pass-through cursors (Error 1504)

This command applies to view cursors only.

  • SQL pass-through cursors do not necessarily return single result sets.

    Do not use REQUERY( ) on a SQL pass-through cursor.


Function requires row or table buffering mode (Error 1586)

The function you have attempted call is only enabled for cursors with row or table buffering enabled. Set the Buffering property to 2, 3, 4, or 5 with CURSORSETPROP( ) to enable row or table buffering.


GDI memory is low, close one or more windows and try again (Error 1986)

Close all open applications and restart Windows on your computer.


General fields cannot be used in the WHERE condition of an update statement. Change the WhereType property of the view (Error 1489)

In the WHERE clause of a SQL update statement, expressions you use to enforce optimistic locking cannot include general fields. Use the WhereType view property (you can change it from the default KeyAndModified to Key) to remove general fields from the update WHERE clause.

For more information on the WhereType property, see CURSORGETPROP( ) or DBGETPROP( ).


GroupBy clause is too long. (Error 2053)

You have specified a GroupBy clause using more than 256 characters.


Help for this topic/context not implemented. (Error 2050)

You have specified a topic for which there is no top-level information. Try using the search function.


Icon is corrupt or in wrong format (Error 1167)

An invalid icon (.ICO) file was encountered during BUILD EXE.


Illegal nested OLDVAL( ) or CURVAL( ) (Error 1587)

The expression you are passing to OLDVAL( ) or CURVAL( ) references the OLDVAL( ) or CURVAL( ) function. This is not a supported operation.


Illegal printer driver recursion (Error 1910)

Your printer driver program calls upon the printer driver.


Illegal recursion in rule evaluation (Error 1887)

A rule or trigger code caused the original cursor, the cursor from which the rule or trigger was fired, to try to evaluate a rule or trigger recursively. This can occur under the following conditions:

  • Attempting to move the record pointer or change values in the original cursor.
  • Attempting to move the record pointer in the BeforeUpdate event for a CursorAdapter object.

Check your rule or trigger code.


Illegal redefinition of variable "name" (Error 1960)

The PUBLIC or LOCAL command tried to change the state of a variable that already exists. For example, if you have a variable x that is not public and then issue PUBLIC x, you get this error.

Variables created in the Command window are public by definition. To create a variable that is not public, use a program (.PRG) file.


Illegal to attempt a file lock in a transaction after taking prior record locks (Error 1594)

You have either explicitly (with FLOCK( )) or implicitly (with REPLACE ALL, for example) attempted to take a file lock in a transaction. This is illegal if any record locks have already been taken either explicitly or implicitly at this transaction level or any lower transaction level. This is illegal even if those record locks have been freed inside the transaction.

You must roll back all record locks on this file before attempting this file lock. For more information, see ROLLBACK.


Import only Worksheet A for Lotus 1-2-3 version 3.0 files (Error 1679)

Worksheets B and C cannot be imported into Visual FoxPro because a table is two-dimensional.


Improper data type in the group expression (Error 1241)

A picture data type was encountered by REPORT for the group expression.


Include file "name" is not found (Error 1994)

The file specified in the form does not exist or #INCLUDE contains an invalid reference.


Incorrect column format (Error 1471)

You have attempted to pass an incorrect column type descriptor to SQLCOLUMNS( ).


Incorrect property name (Error 1470)

You have attempted to use an unknown property name.


Index does not accept NULL (Error 1886)

Your primary or candidate key index expression evaluated to NULL, which is an invalid value for these types of indexes.

Change record values so the expression does not evaluate to NULL.


Index does not match the table. Delete the index file and re-create the index (Error 114)

A damaged structure within an index file has been detected.

Delete the index file (.CDX or .IDX) and recreate it.


Index expression exceeds maximum length (Error 23)

The index expression for this index exceeds the maximum length of 220 bytes.


Index file does not match table (Error 19)

The index expression for the current index uses variables that are not contained within the current table.


Index or expression does not match an existing member of the collection. (Error 2061)

The index or expression provided does not match any of those that correspond to a member in the collection. Make sure you provide a valid index or expression for an existing member.


Index tag is not found (Error 1683)

The tag you have specified could not be found in the index.

Verify the TAG clause of your command.


Index tag or file name must be specified (Error 1684)

You have attempted to exit without specifying a tag name.


Input/output operation failure (Error 1002)

The operating system is unable to perform a file or hardware operation.


INSERT cannot be issued when row or table buffering is enabled or when integrity constraints are in effect (Error 1588)

Either set row and table buffering off by setting the Buffering property to 1 with CURSORSETPROP( ), or use APPEND instead of INSERT.


Insufficient stack space (Error 1308)

One of the following has occurred:

  • Your program is too recursive.
  • Your program is too complex and is nested too deeply.
  • An error in Visual FoxPro.


Interface "name" not found (Error 1443)

When using IMPLEMENTS, you have specified an interface for a COM object incorrectly.


Internal consistency error (Error 1000)

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Internal error: Too many characters in the report (Error 1243)

The total size of all the headings and expressions defined for the report in CREATE REPORT or MODIFY REPORT is too large to be contained in the standard report file.


Invalid argument used with the SET function (Error 231)

An invalid argument has been used with the SET( ) function.


Invalid call issued while executing a SQLCOLUMNS( ) sequence (Error 1477)

An invalid SQL pass-through (SPT) function call has been made while a SQLCOLUMNS( ) call was expected to continue the SPT call sequence in progress.

Call SQLCANCEL( ) to cancel the SPT sequence or make valid SPT calls to finish the call sequence.


Invalid call issued while executing a SQLEXEC( ) sequence (Error 1474)

An invalid SQL pass-through (SPT) function call has been made while a SQLEXEC( ) call was expected to continue the SPT call sequence in progress.

Call SQLCANCEL( ) to cancel the SPT sequence or make valid SPT calls to finish the call sequence.


Invalid call issued while executing a SQLMORERESULTS( ) sequence (Error 1475)

An invalid SQL pass-through (SPT) function call has been made while a SQLMORERESULTS( ) call was expected to continue the SPT call sequence in progress.

Call SQLCANCEL( ) to cancel the SPT sequence or make valid SPT calls to finish the call sequence.


Invalid call issued while executing a SQLTABLES( ) sequence (Error 1476)

An invalid SQL pass-through (SPT) function call has been made while a SQLTABLES( ) call was expected to continue the SPT call sequence in progress.

Call SQLCANCEL( ) to cancel the SPT sequence or make valid SPT calls to finish the call sequence.


Invalid class specified for @...Class command (Error 1783)

You cannot specify a form, form set, or toolbar class when using @ ... Class.


Invalid COMATTRIB value for "name" (Error 2048)

You have specified an incorrect value for this named property specified in your class definition.


Invalid compact EXE file. Rebuild EXE.

Your compact executable (.EXE) file has become corrupt.

Rebuild the file.


Invalid coordinates (Error 1959)

Coordinate values must be greater than -32768 and less than 32767.


Invalid database table name (Error 1578)

Valid database table names contain only alphanumeric characters and spaces, and cannot start with a number. They may not be longer than 128 characters.


Invalid element in XMLTable.Fields collection. (Error 2098)

Visual FoxPro has detected an invalid object in the XMLField collection.


Invalid expression in label definition file (Error 1245)

An invalid expression was encountered in a label file (.LBX).


Invalid file descriptor (Error 1111)

Visual FoxPro is unable to open a file.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Invalid file format. If this is a dBASE file, it must be converted first. To convert it, type MODIFY LABEL file (Error 1510)

Convert your dBASE file and try again.


Invalid key column name "name". (Error 2146)

Occurs when the CursorAdapter objects, KeyFieldList property, contains an invalid value.

  • Make sure the value assigned to the KeyFieldList property is valid.


Invalid key length (Error 112)

  • If you created an index key that exceeds the following limits, create a shorter index key.

    The length of an index key for an index or compiled index (.idx) must be between 1 and 100 characters. The length for a compound index (.cdx) must between 1 and 240 characters.

    For certain collating sequences, or when using double-byte character sets (DBCS) characters, each character in the eExpression parameter in the INDEX command uses two characters in the index key. In these cases, the length of eExpression is limited to 120 characters.

  • If you created an index key with length of 0, make sure the first record of the fields you base the index on contains some data.

    When Visual FoxPro creates an index, it evaluates fields in the first record in the table.


Invalid locale ID. (Error 2026)

The locale ID specified in STRCONV( ) isn't supported by the operating system.


Invalid operation for offline view (Error 2011)

Some operations are not valid for offline views.

  • You tried to modify the view definition or table, compact the view, insert or delete records, or refresh the view.

    Do not use these commands on offline views.


Invalid operation for offline view while being used online (Error 2008)

Some operations are not valid when an offline view is being used online.

  • You tried to change the buffer mode of the view.

    By definition, offline views used online are in table buffer mode. Do not call CURSORSETPROP( ) to change the buffer mode.

  • You tried to create an index.

    Do not use SET ORDER TO or INDEX on offline views while you are using it online.


Invalid operation for offline view while offline (Error 2007)

Some operations are not valid when an offline view is being used offline.

  • You tried to create an offline view from a view that is already offline.

    Use the original view directly, or use a different view as the basis for your new offline view.

For more information, see CREATEOFFLINE( ).


Invalid operation for the cursor (Error 1115)

An attempt was made to use the PACK command on a cursor.


Invalid or duplicate field name.

The field name you specified already exists in the table.

  • Specify a unique field name for each field in the table.


Invalid or missing EXE file.

The .EXE file you specified is either corrupted or missing.


Invalid path or file name (Error 202)

You attempted to execute a Visual FoxPro command that contains an invalid path or file name.


Invalid seek offset (Error 1103)

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Invalid subscript reference (Error 31)

A subscript was used that is outside of the valid range of array subscripts defined in the DIMENSION statement. This might also be caused by using two subscripts with a one-dimensional array.


Invalid update column name "name" (Error 1479)

The column name is not found in the column list of the view.

Correct the column name.


Invalid use of a Visual FoxPro function as an array (Error 1652)

Visual FoxPro encountered a function when it was expecting an array name.

Replace the function with a valid array name.


Invalid variable reference (Error 1223)

A function was used where a variable was expected.

Replace the reference with a valid variable or array name.


Key exceeds allowed size (Error 1124)

The compiled version of the index expression has exceeded 150 bytes.


Key field length does not match (Error 1117)

The key field length does not match for an UPDATE or SET RELATION TO operation between two files.


Key label "label" is invalid (Error 1255)

The key label you have used is not supported. See ON KEY LABEL for a list of supported key labels.


Key string is too long (Error 1257)

The character expression included with KEYBOARD is too long. Reduce its length.


Keyboard macro file format is invalid (Error 356)

An attempt has been made to use a macro file with invalid data.


Label file is invalid (Error 54)

An attempt was made to modify or print labels using a label file that was not created with CREATE LABEL or MODIFY LABEL.


Label nesting error (Error 1653)

A user-defined function in a label form has called LABEL with a FORM clause again.


Left margin including indent must be less than the right margin (Error 221)

The position of the right margin must be greater than the position of the left margin.

Adjust the margin settings and try this operation again.


Length of variable strings exceeds amount of memory (Error 21)

The combined length of all variable strings has exceeded the amount of memory.


Library file "name" is invalid (Error 1691)

Visual FoxPro cannot use the library file you specified.

Rebuild the library.


Line is too long (Error 18)

The maximum length for a command line (8,192 bytes) has been exceeded.

  • Macro substitution might have caused the line to expand beyond the 8,192-byte limit.


Line number must be less than page length (Error 222)

The line number used falls beyond the page length variable.


Link command failed (Error 1194)

A compilation error occurred and an .EXE was not created on the disk.


Localized product is required for this environment (Error 1911)

There was an attempt to use a US version of Visual FoxPro with a non-US system.


LOG( ): Zero or negative used as argument (Error 58)

A zero or a negative number has been used as the argument of the natural log function.


Logical expression required

The expression provided in the Expression Builder must be of Logical type. For more information, see Creating Logical Expressions.


Lotus 1-2-3 version 1.0 file format is invalid (Error 1662)

The Lotus 1-2-3 file you have attempted to import is either not version 1.0 or has been corrupted.


Lotus 1-2-3 version 2.0 file format is invalid (Error 297)

The Lotus 1-2-3 file you have attempted to import is not version 2.0. Use the Lotus conversion utility to convert the file to version 2.0 before attempting to import it.


Lotus 1-2-3 version 3.0 file format is invalid (Error 1678)

The Lotus 1-2-3 file you have attempted to import is either not version 3.0 or has been corrupted.


Macro is not defined (Error 355)

An attempt has been made to play a macro that does not exist.


Maximum menu item length (50) is exceeded (Error 1609)

Reduce the number of menu items.


Maximum menu items allowed (128) is exceeded (Error 1607)

The maximum number of items that may be contained in a menu (128) was exceeded.


Maximum menus allowed (Error 25) is exceeded (Error 1608)

The maximum number of menus that may be defined (25) was exceeded.


Maximum number of OLE arguments is exceeded (Error 1431)

You have specified more arguments for an Automation method than is allowed in Visual FoxPro.

Call the method with fewer than 64 arguments.


Maximum record length exceeded in the import file (Error 392)

The file you have attempted to import has a record length greater than 4,001 bytes.


Member "name" does not evaluate to an object (Error 1943)

Invalid syntax. The syntax indicates that the next element being evaluated should be an object but it isn't.

For example, if you had a form called myform with a text box called text1, the command myform.txt.value = "help" would generate this error. The command should be myform.text1.value = "help".


Member "name" is a class member (Error 1760)

You have attempted to remove a member from an object. The member cannot be removed because it is a member of the class the object is based on.

To remove the member, modify the class.


Member object "name" has not been instantiated (Error 1975)

A reference was made to a member object in an Init event before that object was instantiated.


Member object removed – cannot complete Save operation (Error 1756)

The class could not be saved.

  • The .vcx file or memory is corrupted.


Memo file "name" is missing or is invalid (Error 41)

An attempt was made to use a table file whose associated memo file (.dct or .fpt) has been deleted, removed, or cannot be found.


Memory file is invalid (Error 55)

An attempt was made to use RESTORE FROM on a file that is not a valid memory (.mem) file.


Memory is low, so streaming output updating has been disabled (Error 2000)

The off-screen bitmap could not be created by a command such as ?, LIST, or DISPLAY.

  • Visual FoxPro memory is low.

    Free up some memory.


Menu file is invalid (Error 1687)

The menu file you specified has become corrupted.


Menu has not been activated with ACTIVATE MENU (Error 178)

You have attempted to select from a menu before the menu has been activated. For more information, see ACTIVATE MENU.


Menu has not been activated with ACTIVATE POPUP (Error 179)

You have attempted to select a menu title from a menu before the menu has been activated. For more information, see ACTIVATE POPUP.


Menu has not been defined with DEFINE MENU (Error 168)

You have attempted to activate a menu that has not been defined. For more information, see DEFINE MENU.


Menu has not been defined with DEFINE POPUP (Error 165)

You have attempted to activate a menu before it has been defined. For more information, see DEFINE POPUP.


Menu item position must be a positive number (Error 167)

You have attempted to position a menu or menu title using a negative number.


Menu items and titles must be type Character (Error 1611)

A menu item or menu title was encountered, which was defined with a data type other than Character.


Menu item's conditional statement is too long. (Error 2051)

You have specified a condition using more than 256 characters.


Menu size is too small (Error 287)

The menu is too small to display menu items.

Define a larger menu.


Menu specified in ACTIVATE MENU is already in use (Error 181)

You have attempted to activate a menu that is already active.


Menu specified in ACTIVATE POPUP is already in use (Error 182)

You have attempted to activate a menu that is already activated.


Menu title has not been defined with DEFINE PAD (Error 164)

There is a reference to a menu title that doesn't exist. For more information, see DEFINE PAD.


Menu was not pushed (Error 279)

An attempt has been made to pop a menu or popup that was not pushed.


Method contains syntax errors. Method is not saved (Error 1765)

You have either included more than one procedure or have a class declaration in the code.

Fix the code and try again.


Microsoft Excel file format is invalid (Error 1661)

The Microsoft Excel file you have attempted to import is either not version 5.0 or has been corrupted.


Mismatched #IF/#ELSIF/#ELSE/#ENDIF (Error 1723)

You have included an incomplete or incorrect #IF preprocessor command.


Mismatched braces in key label (Error 1256)

A left or right brace is missing from a key label.


Missing #ENDIF (Error 1724)

You have issued an #IF command without a matching #ENDIF.


Missing .RTT section (Error 1193)

The Microsoft Visual FoxPro distribution component is not properly installed.


Missing comma (,) (Error 1306)

Visual FoxPro was expecting a comma and didn't find one.

  • You might not have included the proper number of arguments with a function.

    Check your syntax.


Missing expression (Error 152)

A valid expression was expected, but not found.


Missing operand (Error 1231)

An operator that requires two operands was used without the second operand, such as ? (13+4)/.


Multiplan version 4.0 file format is invalid (Error 1670)

The Multiplan file you have attempted to import is either not version 4.0 or has been corrupted.


Multiple warnings occurred performing the requested index modifications (Error 1875)

All structural and property changes to the table were completed successfully.

  • Since you registered an ON ERROR handler, warnings were processed there.

    Add code to verify the changes and handle the warnings you received.


MULTISELECT or MOVER clause is not supported for PROMPT style menus (Error 1710)

Commands that have the clauses PROMPT FIELD, PROMPT FILE, or PROMPT STRUCTURE do not allow the clauses MULTISELECT or MOVER.


Must be a character or numeric key field (Error 1145)

The key field used to UPDATE ON must be of type Character, Date or Numeric.


Must be a file variable (Error 1226)

A variable or an array was used where a file variable (field) is required.


Must be a variable or array (Error 1225)

A file variable (field) was used where a variable or array was required.


Must specify additional parameters (Error 94)

Occurs when:

The number of parameters specified in a DO ... WITH statement is greater than the number of parameters defined by the PARAMETERS statement in the called program.

-or-

The delegate method does not have the same number of parameters as the event specified in cEvent in the BINDEVENT( ) function.


Nesting error (Error 96)

One of these situations has been encountered:

  • A DO is present without a matching ENDDO or vice versa
  • A SCAN is present without a matching ENDSCAN or vice versa
  • A FOR is present without a matching ENDFOR or vice versa
  • A LOOP or EXIT clause is present outside the DO WHILE ... ENDDO, FOR ... ENDFOR, or SCAN ... ENDSCAN commands.


No connection associated with this cursor (Error 1488)

The connection was closed.

  • You closed the connection with SQLDISCONNECT( ). and then tried to update, requery, or refresh the view.

    Make sure you have an open connection before performing this command on a remote view.


No database is open or set as the current database (Error 1520)

You have attempted to perform an action which requires a database to be open and set as current.

Use the OPEN DATABASE or SET DATABASE TO commands, or select a database from the database drop-down list in the standard toolbar.


No default value to DROP (Error 1878)

You have attempted to use the DROP DEFAULT clause of the ALTER TABLE command on a column with no default value. This is not a valid operation.


No fields found to process (Error 47)

No fields can be found, usually because a SET FIELDS TO was in effect.


No fields were found to copy (Error 138)

During an attempt to copy to a file, no visible fields were found.


No key columns specified for the update table "name". Use the KeyFieldList property of the cursor (Error 1492)

No key column(s) have been specified in the KeyFieldList property for a base table that is being updated.

Modify the KeyFieldList property to include key columns for each table that is being updated. The key fields also need to be included in the UpdateNameList property. For most views, you can use the View Designer to set the view update properties and then save the view back into the database. For more information, see CURSORGETPROP( ).


No menu is defined (Error 1605)

You attempted to activate a menu before defining a menu bar.


No menu item is defined (Error 1604)

You attempted to read a menu bar that has not been defined.


No menu items have been defined for this menu (Error 166)

You must define menu item bars for each menu.


No menu titles have been defined for this menu (Error 1621)

You attempted to activate a menu that has no titles.


No PageFrame or Page is found in FormSet or Form with WindowType set to READ or READ MODAL (Error 1964)

You attempted to manually make a form set of type READ or READMODAL and you don't have the right combination of pages and page frames. This operation should be performed only by the Converter.


No PARAMETER statement is found (Error 1238)

After doing a program with a parameter list, the called program must begin with a PARAMETER statement.


No previous PRINTJOB command to correspond to this command (Error 1649)

An ENDPRINTJOB command was encountered without a matching PRINTJOB command preceding it.


No primary key (Error 1879)

You have attempted to use the DROP PRIMARY KEY clause of the ALTER TABLE command on a table with no primary key. This is not a valid operation.


No records are found for the current platform (Error 1796)

You have attempted to modify a file that has no records from the current platform.

Use the transport program to convert the file.


No result set has been returned by the server (Error 1463)

The remote query did not generate a result set.

Check your query and its parameters to make sure you are producing a result set on the server.


No rule to DROP (Error 1877)

You have attempted to use the DROP CHECK clause of the ALTER TABLE command on a column (or table) with no rule. This is not a valid operation.


No sheet is found (Error 1774)

The .XLS file you are referencing contains no worksheet records. This can also occur for a file containing only charts or macros.


No such menu or menu item is defined (Error 1612)

The values passed to a READ MENU TO or READ MENU BAR TO command do not correspond to a defined menu or menu item.


No table is open in the current work area (Error 52)

A table was not in use at the time Visual FoxPro attempted to execute a table command.

  • The current work area doesn't have an open table.

    Open a table or change work areas.


No update tables are specified. Use the Tables property of the cursor (Error 1491)

No base tables are specified in the Tables property of the view.

Set the Tables property to specify the base table or tables that should be updated from the view. For most views you can use the View Designer to set the view update properties and then save the view back into the database. For more information, see CURSORGETPROP( ).


Not a character expression (Error 45)

You have attempted to call a module with an expression whose value is not of the type Character.


Not a numeric expression (Error 27)

You have attempted to use the SUM command on a non-numeric field.


Not a ProjectHook class. (Error 1439)

The default ProjectHook class you specify as a template for new projects must be based on a ProjectHook class.


Not a table (Error 15)

The file that Visual FoxPro is attempting to use as a table contains an improper header.


Not a user-defined window (Error 1682)

You have attempted to use a command containing a WINDOW clause on a window that is not user-defined, such as the Command window.


Not a valid Framework II database/spreadsheet (Error 256)

The file you have attempted to import is not a valid Framework II file format.


Not a valid RapidFile database (Error 255)

The file you have attempted to import is not a valid RapidFile file format.


Not enough memory for buffer (Error 1149)

There is not enough memory for Visual FoxPro to allocate memory for a buffer.

  • Available memory is extremely limited.

    Add memory or remove memory-resident programs to give Visual FoxPro more working memory.


Not enough memory for file map (Error 1150)

There is not enough memory for Visual FoxPro to allocate memory for a Visual FoxPro internal resource.

  • Available memory is extremely limited.

    Add memory or remove memory-resident programs to give Visual FoxPro more working memory.


Not enough memory for filename (Error 1151)

There is not enough memory for Visual FoxPro to allocate memory for a Visual FoxPro internal resource.

  • Available memory is extremely limited.

    Add memory or remove memory-resident programs to give Visual FoxPro more working memory.


Not enough memory to open a table with the USE command (Error 1600)

There was not enough memory to open an additional table.


NOWAIT/SAVE/NOENVIRONMENT/IN/WINDOW clauses are not allowed with the FROM clause (Error 1696)

These clauses cannot be included when you create a quick report with the FROM clause.


Numeric overflow. Data was lost (Error 39)

A mathematical operation resulted in a number that was too large to be stored in the field or variable in which it was placed.


Object "name" is not found (Error 1766)

The object you have specified is protected and cannot be found.


Object "name" is not found (Error 1923)

The object you have specified cannot be found.


Object already has a data environment; cannot use another one with the SaveAs method (Error 1985)

You cannot specify another data environment with the SaveAs method.


Object class is invalid for this container (Error 1744)

You have attempted to add a member object to a parent object with the AddObject method. It cannot be added because the member object's class cannot be a member of the parent's object class. For example, you cannot add a Grid object to a PageFrame object.


Object file "file" was compiled in a previous version of FoxPro (Error 1195)

You have attempted to run an application compiled in a previous version of FoxPro.

Recompile the source code in the current version.


Object file "name" is in use and cannot be removed from memory (Error 1719)

A program specified in the project is suspended.

Cancel execution of the program so that you can successfully build from the project.


Object is not an offline view (Error 2009)

Some commands and clauses require an offline view.

  • You tried to use the ONLINE or ADMIN clauses.

    You must provide an offline view with these clauses. For more information, see USE.

  • You tried to drop a view.

    Use DROPOFFLINE( ) only with offline views.


Object is not contained in a "name" (Error 1938)

This message is produced by the scope operator when the parent class you have specified is not in the inheritance hierarchy of the current (THIS) object. For example, this error will occur if you put FORMSET::Click in the Click event of a form that is not contained in a form set.


Object name is invalid (Error 1575)

You have specified a name for a member object in the AddObject method that is invalid.

Check the name and try again.


Objects cannot be assigned to arrays (Error 1942)

Array elements can only contain values.


Objects cannot be programmatically added to the Form Designer's FormSet (Error 1987)

You have attempted to programmatically add forms to the Form Designer form set. This cannot be done.


Objects cannot be programmatically deleted from the Form Designer (Error 1989)

You have attempted to programmatically delete forms from the Form Designer form set. This cannot be done.


ODBC entry point missing, "name" (Error 1528)

The entry point for the specified function is not found in the ODBC32 dynamic-link library. The file ODBC32.DLL is invalid.

Reinstall the ODBC component of Visual FoxPro.


Offline view must be used online for this command (Error 2015)

When you are using a view in administrator mode, normal online use and table update operations are not valid. For more information, see the VIEW ADMIN clause of the USE command.


Offline views must be used exclusively when being used online (Error 2010)

Use the EXCLUSIVE clause together with the ONLINE clause to access the offline view. For more information, see USE.


OLE Changed Properties stream is the wrong version. Subclassed properties ignored. (Error 2003)

The names and values of the OLE object properties could not be read from the form (.scx) or class (.vcx) file.

  • The information is missing from the file or the file is corrupt.

    Reapply your recent changes and save the file in the Form Designer or Class Designer. The correct information is written out.

  • The version number for the OLE object has changed.

    Contact the vendor of the OLE object.


OLE error code 0x"name" (Error 1426)

You have received an error code from OLE (in hex), and a brief description of the error. The remedy depends on the error returned by OLE.


OLE exception error "name". OLE object may be corrupt. (Error 1440)

A COM object or COM control caused a general protection fault, possibly because it was passed bad parameters. Release or reload the COM object or COM control.


OLE IDispatch exception code "name" (Error 1427)

You have received an error code returned by an Automation object. It is specific to the OLE object. The object did not provide any other textual information about the error.

Refer to the object's documentation for more information.


OLE IDispatch exception code "number" from "name": "name" (Error 1428)

You have received an error code returned by an Automation object. It is specific to the OLE object.In this case, the object returns a textual description of the error, as well as the source (usually OLE object name) of the error.

Refer to the object's documentation for more detailed information.


OLE object is invalid or corrupted (Error 1420)

The data stored in a general field for an OLE object cannot be validated.


One of the members of this class is based on a nonvisual class. Cannot write .VCX file (Error 1965)

You have included a non-visual class in your class definition.

Remove it and try again.


One of the members of this Form or FormSet is based on a nonvisual class. Cannot write .SCX file (Error 1968)

You have included a non-visual class in your form set.

Remove it and try again.


Only insertable objects are allowed in General fields (Error 1436)

Insertable objects are objects such as a Microsoft Excel worksheet or Microsoft Word document. These are allowed in General fields. Non-insertable objects are objects such as ActiveX controls. ActiveX controls are not allowed in General fields.


Only structural tags can be defined as candidate (Error 1885)

You have attempted to create a candidate key (as with INDEX ON ... CANDIDATE) that was either an IDX file or a tag in a CDX file other than the CDX file specified.

Create the candidate index in the structural CDX file.


Operation is invalid for a General field (Error 1912)

You have attempted to perform an invalid operation, such as a calculation or indexing, on a General field.


Operation is invalid for a Memo, General, or Picture field (Error 34)

  • An INDEX command cannot specify a Memo field as its key expression.
  • There was not enough memory for Visual FoxPro to complete an operation.
  • Unions between differing column types are not allowed when one of the columns is of Memo or General type unless UNION ALL is used.


Operation is not allowed for CursorAdapter. (Error 2076)

Occurs when attempting an operation that is not permitted such as when the TABLEUPDATE( ) function attempts to perform an insert, update, or delete operation, and the corresponding CursorAdapter AllowUpdate, AllowDelete, or AllowInsert properties are set to False (.F.).


Operation is not allowed for CursorAdapter at this time. (Error 2077)

The CursorAdapter object is currently being used in another process or otherwise cannot be used at the time it was called.


Operator/operand type mismatch (Error 107)

An arithmetic, string, or logical operator or function is being used with an invalid data type. This error would occur, for example, if you were to attempt to add two logical values.


OrderBy clause is too long. (Error 2052)

You have specified an OrderBy clause using more than 256 characters.


Page frame cannot be sized that small (Error 1413)

Page frames must be tall enough to display one row of tabs, if the Tabs property is set; otherwise, they must be at least one pixel tall.

  • You tried to resize the page frame to less than the height of one row of tabs.

    Make the page frame taller.


Paradox file format is invalid (Error 1688)

The Paradox file you have attempted to import is either not version 3.5 or has been corrupted.


Parent object will not allow this property setting for "name" (Error 1767)

You have attempted to set a property value on an object whose parent is controlling the setting of that property.

For example, when you try to set the ControlSource property of a contained control in a grid column, and the Bound property for the grid column has been set to true (.T.), you will get this error message because the ControlSource property for the control is taken from the grid column's ControlSource Property.


Picture error in GET statement (Error 1217)

The PICTURE clause within an @ ... SAY or @ ... GET statement contains a picture that cannot include the value to be formatted. This error might be occurring because the picture is corrupt or because the value to be formatted does not match the picture format.


Picture too big, corrupt, or in wrong format (Error 1108)

You attempted to use an invalid picture file.


Popup too big, first nExpr entries shown.

You specified too many items to be shown in the menu.


Preprocessor expression is invalid (Error 1722)

Only simple expressions (evaluation, concatenation, and math) are allowed in preprocessor commands (#IF and so on).


PREVIEW clause is not allowed with OFF/NOCONSOLE or TO PRINT/FILE (Error 1681)

Page preview is not allowed when the console is not on or when printing to the printer or a file.


Primary key already exists (Error 1883)

You have attempted to use the ADD PRIMARY KEY clause of the ALTER TABLE command on a table that already has a primary key.

Remove the existing primary key first.


Primary key property is invalid; please validate database (Error 1567)

The primary key property for this table in the database is corrupted.

Use VALIDATE DATABASE to correct the problem.


Printer access denied (Error 1956)

An internal call to the OpenPrinter( ) function has failed. Visual FoxPro calls this function through either PRTINFO( ) or SET PRINTER TO.


Printer driver is corrupted (Error 1643)

An attempt has been made to load a printer driver that is corrupted.


Printer driver is not found (Error 1644)

The specified printer driver could not be located.


Printer is not ready (Error 125)

The printer device specified is currently not accessible or the printer is timing out. The TIME parameter in your Visual FoxPro configuration file might need to be increased.


Printer redirection is invalid (Error 124)

Either a path to a printer is not established or the print device cannot be shared.


Procedure "name" is not found (Error 1162)

The procedure specified with the IN clause of the DO command could not be located.


Procedure file "name" is not found (Error 1937)

You have specified a name in a RELEASE PROCEDURE name command that is not in the SET PROCEDURE list.


Product has not been properly installed.

Reinstall your copy of Visual FoxPro.


Program is too large (Error 1202)

The program that Visual FoxPro is attempting to load will not fit into memory. The largest program or individual procedure Visual FoxPro can load is one containing 65,000 bytes.


Project file "name" is in the wrong version (Error 1946)

The project file specified does not match the version of Visual FoxPro.


Project file is invalid (Error 1685)

The project file specified has become corrupted.


Project file is read-only (Error 1169)

Visual FoxPro does not allow you to open read-only projects.

Make the project writable and then try again.


Property "name" already exists (Error 1763)

The object already has a property with this name.

Give the new property a unique name.


Property "name" has invalid value. (Error 2145)

Occurs when the CursorAdapter objects UpdateableFieldList and UpdateNameList properties are set to invalid values.

  • Make sure the values assigned to the above properties are valid. For more information see, Data Access Management Using CursorAdapters.


Property "name" is not a method or event (Error 1738)

You used a name that is not a method or event.


Property "name" is not found (Error 1734)

The property name you specified cannot be found.

Check the name of the property and try again.


Property "name" is protected (Error 1757)

You cannot change the value of a protected property.


Property "name" is read-only (Error 1743)

You cannot change the value of a read-only property.


Property does not have a default value. (Error 1138)

ResetToDefault can only be called for properties that have inheritable default values.

  • The property is read-only or is one of the following:

    Alias, ChildOrder , CursorSource., Database, Name, Order, ParentAlias, RelationalExpr.


Property is invalid for local cursors (Error 1467)

The property is not supported for cursors based on local tables or local views; it applies only to cursors based on remote views. Use the property only for remote view cursors.

When using the CURSORGETPROP( ) function, the ADORecordset property is not valid for cursors that are not based on ADO Recordsets.


Property is invalid for table cursors (Error 1468)

The property is not supported for cursors based on tables; it applies only to cursors based on views. Use the property only for view cursors.

For a cursor created by a CursorAdapter object, the SQL property for CURSORGETPROP( ) is not valid for table cursors when the DataSourceType property is specified as "XML".


Property is not found (Error 1559)

The property name you specified cannot be found or is not valid for the specified object.

Check the name of the property and try again. Make sure the object and property are compatible.


Property setting will not take effect until data environment reloaded (Error 1739)

You attempted to set a property on a data environment object (Relation, Cursor) while the data environment is loaded. The property value will be stored with the object, but the property will not take effect until the data environment is unloaded and then reloaded.

To unload the data environment

  • Issue CloseTables in the form:
    [Formset.]Form.DataEnvironment.CloseTables

To reload the data environment

  • Issue OpenTables in the form:
    [Formset.]Form.DataEnvironment.OpenTables


Property value is invalid (Error 1560)

You attempted to set a property value for a cursor or database object that was not in the range or type defined for that property.

Check for valid values and change the value to match the property type.


Property value is out of bounds (Error 1469)

The property value is outside the limits allowed for this property.

Change the value to be valid for this property.


Query Parse Error - try rebuilding in Query Wizard or by using View Designer Join Tab (Error 2055)

This error may occur in certain circumstances when the View Designer or Query Designer is unable to parse the query.

  • Attempt to rebuild the query using the Query Wizard.
  • Make changes to the query in the View Designer Join Tab by removing, changing, or re-adding tables and relations to the query.


Queue "queue" is not found (Error 1716)

The queue specified in the SET PRINTER TO command cannot be found.


Reconnect of offline view failed (Error 2018)

The view cannot be reconnected as an online view: one of the components of the view is not available or missing. For example, a base table for the view might be locked exclusively or be missing, or the database container (.dbc) file might be missing.


Record is in use by another user (Error 109)

You have attempted to write to a record that is locked by another user.


Record is not in index (Error 20)

A key field of the table in use has been modified without the index having been active.

Apply the REINDEX command to the table file.


Record is not locked (Error 130)

An attempt was made to use a BROWSE, CHANGE, EDIT, DELETE, GATHER, MODIFY MEMO, READ, RECALL, or REPLACE command on a record that was not locked.


Record is out of range (Error 5)

The record number you attempted to access is beyond the actual number of records contained in the current table.

  • The current index does not match the table

    Issue REINDEX on the table to try and correct the problem.


Record is too long (Error 1126)

While attempting to create a table file, the maximum length for the data portion of a record (65,500 bytes) was exceeded. The length of the data portion of a record is equal to the sum of the lengths of the individual record fields.


Record validation rule is violated (Error 1583)

The operation you have attempted is in violation of a record validation rule.

Fix the record values or revert the record.


Recursive macro definition (Error 1206)

The maximum number of macro substitutions (256 in any one statement) has been performed in the current line.

  • A macro references itself.


Related table is not found in current database (Error 1880)

A database relation object is being created or referenced for which the related table could not be found.

  • You used the REFERENCES clause of the CREATE TABLE or ALTER TABLE command.

    Make sure both tables involved in the relation are in the database.


Related tag is not found or not primary or candidate (Error 1882)

A database relation object is being created or referenced in which some of the related information was missing, not primary or candidate, or invalid.

  • You used the REFERENCES and TAG clauses of the CREATE TABLE or ALTER TABLE command.

    Make sure both tables involved in the relation are in the database.


Relation already exists. (Error 1183)

The tables are already related.


Relational expression is not valid (Error 1555)

The RelationalExpr property is not valid.

Make sure the expression is not empty and can be evaluated.


Removing a class member is not allowed (Error 2016)

An instance of a class cannot remove class members.

  • You tried to use RemoveObject.

    Use AddObject and then set the CurrentControl property.


Report contains a nesting error (Error 1645)

A user-defined function in a report form has called REPORT FORM.


Report file "name" is invalid (Error 50)

A report description contains an error.


Result is incompatible with cursor schema. (Error 2074)

Occurs if the CursorFill method is called with the lUserCursorSchema parameter set to True (.T.), and the field definitions do not match with the type or precision of the fields in the base table.

  • Make sure that the field types and precisions match the base table.
  • The lUserCursorSchema parameter should only be used if necessary, such as when converting XML that does not have a schema, and you need to control the field types.


RETURN/RETRY statement not allowed in TRY/CATCH. (Error 2060)

A RETURN statement cannot appear in a TRY...CATCH...FINALLY structure.


ROLLBACK command cannot be issued without a corresponding BEGIN TRANSACTION command (Error 1592)

A transaction must be ongoing to use the ROLLBACK command.


Row or column position is off the screen (Error 30)

A row or column number specified in an @ command is larger than the number of rows or columns on the screen, window, or printer.


Rule and trigger code must balance transaction usage (Error 1598)

A rule or trigger expression, or code invoked from an expression, has either started a transaction that it did not finish or finished one that it did not start. The write attempt that fired the rule or trigger code has been aborted.


RUN|! Command failed. "Details" (Error 1405)

The operating system message that accompanies this Visual FoxPro message indicates why it cannot create a process to execute a RUN command.

Most often, this error occurs because of the inability to find the shell program to be executed or does not have sufficient free memory to load the shell program into memory.


RUN|! command string is too long (Error 1411)

The command string included with the RUN command is too long. The maximum length allowed is approximately 240 characters.


Saving a converted form as a class is not supported (Error 1490)

You have attempted to save a FoxPro 2.x converted screen as a class with the SaveAsClass method. This is not a valid operation.


Screen code is too large for available memory (Error 1507)

The screen object you are trying to copy has code larger than 64 KB.


SelectCmd is empty. (Error 2139)

Occurs when the SelectCmd property is empty. Visual FoxPro requires that the SelectCmd property is set to a valid value, appropriate to the what the DataSourceType property specifies, when the CursorFill method is called.

  • Make sure that the SelectCmd property is set to a valid value.


SELECTs are not UNION compatible. "Details" (Error 1851)

This occurred for one of the following possible reasons:

  • The number of fields do not match. Make sure the number of fields match.
  • The specified fields are not compatible. Make sure the specified fields are compatible.
  • Data types or sizes of fields being projected in each SELECT statement are not identical.


Server "server" is not found (Error 1715)

The server specified with the SET PRINTER TO command could not be found.


Session number is invalid (Error 1540)

Use a valid session number with SET DATASESSION TO.


Source code not found.

The file you specified cannot be located in the specified directory.


Source code out of date.

The date source code you specified does not match the compiled (.FXP) file.


SQL expression is too complex (Error 1845)

Visual FoxPro ran out of memory when it tried to expand the SELECT statement in order to analyze it.


SQL parameter "name" is invalid (Error 1499)

The SQL parameter definition in a SQLEXEC( ) call, or in a view definition, contains a syntax error.

  • It is missing the closing character for a string constant or a closing right parenthesis.

    Check the parameter definition following the "?" operator in the SQL string and correct the parameter syntax.


SQL parameter is missing (Error 1493)

The parameter marker (?) in a SQL statement used in SQLEXEC( ) or in a view definition is not followed by the parameter expression.

Add the parameter expression after the parameter marker.


SQL pass-through internal consistency error (Error 1465)

Internal SQL pass-through error.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


SQL SELECT statement is invalid (Error 1498)

The SQL statement which defines a view is missing the SELECT or FROM clause. Correct the syntax of the SQL statement. For more information, see SELECT - SQL.


SQL statement parameter is required for non-prepared SqlExec( ) calls (Error 1472)

You must either use SQLPREPARE( ) first or include a SQL statement in the call to SQLEXEC( ).

  • SQLPREPARE( ) has not been called.

    Include a SQL statement directly in SQLEXEC( ) or call SQLPREPARE( ) before calling SQLEXEC( ).

  • The prepared state has been cleared because SQLEXEC( ) was called with a cSQLCommand argument or because SQLPREPARE( ) was called.

    Call SQLPREPARE( ) again.


SQL: Aggregate on non-numeric expression (Error 1811)

There was an attempt to perform an average, sum, standard deviation or variance on a non-numeric field.


SQL: Cannot determine data type of SQL column "column" (Error 1890)

Visual FoxPro cannot determine the data type of the specified SQL column because the first record in the field contains a null value.


SQL: Cannot locate table (Error 1802)

The table you have specified could not be found.


SQL: Column "field | variable" is not found (Error 1806)

The field or variable you specified cannot be found.


SQL: DISTINCT is invalid (Error 1819)

You can use only one DISTINCT clause per level.


SQL: Error building temporary index (Error 1831)

A temporary index could not be built, possibly due to insufficient disk space.


SQL: Error correlating fields (Error 1801)

An outer reference can be used only in syntax similar to the following:

X = Y

Syntax such as X = Y + 1 or X = 5 will produce this error.


SQL: FROM clause is required (Error 1818)

There must be a FROM clause in the SELECT command. For more information, see SELECT - SQL.


SQL: GROUP BY clause is invalid (Error 1807)

There is an error in the GROUP BY clause. For more information, see SELECT - SQL or SET ENGINEBEHAVIOR.


SQL: HAVING clause is invalid (Error 1803)

There is an error in the HAVING clause.

For example, the clause might not contain a logical expression. For more information, see SELECT - SQL.


SQL: Illegal GROUP BY in subquery (Error 1828)

When using one of the six operators +, -, *, /, < and >, there can be only one row of output. For more information, see SELECT - SQL.


SQL: Index is not found (Error 1830)

Visual FoxPro could not find the existing index. For more information, see SELECT - SQL.


SQL: Internal error (Error 1800)

An internal error has occurred.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


SQL: Invalid aggregate field (Error 1822)

You have attempted to perform aggregation on a Memo field.


SQL: Invalid SET expression in UPDATE (Error 1865)

Check the expressions in your SET clauses. For more information, see the UPDATE command.


SQL: Invalid TOP specification (Error 1866)

The TOP clause of the SELECT - SQL command requires a value greater than zero. If the PERCENT clause is present, the value must be greater than zero and less than 100. In both cases, the value must be numeric.


SQL: Invalid use of subquery (Error 1810)

A subquery was used in a place where it wasn't expected. For more information, see SELECT - SQL.


SQL: Operation was canceled (Error 1839)

There was an attempt to run a SELECT statement on a table when SAFETY was ON and the user chose not to overwrite the table. For more information, see SELECT - SQL.


SQL: ORDER BY clause is invalid (Error 1808)

One of the fields chosen for the ORDER BY clause is not in the SELECT list. This occurs only when using numeric indexing as in the following example where the number chosen exceeds the number of fields selected:

SELECT a,b,c FROM table ORDER BY 4

For more information, see SELECT - SQL.


SQL: Out of memory (Error 1809)

Visual FoxPro has run out of memory while trying to process your SELECT command. For more information, see SELECT - SQL.


SQL: Queries of this type are not supported (Error 1814)

You have attempted to run a query that is not supported by FoxPro versions 2.5 through the current version. For more information, see SELECT - SQL.


SQL: SELECT contains invalid * (Error 1820)

You have attempted to use * in one of the aggregate functions of MAX( ), MIN( ), AVG( ), or SUM( ).

For more information, see SELECT - SQL and the CALCULATE command.


SQL: SELECT is invalid (Error 1826)

You have attempted to select more than one field in a subquery. For more information, see SELECT - SQL.


SQL: Statement is invalid (Error 1804)

There is an error in the projection list. For more information, see SELECT - SQL.


SQL: Statement too long (Error 1812)

The object code is too long to be compiled. For more information, see SELECT - SQL.


SQL: Subquery is invalid (Error 1825)

Something in the subquery is erroneous. For more information, see SELECT - SQL.


SQL: Subquery nesting is too deep (Error 1842)

Visual FoxPro does not support nested subqueries. For more information, see SELECT - SQL.


SQL: Too many columns referenced (Error 1841)

There must be no more than 256 columns total referenced in any SELECT command. For more information, see SELECT - SQL.


SQL: Too many fields in UPDATE (Error 1864)

You have attempted to issue UPDATE - SQL with more than 128 fields to update.


SQL: Too many subqueries (Error 1805)

The number of subqueries allowed in Visual FoxPro is two per SELECT statement. For more information, see SELECT - SQL.


SQL: Too many UNIONs (Error 1834)

The maximum number of UNIONs (10) has been exceeded. For more information, see SELECT - SQL.


SQL: TOP requires an ORDER BY (Error 1867)

You must provide an ORDER BY clause if you use the TOP clause. For more information, see SELECT - SQL.


SQL: Use of UNION in subquery is invalid (Error 1813)

UNION is not supported in subqueries in Visual FoxPro. For more information, see SELECT - SQL.


SQL: WHERE clause is invalid (Error 1833)

There is an error in the WHERE clause. For more information, see SELECT - SQL.


SQRT( ) argument cannot be negative (Error 61)

SQRT( ) function arguments must not be negative.


Statement is not allowed in interactive mode (Error 95)

The commands IF, ELSE, ENDIF, TEXT, ENDTEXT, EXIT, RETRY, RETURN, SUSPEND, DO WHILE, ENDDO, DO CASE, ENDCASE, SCAN, ENDSCAN, FOR, and ENDFOR are not allowed in the Command window; you must use these statements in a program.


Statement is not in a procedure (Error 1931)

Statements are not allowed after the ENDPROC clause. For more information, see DEFINE CLASS.


Statement is not valid in a class definition (Error 1927)

You have used a command that is not permitted within a DEFINE CLASS structure. Valid commands are: ADD OBJECT, ADD PROTECTED OBJECT, DIMENSION, FUNCTION, PROCEDURE, and PROTECTED. For more information, see DEFINE CLASS.


Statement is only valid within a class definition (Error 1928)

PROTECTED, ADD OBJECT, and ADD PROTECTED OBJECT commands are valid only within a class definition. For more information, see DEFINE CLASS.


Statement only valid within a method (Error 1934)

You have attempted to use the :: (scope resolution) operator outside of a method. Since the scope operator is driven from the THIS object reference, it can only be used within a method.


String is too long to fit (Error 1903)

The allowable string length was exceeded.


Structural .CDX file is not found (Error 1707)

The structural index file associated with a table file could not be found.


Structure is invalid (Error 1235)

In CREATE FROM, a table was specified whose structure does not match the STRUCTURE EXTENDED format.


Structure nesting is too deep (Error 1212)

The maximum structured programming command nesting of 64 levels has been exceeded.


Subquery returned more than one record (Error 1860)

Subqueries linked with the six normal operators <>, =, <=, >=, < or >, excluding ALL or ANY, can produce only a one-row result.


Subscript is outside defined range (Error 1234)

An attempt was made to reference an array element with a subscript that is outside of the range defined in the DIMENSION statement.


Suspend program before using RESUME (Error 1236)

RESUME is applicable only when a program is suspended.


Symphony version 1.0 file format is invalid (Error 1673)

The Symphony file you have attempted to import is either not version 1.0 or has been corrupted.


Symphony version 1.1 file format is invalid (Error 1674)

The Symphony file you have attempted to import is either not version 1.1 or has been corrupted.


Syntax error (Error 10)

You have issued a command that is syntactically incorrect.

  • You might have misspelled the command or variable name, or used a clause that is not valid in the current context.

    Press F1 to see context-sensitive help on the command.


Syntax error in the field expression (Error 1242)

There is an invalid expression involving a field.


Tab stops must be in ascending order (Error 228)

The tab stops defined for the system variable _TABS must be in ascending order.


Table "alias" has one or more non-structural indexes open. Please close them and retry the Begin Transaction (Error 1548)

Close all non-structural (non-.CDX) indexes and try the operation again.

If other indexes are open on the file, their writes will go directly to disk and will not be reflected in the table changes until you issue END TRANSACTION. Consequently, if a ROLLBACK is issued, the non-structural indexes will be incorrect.


Table "name" already exists in the database (Error 1564)

You have attempted to add a table to the database that was already in the database.


Table "name" has become corrupted. The table will need to be repaired before using again. (Error 2091)

Either the table record count does not match the actual records in the table, or the file size on the disk does not match the expected file size from the table header. Repair the table using an appropriate third-party repair utility for Visual FoxPro tables before opening the table again.


Table "name" is referenced in a relation (Error 1577)

You cannot remove a table from a database if that table is involved in a relation.

Delete the relation first.


Table buffer for alias "name" contains uncommitted changes (Error 1545)

The named cursor has a modified table buffer, so changes must be explicitly committed using TABLEUPDATE( ) or discarded using TABLEREVERT( ) before either closing the cursor or changing the buffering mode.


Table buffering is not enabled (Error 1596)

You have attempted to use the GETNEXTMODIFIED( ) function, which requires table buffering to be enabled.

Enable table buffering or use a different function.


Table cannot be browsed because cursor object is no longer valid. (Error 1556)

Close and reopen the Form Designer to resynchronize the table and the cursor.


Table has no index order set (Error 26)

The records in the table have no order.

  • An index for the table file was not selected when an UPDATE command using the RANDOM clause was encountered.

    Select an index for the table file.

  • A FIND or SEEK was attempted against a table with no index ordering.

    Use SET ORDER TO to specify an index order.

  • SET RELATION was issued with a non-numeric expression.

    Provide a numeric expression.


Table number is invalid (Error 17)

Select a table number between 1 and 225.


Table operation is invalid during indexing (Error 1690)

You have attempted to perform a table operation in a user-defined function referenced with an index expression.


Table or row buffering requires that SET MULTILOCKS is set to ON (Error 1589)

All buffering modes require MULTILOCKS to be enabled. TO disable buffering, set buffering to 1 (DB_BUFOFF) using CURSORSETPROP( ).


Tag name is too long (Error 1888)

Tag names cannot exceed 10 characters.


Target table is already engaged in a relation (Error 1147)

There is more than one relationship between the currently selected table file and one of its targets.


Text generation is canceled (Error 1792)

The text generation program, SCCTEXT.PRG (or the program whose value is stored in the _SCCTEXT system variable), has been halted.

  • You pressed the ESC key.

    The program was creating text versions of project files to check into source control. Avoid pressing ESC while checking files in.


Textmerge is recursive. (Error 2044)

The textmerge statement evaluates to an expression that, itself, performs a textmerge.


The ActiveX control module failed to register correctly (Error 1438)

The file does not appear to be a valid ActiveX control.

  • The ActiveX control does not have a self-registration function.

    Contact the ActiveX control vendor for an updated control that contains a working DllRegisterServer function.


The builder program is already running (Error 1954)

You have attempted to invoke a builder program while the builder is already running. This is not a valid operation.


The ChildOrder property of a relation object in the data environment is no longer valid. The relation is being removed (Error 1478)

Due to data environment changes, the relation of a ChildOrder property has been removed.


The class file associated with this field cannot be found - class association cleared. (Error 2020)

The class is not valid or cannot be found.

  • You modified a table that had a field/class association whose class file could not be read.

    Assign a valid class to the field.


The clipboard contained one or more objects that could not be added to the container. Those objects were not pasted (Error 1969)

You have attempted to paste something invalid ? for instance, a toolbar separator ? onto a form or control.


The current Help file is empty. (Error 2036)

The Help file you have specified contains no information. Specify another file.


The current object does not inherit from class "name" (Error 1935)

You have specified a class name that is not in the inheritance hierarchy of the current object.


The current object has been released (Error 1945)

You have issued RELEASE THIS in the destroy event of the current object.


The data source for this object must be a variable reference (Error 1742)

You have specified an invalid data source or control source for an object.

  • A data source or ControlSource property must contain a variable.

    Make sure you have not specified an expression.


The database must be opened exclusively (Error 1557)

Commands such as VALIDATE DATABASE RECOVER, PACK DATABASE, and those involving creation or modification of database objects require exclusive access to the database.

Close the database and reopen it using OPEN DATABASE FileName EXCLUSIVE.


The DataObject cannot be modified in the OLEDragOver or OLEDragDrop event. (Error 2021)

The DataObject methods are not supported in these events.


The default value for field "name" does not evaluate to the correct type for the field (Error 1997)

A default value expression must evaluate to the data type for the field.

Change the expression to evaluate to the correct data type.


The directory is not empty (Error 1962)

You cannot delete a directory that contains files or subdirectories.


The fields in table "name" did not match the entries in the database (Error 1984)

When opening a database-owned table, Visual FoxPro tries to confirm that each field of the table has a matching field object in the database.

  • The database or the table has been corrupted.

    Use VALIDATE DATABASE to identify the problem.

  • The table being opened is the wrong one.

    Remove and re-add the table to the database.


The file specified in the FROM clause is empty (Error 1131)

There are no records in this file.


The IN clause is not supported for this window (Error 1699)

This window cannot be placed inside another window.

  • You used the ACTIVATE WINDOW command to try and place one of the debugger windows inside another window.

    Use a different window, or change your debugging environment in the Debug tab of the Options dialog box.


The index expression for index "name" contains an invalid reference to a Memo, General, or Picture field (Error 1998)

You cannot index on Memo, General, or Picture field types.


The LOCATE command must be issued before the CONTINUE command (Error 42)

You have attempted to execute a CONTINUE command without first executing a LOCATE command.


The name "name" is already used for another object. Please choose a different name (Error 1571)

No two top-level objects in the database can have the same database name.

Use DISPLAY DATABASE to see a list of all the objects in the database.


The name of the object file for "file" is already used by another program in the project (Error 2001)

Select a different file name.


The network request is not supported (Error 1793)

Visual FoxPro was unable to obtain information about a file on the network.

  • There are no drive letters available.

    Free up a drive letter and try the request again.


The Remote View Wizard was unable to obtain column information for this remote table. This may be the result of an ODBC error, or the remote table may not be owned by the current user.

If the query you are using doesn't contain the owner name for the table you specified, the information from the remote table will be unavailable.

To correct this problem, use the View Designer to add the current user as the owner of the table to the SQL string.

If you still get an error, you must correct the problem in ODBC.


The selected printer driver does not support direct access (Error 1524)

The printer you have selected and set through your operating system does not allow direct access. You can try the Generic/Text Only driver, or the equivalent, in Windows. Bear in mind that the "ASCII File" option in Visual FoxPro bypasses the printer driver and sends the contents of the selected file directly to the printer. You are responsible for making sure that any file sent in this manner contains valid printer commands, and/or that an appropriate driver is selected.


The specified class library does not exist or does not contain a valid member class. (Error 2057)

Make sure the class library you specify exists and contains a valid member class.


The specified file or path was not found. (Error 2022)

The file that you attempted to drop in an OLE drag-and-drop operation could not be located.


The specified Key already exists. (Error 2062)

The specified key exists for a member in the collection. Try using a different key. Keys are case-sensitive, so you can use a key that has different casing.


The specified member class does not exist or is of wrong type. (Error 2056)

Make sure the member class you specify exists and is of the correct type.


The table changes cannot be performed as the index or filter expression for index name would be invalid (Error 1531)

You have attempted to use the ALTER TABLE command where the result would render an existing index or filter expression invalid, even if it not explicitly modified by the ALTER TABLE command.


The table file "name" has moved. Please validate database "name" and try again (Error 2004)

A cursor that is part of a data environment cannot find a table that is part of a database (.dbc file).


The table has memo fields that cannot be converted while open read-only (Error 1659)

You have attempted to perform a read-only operation on a dBASE IV style memo. Visual FoxPro cannot convert a memo in a read-only operation.


The table must be converted before appending (Error 1778)

You have attempted to use the APPEND FROM command on a table that was not created with Visual FoxPro.

Back up your original file and convert a copy of the table for use with Visual FoxPro.


The TO clause can only be used with modal Forms and FormSets (Error 1982)

You have attempted to use the DO FORM command with the TO clause:

DO FORM x TO variable.

This operation is illegal on modeless forms and form sets.


The validation rule for field "name" does not evaluate to a logical or NULL type (Error 1996)

The field validation rule result must be either a Logical type or a NULL.


There is a duplicate field "name" in XML schema. (Error 2105)

Visual FoxPro does not allow schemas to define more than one field with the same name.

  • Make sure the XML source returns the XML in a correct and expected format.
  • Correct the supplied schema and XML document.


There is a duplicate table "name" in XML schema. (Error 2104)

Visual FoxPro does not allow schemas to define more than one table with the same name.

  • Make sure the XML source returns the XML in a correct and expected format.
  • Correct the supplied schema and XML document.


There is a missing keyword in the FOR ... ENDFOR or DO CASE ... ENDCASE command structure (Error 1213)

For more information, see the FOR ... ENDFOR and DO CASE ... ENDCASE topics.


There is no application associated with the given filename extension. (Error 2023)

The file that you attempted to drop in an OLE drag-and-drop operation doesn't have an application associated with it.


There is not enough disk space for "name" (Error 56)

There is no room on the disk to complete this operation.

  • Your disk is full.

    Free up some disk space and retry the operation.

  • Under certain versions of Novell, you tried to extend a file that has no owner. This error is returned but is not correct.

    Work around the problem by assigning an owner to the file first.

  • You have a table file larger than 2 gigabytes in size.

    You have exceeded the maximum size for a Visual FoxPro DBF, FPT, or CDX file. Reduce the size of the specified file.


There is not enough memory to complete this operation (Error 43)

Free some memory currently in use and try this operation again.


This array element has been defined as an object and cannot be redefined in the class definition (Error 1780)

Once you have defined an array element as an object member in a class definition, it cannot be redefined.

For example, the following code would cause this error:

DEFINE CLASS test AS form
   DIME a[1]
   ADD OBJECT a[1] AS commandbutton
   a[1] = 10
ENDDEFINE


This command is not supported for views (Error 1777)

Views cannot be changed with this command. This error has the following causes and solutions:

  • Using one of the following commands to change view structure: ALTER TABLE, CREATE TRIGGER, DELETE TRIGGER, and MODIFY STRUCTURE.

    Use a command that operates on views, or use a table instead.

  • Modifying the structure of a view cursor with the Table Designer.

    Use the View Designer to permanently modify the structure of cursors produced with a view definition.


This feature requires MSXML4 SP1 or later. (Error 2116)

Visual FoxPro requires that MSXML 4 SP1 or later is installed to use the XMLAdapter object.


This file is incompatible with the current version of Visual FoxPro (Error 1748)

A file created in a pre-release version of Visual FoxPro 3.0 isn't compatible with the current version of Visual FoxPro. Run 30Update.prg, included with the pre-release version of Visual FoxPro 3.0 to convert the file to a current format.


This object is derived from a base class and does not have a parent class. (Error 1784)

The default class cannot be found. For more information, see DODEFAULT( ).


This OLE property cannot be an expression (Error 1782)

You have attempted to set some of the OLE properties to be an expression in the property sheet. This is not a valid operation.


This operation not supported for class member objects (Error 1521)

You have attempted to clone or copy an object that is a member of a class.


This property is read-only (Error 1533)

You cannot change the value of a read-only property.


To use this feature, set CODEPAGE=AUTO in your CONFIG.FPW file and restart Visual FoxPro (Error 1916)

This error occurred due to an invalid designation with the SET COLLATE command.


Too few arguments (Error 1229)

A function call contains less than the required number of arguments.


Too many arguments (Error 1230)

A function call contains more than the permitted number of arguments.


Too many characters are specified in the PICTURE clause (Error 1310)

The amount of characters permitted in a PICTURE clause is limited by memory.


Too many columns (Error 1872)

You can have a maximum of 255 fields per record.


Too many extensions are specified (Error 1694)

Too many file extensions have been included in a GETFILE( ), LOCFILE( ), or PUTFILE( ) function.

Include no more than 30 file extensions.


Too many files open (Error 6)

Visual FoxPro has attempted to open more than its internal limit of files.


Too many names used (Error 1201)

As a program was being loaded or a table was being opened, the Visual FoxPro name table overflowed.

Divide the program into smaller modules.


Too many PROCEDURE commands are in effect (Error 1250)

The number of procedures is limited to the amount of memory you have.


Too many READ commands are in effect (Error 1249)

The maximum nesting level for the READ command (5) in effect has been exceeded.


Too many variables (Error 22)

The maximum number of variables that can be created has been exceeded.


Too many windows open (Error 1116)

No more windows can be created.

  • You have too many application windows open.

    Close open applications.

  • There are not enough resources available.

    Restart Windows.


Total field type must be Date or Numeric (Error 1646)

A report expression that includes a total specification is not numeric type.


Total label width exceeds allowed size (Error 1246)

The LABEL command detected a condition where the sum of the individual label widths plus separating spaces is greater than the maximum width allowed.


Trigger failed in "cursor". (Error 1539)

Fix record values so the trigger does not fail, or revert the record.


TRY/CATCH/FINALLY/ENDTRY mismatch or error (Error 2058)

TRY...CATCH...FINALLY needs to end with an ENDTRY statement to compile.


Type conversion is not supported (Error 1532)

SQL parameter conversion error. Internal connectivity error.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Type conversion is not supported for output parameters (Error 1501)

SQL parameter conversion error. Internal connectivity error.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Type conversion required by the DataType property for field "name" is invalid (Error 1543)

The type conversion between the remote data type and the Visual FoxPro data type, specified by the view field DataType property, is not supported for the field of the view that is being activated.

Change the view field DataType property to a valid type.


Type Library "name" not found (Error 1444)

You have specified a library that does not exist. Check your statement, the location, and the library name to make sure the file exists where you have specified it.


Unable to attach object with empty XMLName property. (Error 2101)

The XMLName field cannot be empty when adding an XMLTable object or an XMLField object to a collection.

  • Make sure that the XMLName property for the XMLField object or the XMLTable object is set to a valid value, and that this value is used as the key.


Unable to change XMLName property while XMLField object belongs to XMLTable object. (Error 2103)

Visual FoxPro does not allow the XMLName property for an XMLField object, to be changed, when the XMLField object belongs to an XMLTable object.


Unable to change XMLName property while XMLTable object belongs to XMLAdapter object. (Error 2102)

Visual FoxPro does not allow the XMLName property for an XMLTable object, to be changed, when the XMLTable object belongs to an XMLAdapter object.


Unable to close offline view in ADMIN/ONLINE mode inside a transaction. (Error 2122)

You cannot close an offline view in ADMIN or ONLINE mode from within a transaction.


Unable to create temporary work files (Error 1410)

A SORT or INDEX command that requires temporary work files was not permitted by the operating system to create them.

  • Your directory is full.

    Remove some files.

  • Visual FoxPro does not have permission to access the temporary files directory.

    Verify your permissions.


Unable to emit XML, two or more cursors use different code pages. (Error 2133)

Occurs when attempting to call an XMLAdapter objects, ToXML method, when the XMLAdapter objects, AddTableSchema method, was used to add a schema from two or more cursors that have differing code pages.

  • Check to make sure that all of the cursors being converted to XML have the same code page.


Unable to generate a printer driver (Error 1717)

The printer driver associated with the report or label you have chosen cannot be generated or loaded.


Unable to infer XML schema. (Error 2120)

Occurs when the XMLTOCURSOR( ) function is not able to successfully parse the supplied schema and create the cursor.


Unable to locate desired version of Visual FoxPro.

The version of Visual FoxPro requested is not on the designated path.


Unable to open offline view in ADMIN/ONLINE mode inside a transaction. (Error 2121)

You cannot open an offline view in ADMIN or ONLINE mode from within a transaction.


Unable to process error.

No error number is returned. Visual FoxPro closes all open files and exits.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Unable to register the ActiveX control (Error 1437)

The file does not appear to be a valid ActiveX control.

  • The ActiveX control does not have a self-registration function.

    Contact the ActiveX control vendor for an updated control that contains a working DllRegisterServer function.


Unable to set external schema location when inline schema is used. (Error 2123)

The value of the XMLAdapter property, XMLSchemaLocation, cannot be set to Inline Schema (1), when the cSchemaLocation parameter has been populated.


Unhandled Structured Exception (Error 2059)

An unhandled exception can occur under the following conditions:

  • An error that occurred or exception that was thrown in a TRY, CATCH, or FINALLY block was not caught by a structured error handler such as TRY...CATCH...FINALLY.
  • A structured error handler did not catch a thrown exception that occured outside a TRY...CATCH...FINALLY structure.

You can catch an unhandled structured exception using the following unstructured exception handlers:

  • ON ERROR Command
  • Error Event
  • Visual FoxPro system handler

For each of these error handlers, the error number returned by the ERROR( ) function is 2059. Visual FoxPro provides details about the original error. You can also obtain additional information about the original error that caused the unhandled exception from the SYS(2018) - Error Message Parameter, MESSAGE( ), and AERROR( ) functions. The SYS(2018) function returns the same value as the third element in the array returned by the AERROR( ) function. The MESSAGE( ) function returns the same value as the second element in the array returned by AERROR( ).

If the unhandled exception was caused by a THROW statement, the value of SYS(2018) is 2071, or User Thrown Error.


Uniqueness of index "name" is violated (Error 1884)

The uniqueness of primary or candidate key is violated.

Fix the record values or revert them.


Unknown error code nExpr.

No error number is returned. Visual FoxPro closes all open files and exits.

Record your recent actions while using Visual FoxPro and then call Microsoft Support.


Unknown function key (Error 104)

An attempt was made to use SET FUNCTION with a function key that does not match the name or number of an existing function key.


Unknown member "name" (Error 1925)

Visual FoxPro attempted to evaluate the following syntax:

objvar.memberobj.property

No member named memberobj was found.

  • You were attempting to access the members of a control class from outside the class.

    Make sure references to controls, such as with .ActiveControl, are within scope.


Unrecognized command verb (Error 16)

A word used at the beginning of the command line was not a valid Visual FoxPro command. For more information, see Reserved Words.


Unrecognized index file revision. Re-create the index (Error 1141)

The index file is in a format that is not compatible with this version of Visual FoxPro.

Recreate the index.


Update conflict (Error 1585)

An optimistic locking conflict has been detected while trying to update a view.

Make sure your update key is valid.

If you want to commit your changes to the base table(s), call TABLEUPDATE( ) with lForce. This will overwrite the changes made to the base table since the view was last fetched.

To discard the local changes made to the view, call TABLEREVERT( ).


Update conflict. Some of your changes in the current row batch were committed (Error 1595)

The full text of this error message is:

Update conflict. Some of your changes in the current row batch were committed. Use TABLEUPDATE( ) with the lForce parameter to commit the update or the manual transaction to roll back the update (Error 1595)

The multitable update was not included in a remote transaction and failed.

  • Some of the tables involved in the update may be committed in the base remote tables.

    Force the update for the current row or current row batch or rollback the remote manual transaction on the current connection. For more information, see TABLEUPDATE( ).


User-defined functions are not allowed (Error 1097)

User-defined functions are not supported in this area of Visual FoxPro.

Remove the user-defined function.


User-interface operation not allowed at this time. (Error 2031)

This error is generated when unattended server mode is enabled with SYS(2335). If possible, remove the code from your server that creates the modal state that generates this error.


User Thrown Error (Error 2071)

Occurs when you use the THROW command to throw an exception.


Value of XMLField.XMLName must be used as key value for collection. (Error 2100)

The XMLName property for an XMLField must be used as the key, when adding the XMLField to a Fields collection.

  • Make sure that any XMLField objects, that are going to be added to a collection have the XMLName property set to a valid value, and that this value is used as the key.


Value of XMLName, XMLNamespace or XMLPrefix property should be a Unicode string. (Error 2134)

Non-Unicode strings cannot be assigned as values to the XMLAdapter objects, XMLName, XMLNamespace, and XMLPrefix properties.

  • Use the STRCONV( ) function to convert a string to Unicode. The following code converts a string to Unicode.
    oXMLTable = CREATEOBJECT("XMLTABLE")
oXMLTable.XMLName = STRCONV("MyTable",12)


Value of XMLTable.XMLName must be used as key value for collection. (Error 2099)

The XMLName property for an XMLTable must be used as the key, when adding the XMLTable to a Tables collection for an XMLAdapter.

  • Make sure that any XMLTable objects, that are going to be added to a collection have the XMLName property set to a valid value, and that this value is used as they key.


Variable "variable" is not found (Error 12)

The specified variable or field name could not be found.


Variable must be in the selected table (Error 1134)

You can only use fields from the currently selected table in quick screens.


vfp.VFPXMLProgId doesn't support cSchemaLocation parameter for XMLUpdateGram(). (Error 2137)

Occurs when Visual FoxPro attempts to use the cSchemaLocation parameter in a custom implementation of XMLUpdateGram with the vfp.VFPXMLProgid. Visual FoxPro does not allow the use of the cSchemaLocation parameter in custom implementations.

  • If the cSchemaLocation parameter is required in your custom implementation of XMLUpdateGram, add the value to the schema via your own implementation.


View definition has been changed (Error 1494)

The view cannot be re-queried.

  • The view definition in the database has been changed.

    Close and reopen the view. To ensure that the view is not changed, open the database exclusively.


View fields have been changed. The Update and Key field properties have been reset to the default values (Error 1568)

You have attempted to modify a view whose table structure has changed. When you choose OK, the View Designer displays previous view conditions, but the Update Criteria tab resets to the default conditions. There has been no update.


View file is invalid (Error 127)

An attempt has been made to open a view file with invalid data.


Views require either DB_BUFOPTROW or DB_BUFOPTTABLE (Error 1597)

Local or remote view-based cursors support updating only by way of an optimistic buffering mode.


Visual FoxPro cannot start

Visual FoxPro cannot be initialized or configured for one of the following reasons:

  • Insufficient memory.

    Visual FoxPro could not allocate sufficient memory for internal structures. Free up memory and restart Visual FoxPro.

  • Insufficient disk space.

    Visual FoxPro could not allocate temporary files. Free up disk space and restart Visual FoxPro.

  • Vfp7enu.dll could not be loaded.

    Visual FoxPro cannot find Vfp7enu.dll because it is missing or has been renamed. Reinstall Visual FoxPro.

  • The resource file you specified with the -L startup switch could not be loaded.

    Visual FoxPro cannot find the file you specified. Check that the file you specified with the -L switch is available.

  • Visual FoxPro requires Windows 98, Windows ME, or Windows 2000 or later.

    Install one of the supported Windows operating systems.

  • Product in use by another.

    Make sure that you have the correct network access rights. See your Windows documentation.

  • Invalid or missing .EXE file.

    Reinstall Visual FoxPro.


Volume does not exist (Error 1922)

The volume specified in the SET VOLUME command (supported only in Visual FoxPro for Macintosh) doesn't exist.


Warning: Invalid data conversion(s) starting at record "number" (Error 1485)

A data conversion error was reported while fetching data in record number of the remote result set.

  • The ODBC driver cannot convert some remote data values into the local view data type.

    Use a conversion function in the remote SQL statement to convert the data to a different data type before being fetched; use the DataType view field property to change the local data type.


Warning: Invalid memo field conversion(s) starting at record "number" (Error 1486)

A memo conversion error was reported while fetching large data in record number of the remote result set.

  • The ODBC driver cannot convert some large remote data values into the local view data type.

    Use a conversion function in the remote SQL statement to convert the data to a different data type before being fetched; use the DataType view field property to change the local data type. Use server-specific settings to limit the amount of data sent for each large data value.


Warning: No information is available to check remote update conflicts (Error 1496)

The ODBC driver does not report the number of records affected by an UPDATE, DELETE, or INSERT statement. Optimistic locking conflicts on remote views using this connection will not be reported.

Be sure your update code handles this limitation.


Warning: The connection packet size cannot be set (Error 1483)

The connection packet size cannot be set by the ODBC driver. The connection will use the default driver defined packet size. This might affect performance on this connection.

Check the driver and network documentation for alternative ways to set up the network packet size.


Warning: The connection sync/async mode cannot be set (Error 1480)

The connection sync/async mode cannot be set by the ODBC driver. The connection will use the default driver defined sync/async mode. This will not allow SQL pass-through functions to return control while an ODBC call is in progress.


Warning: The connection timeout cannot be set (Error 1481)

The connection timeout interval cannot be set by the ODBC driver. The connection will use the default driver defined timeout interval. This will not allow SQL pass-through functions to return control while an ODBC call is in progress.


Warning: The connection transaction mode cannot be set (Error 1487)

The connection transaction mode cannot be set by the ODBC driver. The connection will use the default driver defined transaction mode.


Warning: The key defined by the KeyField property for table "alias" is not unique (Error 1495)

The key specified for this table changed more than one row in the base table for some of the remote view rows being updated.

Redefine the key using the KeyField view property.


Warning: The next "cExpr" modified records have already been updated remote (Error 1484)

An error has occurred while trying to update a batch of modified rows of a remote view, in the view cursor, after the batch has been successfully updated in the remote base table.

Turn off the SendUpdates view property and commit the records by calling TABLEUPDATE( ).


Warning: The query timeout cannot be set (Error 1482)

The connection query timeout cannot be set by the ODBC driver. The connection will use the default driver defined query timeout.


Width or decimal place argument is invalid (Error 1908)

Either the length or decimal argument was invalid in the STR( ) function.

The sum of the specified left margin and paragraph indent exceeds the right margin.


WIN.INI/registry is corrupted (Error 1955)

You have attempted to get print information from the operating system by using PRTINFO( ) or SET PRINTER TO but no default printer is selected.

Use the Printer Control Panel to select set a default printer.


Window "name" has not been defined (Error 1714)

You have referenced a window that does not exist.

  • The window has not been created, or it has already been destroyed.

    Create the window, or reference a different window.


Window file format is invalid (Error 1632)

The window save file (.WIN) being restored does not contain valid data.


Window has not been activated with ACTIVATE WINDOW (Error 215)

An attempt was made to use a window, which has not been activated. For more information, see ACTIVATE WINDOW.


Window has not been defined with DEFINE WINDOW (Error 214)

An attempt has been made to activate a window that has not been defined.

Use the DEFINE WINDOW command before using the ACTIVATE WINDOW command.


Window specified in DEFINE WINDOW has invalid coordinates (Error 332)

An attempt was made to define a window's coordinates outside the allowable range.


WITH/ENDWITH mismatch (Error 1939)

You must have a corresponding ENDWITH statement for every WITH statement.


Worksheet "name" is not found (Error 1775)

You are trying to specify a worksheet name that does not match a name in the specified .XLS file.

Verify the worksheet name and try the operation again.


Worksheet A for Lotus 1-2-3 version 3.0 file is hidden (Error 1680)

Visual FoxPro cannot import a worksheet that has been hidden.


XML document does not have a root element. (Error 2124)

Visual FoxPro does not allow empty DOM or DOM Nodes to be attached to the XMLAdapter object.


XML document is not a DiffGram. (Error 2126)

Visual FoxPro does not allow the ApplyDiffGram method and the ChangesToCursor method to be called when the IsDiffgram property of the XMLTable object is set to False (.F.).


XML document is not loaded. (Error 2096)

The ApplyDiffGram method, ChangesToCursor method, and ToCursor method and the associated XMLAdapter object must have an XML document loaded.

  • Check the XMLAdapter objects IsLoaded property to see if an XML document has been loaded.


XML Error: "error" (Error 2110)

Occurs when an error is called from the MSXML object, while attempting to load or attach XML.


XML node does not belong to MSXML4.DOMDocument. (Error 2128)

Visual FoxPro requires that XML data cannot be accessed when there is not a parent document.


XML Parse Error (Error 1435)

This error is caused by an MSXML parser error reading an XML source when passed to the XMLTOCURSOR() function, which is usually due to improperly formatted XML. To see the specific parser error, view the XML file in a browser.


XML Schema is too complex. (Error 2094)

The LoadXML method was unable to fully understand the supplied XML Schema

  • Check to make sure the supplied schema contains valid XSD data types or the schema and XML format is supported by Visual FoxPro.


XMLAdapter object doesn't have associated tables. (Error 2129)

Visual FoxPro requires that an XMLTable object or objects is associated with an XMLAdapter object, before attempting to call the ToXML method.

  • Execute the XMLAdapter objects, AddTableSchema method, to create the XMLTable and XMLField collections, or otherwise create these items.


XMLAdapter.ToXML cannot be called while there is a loaded XML document. (Error 2107)

Visual FoxPro does not allow the ToXML method to execute when an XML document is already loaded.

  • Check the IsLoaded property to make sure that a XML document is not already loaded.
  • Use the ReleaseXML method to release the currently loaded XML document.


XMLAdapter.XMLName is empty. (Error 2127)

Visual FoxPro requires that the XMLName property, for an XMLTable is specified, before the ApplyDiffgram and the ChangesToCursor methods are called.


XMLAdapter: fractionDigits must not be greater than or equal to maxLength. (Error 2118)

The value of the FractionDigits property cannot be greater than the value of the MaxLength property.


XMLField object is already associated with XMLTable object. (Error 2144)

Visual FoxPro does not allow XMLField objects to be added to an XMLTable objects, XMLField collection, when they are already associated with another XMLTable object.

  • You can check to see if an XMLField object is already associated with an XMLTable object by checking its XMLTable property. If it is not associated, the value of the XMLTable property will be NULL. Otherwise, it will return an object reference to the owning XMLTable object.


XMLTable has child table. (Error 2109)

Visual FoxPro does not allow the use of the ChangesToCursor method on an XMLTable object that contains a child XMLTable object reference. You cannot create a cursor using the ChangesToCursor method when the XMLTable represents the results of a join on more or more tables.


XMLTable object already has parent or is associated with XMLAdapter object. (Error 2132)

The XMLTable object cannot be added as a child table reference to another XMLAdapter object, if it is already a child table or is associated with another XMLAdapter object.


XMLTable object does not have associated fields. (Error 2097)

An XMLTable object must have associated XMLField objects to execute the ToCursor and ChangesToCursor methods.


XMLTable object does not have associated XMLAdapter object. (Error 2095)

Visual FoxPro requires that XMLTable objects have a contained XMLAdapter object.

  • Check to make sure the XMLTable.XMLAdapter property is associated with an XMLAdapter object.


XMLTable object with XMLName "name" does not have associated fields. (Error 2130)

Visual FoxPro requires that the XMLTable object must contain an associated XMLField object or objects, before the XMLAdapter objects, ToXML method can be called.

  • Execute the XMLAdapter objects, AddTableSchema method, to create the XMLTable and XMLField collections, or otherwise create these items.


XMLTable.Alias is empty. (Error 2108)

The ToCursor method and the ChangesToCursor method cannot be called when the XMLTable's Alias property is empty and the cAlias parameter was not used.


You may not change the RecordSource of a BROWSE object (Error 1772)

The browse object must remain aligned with its table.

  • You tried to change the RecordSource property programmatically.

    To browse a different table, close the current browse and browse the new table. For more information, see BROWSE or RecordSource.


You must use a logical expression with a FOR or WHILE clause (Error 1127)

A FOR or WHILE clause within a command does not contain a logical expression. For more information, see Creating Logical Expressions.


You must use a logical expression with FILTER (Error 37)

You have attempted to issue SET FILTER TO on an expression that is not a logical expression. For more information, see Creating Logical Expressions.


Error Messages by Number

Jump to this number:

1 | 100 | 200 | 300 | 1000
1100 | 1200 | 1300 | 1400 | 1500
1600 | 1700 | 1800 | 1900 | 2000
2100 |  |  |  |

***

*** | *bad date*
*** | Cannot allocate screen map
*** | Cannot create program workspace.
*** | Cannot find spell check program.
*** | Cannot find the beautify program.
*** | Cannot find the spell check program.
*** | Cannot find the wizard program.
*** | Cannot open configuration file.
*** | Fatal error nExpr reporting error nExpr.
*** | *Interrupted*
*** | Invalid compact EXE file. Rebuild EXE.
*** | Invalid or duplicate field name.
*** | Invalid or missing EXE file.
*** | Logical expression required
*** | Popup too big, first nExpr entries shown.
*** | Product has not been properly installed.
*** | Source code not found.
*** | Source code out of date.
*** | The Remote View Wizard was unable to obtain column information for this remote table. This may be the result of an ODBC error, or the remote table may not be owned by the current user.
*** | Unable to locate desired version of Visual FoxPro.
*** | Unable to process error.
*** | Unknown error code nExpr.
*** | Visual FoxPro cannot start.

1

1 | File "name" does not exist.
3 | File is in use.
4 | End of file encountered.
5 | Record is out of range.
6 | Too many files open.
7 | File already exists.
9 | Data type mismatch.
10 | Syntax error.
11 | Function argument value, type, or count is invalid.
12 | Variable "variable" is not found.
13 | Alias is not found.
15 | Not a table.
16 | Unrecognized command verb.
17 | Table number is invalid.
18 | Line is too long.
19 | Index file does not match table.
20 | Record is not in index.
21 | Length of variable strings exceeds amount of memory.
22 | Too many variables.
23 | Index expression exceeds maximum length.
24 | Alias name is already in use.
26 | Table has no index order set.
27 | Not a numeric expression.
30 | Row or column position is off the screen.
31 | Invalid subscript reference.
34 | Operation is invalid for a Memo, General, or Picture field.
36 | Command contains unrecognized phrase/keyword.
37 | You must use a logical expression with FILTER.
38 | Beginning of file encountered.
39 | Numeric overflow. Data was lost.
41 | Memo file "name" is missing or is invalid.
42 | The LOCATE command must be issued before the CONTINUE command.
43 | There is not enough memory to complete this operation.
44 | Cyclic relation.
45 | Not a character expression.
46 | Expression evaluated to an illegal value.
47 | No fields found to process.
50 | Report file "name" is invalid.
52 | No table is open in the current work area.
54 | Label file is invalid.
55 | Memory file is invalid.
56 | There is not enough disk space for "name".
58 | LOG( ): Zero or negative used as argument.
61 | SQRT argument cannot be negative.
62 | Cannot access characters beyond string.
67 | Expression evaluator failed.
78 | ** or ^ domain error.
91 | File was not placed in memory using the LOAD command.
94 | Must specify additional parameters.
95 | Statement is not allowed in interactive mode.
96 | Nesting error.

100

101 | Cannot open file "file".
102 | Cannot create file "file".
103 | Allowed DO nesting level exceeded.
104 | Unknown function key.
107 | Operator/operand type mismatch.
108 | File is in use by another user.
109 | Record is in use by another user.
110 | File must be opened exclusively.
111 | Cannot update the cursor "cursor", since it is read-only.
112 | Invalid key length.
114 | Index does not match the table. Delete the index file and re-create the index.
115 | .DIF file header is invalid.
116 | .DIF vector is invalid - .DBF field mismatch.
117 | .DIF type indicator is invalid.
119 | .SYLK file header is invalid.
120 | .SYLK file dimension bounds are invalid.
121 | .SYLK file format is invalid.
124 | Printer redirection is invalid.
125 | Printer is not ready.
127 | View file is invalid.
130 | Record is not locked.
138 | No fields were found to copy.
152 | Missing expression.
164 | Menu title has not been defined with DEFINE PAD.
165 | Menu has not been defined with DEFINE POPUP.
166 | No menu items have been defined for this menu.
167 | Menu item position must be a positive number.
168 | Menu has not been defined with DEFINE MENU.
169 | Cannot define menu item.
170 | Cannot release menu item.
174 | Cannot redefine a menu that is in use.
175 | Cannot redefine popup that is in use.
176 | Cannot clear menu that is in use.
177 | Cannot clear popup that is in use.
178 | Menu has not been activated with ACTIVATE MENU.
179 | Menu has not been activated with ACTIVATE POPUP.
181 | Menu specified in ACTIVATE MENU is already in use.
182 | Menu specified in ACTIVATE POPUP is already in use.

200

202 | Invalid path or file name.
214 | Window has not been defined with DEFINE WINDOW.
215 | Window has not been activated with ACTIVATE WINDOW.
216 | Display mode is not available.
221 | Left margin including indent must be less than the right margin.
222 | Line number must be less than page length.
223 | Column number must be between 0 and 255.
225 | "name" is not a variable.
226 | "name" is not a file variable.
227 | Box dimensions are invalid.
228 | Tab stops must be in ascending order.
230 | Array dimensions are invalid.
231 | Invalid argument used with the SET function.
232 | "name" is not an array.
255 | Not a valid RapidFile database.
256 | Not a valid Framework II database/spreadsheet.
279 | Menu was not pushed.
287 | Menu size is too small.
291 | Expression used with ASIN( ) is out of range.
292 | Cannot use 0 or negative as the argument for LOG10( ).
293 | Expression used with ACOS( ) is out of range.
297 | Lotus 1-2-3 version 2.0 file format is invalid.

300

332 | Window specified in DEFINE WINDOW has invalid coordinates.
350 | Field must be a Memo field.
355 | Macro is not defined.
356 | Keyboard macro file format is invalid.
392 | Maximum record length exceeded in the import file.

1000

1000 | Internal consistency error.
1001 | Feature is not available.
1002 | Input/output operation failure.
1088 | Field "name" is read-only.
1097 | User defined functions are not allowed.
1098 | API function _UserError( ) was called.

1100

1102 | Cannot create file "file".
1103 | Invalid seek offset.
1104 | Error reading file "file".
1105 | Error writing to file "file".
1106 | Cannot access file "file"; transaction is in progress.
1108 | Picture too big, corrupt, or in wrong format.
1111 | Invalid file descriptor.
1112 | Error closing the file.
1113 | File is not open.
1115 | Invalid operation for the cursor.
1116 | Too many windows open.
1117 | Key field length does not match.
1124 | Key exceeds allowed size.
1126 | Record is too long.
1127 | You must use a logical expression with a FOR or WHILE clause.
1130 | 'field' phrase is not found.
1131 | The file specified in the FROM clause is empty.
1134 | Variable must be in the selected table.
1138 | Property does not have a default value.
1140 | FILTER expression exceeds allowed size.
1141 | Unrecognized index file revision. Re-create the index.
1145 | Must be a character or numeric key field.
1147 | Target table is already engaged in a relation.
1148 | Expression has been re-entered while the filter is executing.
1149 | Not enough memory for buffer.
1150 | Not enough memory for file map.
1151 | Not enough memory for filename.
1152 | Cannot access the selected table.
1153 | Cannot rename the file to different device.
1156 | Duplicate field names.
1157 | Cannot update the file "file".
1162 | Procedure "procedure" is not found.
1163 | Browse table is closed.
1164 | Browse structure has changed.
1165 | "field" is not related to the current work area.
1166 | Cursor is corrupt or in wrong format.
1167 | Icon is corrupt or in wrong format.
1168 | Could not add icon to executable file.
1169 | Project file is read-only.
1178 | Application file "file" is not closed.
1181 | Could not add version resource to executable file.
1183 | Relation already exists.
1184 | File cannot be closed because outstanding references exist.
1190 | File "name" is too large.
1191 | Cannot save form: an object has an invalid name
1193 | Missing .RTT section.
1194 | Link command failed.
1195 | Object file "file" was compiled in a previous version of FoxPro.
1196 | "file" is not a Visual FoxPro .EXE file.

1200

1201 | Too many names used.
1202 | Program is too large.
1206 | Recursive macro definition.
1211 | An IF | ELSE | ENDIF statement is missing.
1212 | Structure nesting is too deep.
1213 | There is a missing keyword in the FOR ... ENDFOR or DO CASE ... ENDCASE command structure.
1214 | ENDTEXT does not have corresponding TEXT statement.
1217 | Picture error in GET statement.
1220 | Command contains invalid character.
1221 | Command is missing required clause.
1223 | Invalid variable reference.
1225 | Must be a variable or array.
1226 | Must be a file variable.
1229 | Too few arguments.
1230 | Too many arguments.
1231 | Missing operand.
1232 | DIMENSION contains variable declaration without required subscript arguments.
1234 | Subscript is outside defined range.
1235 | Structure is invalid.
1236 | Suspend program before using RESUME.
1238 | No PARAMETER statement is found.
1241 | Improper data type in the group expression.
1242 | Syntax error in the field expression.
1243 | Internal error: Too many characters in the report.
1245 | Invalid expression in label definition file.
1246 | Total label width exceeds allowed size.
1249 | Too many READ commands are in effect.
1250 | Too many PROCEDURE commands are in effect.
1252 | Compiled code for this line is too long.
1253 | Cannot rename the current directory.
1254 | Cannot nest key labels.
1255 | Key label "label" is invalid.
1256 | Mismatched braces in key label.
1257 | Key string is too long.
1258 | Error in the PICTURE clause.
1294 | "name" is not a valid resource file.
1296 | Error reading the resource.
1297 | Command is allowed only in interactive mode.
1298 | "name" band is too large to fit on page.

1300

1300 | Function name is missing ).
1304 | Function name is missing (.
1306 | Missing comma (,).
1307 | Cannot divide by 0.
1308 | Insufficient stack space.
1309 | "file" is not an object file.
1310 | Too many characters are specified in the PICTURE clause.
1313 | Class creation canceled.
1337 | Cannot nest the PRINTJOB command.
1338 | File is the wrong version.

1400

1405 | RUN|! Command failed. "Details".
1410 | Unable to create temporary work files.
1411 | RUN|! command string is too long.
1412 | Cannot locate the COMSPEC environment variable.
1413 | Page frame cannot be sized that small.
1420 | OLE object is invalid or corrupted.
1421 | Cannot activate the OLE server.
1422 | Error saving the OLE object.
1423 | Error creating the OLE object.
1424 | Error copying the OLE object to Clipboard.
1426 | OLE error code 0x"name".
1427 | OLE IDispatch exception code "name".
1428 | OLE IDispatch exception code "number" from "name": "name".
1429 | "OLE error".
1431 | Maximum number of OLE arguments is exceeded.
1434 | Class "name" has not been registered.
1435 | XML Parse Error
1436 | Only insertable objects are allowed in General fields.
1437 | Unable to register the ActiveX control.
1438 | The ActiveX control module failed to register correctly.
1439 | Not a ProjectHook class.
1440 | OLE exception error "name". OLE object may be corrupt.
1441 | Class cannot be instantiated because member "name" does not exist
1442 | Class cannot be instantiated because member "name" has wrong # of parameters
1443 | Interface "name" not found
1444 | Type Library "name" not found
1445 | EventHandler object "name" does not IMPLEMENT an interface
1462 | "name" internal consistency error.
1463 | No result set has been returned by the server.
1465 | SQL pass-through internal consistency error.
1466 | Connection handle is invalid.
1467 | Property is invalid for local cursors.
1468 | Property is invalid for table cursors.
1469 | Property value is out of bounds.
1470 | Incorrect property name.
1471 | Incorrect column format.
1472 | SQL statement parameter is required for non-prepared SqlExec( ) calls.
1473 | Environment-level property is invalid.
1474 | Invalid call issued while executing a SQLEXEC( ) sequence.
1475 | Invalid call issued while executing a SQLMORERESULTS( ) sequence.
1476 | Invalid call issued while executing a SQLTABLES( ) sequence.
1477 | Invalid call issued while executing a SQLCOLUMNS( ) sequence.
1478 | The ChildOrder property of a relation object in the data environment is no longer valid. The relation is being removed.
1479 | Invalid update column name \"name"\.
1480 | Warning: The connection sync/async mode cannot be set.
1481 | Warning: The connection timeout cannot be set.
1482 | Warning: The query timeout cannot be set.
1483 | Warning: The connection packet size cannot be set.
1484 | Warning: The next "cExpr" modified records have already been updated remote.
1485 | Warning: Invalid data conversion(s) starting at record "name".
1486 | Warning: Invalid memo field conversions starting at record "name".
1487 | Warning: The connection transaction mode cannot be set.
1488 | No connection associated with this cursor
1489 | General fields cannot be used in the WHERE condition of an update statement. Change the WhereType property of the view.
1490 | Saving a converted form as a class is not supported.
1491 | No update tables are specified. Use the Tables property of the Cursor object.
1492 | No key columns specified for the update table "name". Use the KeyFieldList property of the cursor.
1493 | SQL parameter is missing.
1494 | View definition has been changed.
1495 | Warning: The key defined by the KeyField property for table "alias" is not unique.
1496 | Warning: No information is available to check remote update conflicts.
1497 | Connection name is invalid.
1498 | SQL SELECT statement is invalid.
1499 | SQL parameter "name" is invalid.

1500

1501 | Type conversion is not supported for output parameters.
1502 | Cannot write to the record because it is in use.
1503 | File cannot be locked.
1504 | Function not supported for SQL pass-through cursors.
1507 | Screen code is too large for available memory.
1508 | Error initializing OLE.
1509 | Conversion canceled. Adjust the memo BLOCKSIZE.
1510 | Invalid file format. If this is a dBASE file, it must be converted first. To convert it, type MODIFY LABEL labelfilename.
1520 | No database is open or set as the current database.
1521 | This operation not supported for class member objects.
1522 | Connectivity internal consistency error.
1523 | Execution was canceled by the user.
1524 | The selected printer driver does not support direct access.
1525 | Function is not supported on remote tables.
1526 | Connectivity error: "name".
1527 | Cannot locate ODBC library, ODBC32.DLL.
1528 | ODBC entry point missing, "name".
1529 | File "name" already exists as part of a database.
1530 | Fetching canceled; remote table is closed.
1531 | The table changes cannot be performed as the index or filter expression for index name would be invalid.
1532 | Type conversion is not supported.
1533 | This property is read-only.
1534 | Database "alias" is not open.
1535 | Cannot close this database because it is being used by a project.
1536 | Function is not supported on native tables.
1537 | Cannot add this table: it belongs to database "name".
1538 | A stored procedure is executing.
1539 | Trigger failed in "cursor".
1540 | Session number is invalid.
1541 | Connection "name" is busy.
1542 | Base table fields have been changed and no longer match view fields. View field properties cannot be set.
1543 | Type conversion required by the DataType property for field '"name"' is invalid.
1544 | DataType property for field '"name"' is invalid.
1545 | Table buffer for alias "name" contains uncommitted changes.
1546 | Cannot close table during execution of a table-bound expression.
1547 | Cannot insert an empty row from a view into its base table(s).
1548 | Table "alias" has one or more non-structural indexes open. Please close them and retry the Begin Transaction.
1549 | Data session #number cannot be released with open transaction(s).
1550 | .DBC internal consistency error.
1551 | File "name" is an invalid database.
1552 | File "name" is not a database.
1553 | File "name" is a database.
1554 | Error instantiating cursor object. Table "alias" cannot be opened. Object will be ignored.
1555 | Relational expression is not valid.
1556 | Table cannot be browsed because cursor object is no longer valid.
1557 | The database must be opened exclusively.
1558 | File "name" is not part of a database.
1559 | Property is not found.
1560 | Property value is invalid.
1561 | Database is invalid. Please validate.
1562 | Cannot find object "name" in the database.
1563 | Cannot find view "name" in the current database.
1564 | Table "name" already exists in the database.
1565 | File "name" is part of a database.
1566 | Cannot issue the PACK command on a database while its objects have open cursors.
1567 | Primary key property is invalid; please validate database.
1568 | View fields have been changed. The Update and Key field properties have been reset to the default values.
1569 | Database "name": File access denied.
1570 | Database is read-only.
1571 | The name "name" is already used for another object. Please choose a different name.
1572 | Cannot delete a database object while it is open in a designer.
1573 | Cannot change modality of a visible form.
1574 | Error initializing application object.
1575 | Object name is invalid.
1576 | Class "name" is not found in the class library.
1577 | Table "name" is referenced in a relation.
1578 | Invalid database table name.
1579 | Command cannot be issued on a table with cursors in table buffering mode.
1580 | Feature is not supported for non-.DBC tables.
1581 | Field "name" does not accept null values.
1582 | Field "name" validation rule is violated.
1583 | Record validation rule is violated.
1584 | Error reading a property from the database. The property is ignored.
1585 | Update conflict. Use TABLEUPDATE( ) with the lForce parameter to commit the update or TABLEREVERT( ) to roll back the update.
1586 | Function requires row or table buffering mode.
1587 | Illegal nested OLDVAL( ) or CURVAL( ).
1588 | INSERT cannot be issued when row or table buffering is enabled or when integrity constraints are in effect.
1589 | Table or row buffering requires that SET MULTILOCKS is set to ON.
1590 | BEGIN TRANSACTION command failed. Nesting level is too deep.
1591 | END TRANSACTION command cannot be issued without a corresponding BEGIN TRANSACTION command.
1592 | ROLLBACK command cannot be issued without a corresponding BEGIN TRANSACTION command.
1593 | Command cannot be issued within a transaction.
1594 | Illegal to attempt a file lock in a transaction after taking prior record locks.
1595 | Update conflict. Some of your changes in the current row batch were committed. Use TABLEUPDATE( ) with the lForce parameter to commit the update or the manual transaction to roll back the update.
1596 | Table buffering is not enabled.
1597 | Views require either DB_BUFOPTROW or DB_BUFOPTTABLE.
1598 | Rule and trigger code must balance transaction usage.
1599 | Data session #number was forced to ROLLBACK all transactions to avoid deadlock.

1600

1600 | Not enough memory to open a table with the USE command.
1604 | No menu bar is defined.
1605 | No menu is defined.
1607 | Maximum menu items allowed (128) is exceeded.
1608 | Maximum menus allowed (25) is exceeded.
1609 | Maximum menu item length (50) is exceeded.
1611 | Menu items and titles must be type Character.
1612 | No such menu or menu item is defined.
1621 | No menu titles have been defined for this menu.
1632 | Window file format is invalid.
1637 | File must be opened exclusively to convert the Memo file.
1640 | Access to system Registry denied
1642 | Color set resource is not found.
1643 | Printer driver is corrupted.
1644 | Printer driver is not found.
1645 | Report contains a nesting error.
1646 | Total field type must be Date or Numeric.
1647 | Field expression contains an invalid data type.
1649 | No previous PRINTJOB command to correspond to this command.
1651 | CANCEL or SUSPEND is not allowed.
1652 | Invalid use of a Visual FoxPro function as an array.
1653 | Label nesting error.
1657 | Column number must be between 0 and the right margin.
1659 | The table has memo fields that cannot be converted while open read-only.
1661 | Microsoft Excel file format is invalid.
1662 | Lotus 1-2-3 version 1.0 file format is invalid.
1670 | Multiplan version 4.0 file format is invalid.
1671 | Cannot import from password-protected file.
1672 | Cannot append from password protected file.
1673 | Symphony version 1.0 file format is invalid.
1674 | Symphony version 1.1 file format is invalid.
1678 | Lotus 1-2-3 version 3.0 file format is invalid.
1679 | Import only Worksheet A for Lotus 1-2-3 version 3.0 files.
1680 | Worksheet A for Lotus 1-2-3 version 3.0 file is hidden.
1681 | PREVIEW clause is not allowed with OFF/NOCONSOLE or TO PRINT/FILE.
1682 | Not a user-defined window.
1683 | Index tag is not found.
1684 | Index tag or file name must be specified.
1685 | Project file is invalid.
1686 | Form file "name" is invalid.
1687 | Menu file is invalid.
1688 | Paradox file format is invalid.
1689 | Cannot build without a main program.
1690 | Table operation is invalid during indexing.
1691 | Library file "name" is invalid.
1693 | Cannot find the menu-generation program.
1694 | Too many extensions are specified.
1695 | COLUMN | FORM | ALIAS | NOOVERWRITE | WIDTH are only allowed with the FROM clause.
1696 | NOWAIT | SAVE | NOENVIRONMENT | IN | WINDOW clauses are not allowed with the FROM clause.
1698 | COLUMN | ROW | ALIAS | NOOVERWRITE | SIZE | SCREEN are only allowed with the FROM clause.
1699 | The IN clause is not supported for this window.

1700

1705 | File access is denied.
1706 | Cannot sort .IDX files in descending order.
1707 | Structural .CDX file is not found.
1708 | File is open in another work area.
1709 | Database object is being used by someone else.
1710 | MULTISELECT or MOVER clause is not supported for PROMPT style menus.
1711 | API library revision mismatch. Rebuild library.
1712 | Field name is a duplicate or invalid.
1713 | Field width or number of decimal places is invalid.
1714 | Window "name" has not been defined.
1715 | Server "server" is not found.
1716 | Queue "queue" is not found.
1717 | Unable to generate a printer driver.
1718 | File "name" is read-only.
1719 | Object file "name" is in use and cannot be removed from memory.
1720 | Cannot issue the SET FORMAT command while a READ command is in progress on a format file.
1722 | Preprocessor expression is invalid.
1723 | Mismatched #IF/#ELSIF/#ELSE/#ENDIF.
1724 | Missing #ENDIF.
1725 | Constant is already created with #DEFINE.
1726 | API library is not found.
1727 | A .DBF-style Help file is required.
1728 | Color scheme is reserved.
1731 | Cannot modify a base class.
1732 | Data type is invalid for this property.
1733 | Class definition "name" is not found.
1734 | Property "name" is not found.
1735 | Error in the class definition. "Details"
1736 | Error instantiating the object "object".
1737 | "name" is a method, event, or object.
1738 | Property "name" is not a method or event.
1739 | Property setting will not take effect until data environment reloaded.
1740 | "name" is a read-only property.
1741 | Cannot add "name". Class definition is cyclical.
1742 | The data source for this object must be a variable reference.
1743 | Property "name" is read-only.
1744 | Object class is invalid for this container.
1745 | "name" is not a Visual FoxPro event.
1746 | Class file name for "name" is not valid.
1747 | Class file "name" is invalid.
1748 | This file is incompatible with the current version of Visual FoxPro.
1749 | Form (.SCX) file must contain at least one Form.
1750 | File was created in a later version of Visual FoxPro than the current version.
1751 | Class file version is greater than the current version.
1752 | Class "name" is in use by MODIFY CLASS.
1753 | Cannot load 32-bit DLL "name".
1754 | Cannot find entry point "name" in the DLL.
1755 | Cannot add an object to this class.
1756 | Member object removed – cannot complete the Save operation.
1757 | Property "name" is protected.
1758 | Cannot change property "name" in SetAll method.
1759 | Expression is invalid. Use a valid expression for "name" property.
1760 | Member "name" is a class member.
1761 | Class "name" already exists.
1762 | Class "name" is not found.
1763 | Property "name" already exists.
1764 | Array is not a member of the parent object.
1765 | Method contains syntax errors. Method is not saved.
1766 | Object "name" is not found.
1767 | Parent object will not allow this property setting for "name".
1768 | Cannot add this object to a Grid.
1769 | Cannot add this object to a Column.
1770 | Cannot clear class "class" because it is in use.
1771 | A member object with this name already exists.
1772 | You may not change the RecordSource of a BROWSE object.
1773 | Database object type is invalid.
1774 | No sheet is found.
1775 | Worksheet "name" is not found.
1776 | Class "name" is in use.
1777 | This command is not supported for views.
1778 | The table must be converted before appending.
1779 | Error adding "name" to the object. Duplicate member/property name.
1780 | This array element has been defined as an object and cannot be redefined in the class definition.
1781 | An object's control source cannot be set to its Value property.
1782 | This OLE property cannot be an expression.
1783 | Invalid class specified for @...Class command.
1784 | This object is derived from a base class and does not have a parent class.
1791 | Cannot find the text generation program.
1792 | Text generation is canceled.
1793 | The network request is not supported.
1794 | "name" cannot be enumerated.
1795 | Cannot arrange an untransported form.
1796 | No records are found for the current platform.
1797 | Error occurred in conversion.
1798 | Cannot find the converter program.
1799 | Conversion is canceled.

1800

1800 | SQL: Internal error.
1801 | SQL: Error correlating fields.
1802 | SQL: Cannot locate table.
1803 | SQL: HAVING clause is invalid.
1804 | SQL: Statement is invalid.
1805 | SQL: Too many subqueries.
1806 | SQL: Column "field | variable" is not found.
1807 | SQL: GROUP BY clause is invalid.
1808 | SQL: ORDER BY clause is invalid.
1809 | SQL: Out of memory.
1810 | SQL: Invalid use of subquery.
1811 | SQL: Aggregate on non-numeric expression.
1812 | SQL: Statement too long.
1813 | SQL: Use of UNION in subquery is invalid.
1814 | SQL: Queries of this type are not supported.
1815 | "cursor" must be created with SELECT ... INTO TABLE.
1818 | SQL: FROM clause is required.
1819 | SQL: DISTINCT is invalid.
1820 | SQL: SELECT contains invalid *.
1822 | SQL: Invalid aggregate field.
1825 | SQL: Subquery is invalid.
1826 | SQL: SELECT is invalid.
1828 | SQL: Illegal GROUP BY in subquery.
1830 | SQL: Index is not found.
1831 | SQL: Error building temporary index.
1832 | "field | variable" is not unique and must be qualified.
1833 | SQL: WHERE clause is invalid.
1834 | SQL: Too many UNIONs.
1839 | SQL: Operation was canceled.
1841 | SQL: Too many columns referenced.
1842 | SQL: Subquery nesting is too deep.
1844 | Cannot nest aggregate functions.
1845 | SQL expression is too complex.
1846 | Cannot GROUP by aggregate field.
1851 | SELECTs are not UNION compatible. "Details"
1860 | Subquery returned more than one record.
1864 | SQL: Too many fields in UPDATE.
1865 | SQL: Invalid SET expression in UPDATE.
1866 | SQL: Invalid TOP specification.
1867 | SQL: TOP requires an ORDER BY.
1870 | ALTER TABLE operation interrupted.
1871 | Cannot DROP all existing columns.
1872 | Too many columns.
1875 | Multiple warnings occurred performing the requested index modifications.
1877 | No rule to DROP.
1878 | No default value to DROP.
1879 | No primary key.
1880 | Related table is not found in current database.
1881 | Error loading file - record number n. "object" <or one of its members>. "Issue": "error".
1882 | Related tag is not found or not primary or candidate.
1883 | Primary key already exists.
1884 | Uniqueness of index "name" is violated.
1885 | Only structural tags can be defined as candidate.
1886 | Index does not accept NULL.
1887 | Illegal recursion in rule evaluation.
1888 | Tag name is too long.
1889 | A table in multiple relationships can only have one child order.
1890 | SQL: Cannot determine data type of SQL column "column".

1900

1903 | String is too long to fit.
1907 | Drive specifier is invalid.
1908 | Length or decimal place argument is invalid.
1909 | Cannot update project from project metafile.
1910 | Illegal printer driver recursion.
1911 | Localized product is required for this environment.
1912 | Operation is invalid for a General field.
1913 | Field must be a General field.
1914 | Code page number is invalid.
1915 | Collating sequence "name" is not found.
1916 | To use this feature, set CODEPAGE=AUTO in your CONFIG.FPW file and restart Visual FoxPro.
1918 | File name is too long.
1922 | Volume does not exist.
1923 | Object "name" is not found.
1924 | "name" is not an object.
1925 | Unknown member "name".
1926 | Cannot nest class definitions.
1927 | Statement is not valid in a class definition.
1928 | Statement is only valid within a class definition.
1929 | "name" can only be used within a method.
1930 | Cannot redefine "name".
1931 | Statement is not in a procedure.
1932 | "name" cannot be closed while suspended.
1933 | File "name" is not closed.
1934 | Statement only valid within a method.
1935 | The current object does not inherit from class "name".
1936 | Application object not initialized.
1937 | Procedure file "name" is not found.
1938 | Object is not contained in a "name".
1939 | WITH/ENDWITH mismatch.
1940 | Expression is not valid outside of WITH/ENDWITH.
1941 | Error code is not valid.
1942 | Objects cannot be assigned to arrays.
1943 | Member "name" does not evaluate to an object.
1944 | Cannot find the builder program.
1945 | The current object has been released.
1946 | Project file "name" is in the wrong version.
1947 | Expression is too complex.
1948 | Cannot modify a class that is in use.
1949 | Class name is invalid.
1950 | Class definition "name" is recursive.
1951 | Cannot clear the object "object" because it is in use.
1952 | Cannot base a view on itself.
1953 | Feature is only available if the object is in design mode.
1954 | The builder program is already running.
1955 | WIN.INI/registry is corrupted.
1956 | Printer access denied.
1957 | Error accessing printer spooler.
1958 | Error loading printer driver.
1959 | Invalid coordinates.
1960 | Illegal redefinition of variable "name".
1961 | A subdirectory or file "name" already exists.
1962 | The directory is not empty.
1963 | Directory is not found.
1964 | No PageFrame or Page is found in FormSet or Form with WindowType set to READ or READ MODAL.
1965 | One of the members of this class is based on a nonvisual class. Cannot write .VCX file.
1966 | Data environment is already loaded.
1967 | Data environment is already unloaded.
1968 | One of the members of this Form or FormSet is based on a nonvisual class. Cannot write .SCX file.
1969 | The clipboard contained one or more objects that could not be added to the container. Those objects were not pasted.
1970 | Cannot reopen project file "name".
1971 | Cannot compile until the current COMPILE command has completed.
1972 | Array "name" is in use.
1973 | Error creating table: "name".
1974 | Arrays cannot be assigned to array elements.
1975 | Member object "name" has not been instantiated.
1976 | Cannot resolve backlink.
1977 | Exclusive open required to update this file. Please reopen.
1978 | Cannot visually modify a class of this type.
1979 | Cannot visually modify a class based on a nonvisual class.
1981 | Compile error in file "name".
1982 | The TO clause can only be used with modal Forms and FormSets.
1983 | "name" objects cannot return a value.
1984 | The fields in table '"name"' did not match the entries in the database.
1985 | Object already has a data environment; cannot use another one with the SaveAs method.
1986 | GDI memory is low, close one or more windows and try again.
1987 | Objects cannot be programmatically added to the Form Designer's FormSet.
1988 | Currency value is out of range.
1989 | Objects cannot be programmatically deleted from the Form Designer.
1991 | Form file "name" is from a previous version of FoxPro. It must be converted to the current format before it can be executed.
1992 | "name" is not a function, procedure or program.
1993 | Class library file "name" is not found.
1994 | Include file "name" is not found.
1995 | Error loading the data environment. Table is in use.
1996 | The validation rule for field "name" does not evaluate to a logical or NULL type.
1997 | The default value for field "name" does not evaluate to the correct type for the field.
1998 | The index expression for index "name" contains an invalid reference to a Memo, General, or Picture field.
1999 | Function is not implemented.

2000

2000 | Memory is low, so streaming output updating has been disabled.
2001 | The name of the object file for "file" is already used by another program in the project.
2002 | Cannot build a DLL without OLE public classes.
2003 | OLE Changed Properties stream is the wrong version. Subclassed properties ignored.
2004 | The table file "name" has moved. Please validate database "name" and try again.
2005 | Error with "name" - "property": "error".
2006 | Cannot locate your Web browser.
2007 | Invalid operation for offline view while offline.
2008 | Invalid operation for offline view while being used online.
2009 | Object is not an offline view.
2010 | Offline views must be used exclusively when being used online.
2011 | Invalid operation for offline view.
2012 | Cannot call SetFocus from within a When, Valid, RangeHigh or RangeLow event.
2013 | Cannot open persistent table buffer directly.
2014 | Fields marked as update keys will be cleared.
2015 | Offline view must be used online for this command
2016 | Removing a class member is not allowed.
2017 | Cannot reuse offline view in different mode.
2018 | Reconnect of offline view failed.
2019 | Cannot create offline view on a currently modified view.
2020 | The class file associated with this field cannot be found – class association cleared.
2021 | The DataObject cannot be modified in the OLEDragOver or OLEDragDrop event.
2022 | The specified file or path was not found.
2023 | There is no application associated with the given filename extension.
2024 | A sharing violation occurred.
2026 | Invalid locale ID.
2027 | Declare DLL call caused an exception.
2028 | API call caused an exception.
2029 | Class "name" is not a Form class.
2030 | Cannot delete file "name".
2031 | User-interface operation not allowed at this time.
2032 | Ambiguous date/datetime constant.
2033 | CTOD and CTOT can produce incorrect results.
2034 | Date/datetime evaluated to an invalid value.
2035 | Date/datetime contains illegal characters.
2036 | The current Help file is empty.
2042 | Foxcode table not found, is not correct version or is incompatible.
2043 | Foxcode script "name" failure.
2044 | Textmerge is recursive.
2045 | Cannot set DBCEventFile property when DBCEvents is off.
2046 | Foxtask table is corrupted or not the correct version.
2048 | Invalid COMATTRIB value for "name"
2049 | Error loading HtmlHelp 2.0 collection.
2050 | Help for this topic/context not implemented.
2051 | Menu item's conditional statement is too long.
2052 | OrderBy clause is too long.
2055 | Query Parse Error - Try rebuilding in Query Wizard or by using View Designer Join Tab.
2056 | The specified member class does not exist or is of wrong type.
2053 | GroupBy clause is too long.
2056 | The specified member class does not exist or is of wrong type.
2057 | The specified class library does not exist or does not contain a valid member class.
2058 | TRY/CATCH/FINALLY/ENDTRY mismatch or error.
2059 | Unhandled Structured Exception
2060 | RETURN/RETRY statement not allowed in TRY/CATCH.
2061 | Index or expression does not match an existing member of the collection.
2062 | The specified Key already exists.
2063 | A Key must be specified when adding an item to this collection.
2064 | A Key cannot be specified when adding an item to this collection.
2068 | Data environment "name" does not contain a cursor object.
2069 | Forms or Form classes that specify a DEClass and DEClassLibrary cannot be converted to or used with a FormSet.
2071 | User Thrown Error.
2074 | Result is incompatible with cursor schema.
2075 | CursorSchema property is not specified.
2076 | Operation is not allowed for CursorAdapter.
2077 | Operation is not allowed for CursorAdapter at this time.
2078 | CursorAdapter "name" cannot be loaded for design.
2079 | Cannot close or detach extended cursor because it is currently in design mode.
2080 | ADODB.Recordset is already opened.
2081 | ADODB.Command is already opened.
2082 | Cannot update ADODB.Recordset while cursor, created by CursorAdapter.CursorFill method, is not attached to a CursorAdapter object.
2083 | Cannot update ADODB.Recordset because it is read-only.
2084 | Cannot update ADODB.Recordset because it does not support a Bookmark property.
2085 | Cannot update ADODB.Recordset because FOX cursor does not have an ADOBookmark column.
2090 | CursorAdapter does not have an associated cursor.
2091 | Table "name" has become corrupted. The table will need to be repaired before using again.
2092 | CursorAdapter cannot locate current record in the buffer. The record may have been reverted.
2094 | XML Schema is too complex.
2095 | XMLTable object does not have associated XMLAdapter object.
2096 | XML document is not loaded.
2097 | XMLTable object does not have associated fields.
2098 | Invalid element in XMLTable.Fields collection.
2099 | Value of XMLTable.XMLName must be used as key value for collection.

2100

2100 | Value of XMLField.XMLName must be used as key value for collection.
2101 | Unable to attach object with empty XMLName property.
2102 | Unable to change XMLName property while XMLTable object belongs to XMLAdapter object.
2103 | Unable to change XMLName property while XMLField object belongs to XMLTable object.
2104 | There is a duplicate table "name" in XML schema.
2105 | There is a duplicate field "name" in XML schema.
2107 | XMLAdapter.ToXML cannot be called while there is a loaded XML document.
2108 | XMLTable.Alias is empty.
2109 | XMLTable has child table.
2110 | XML Error: "error"
2112 | Cursor "name" is attached to another CursorAdapter object.
2116 | This feature requires MSXML4 SP1 or later.
2118 | XMLAdapter: fractionDigits must not be greater than or equal to maxLength.
2120 | Unable to infer XML schema.
2121 | Unable to open offline view in ADMIN/ONLINE mode inside a transaction.
2122 | Unable to close offline view in ADMIN/ONLINE mode inside a transaction.
2123 | Unable to set external schema location when inline schema is used.
2124 | XML document does not have a root element.
2125 | CursorAdapter and XMLTable objects do not belong to the same data session.
2126 | XML document is not a DiffGram.
2127 | XMLAdapter.XMLName is empty.
2128 | XML node does not belong to MSXML4.DOMDocument.
2129 | XMLAdapter object doesn't have associated tables.
2130 | XMLTable object with XMLName "name" does not have associated fields.
2132 | XMLTable object already has parent or is associated with XMLAdapter object.
2133 | Unable to emit XML, two or more cursors use different code pages.
2134 | Value of XMLName, XMLNamespace or XMLPrefix property should be a Unicode string.
2135 | Conversion to Unicode has failed.
2136 | Conversion from Unicode has failed.
2137 | Vfp.VFPXMLProgId doesn't support cSchemaLocation parameter for XMLUpdateGram().
2138 | CursorAdapter is unable to determine DataSourceType for the operation.
2139 | SelectCmd is empty.
2140 | Both Unicode and IsBinary properties can not be set to .T..
2141 | Field size for Unicode value can not be odd number.
2142 | Field for Unicode value should not use code page translation.
2143 | ADODB.Recordset is not opened.
2144 | XMLField object is already associated with XMLTable object.
2145 | Property "name" has invalid value.
2146 | Invalid key column name "name".
2147 | Calling OpenTables or CloseTables is not allowed while either of those methods are in the process of executing.

See Also

Error Messages A-Z | Error Message Parameters | ERROR Command | ERROR( ) Function


Error Message Parameters

Using SYS(2018), you can return the file, field, or variable name as a parameter for the error messages listed here. Error messages that have optional error message parameters may not always return a parameter through SYS(2018).

"cursor" must be created with SELECT ... INTO TABLE. (1815)

"field | variable" is not unique and must be qualified. (1832)

"field" is not related to the current work area. (1165)

"file" is not a Visual FoxPro .EXE file. (1196)

"file" is not an object file. (1309)

"name" band is too large to fit on page. (1298)

"name" can only be used within a method. (1929)

"name" cannot be closed while suspended. (1932)

"name" internal consistency error. (1462)

"name" is a method, event, or object. (1737)

"name" is a read-only property. (1740)

"name" is not a file variable. (226)

"name" is not a variable. (225)

"name" is not an array. (232)

"name" is not an object. (1924)

"name" objects cannot return a value. (1983)

A subdirectory or file "name" already exists. (1961)

Application file "file" is not closed. (1178)

Array "name" is in use. (1972)

Cannot add "name". Class definition is cyclical. (1741)

Cannot add this table: it belongs to database "name". (1537)

Cannot change property "name" in SetAll method. (1758)

Cannot create file "file". (102)

Cannot find entry point "name" in the DLL. (1754)

Cannot find object "name" in the database. (1562)

Cannot find view "name" in the current database. (1563)

Cannot load 32-bit DLL "name". (1753)

Cannot redefine "name". (1930)

Cannot reopen project file "name". (1970)

Class "name" already exists. (1761)

Class "name" has not been registered. (1434)

Class "name" is in use. (1776)

Class "name" is in use by MODIFY CLASS. (1752)

Class "name" is not found in the class library. (1576)

Class "name" is not found. (1762)

Class definition "name" is not found. (1733)

Class definition "name" is recursive. (1950)

Class file "name" is invalid. (1747)

Class file name for "name" is not valid. (1746)

Class library file "name" is not found. (1993)

Collating sequence "name" is not found. (1915)

Compile error in file "name". (1981)

Connection "name" is busy. (1541)

Connectivity error: "name". (1526)

Data session #number cannot be released with open transaction(s). (1549)

Data session #number was forced to ROLLBACK all transactions to avoid deadlock. (1599)

Database "alias" is not open. (1534)

Database "name": File access denied. (1569)

DataType property for field "name" is invalid. (1544)

Error adding "name" to the object. Duplicate member/property name. (1779)

Error creating table: "name". (1973)

Error instantiating cursor object. Table "alias" cannot be opened. Object will be ignored. (1554)

Error loading file - record number n. "object" <or one of its members>. "Issue": "error". (1881)

Error with "name" - "property": "error". (2005)

Expression is invalid. Use a valid expression for "name" property. (1759)

Fatal error expN reporting error expN.

Field "name" does not accept null values. (1581)

Field "name" validation rule is violated. (1582)

File "name" already exists as part of a database. (1529)

File "name" is a database. (1553)

File "name" is an invalid database. (1551)

File "name" is not a database. (1552)

File "name" is not closed. (1933)

File "name" is not part of a database. (1558)

File "name" is part of a database. (1565)

File "name" is read-only. (1718)

File "name" is too large. (1190)

Form file "name" is from a previous version of FoxPro. It must be converted to the current format before it is executed. (1991)

Form file "name" is invalid. (1686)

Illegal redefinition of variable "name". (1960)

Include file "name" is not found. (1994)

Invalid file format. If this is a dBASE file, it must be converted first. To convert it, type MODIFY LABEL labelfilename. (1510)

Invalid update column name "name". (1479)

Key label "label" is invalid. (1255)

Library file "name" is invalid. (1691)

Member "name" does not evaluate to an object. (1943)

Member "name" is a class member. (1760)

Member object "name" has not been instantiated. (1975)

Memo file "name" is missing or is invalid. (41)

No key columns specified for the update table \"name"\. Use the \"KeyFieldList\" property of the Cursor object. (1492)

Object "name" is not found. (1766)

Object "name" is not found. (1923)

Object file "file" was compiled in a previous version of FoxPro. (1195)

Object file "name" is in use and cannot be removed from memory. (1719)

Object is not contained in a "name". (1938)

ODBC entry point missing, "name". (1528)

"OLE error". (1429)

OLE error code 0x"name". (1426)

OLE IDispatch exception code "name". (1427)

OLE IDispatch exception code "number" from "name": "name". (1428)

Parent object will not allow this property setting for "name". (1767)

Popup too big, first expN entries shown.

Procedure "procedure" is not found. (1162)

Procedure file "name" is not found. (1937)

Project file "name" is in the wrong version. (1946)

Property "name" already exists. (1763)

Property "name" is not a method or event. (1738)

Property "name" is not found. (1734)

Property "name" is protected. (1757)

Property "name" is read-only. (1743)

Queue "queue" is not found. (1716)

Report file "name" is invalid. (50)

Server "server" is not found. (1715)

SQL parameter "name" is invalid. (1499)

SQL: Column "field | variable" is not found. (1806)

Table "alias" has one or more non-structural indexes open. Please close them and retry the Begin Transaction. (1548)

Table "name" already exists in the database. (1564)

Table "name" is referenced in a relation. (1577)

Table buffer for alias "name" contains uncommitted changes. (1545)

The current object does not inherit from class "name". (1935)

The default value for field "name" does not evaluate to the correct type for the field. (1997)

The fields in table "name" did not match the entries in the database. (1984)

The index expression for index "name" contains an invalid reference to a Memo, General, or Picture field. (1998)

The name "name" is already used for another object. Please choose a different name. (1571)

The name of the object file for "file" is already used by another program in the project. (2001)

The table changes cannot be performed as the index or filter expression for index name would be invalid. (1531)

The validation rule for field "name" does not evaluate to a logical or NULL type. (1996)

There is not enough disk space for "name". (56)

Type conversion required by the DataType property for field "name" is invalid. (1543)

Uniqueness of index "name" is violated. (1884)

Unknown error code expN.

Unknown member "name". (1925)

Variable "variable" is not found. (12)

Warning: Invalid data conversion(s) starting at record "number". (1485)

Warning: Invalid memo field conversion(s) starting at record "number". (1486)

Warning: The key defined by the KeyField property for table "alias" is not unique. (1495)

Warning: The next "string" modified records have already been updated remote. (1484)

Window "name" has not been defined. (1714)

See Also

Error Messages A-Z | Error Messages by Number | SYS(2018) - Error Message Parameter


Product Support

Learn more about about Microsoft technical support options and copyright information.

In This Section

Microsoft Visual FoxPro Technical Support
Provides information about Microsoft technical support.
Copyright
Includes information about Microsoft copyright.

Related Sections

Getting Started with Visual FoxPro
Visual FoxPro is the object-oriented relational database management system that makes it possible for you to create state-of-the-art enterprise database solutions. Visual FoxPro includes professional productivity tools, documentation, and sample code for quickly building, managing, and deploying solutions.
What's New in Visual FoxPro
Listed here are the new features and enhancements made to this version of Visual FoxPro.
Installing Visual FoxPro
This section describes the requirements for installing this version of Visual FoxPro and then explains how to install, customize, and start it.
Upgrading from Earlier Versions
This version of Visual FoxPro protects your investment in applications built in previous versions of FoxPro.
Optimizing Your System
Visual FoxPro is designed to be the fastest relational database development system. Because of this variety, you might want to optimize the operating system, Visual FoxPro, or your application for maximum performance.
Microsoft Visual FoxPro Web Site
For additional information and resources for Visual FoxPro, visit the Visual FoxPro Web site. This Web site will be updated regularly with the latest information.


Microsoft Visual FoxPro Technical Support

Product Name | Microsoft Visual FoxPro
OEM distributed | If your product came installed with a new computer or device, the hardware manufacturer provides technical support and assistance for this software. Please contact your manufacturer directly for support.
Support Info Online | http://support.microsoft.com In Canada, visit http://microsoft.ca/support
TTY Users | Microsoft text telephone (TTY/TDD) services are available at (425) 635-4948 in Washington state or (800) 892-5234 in the U.S. Call (905) 568-9641 in Canada.
Worldwide | The support terms listed here are available in the United States and Canada only. Support elsewhere might vary. For regional contact information, please see the International Support list at http://support.microsoft.com/common/international.aspx. If there is no Microsoft subsidiary office in your country or region, please contact the establishment from which you obtained your Microsoft product.
Conditions | Microsoft support services are subject to then-current prices, terms, and conditions, which can change without notice.

Professional Support Options

Advanced support for experts & businesses. Visit our customized support sites for pay-per-incident assistance online in the U.S. and phone in the U.S. by experts trained to assist business professionals. To advance-purchase support incidents, please call Professional Support Sales at (800) 936-3500. If you are calling from Canada, Professional support is available by calling (800) 805-4440 from 8:00 a.m. – 8:00 p.m. Monday – Friday Eastern Time.

Submit your incident online in the U.S.

  • http://support.microsoft.com/directory/directory/onlinesrpro.asp

Get additional information on our support offerings in the U.S.

  • Professional Support for Developers
  • Professional Support for IT Professionals
  • Professional Support for Value-Add Partners, Resellers, Consultants
  • Professional Support for Microsoft Certified Partners
  • Professional Support for OEMs

Submit your incident over the phone in the U.S.

  • Developers: (800) 936-5800
  • IT Professionals: (800) 936-4900
  • Partners (resellers/consultants): (888) 456-5570
  • Microsoft Certified Partners: (888) 677-9444
  • Original Equipment Manufacturers: (800) 936-2197
  • System Builders: (888) 456-5570

Advisory Services

Microsoft Advisory Services provides short-term advice and guidance for problems not covered by Problem Resolution Service as well as requests for consultative assistance for design, development, and deployment issues. Please see our Advisory Services support page for more information.

Premier Support

For larger organizations requiring managed support direct from Microsoft, contracts are also available through various Premier Support & Alliance Support offerings. Click here for more information.

MSDN Support

Customers with MSDN subscription have the option to use any available MSDN incidents.

See Also

Product Support


Copyright

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, people and events depicted herein are fictitious and no association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document can be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft might have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1992-2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BackOffice, IntelliSense, JScript, MSDN, MSN, Microsoft Office, Outlook, PivotTable, PowerPoint, Microsoft SQL Server, Visual Basic, Visual C++, Visual FoxPro, Visual Studio, Win32 and Win32s are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other product and company names mentioned herein might be the trademarks of their respective owners.